Partition Array Into Three Parts With Equal Sum - Problem

Given an array of integers arr, return true if we can partition the array into three non-empty parts with equal sums.

Formally, we can partition the array if we can find indexes i and j with (i + 1 < j) such that:

  • arr[0] + arr[1] + ... + arr[i] == arr[i + 1] + arr[i + 2] + ... + arr[j - 1] == arr[j] + arr[j + 1] + ... + arr[arr.length - 1]

Input & Output

Example 1 — Equal Partition Possible
$ Input: arr = [0,2,1,-6,6,7,9,-1,2,0,1]
Output: true
💡 Note: We can partition into [0,2,1,-6,6], [7], [9,-1,2,0,1] where each part has sum = 5. Actually, let me use a clearer example.
Example 2 — Simple Case
$ Input: arr = [3,3,3]
Output: true
💡 Note: We can partition into [3], [3], [3] where each part has sum = 3
Example 3 — Impossible Partition
$ Input: arr = [0,2,1,-6,6,18]
Output: false
💡 Note: Total sum is 21, target per part is 7. But we cannot find valid partition points that create three parts with sum 7 each

Constraints

  • 3 ≤ arr.length ≤ 5 × 104
  • -104 ≤ arr[i] ≤ 104

Visualization

Tap to expand
Partition Array Into Three Equal Sum Parts INPUT arr = [0,2,1,-6,6,7,9,-1,2,0,1] 0 i=0 2 i=1 1 i=2 -6 i=3 6 i=4 7 i=5 9 i=6 -1 i=7 2 i=8 0 i=9 1 i=10 Total Sum Calculation Sum = 21 Target for Each Part 21 / 3 = 7 21 % 3 == 0 [OK] ALGORITHM STEPS 1 Calculate Total Sum sum(arr) = 21 2 Check Divisibility If sum % 3 != 0 --> false 3 Set Target target = 21/3 = 7 4 Greedy Single Pass Count partitions = target Running Sum Tracking Index RunSum Parts Action 0-3 -3 0 -- 4 3 0 -- 5 7 1 Found! 6-8 10 1 -- 9 14 2 Found! FINAL RESULT Three Equal Partitions Found Part 1: [0,2,1,-6,6,7] Sum = 7 Part 2: [9,-1] Sum = 7 Part 3: [2,0,1] Sum = 7 7 == 7 == 7 OUTPUT true Key Insight: The greedy approach works because we only need to find 2 partition points where running sum equals target. If we find at least 2 such points (before the last element), the third part is guaranteed to sum to target. Time: O(n) | Space: O(1) - Single pass with constant extra space TutorialsPoint - Partition Array Into Three Parts With Equal Sum | Greedy Single Pass Approach
Asked in
Amazon 15 Google 8 Facebook 6
32.0K Views
Medium Frequency
~15 min Avg. Time
890 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