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
Difficulty
and has an acceptance rate of about 35% (100k+ submissions).
Typical patterns to solve this problem:
- Array
- Binary Search
- Prefix Sum
- Two Pointers
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 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:
lowMidis twice the left sum, reflecting the conditionmid ≥ left. Because the prefix sum includes the left part, the smallest permissible middle sum is2 * left.highMidis the integer division of(total + left)by 2, derived from the inequalitymid ≤ right. Sinceright = total - mid, the conditionmid ≤ rightsimplifies tomid ≤ (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+1argument forbisect_leftguarantees that the middle segment starts strictly after the left segment, preventing overlap. - The
lo=lowargument forbisect_rightensures that the right bound search begins at the first feasible middle index, eliminating unnecessary comparisons. - The
hi=size-1limit 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,
lowMidbecomes zero as well. Thebisect_leftcall starts ati+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
lowMidexceeds the total sum,bisect_leftreturns a position beyond the array’s end, causinghigh - lowto be zero for that iteration, which correctly contributes no valid splits. - When
highMidis less thanlowMid, the range defined bybisect_leftandbisect_rightcollapses, 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-1argument 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_leftandbisect_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.
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.
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 | |||
| 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++ |
Videos
Similar Problems
- problem 2147: Number of Ways to Divide a Long Corridor
- problem 2270: Number of Ways to Split Array
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