Skip to main content
Back to problems
#927
Hard Algorithms

Three equal parts

Array Math
41.2% acceptance
Feb 25, 2026
855
125
You are given an array arr which consists of only zeros and ones, divide the array into three non-empty parts such that all of these parts represent the same binary value. If it is possible, return any [i, j] with i + 1 < j, such that: arr[0], arr[1], ..., arr[i] is the first part, arr[i + 1], arr[i + 2], ..., arr[j - 1] is the second part, and arr[j], arr[j + 1], ..., arr[arr.length - 1] is the third part. All three parts have equal binary values. If it is not possible, return [-1, -1]. Note that the entire part is used when considering what binary value it represents. For example, [1,1,0] represents 6 in decimal, not 3. Also, leading zeros are allowed, so [0,1,1] and [1,1] represent the same value.

Solution

Rust
Time O(n)
Space O(n)
LeetCode
solution.rs
impl Solution {
  pub fn three_equal_parts(arr: Vec<i32>) -> Vec<i32> {
    let ones: Vec<usize> = arr.iter().enumerate().filter(|&(_, &v)| v == 1).map(|(i, _)| i).collect();
    let total = ones.len();
    if total == 0 { return vec![0, 2]; }
    if total % 3 != 0 { return vec![-1, -1]; }
    let t = total / 3;
    // The pattern of 1s in each part must match
    // Third part starts at ones[2*t]
    let mut i = ones[0];
    let mut j = ones[t];
    let mut k = ones[2*t];
    let n = arr.len();
    while k < n {
      if arr[i] != arr[j] || arr[j] != arr[k] { return vec![-1, -1]; }
      i += 1; j += 1; k += 1;
    }
    vec![i as i32 - 1, j as i32]
  }
}