Problem 1712

Abstract / Summary

Find how many ways to split an array into three parts so each part has the same sum.

Note

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

Python 1712.py

class Solution:
    def waysToSplit(self, nums: List[int]) -> int:
        result = 0
        size = len(nums)

        # prefix sum (in-place)
        total = 0
        for i in range(size):
            total  += nums[i]
            nums[i] = total

        for i, left in enumerate(nums):
            # mid >= left, but the prefix includes left, too, therefore 2*left
            lowMid  = left + left
            # split even between mid and right
            highMid = (total + left) // 2

            low     = bisect_left (nums, lowMid,  lo = i + 1) # lo avoids edge cases with nums[i] = 0
            high    = bisect_right(nums, highMid, lo = low, hi = size - 1)
            result += high - low

        return result % 1_000_000_007
22 lines | 765 bytes | submitted July 29, 2024 | GitHub   26% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 35% (100k+ submissions).

Typical patterns to solve this problem:
  • Array
  • Binary Search
  • Prefix Sum
  • Two Pointers
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 computes the number of ways to split an integer array into three contiguous parts (left, middle, right) such that the sum of the left part is less than or equal to the sum of the middle part, and the sum of the middle part is less than or equal to the sum of the right part. The algorithm works in two phases: it first transforms the input array into a prefix-sum representation, then it iterates over each possible left-segment endpoint and uses binary search to locate the range of valid middle-segment endpoints. The final count is returned modulo 1 000 000 007.

Prefix-Sum Construction

The first loop replaces each element of the original list with the cumulative sum up to that index. This in-place transformation enables constant-time range-sum queries later in the algorithm.

total = 0
for i in range(size):
    total  += nums[i]
    nums[i] = total

After this loop, nums[i] holds the sum of nums[0] … nums[i], and total stores the sum of the entire array. The in-place update avoids allocating an auxiliary array, reducing memory pressure.

Iterating Over Possible Left Segments

The outer for loop enumerates each index i that could serve as the end of the left segment. The variable left is the prefix sum at that index, representing the total of the left part.

for i, left in enumerate(nums):
    lowMid  = left + left
    highMid = (total + left) // 2
    ...

Two thresholds are derived from left:

  • lowMid is twice the left sum, reflecting the condition mid ≥ left. Because the prefix sum includes the left part, the smallest permissible middle sum is 2 * left.
  • highMid is the integer division of (total + left) by 2, derived from the inequality mid ≤ right. Since right = total - mid, the condition mid ≤ right simplifies to mid ≤ (total + left) / 2.

These thresholds define the inclusive range of valid middle-segment sums.

Binary Search for the Middle Range

The algorithm employs the standard library’s bisect_left and bisect_right to locate the first index where the prefix sum reaches at least lowMid and the first index beyond the last position where the prefix sum does not exceed highMid. The search bounds are carefully chosen to avoid invalid configurations.

low  = bisect_left(nums, lowMid, lo=i + 1)
high = bisect_right(nums, highMid, lo=low, hi=size - 1)
result += high - low
  • The lo=i+1 argument for bisect_left guarantees that the middle segment starts strictly after the left segment, preventing overlap.
  • The lo=low argument for bisect_right ensures that the right bound search begins at the first feasible middle index, eliminating unnecessary comparisons.
  • The hi=size-1 limit excludes the final element, because the right segment must be non-empty.

The difference high - low yields the count of middle-segment endpoints that satisfy both inequalities for the current left endpoint.

Result Accumulation and Modulo

Each iteration adds the number of valid middle splits to result. After processing all possible left endpoints, the method returns the total modulo 1 000 000 007, which keeps the result within the required integer range for large inputs.

return result % 1_000_000_007

Edge Cases Handled

The code explicitly addresses several boundary conditions:

  • When the left segment sum is zero, lowMid becomes zero as well. The bisect_left call starts at i+1, ensuring that a zero-valued middle segment is only considered if it begins after the left segment, thereby avoiding a degenerate split where the left and middle parts share the same index.
  • If the computed lowMid exceeds the total sum, bisect_left returns a position beyond the array’s end, causing high - low to be zero for that iteration, which correctly contributes no valid splits.
  • When highMid is less than lowMid, the range defined by bisect_left and bisect_right collapses, again yielding a zero contribution. This situation arises when the left sum is already too large to permit any middle segment that also satisfies the right-segment condition.
  • The hi=size-1 argument prevents the middle segment from extending to the last element, guaranteeing that the right segment remains non-empty.

Performance Optimizations

The algorithm achieves efficiency through several deliberate choices:

  • Transforming the input list into a prefix-sum array in place eliminates the need for an extra data structure, reducing memory allocation overhead.
  • Using binary search (bisect_left and bisect_right) to locate the valid middle range yields logarithmic time per left endpoint, avoiding a linear scan of potential middle positions.
  • Restricting the search interval for the second binary search (lo=low) narrows the examined portion of the array, decreasing the number of comparisons required for each iteration.
  • Accumulating the result incrementally and applying the modulo operation only once at the end prevents repeated costly modulus calculations inside the loop.

Collectively, these techniques enable the solution to handle large input sizes efficiently while maintaining a compact memory footprint.

written by openai gpt

ELI5 - Simplified Explanation

Imagine a long train made of many toy blocks, each with a different number painted on it. The goal is to chop this train into three smaller pieces so that the total of the numbers in the first piece is the smallest, the middle piece has more, and the end piece has the most.

First, the code goes through the train and marks each block with a running total. This turns the train into a map of cumulative weights so it is easy to find the sum of any section instantly by looking at the difference between two blocks.

Next, a special loop looks at every possible place where the first cut could be made. For each of these cuts, it calculates the range of numbers that would work for the middle piece. It knows the middle section cannot be smaller than the first section, and the end section cannot be smaller than the middle section.

Because the train is already organized by these running totals, the code uses a neat trick to find exactly how many spots for the second cut are valid. It searches for the smallest spot that is big enough for the middle piece and the largest spot that keeps the end piece heavy enough. The number of valid spots between those two limits is added to the total count. This continues until every possible first cut has been checked, giving the total amount of ways to split the blocks correctly.

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 = 7 | μ = 7.15 | σ = 1.11

Complexity Analysis

Time: loglinear
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
Progiez C++ Python Java
github black-shadows C++
charles-wangkai Java
everthis JS
fsq C++
haoel C++
JoshCrozier JS
lkwq007 Python
suxrobGM C#
wisdompeak C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, Go, Java, JavaScript, Python
Progiez C++, Java, Python
black-shadows C++, C++
charles-wangkai Java
everthis JavaScript
fsq C++
haoel C++
JoshCrozier JavaScript
lkwq007 Python
suxrobGM C#
wisdompeak C++
24 links | 13 authors | 7 languages

Videos

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

Similar Problems

2 similar problems

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