Number of Ways to Split Array - 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 last n - 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.

Input & Output

Example 1 — Basic Array
$ Input: nums = [10,4,-8,7]
Output: 2
💡 Note: Split at index 0: [10] vs [4,-8,7] → 10 >= 3 ✓. Split at index 1: [10,4] vs [-8,7] → 14 >= -1 ✓. Split at index 2: [10,4,-8] vs [7] → 6 < 7 ✗. Total: 2 valid splits.
Example 2 — All Positive
$ Input: nums = [2,3,1,0]
Output: 2
💡 Note: Split at index 0: [2] vs [3,1,0] → 2 < 4 ✗. Split at index 1: [2,3] vs [1,0] → 5 >= 1 ✓. Split at index 2: [2,3,1] vs [0] → 6 >= 0 ✓. Total: 2 valid splits.
Example 3 — Minimum Size
$ Input: nums = [1,1]
Output: 1
💡 Note: Only one possible split at index 0: [1] vs [1] → 1 >= 1 ✓. Total: 1 valid split.

Constraints

  • 2 ≤ nums.length ≤ 105
  • -105 ≤ nums[i] ≤ 105

Visualization

Tap to expand
Number of Ways to Split Array INPUT Array nums (n=4) 10 i=0 4 i=1 -8 i=2 7 i=3 Valid Split Conditions: 1. sum(0..i) >= sum(i+1..n-1) 2. At least 1 element on right (0 <= i < n-1) Total Sum = 10+4-8+7 = 13 Input: nums = [10, 4, -8, 7] ALGORITHM STEPS 1 Calculate Total Sum totalSum = 13 2 Init leftSum = 0 Track running prefix sum 3 Iterate i from 0 to n-2 rightSum = totalSum - leftSum 4 Check: leftSum >= rightSum If true, count++ Iteration Details i left right valid? 0 10 3 OK 1 14 -1 OK 2 6 7 NO Time: O(n) Space: O(1) FINAL RESULT Valid Splits Found Split at i=0 10 | 4,-8,7 10 >= 3 [OK] Split at i=1 10,4 | -8,7 14 >= -1 [OK] Invalid: i=2 6 < 7 [NO] OUTPUT 2 Key Insight: Instead of recalculating sums for each split, use prefix sum optimization: leftSum accumulates as we iterate, rightSum = totalSum - leftSum (computed once). This reduces time complexity from O(n^2) to O(n) with constant space. TutorialsPoint - Number of Ways to Split Array | Optimal Solution
Asked in
Microsoft 15 Google 12 Amazon 8
23.4K Views
Medium Frequency
~15 min Avg. Time
856 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen