Ctrl K

Three Equal Binary Pieces

Hard
You are given an array bits of zeros and ones. Cut it into three non-empty consecutive pieces so that every piece, read as a binary number (most significant bit on the left), has the same value. A piece is read in full: [1, 1, 0] is 6, not 3. Leading zeros are fine: [0, 1, 1] and [1, 1] are both 3. Return a pair [i, j] where the first piece is bits[0..i], the second is bits[i+1..j-1] and the third is bits[j..] (so i + 1 < j). If no such cut exists, return [-1, -1]. When the array contains at least one 1, a valid cut, if there is one, is unique. When the array is all zeros, every cut works; return [0, len(bits) - 1] in that case.
Example 1
bits=[0, 1, 1, 0, 1, 1, 0, 1, 1] → [2, 6]

The pieces [0, 1, 1], [0, 1, 1] and [0, 1, 1] are each worth 3. The first ends at index 2 and the third starts at index 6.

Example 2
bits=[1, 0, 0, 1, 0] → [-1, -1]

There are two ones, which cannot be shared equally among three pieces.

Example 3
bits=[1, 0, 1, 0, 0, 1, 0] → [1, 4]

[1, 0], [1, 0] and [0, 1, 0] are all worth 2. The zero at index 3 can only go to the third piece as a leading zero: in the second piece it would become an extra low bit and double its value.

Constraints
  • 3 ≤ len(bits) ≤ 3 · 10⁴
  • bits[i] is 0 or 1
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsStars on One Straight Line HardWhere the Friends Should Meet HardDoes the Robot Cross Its Trail HardRope Around the Posts HardReach Twenty-Four Hard
loading Python…
Input
bits=[0, 1, 1, 0, 1, 1, 0, 1, 1]
Expected
[2, 6]

Run checks the first 3 tests in your browser. Submit checks all 102 tests on the server, hidden ones included.