Python 1013.py
class Solution:
def canThreePartsEqualSum(self, arr: List[int]) -> bool:
total = sum(arr)
if total % 3 != 0:
return False
third = total // 3
completed = 0
current = 0
for a in arr:
current += a
if current == third:
completed += 1
current = 0
return completed >= 3
Difficulty
and has an acceptance rate of about 43% (200k+ submissions).
Typical patterns to solve this problem:
- Array
- Greedy
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 determines whether a given integer array can be split into three contiguous parts whose sums are equal. It follows a straightforward procedural approach: first it validates that the overall sum is divisible by three, then it iterates through the array once, accumulating a running total and counting how many times this running total matches one-third of the overall sum. The function finally returns a Boolean indicating whether at least three such segments were found.
Initial Validation
The algorithm begins by computing the total sum of the input list. This is performed with Python’s built-in sum function, which efficiently aggregates the elements in C-level code. Immediately after obtaining the total, the code checks whether the total is a multiple of three. If the remainder of the division by three is non-zero, the function returns False without further processing. This early exit prevents unnecessary work on inputs that cannot possibly satisfy the partition condition.
total = sum(arr)
if total % 3 != 0:
return False
Determining the Target Segment Sum
When the total passes the divisibility test, the target sum for each of the three parts is calculated by integer division of the total by three. Storing this value in a variable avoids repeated division inside the loop, which contributes to a modest performance gain.
third = total // 3
Accumulating Segment Sums
Two auxiliary counters are introduced: completed tracks how many segments have reached the target sum, and current holds the running sum of the elements examined so far. The core of the algorithm is a single for loop that traverses the array from left to right. For each element, the value is added to current. When current equals the pre-computed third, a segment boundary is recognized: completed is incremented, and current is reset to zero to start accumulating the next segment.
completed = 0
current = 0
for a in arr:
current += a
if current == third:
completed += 1
current = 0
Final Decision
After the loop finishes, the function evaluates whether at least three segments have been identified. The condition completed >= 3 ensures that the array can indeed be divided into three contiguous parts with equal sums. The result of this Boolean expression is returned directly.
return completed >= 3
Edge Cases Handled
The code gracefully handles several subtle scenarios:
When the total sum is zero, the divisibility test succeeds because 0 % 3 equals zero. In this situation, the target segment sum third is also zero. The loop then treats any prefix whose cumulative sum remains zero as a valid segment. Consequently, arrays consisting entirely of zeros, or arrays where positive and negative numbers cancel out to produce a zero total, are correctly identified as partitionable, provided that at least three zero-sum segments can be formed.
If the array contains more than three qualifying segments, the algorithm still returns True. The final check uses a “greater than or equal” comparison, so any surplus segments beyond the required three do not affect the outcome. This behavior aligns with the problem’s requirement that the array be split into exactly three parts, because the extra segments would simply be merged into the last part without violating the equal-sum condition.
When the array length is less than three, the early divisibility test may still pass (for example, a single element [0]). The loop will count a single segment, but the final condition completed >= 3 will evaluate to False, correctly indicating that a three-part split is impossible due to insufficient elements.
Performance Optimizations
The implementation exhibits several efficiency-focused choices. First, the use of Python’s built-in sum leverages highly optimized native code for the initial aggregation, avoiding a manual Python-level loop. Second, the algorithm performs only a single pass over the input list after the initial sum, resulting in minimal iteration overhead. By resetting the current accumulator to zero each time a segment is completed, the code avoids the need for additional data structures such as auxiliary arrays or prefix-sum tables.
Storing the target segment sum in the variable third eliminates repeated division operations inside the loop, which, while inexpensive, can add up for large inputs. The early return on a non-divisible total prevents the loop from executing at all when the condition cannot be satisfied, saving time for inputs that would otherwise require full traversal.
Overall, the solution balances clarity with computational efficiency, achieving the desired result with a compact amount of code and a low constant factor in its runtime behavior.
ELI5 - Simplified Explanation
Imagine you have a long train made of many colorful blocks, and each block has a number written on it. This code is like a game to see if you can chop the train into three pieces so that every piece adds up to the exact same amount.
First, the code adds up all the numbers on every block to see the grand total. If the grand total cannot be divided into three equal piles, then the game is over before it even starts because the pieces would not be fair.
If the math works out, it finds the goal number for each piece. Then, it walks down the line of blocks one by one, adding them up as it goes along. Every time the current pile matches the goal number, the code marks that as a completed piece and starts counting again for the next one. After looking at every block in the train, it checks to see if at least three pieces were successfully made.
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++ | Python | Java | Go | Rust | TS | |||
| LeetcodeHelp | C++ | Python | Java | ||||||
| Progiez | C++ | Python | Java | ||||||
| github | BigEggStudy | C# | |||||||
| black-shadows | C++ | ||||||||
| charles-wangkai | Java | ||||||||
| everthis | JS | ||||||||
| fsq | C++ | ||||||||
| Garvit244 | Python | ||||||||
| JoshCrozier | JS | ||||||||
| lkwq007 | Python | ||||||||
| suxrobGM | C# | ||||||||
| varunu28 | Java | ||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||
| WalkCCC | C++, Python, Java | ||||||||
| leetcode.ca | C++, Go, Java, Python, Rust, TypeScript | ||||||||
| LeetcodeHelp | C++, Java, Python | ||||||||
| Progiez | C++, Java, Python | ||||||||
| BigEggStudy | C# | ||||||||
| black-shadows | C++, C++ | ||||||||
| charles-wangkai | Java | ||||||||
| everthis | JavaScript | ||||||||
| fsq | C++ | ||||||||
| Garvit244 | Python | ||||||||
| JoshCrozier | JavaScript | ||||||||
| lkwq007 | Python | ||||||||
| suxrobGM | C# | ||||||||
| varunu28 | Java |
Videos
Solved On The Same Day
- problem 1668: Maximum Repeating Substring
- problem 1736: Latest Time by Replacing Hidden Digits
- problem 1784: Check if Binary String Has at Most One Segment of Ones
- problem 2099: Find Subsequence of Length K With the Largest Sum
- problem 2383: Minimum Hours of Training to Win a Competition
- problem 2511: Maximum Enemy Forts That Can Be Captured
- problem 2739: Total Distance Traveled
- problem 331: Verify Preorder Serialization of a Binary Tree
- problem 400: Nth Digit
- problem 447: Number of Boomerangs
- problem 1476: Subrectangle Queries
- problem 1828: Queries on Number of Points Inside a Circle
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