Ways to Split Array Into Three Subarrays — LeetCode 1712 Python Solution

MediumArrayTwo PointersBinary SearchPrefix Sum
Problem
#1712
Pattern
Prefix Sum
Reading time
2 min

The problem

A split of an integer array is good if: The array is split into three non-empty contiguous subarrays - named left, mid, right respectively from left to right. The sum of the elements in left is less than or equal to the sum of the elements in mid, and the sum of the elements in mid is less than or equal to the sum of the elements in right.

Example

Input
nums = [1,1,1]
Output
1
Explanation
The only good way to split nums is [1] [1] [1].

Python solution

Python
class Solution:
    def waysToSplit(self, nums: List[int]) -> int:
        mod = 10**9 + 7
        s = list(accumulate(nums))
        ans, n = 0, len(nums)
        for i in range(n - 2):
            j = bisect_left(s, s[i] << 1, i + 1, n - 1)
            k = bisect_right(s, (s[-1] + s[i]) >> 1, j, n - 1)
            ans += k - j
        return ans % mod

Complexity

MeasureComplexity
TimeO(n \times \log n), where n is the length of the array nums
SpaceO(1) auxiliary

Pattern: Prefix Sum

Precompute running totals once so any range query becomes a single subtraction. LeetCode 1712. Ways to Split Array Into Three Subarrays is filed here because LeetCode tags it Prefix Sum, which is the vocabulary this hub collects.

The prefix sum guide has the Python template for the pattern and the 157 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1712. Ways to Split Array Into Three Subarrays?
LeetCode 1712. Ways to Split Array Into Three Subarrays is rated Medium on LeetCode.
What is the time complexity of LeetCode 1712. Ways to Split Array Into Three Subarrays?
The Python solution on this page runs in O(n \times \log n), where n is the length of the array nums.
What is the space complexity of LeetCode 1712. Ways to Split Array Into Three Subarrays?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 1712. Ways to Split Array Into Three Subarrays cover?
LeetCode 1712. Ways to Split Array Into Three Subarrays is tagged Array, Two Pointers, Binary Search and Prefix Sum on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview