Taro Logo

Three Equal Parts

#1 Most AskedHard
0 views
Topics:
ArraysTwo PointersBit Manipulation

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 * 104
  • arr[i] is 0 or 1

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. What are the constraints on the length of the input array `arr`?
  2. If there are multiple valid ways to partition the array into three equal parts, does it matter which set of indices we return?
  3. How should we handle leading zeros when interpreting the binary values of each part? For example, does '01' have the same binary value as '1'?
  4. What should be returned if the array contains fewer than 3 elements, or if it's impossible to divide it into three non-empty parts?
  5. Should the returned indices be inclusive boundaries representing the end of the first part and the start of the third part, or is there a specific format expected for the output?

Brute Force Solution

Approach

Imagine you have a long sequence of binary digits and you want to slice it into three consecutive chunks so that the numerical value represented by each chunk is identical. The brute force strategy works by exhaustively testing every possible pair of split points to divide the sequence into three parts and then comparing their values.

Here's how the algorithm would work step-by-step:

  1. Start by looking at the very first possible spot where you could make your first cut, right after the first digit.
  2. Then, look at all the remaining spots further down the line to choose where you could make your second cut.
  3. Once you have chosen two cutting spots, you have successfully divided the entire sequence of digits into three distinct chunks: a beginning chunk, a middle chunk, and an end chunk.
  4. Next, examine the digits within these three chunks to see what numerical value each one represents, ignoring leading zeros if necessary.
  5. Check if the numerical value of the first chunk matches the numerical value of the second chunk, and also check if it matches the value of the third chunk.
  6. If all three values do not match, discard this cutting combination and go back to try a different pair of cutting spots.
  7. Repeat this process of testing every single combination of two cutting spots until you find a set of cuts where all three resulting chunks represent the exact same value.
  8. If you check every single possibility and none of them produce three equal values, conclude that it is impossible to divide the sequence as requested.

Code Implementation

def three_equal_parts(binary_array):

    # We test every possible pair of split points to ensure we evaluate all partitioning combinations.
    for first_cut_index in range(1, len(binary_array) - 1):

        for second_cut_index in range(first_cut_index + 1, len(binary_array)):
            first_chunk = binary_array[:first_cut_index]
            middle_chunk = binary_array[first_cut_index:second_cut_index]
            final_chunk = binary_array[second_cut_index:]

            # We compare the numeric values of the slices after removing leading zeros for accuracy.
            if int("".join(map(str, first_chunk)), 2) == int("".join(map(str, middle_chunk)), 2) == int("".join(map(str, final_chunk)), 2):
                return [first_cut_index - 1, second_cut_index]

    # If all partition combinations fail, we return negative indices to indicate it is impossible.
    return [-1, -1]

Big(O) Analysis

Time Complexity
O(n³) – The brute force approach uses nested loops to test every possible pair of split points across the sequence of length n, which requires O(n²) pairs. For each pair of cutting spots, comparing the resulting chunks of digits involves evaluating their numerical values up to length n. This combination of checking O(n²) split pairs and processing chunks of size up to n leads to approximately n cubed over 2 operations, which simplifies to O(n³).
Space Complexity
O(1) – The algorithm only requires a few primitive integer variables to store indices, cut points, and counters, regardless of the input size. It does not allocate any dynamic data structures, temporary lists, or recursive call stacks that grow with the input. Therefore, the extra memory usage remains entirely constant as the input size N increases.

Optimal Solution

Approach

The optimal strategy breaks the binary sequence into three equally weighted numerical values by counting the total number of ones and dividing them into three identical groups. It then uses the positions of these specific ones to pinpoint the exact boundaries where the sequence must be cut.

Here's how the algorithm would work step-by-step:

  1. Count the total number of ones in the entire sequence. If the count cannot be cleanly divided by three, immediately realize it is impossible to split the sequence equally and stop.
  2. Determine the exact size of each group by dividing the total number of ones by three. If there are no ones at all, any division will work because all values are zero.
  3. Find the exact positions where the first, second, and third groups of ones begin within the full sequence.
  4. Compare the actual sequence of digits starting from each of these three starting points all the way to the end of the full sequence to ensure they match identically.
  5. Check if there are enough trailing zeros at the end of the full sequence to satisfy the spacing requirements between the three split sections.
  6. If all the corresponding digits match perfectly and the spacing conditions are met, mark the boundaries right after the first and second sections.
  7. If the matching process fails at any point, conclude that an equal three-way split is impossible.

Code Implementation

def three_equal_parts(binary_array):
    total_ones_count = sum(binary_array)

    # If the total ones cannot be split into three equal groups, an equal division is impossible.
    if total_ones_count % 3 != 0:
        return [-1, -1]

    if total_ones_count == 0:
        return [0, len(binary_array) - 1]

    ones_per_group = total_ones_count // 3
    current_ones_seen = 0
    first_group_start = second_group_start = third_group_start = 0

    for index, bit_value in enumerate(binary_array):
        if bit_value == 1:
            current_ones_seen += 1
            if current_ones_seen == 1:
                first_group_start = index
            elif current_ones_seen == ones_per_group + 1:
                second_group_start = index
            elif current_ones_seen == (2 * ones_per_group) + 1:
                third_group_start = index

    trailing_zeros_count = len(binary_array) - third_group_start

    # Ensure there are enough trailing zeros to match the spacing requirements for all three sections.
    if (first_group_start + trailing_zeros_count <= second_group_start) and \
       (second_group_start + trailing_zeros_count <= third_group_start):

        cursor_one = first_group_start
        cursor_two = second_group_start
        cursor_three = third_group_start

        while cursor_three < len(binary_array):
            # Verify that the digits in all three candidate sections match identically from this point.
            if binary_array[cursor_one] == binary_array[cursor_two] == binary_array[cursor_three]:
                cursor_one += 1
                cursor_two += 1
                cursor_three += 1
            else:
                return [-1, -1]

        return [cursor_one - 1, cursor_two]

    return [-1, -1]

Big(O) Analysis

Time Complexity
O(n) – The time complexity is driven by a single pass to count the total ones, followed by locating the starting positions of each group, and finally comparing the digits from these positions to the end of the input array of size n. Each of these steps processes the array elements a constant number of times sequentially rather than with nested iterations. Summing the proportional operations for these linear scans yields approximately 3n operations, which simplifies to O(n).
Space Complexity
O(1) – The algorithm only uses a few primitive integer variables to store the total count of ones, the sizes of each group, and the starting indices for the three sections. No dynamic data structures, temporary lists, or recursive call stacks are created during the execution. Therefore, the extra auxiliary memory remains constant regardless of the input size N, resulting in an optimal space complexity.

Edge Cases

Array length less than 3
How to Handle:
Return [-1, -1] immediately because it is impossible to divide the array into three non-empty parts.
Array contains all zeros
How to Handle:
Count total ones as zero, and split the array at fixed indices around thirds of the length.
Total count of ones is not divisible by 3
How to Handle:
Return [-1, -1] because an equal binary value requires an equal number of significant ones in each part.
Leading or trailing zeros create overlapping part boundaries
How to Handle:
Align the partition indices based on the exact positions of the first ones in each third block.
Maximum length constraints up to thirty thousand elements
How to Handle:
Use a linear time single pass or constant pass approach to avoid time limit exceeded errors.
Trailing zeros after the last partition affecting value equality
How to Handle:
Compare the actual binary digits of the three slices from their starting ones to the end of the third part.
Multiple valid split points due to trailing zeros
How to Handle:
Greedily consume all trailing zeros of the third part by shifting the right partition boundary as far right as possible.
Array contains only a single one or too few ones to form three parts
How to Handle:
The modulo check for the total count of ones will catch this and immediately return [-1, -1].
0/2 completed