Three Equal Parts - Problem

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
  • 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: 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.

Input & Output

Example 1 — Valid Split
$ Input: arr = [0,1,0,1,0,1]
Output: [0,3]
💡 Note: Split into [0], [1,0], [1,0,1]. Values: 0, 2, 5 - not equal. Actually: [0,1], [0,1], [0,1] → all equal to 1.
Example 2 — All Zeros
$ Input: arr = [0,0,0,0,0,0]
Output: [0,2]
💡 Note: All parts will be 0 regardless of split position, so any valid split like [0], [0], [0,0,0,0] works.
Example 3 — Impossible Split
$ Input: arr = [1,1,0,1,1]
Output: [-1,-1]
💡 Note: Total ones = 4, not divisible by 3, so impossible to create three equal binary values.

Constraints

  • 3 ≤ arr.length ≤ 3 × 104
  • arr[i] is 0 or 1

Visualization

Tap to expand
Three Equal Parts: Split Binary Array010101012345Part1: [0,1] = 1Part2: [0,1] = 1Part3: [0,1] = 1All parts equal: 1 = 1 = 1 ✓Output: [1, 4]
Understanding the Visualization
1
Input Array
Binary array [0,1,0,1,0,1] with 3 ones total
2
Find Pattern
Each part needs 1 one. Pattern is '01' (binary value 1)
3
Valid Split
Split at positions [1,4]: [0,1], [0,1], [0,1] - all equal
Key Takeaway
🎯 Key Insight: Count total 1s first - if not divisible by 3, return [-1,-1] immediately
Asked in
Facebook 35 Google 28 Amazon 22
28.0K Views
Medium Frequency
~35 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen