Off-by-one on range boundaries
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Break down a hard problem into reliable checkpoints, edge-case handling, and complexity trade-offs.
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, andarr[j], arr[j + 1], ..., arr[arr.length - 1] is the third part.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.
Example 1:
Input: arr = [1,0,1,0,1] Output: [0,3]
Example 2:
Input: arr = [1,1,0,1,1] Output: [-1,-1]
Example 3:
Input: arr = [1,1,0,0,1] Output: [0,2]
Constraints:
3 <= arr.length <= 3 * 104arr[i] is 0 or 1Problem summary: 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.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array · Math
[1,0,1,0,1]
[1,1,0,1,1]
[1,1,0,0,1]
Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #927: Three Equal Parts
class Solution {
private int[] arr;
public int[] threeEqualParts(int[] arr) {
this.arr = arr;
int cnt = 0;
int n = arr.length;
for (int v : arr) {
cnt += v;
}
if (cnt % 3 != 0) {
return new int[] {-1, -1};
}
if (cnt == 0) {
return new int[] {0, n - 1};
}
cnt /= 3;
int i = find(1), j = find(cnt + 1), k = find(cnt * 2 + 1);
for (; k < n && arr[i] == arr[j] && arr[j] == arr[k]; ++i, ++j, ++k) {
}
return k == n ? new int[] {i - 1, j} : new int[] {-1, -1};
}
private int find(int x) {
int s = 0;
for (int i = 0; i < arr.length; ++i) {
s += arr[i];
if (s == x) {
return i;
}
}
return 0;
}
}
// Accepted solution for LeetCode #927: Three Equal Parts
func threeEqualParts(arr []int) []int {
find := func(x int) int {
s := 0
for i, v := range arr {
s += v
if s == x {
return i
}
}
return 0
}
n := len(arr)
cnt := 0
for _, v := range arr {
cnt += v
}
if cnt%3 != 0 {
return []int{-1, -1}
}
if cnt == 0 {
return []int{0, n - 1}
}
cnt /= 3
i, j, k := find(1), find(cnt+1), find(cnt*2+1)
for ; k < n && arr[i] == arr[j] && arr[j] == arr[k]; i, j, k = i+1, j+1, k+1 {
}
if k == n {
return []int{i - 1, j}
}
return []int{-1, -1}
}
# Accepted solution for LeetCode #927: Three Equal Parts
class Solution:
def threeEqualParts(self, arr: List[int]) -> List[int]:
def find(x):
s = 0
for i, v in enumerate(arr):
s += v
if s == x:
return i
n = len(arr)
cnt, mod = divmod(sum(arr), 3)
if mod:
return [-1, -1]
if cnt == 0:
return [0, n - 1]
i, j, k = find(1), find(cnt + 1), find(cnt * 2 + 1)
while k < n and arr[i] == arr[j] == arr[k]:
i, j, k = i + 1, j + 1, k + 1
return [i - 1, j] if k == n else [-1, -1]
// Accepted solution for LeetCode #927: Three Equal Parts
/**
* [0927] Three Equal Parts
*
* 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.
*
* Example 1:
* Input: arr = [1,0,1,0,1]
* Output: [0,3]
* Example 2:
* Input: arr = [1,1,0,1,1]
* Output: [-1,-1]
* Example 3:
* Input: arr = [1,1,0,0,1]
* Output: [0,2]
*
* Constraints:
*
* 3 <= arr.length <= 3 * 10^4
* arr[i] is 0 or 1
*
*/
pub struct Solution {}
// problem: https://leetcode.com/problems/three-equal-parts/
// discuss: https://leetcode.com/problems/three-equal-parts/discuss/?currentPage=1&orderBy=most_votes&query=
// submission codes start here
impl Solution {
// Credit: https://leetcode.com/problems/three-equal-parts/solutions/1343847/rust-solution/
pub fn three_equal_parts(arr: Vec<i32>) -> Vec<i32> {
let v = arr
.iter()
.enumerate()
.filter_map(|(i, &a)| if a == 1 { Some(i) } else { None })
.collect::<Vec<_>>();
if arr.len() < 3 || v.len() % 3 != 0 {
return [-1, -1].to_vec();
}
if v.is_empty() {
return [0, 2].to_vec();
}
let chunks = v.chunks(v.len() / 3).collect::<Vec<_>>();
let i = chunks[0][v.len() / 3 - 1] + arr.len() - v[v.len() - 1] - 1;
let j = chunks[1][v.len() / 3 - 1] + arr.len() - v[v.len() - 1];
if arr.len() - chunks[2][0] > j - i - 1 || arr.len() - chunks[2][0] > i + 1 {
return [-1, -1].to_vec();
}
for k in 0..(i + 1).min(j - i - 1).min(arr.len() - j) {
if arr[i - k] != arr[j - 1 - k] || arr[i - k] != arr[arr.len() - 1 - k] {
return [-1, -1].to_vec();
}
}
[i as i32, j as i32].to_vec()
}
}
// submission codes end
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_0927_example_1() {
let arr = vec![1, 0, 1, 0, 1];
let result = vec![0, 3];
assert_eq!(Solution::three_equal_parts(arr), result);
}
#[test]
fn test_0927_example_2() {
let arr = vec![1, 1, 0, 1, 1];
let result = vec![-1, -1];
assert_eq!(Solution::three_equal_parts(arr), result);
}
#[test]
fn test_0927_example_3() {
let arr = vec![1, 1, 0, 0, 1];
let result = vec![0, 2];
assert_eq!(Solution::three_equal_parts(arr), result);
}
}
// Accepted solution for LeetCode #927: Three Equal Parts
// Auto-generated TypeScript example from java.
function exampleSolution(): void {
}
// Reference (java):
// // Accepted solution for LeetCode #927: Three Equal Parts
// class Solution {
// private int[] arr;
//
// public int[] threeEqualParts(int[] arr) {
// this.arr = arr;
// int cnt = 0;
// int n = arr.length;
// for (int v : arr) {
// cnt += v;
// }
// if (cnt % 3 != 0) {
// return new int[] {-1, -1};
// }
// if (cnt == 0) {
// return new int[] {0, n - 1};
// }
// cnt /= 3;
//
// int i = find(1), j = find(cnt + 1), k = find(cnt * 2 + 1);
// for (; k < n && arr[i] == arr[j] && arr[j] == arr[k]; ++i, ++j, ++k) {
// }
// return k == n ? new int[] {i - 1, j} : new int[] {-1, -1};
// }
//
// private int find(int x) {
// int s = 0;
// for (int i = 0; i < arr.length; ++i) {
// s += arr[i];
// if (s == x) {
// return i;
// }
// }
// return 0;
// }
// }
Use this to step through a reusable interview workflow for this problem.
Two nested loops check every pair or subarray. The outer loop fixes a starting point, the inner loop extends or searches. For n elements this gives up to n²/2 operations. No extra space, but the quadratic time is prohibitive for large inputs.
Most array problems have an O(n²) brute force (nested loops) and an O(n) optimal (single pass with clever state tracking). The key is identifying what information to maintain as you scan: a running max, a prefix sum, a hash map of seen values, or two pointers.
Review these before coding to avoid predictable interview regressions.
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Wrong move: Temporary multiplications exceed integer bounds.
Usually fails on: Large inputs wrap around unexpectedly.
Fix: Use wider types, modular arithmetic, or rearranged operations.