Problem 927

Abstract / Summary

Split the array into three equal parts with equal sum.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 0927.py

class Solution:
    def threeEqualParts(self, arr: List[int]) -> List[int]:
        size = len(arr)

        # reject if impossible
        total = sum(arr)
        if total % 3 != 0:
            return [ -1, -1 ]

        # only zeros
        if total == 0:
            return [ 0, size - 1 ] # [ 0, 1 ] should be valid, too, but is rejected

        # number of 1s per part
        need = total // 3

        have    = 0
        pattern = ""
        # extract a substring such that it start and ends with "1" and has one third of all "1"
        for pos in range(size):
            x = arr[pos]
            have += x
            if pattern or have == 1:
                pattern += str(x)
            if have == need:
                break

        # trailing zeros
        last = len(arr) - 1
        while arr and arr[last] == 0:
            last    -= 1
            pattern += "0"

        # find pattern three times
        all = "".join(str(a) for a in arr)
        pos = -len(pattern)
        split = []
        for _ in range(3):
            pos = all.find(pattern, pos + len(pattern))
            if pos == -1: # not found
                return [ -1, -1 ]

            split.append(pos + len(pattern))

        return [ split[0] - 1, split[1] ]
45 lines | 1300 bytes | submitted July 31, 2024 | GitHub   25% comment ratio | tab size 4 | moderate complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 42% (80k+ submissions).

Typical patterns to solve this problem:
  • Array
  • Math
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided implementation solves the problem of partitioning a binary array into three parts that represent the same binary value. It proceeds by first checking feasibility, then extracting a canonical pattern that must appear in each part, and finally locating three occurrences of that pattern within the concatenated string representation of the array. The function returns the indices that separate the three equal parts, or [-1, -1] when a partition is impossible.

Key Steps

The algorithm can be broken down into distinct phases, each reflected by a concise code fragment.

Feasibility Check

size = len(arr)

total = sum(arr)
if total % 3 != 0:
    return [ -1, -1 ]

The total number of 1s in the array is computed. If this count is not divisible by three, a three-way equal partition cannot exist, and the function returns the failure sentinel.

All-Zero Shortcut

if total == 0:
    return [ 0, size - 1 ]   # [ 0, 1 ] should be valid, too, but is rejected

When the array contains only zeros, any split yields equal values (zero). The code immediately returns the leftmost possible split, covering the edge case of an all-zero input.

Determining the Required Ones per Part

need = total // 3

The variable need stores the exact number of 1s that each of the three parts must contain.

Extracting the Canonical Pattern

have    = 0
pattern = ""
for pos in range(size):
    x = arr[pos]
    have += x
    if pattern or have == 1:
        pattern += str(x)
    if have == need:
        break

This loop walks through the array from the start, accumulating 1s until the count reaches need. Simultaneously it builds a string pattern that begins with the first 1 encountered and ends at the position where the required number of 1s is satisfied. The resulting pattern is the minimal binary representation that each part must share.

Extending the Pattern with Trailing Zeros

last = len(arr) - 1
while arr and arr[last] == 0:
    last    -= 1
    pattern += "0"

After the core pattern is identified, any zeros that appear at the very end of the original array are appended to pattern. This ensures that the pattern accounts for the necessary trailing zeros that must be present in each part for the values to be equal.

Locating Three Occurrences of the Pattern

all = "".join(str(a) for a in arr)
pos = -len(pattern)
split = []
for _ in range(3):
    pos = all.find(pattern, pos + len(pattern))
    if pos == -1:   # not found
        return [ -1, -1 ]
    split.append(pos + len(pattern))

The entire array is converted into a single string all. Starting from a position just before the first possible match, the loop searches for the pattern three times using str.find. Each successful locate records the index immediately after the pattern, building the list split. If any search fails, the function returns the failure sentinel.

Returning the Partition Indices

return [ split[0] - 1, split[1] ]

The first split point is adjusted to point to the last index of the first part, while the second split point marks the start of the third part. These two indices constitute the required output.

Edge Cases Handled

The code explicitly addresses several boundary conditions:

  • Non-divisible count of ones - The early modulus check prevents unnecessary work when a partition is mathematically impossible.
  • All zeros - A dedicated branch returns a valid split without further processing, covering the scenario where the binary value of each part is zero.
  • Pattern beginning with the first one - The condition if pattern or have == 1 guarantees that leading zeros are omitted from the pattern, aligning the pattern with the true binary representation.
  • Trailing zeros after the last one - By appending trailing zeros from the end of the array to the pattern, the algorithm ensures that each part can accommodate the required number of zeros that follow the significant bits.
  • Missing pattern occurrences - The loop that searches for the pattern three times checks the return value of find. If any occurrence is absent, the function returns [-1, -1], handling cases where the array structure does not permit three identical segments.

Performance Optimizations

Several implementation choices contribute to efficient execution:

  • Early termination of the pattern extraction loop - The break statement stops the scan as soon as the needed count of 1s is reached, avoiding a full traversal of the array.
  • String concatenation only for the pattern - Instead of building separate sub-arrays for each part, the algorithm constructs a compact string representation of the required pattern, reducing memory overhead.
  • Single conversion of the whole array to a string - By joining the entire array into all once, the subsequent find operations work on a contiguous memory block, which is faster than repeated slicing or list operations.
  • Incremental search using the previous match position - The pos variable is advanced by the length of the pattern after each successful find, ensuring that each search starts just after the prior match and eliminating redundant scanning of already examined characters.
  • Avoidance of additional data structures - Apart from the minimal split list that stores two integer positions, the algorithm relies on primitive variables, keeping the runtime footprint low.
written by openai gpt

ELI5 - Simplified Explanation

Imagine a long line of toy blocks that are either white or black. The goal is to cut this line into three pieces so that every piece has the exact same pattern of colors.

First, the code counts how many black blocks are in the whole line. If the count cannot be divided perfectly into three equal groups, then it is impossible to solve the puzzle, so the code gives up. If there are no black blocks at all, the machine knows it can just chop the line anywhere and it will be correct.

Next, the code figures out what the three identical patterns should look like. It looks at the last group of black blocks and counts how many empty white spaces come after them. These trailing white spaces must be part of every piece so that the pieces stay identical. The code creates a secret map of this pattern by looking at where the black blocks start and adding those empty spaces at the end.

Finally, the code walks through the whole line from the beginning to find three copies of that special pattern. It keeps track of where each piece starts and where it ends. If it finds all three matching pieces, it finishes the job. If it struggles to find them or if the pieces do not fit perfectly, it simply reports back that it could not do it.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 4 | μ = 4.78 | σ = 1.73

Complexity Analysis

Time: linear
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Python Java TS
WalkCCC C++ Python Java
leetcode.ca C++ JS Python Java Go
LeetcodeHelp C++ Python Java
Progiez C++ Python Java
github black-shadows C++
charles-wangkai Java
everthis JS
fsq C++
halfrost Go
JoshCrozier JS
lkwq007 Python
suxrobGM C#
wisdompeak C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, Go, Java, JavaScript, Python
LeetcodeHelp C++, Java, Python
Progiez C++, Java, Python
black-shadows C++, C++
charles-wangkai Java
everthis JavaScript
fsq C++
halfrost Go
JoshCrozier JavaScript
lkwq007 Python
suxrobGM C#
wisdompeak C++
27 links | 14 authors | 7 languages

Videos

4 videos   did my crawler come up with invalid videos ? drop me a line.

Solved On The Same Day

2 hard
3 solutions   July 31, 2024

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality