Split Array with Equal Sum - Problem

Given an integer array nums of length n, return true if there is a triplet (i, j, k) which satisfies the following conditions:

  • 0 < i, i + 1 < j, j + 1 < k < n - 1
  • The sum of subarrays (0, i - 1), (i + 1, j - 1), (j + 1, k - 1) and (k + 1, n - 1) is equal.

A subarray (l, r) represents a slice of the original array starting from the element indexed l to the element indexed r.

Note: The array is split into four parts by three dividers at positions i, j, and k.

Input & Output

Example 1 — Valid Split Exists
$ Input: nums = [1,2,1,2,1,2,1]
Output: true
💡 Note: With i=1, j=3, k=5: part1=[1] sum=1, part2=[1] sum=1, part3=[1] sum=1, part4=[1] sum=1. All sums equal 1.
Example 2 — No Valid Split
$ Input: nums = [1,2,3,4,5,6,7]
Output: false
💡 Note: No triplet (i,j,k) can create four subarrays with equal sums from this ascending sequence.
Example 3 — Too Small Array
$ Input: nums = [1,1,1,1]
Output: false
💡 Note: Array too small (length 4 < 7). Need at least 7 elements for valid triplet positions.

Constraints

  • 7 ≤ nums.length ≤ 2000
  • -106 ≤ nums[i] ≤ 106

Visualization

Tap to expand
Split Array with Equal Sum INPUT nums = [1,2,1,2,1,2,1] 1 0 2 1 1 2 2 j=3 1 4 2 5 1 6 Constraints: • 0 < i • i + 1 < j • j + 1 < k < n - 1 Four Equal Parts: Part1 i Part2 j Part3 k Part4 All parts must have equal sum ALGORITHM STEPS 1 Compute Prefix Sum sum[i] = sum[i-1] + nums[i] 1 3 4 6 7 9 10 2 Fix Middle Index j Iterate j from 3 to n-4 3 Use HashSet for Left Store valid left sums HashSet {1} 4 Check Right Side Find k where sum3=sum4 and sum exists in set If sum3 == sum4 AND sum3 in HashSet --> true FINAL RESULT Valid Triplet Found! i=1, j=3, k=5 1 2 i 1 2 j 1 2 k 1 Subarray Sums: Part1 [0,0]: 1 Part2 [2,2]: 1 Part3 [4,4]: 1 Part4 [6,6]: 1 1 = 1 = 1 = 1 Output: true OK Key Insight: Fix middle index j and use a HashSet to store valid left partition sums. For each j, iterate left to find i where sum1=sum2, add to set. Then iterate right to find k where sum3=sum4 and check if sum3 exists in set. Time: O(n^2), Space: O(n). TutorialsPoint - Split Array with Equal Sum | Hash Map with Fixed Middle Approach
Asked in
Google 25 Facebook 18 Microsoft 12
34.5K Views
Medium Frequency
~25 min Avg. Time
892 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