Ways to Split Array Into Three Subarrays - Problem
Array Partitioning Challenge: You need to find all the valid ways to split an array into exactly three contiguous subarrays such that their sums follow a specific order.

Given an array of non-negative integers, a "good" split must satisfy:
• Split into exactly 3 non-empty contiguous parts: left, mid, right
sum(left) ≤ sum(mid) ≤ sum(right)

Goal: Count all possible good splits. Since the answer can be large, return it modulo 10^9 + 7.

Example: For [1,1,1], there's only one way to split: [1] | [1] | [1] where 1 ≤ 1 ≤ 1

Input & Output

example_1.py — Basic Case
$ Input: nums = [1,1,1]
Output: 1
💡 Note: Only one way to split: [1] | [1] | [1]. Sum check: 1 ≤ 1 ≤ 1 ✅
example_2.py — Multiple Valid Splits
$ Input: nums = [1,2,2,2,5,0]
Output: 3
💡 Note: Valid splits: [1] | [2] | [2,2,5,0] (1≤2≤9), [1] | [2,2] | [2,5,0] (1≤4≤7), [1,2] | [2,2] | [5,0] (3≤4≤5)
example_3.py — No Valid Splits
$ Input: nums = [3,2,1]
Output: 0
💡 Note: Only possible split: [3] | [2] | [1]. Sum check: 3 ≤ 2 ≤ 1 ❌ (first condition fails)

Constraints

  • 3 ≤ nums.length ≤ 105
  • 0 ≤ nums[i] ≤ 104
  • All elements are non-negative integers
  • Array must be split into exactly 3 non-empty contiguous subarrays

Visualization

Tap to expand
Ways to Split Array Into Three Subarrays INPUT Array: nums 1 idx: 0 1 idx: 1 1 idx: 2 Input Details nums = [1, 1, 1] Length: 3 Total Sum: 3 Constraints sum(left) <= sum(mid) sum(mid) <= sum(right) ALGORITHM STEPS 1 Prefix Sum Build prefix array [0, 1, 2, 3] 2 First Split (i) Try i=0: left=[1] sum(left) = 1 3 Second Split (j) Binary search for j mid=[1], right=[1] 4 Validate Split Check: 1 <= 1 <= 1 OK - Valid! L M R [1] [1] [1] FINAL RESULT Only 1 Valid Split Found 1 1 1 left mid right Sum Verification 1 <= 1 <= 1 OK - Condition Met! Output 1 Answer: 1 good split (mod 10^9 + 7) Key Insight: Use prefix sums + binary search for O(n log n) solution. For each first split position i, binary search finds valid range of second split positions j where sum(left) <= sum(mid) <= sum(right). With array [1,1,1], only split at positions i=0, j=1 satisfies all conditions. TutorialsPoint - Ways to Split Array Into Three Subarrays | Optimal Solution
Asked in
Google 45 Amazon 38 Meta 25 Microsoft 22
52.1K Views
Medium Frequency
~25 min Avg. Time
1.5K 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