Problem
You are given a 0-indexed integer array nums
of length n
.
nums
contains a valid split at index i
if the following are true:
- The sum of the first
i + 1
elements is greater than or equal to the sum of the lastn - i - 1
elements. - There is at least one element to the right of
i
. That is,0 <= i < n - 1
.
Return the number of valid splits in nums
.
Examples
Example 1:
|
|
Example 2:
|
|
Constraints:
2 <= nums.length <= 105
-105 <= nums[i] <= 105
Solution
Video explanation
Here is the video explaining this method in detail. Please check it out:
Method 1 - Naive
We can iterate for all possible split points and compute the sum on the left and right sides for each split, the naive approach would involve time complexity of O(n^2)
as we check for n-1
split points and calculate the sum for each split point which takes O(n)
time, resulting in overall time complexity of O(n^2)
.
Method 2 - Using Prefix Sum
The problem requires identifying valid splits in the array where the sum of the subarray on the left (up to and including index i) is greater than or equal to the sum on the right (from index i+1 onwards).
To solve the problem efficiently, follow these steps:
- Initial Setup: Calculate the total sum of the array, which represents the sum of the right side when no elements are included on the left side initially.
- Iterate through Possible Splits:
- Use a loop to traverse the array, stopping before the last element (since we need at least one element on the right side for a split).
- For each index:
- Increment the left side sum by adding the current element.
- Update the right side sum by subtracting the current element from the total sum.
- Check whether the left side sum is greater than or equal to the right side sum. If this condition is met, increment the count of valid splits.
- Return Result: After completing the iteration, return the count of valid splits identified.
Code
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n)
, wheren
is the length of the nums array, as we traverse the array once to compute the total sum and again to find the valid splits. - 🧺 Space complexity:
O(1)
as we use a few extra variables for sums and counts, but no additional space proportional to input size.