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 Array104-870123Split 0Left: [10]=10Right: [4,-8,7]=310 >= 3 ✓Split 1: Left=[10,4]=14, Right=[-8,7]=-114 >= -1 ✓Split 2: Left=[10,4,-8]=6, Right=[7]=76 < 7 ✗Answer: 2 valid splits
Understanding the Visualization
1
Input Array
Given array [10, 4, -8, 7] with indices 0 to 3
2
Check Splits
Test each valid split position (0 to n-2)
3
Count Valid
Count splits where left_sum >= right_sum
Key Takeaway
🎯 Key Insight: Use prefix sum to avoid recalculating sums for each split position
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