Problem 1013

Abstract / Summary

Split the array into three parts with equal sums by finding two cut points where each part sums to the same value.

Note

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

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
17 lines | 415 bytes | submitted October 12, 2023 | GitHub   tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 43% (200k+ submissions).

Typical patterns to solve this problem:
  • Array
  • Greedy
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 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.

written by openai gpt

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.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 26 | median = 8 | μ = 7.50 | σ = 1.25

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++ 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
29 links | 15 authors | 8 languages

Videos

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

Solved On The Same Day

13 solutions   October 12, 2023

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