sagelearnai

Number of Ways to Split Array

Difficulty: Medium · Pattern: Prefix Sum · LeetCode #2270

A split at index i (0 ≤ i < n−1) is valid if the sum of nums[0..i] is ≥ the sum of nums[i+1..n−1]. Return the number of valid splits.

Examples

text
[10, 4, -8, 7]  →  2
[2, 3, 1, 0]    →  2

Hints

  1. Right sum = total − left sum.

Approach

Compute the total once, then sweep with a running left sum; at each i < n − 1, count the split if left ≥ total − left. O(n), O(1).

Complexity

Time: O(n). Space: O(1).

Python solution
def waysToSplitArray(nums):
    total, left, count = sum(nums), 0, 0
    for i in range(len(nums) - 1):
        left += nums[i]
        if left >= total - left:
            count += 1
    return count
JavaScript solution
function waysToSplitArray(nums) {
  const total = nums.reduce((a, b) => a + b, 0);
  let left = 0, count = 0;
  for (let i = 0; i < nums.length - 1; i++) { left += nums[i]; if (left >= total - left) count++; }
  return count;
}