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 INPUT arr = [0,1,0,1,0,1] 0 i=0 1 i=1 0 i=2 1 i=3 0 i=4 1 i=5 Total 1s in array: 3 Each part needs: 1 one Goal: Divide into 3 parts with equal binary values Find [i, j] where i+1 < j Part1: arr[0..i] Part2: arr[i+1..j-1] Part3: arr[j..end] ALGORITHM STEPS 1 Count Total 1s Count = 3, must be divisible by 3. Each part gets 1 one. 2 Find 1s Positions 1st one at index 1 2nd one at index 3 3rd one at index 5 3 Pattern Match Match trailing zeros from last part. Part3 = "01" (=1) 4 Verify Partition Part1[0..0]="0,1" binary=1 Part2[1..2]="0,1" binary=1 Part3[3..5]="0,1" binary=1 [0,1] [0,1] [0,1] All equal binary value: 1 FINAL RESULT Partition indices found: [0, 3] i = 0, j = 3 Three Parts: Part1: arr[0..0] = [0,1] = 1 Part2: arr[1..2] = [0,1] = 1 Part3: arr[3..5] = [0,1] = 1 OK - All Equal! Key Insight: The Pattern Matching approach works by first counting total 1s (must be divisible by 3), then finding the positions where each third of 1s start. The trailing zeros after the last 1 determine the pattern. Leading zeros are allowed, so we match the significant bits from right to left for each part. TutorialsPoint - Three Equal Parts | Pattern Matching Approach
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