Ways to Split Array Into Three Subarrays Problem
#1712
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 1712.
A split of an integer array is good if:
- The array is split into three non-empty contiguous subarrays - named
left,mid,rightrespectively from left to right. - The sum of the elements in
leftis less than or equal to the sum of the elements inmid, and the sum of the elements inmidis less than or equal to the sum of the elements inright.
Given nums, an array of non-negative integers, return the number of good ways to split nums. As the number may be too large, return it modulo 10^9+ 7.
Example 1:
Input: nums = [1,1,1]
Output: 1
Explanation: The only good way to split nums is [1] [1] [1].
Example 2:
Input: nums = [1,2,2,2,5,0]
Output: 3
Explanation: There are three good ways of splitting nums:
[1] [2] [2,2,5,0]
[1] [2,2] [2,5,0]
[1,2] [2,2] [5,0]
Example 3:
Input: nums = [3,2,1]
Output: 0
Explanation: There is no good way to split nums.
Constraints:
3 <= nums.length <= 10^50 <= nums[i] <= 10^4
Solution
Approach: Prefix Sums + Binary Search
Build the prefix sums s, where s[i] is the sum of the first i + 1 elements. Since all numbers are non-negative, s never decreases.
Try every end i of left, for i in [0, n - 2). The end of mid must then satisfy:
midat leastleft:s[j] >= 2 * s[i], so binary search for the smallest suchj(afteri);rightat leastmid:s[k] <= (s[n - 1] + s[i]) / 2, so binary search for the firstkpast that bound.
Every end in [j, k) works, so add k - j (with both searches limited to indices before n - 1, so right is not empty). Return the total modulo 10^9 + 7.
Complexity: O(n log n) time and O(n) space, where n is the length of nums.
from bisect import bisect_left, bisect_right
from itertools import accumulate
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