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] ]
Difficulty
and has an acceptance rate of about 42% (80k+ submissions).
Typical patterns to solve this problem:
- Array
- Math
AI Disclaimer
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.
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 == 1guarantees 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
breakstatement stops the scan as soon as the needed count of1s 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
allonce, the subsequentfindoperations work on a contiguous memory block, which is faster than repeated slicing or list operations. - Incremental search using the previous match position - The
posvariable 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
splitlist that stores two integer positions, the algorithm relies on primitive variables, keeping the runtime footprint low.
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.
Code Quality
Complexity Analysis
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
Other Solutions
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++ |
Videos
Solved On The Same Day
- problem 1776: Car Fleet II
- problem 2801: Count Stepping Numbers in Range
Extra
- 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