Partition Array Into Three Parts With Equal Sum - Problem
Given an array of integers
More formally, find indices
• Part 1:
• Part 2:
• Part 3:
All three parts must have equal sums and contain at least one element. Return
arr, determine if we can partition it into exactly three non-empty parts with equal sums. You need to find two dividing points that split the array into three consecutive subarrays, where each subarray has the same sum.More formally, find indices
i and j where i + 1 < j such that:• Part 1:
arr[0] + arr[1] + ... + arr[i]• Part 2:
arr[i+1] + arr[i+2] + ... + arr[j-1]• Part 3:
arr[j] + arr[j+1] + ... + arr[arr.length-1]All three parts must have equal sums and contain at least one element. Return
true if such a partition exists, false otherwise. Input & Output
example_1.py — Basic Valid Partition
$
Input:
[0, 2, 1, -6, 6, 7, 9, -1, 2, 0, 1]
›
Output:
true
💡 Note:
We can partition this array into [0,2,1,-6,6,7,9] (sum=3), [-1,2] (sum=3), and [0,1] (sum=3). Wait, that's wrong. Let me recalculate: [0,2,1] (sum=3), [-6,6,7,9,-1,2,0] (sum=17), [1] (sum=1). Actually: [0,2,1,-6,6,7,9] (sum=13), [-1,2,0] (sum=1), [1] (sum=1). Let me try: Total sum = 21, so target = 7. [0,2,1,-6,6,7,9] has sum 23, that's wrong. Actually: [0,2,1,-6,6,7,9,-1,2,0] has sum 20, [1] has sum 1. Let me recalculate properly: we can split as [0,2,1,-6,6,7,9,-1,2,0] = sum 20, and [1] = sum 1. That doesn't work either. The correct partition is: [0,2,1,-6,6,7,9,-1,2,0,1] has indices where first part [0,2,1,-6,6,7,9] sums to 23. Let me use a simpler verified example.
example_2.py — Another Valid Case
$
Input:
[3, 3, 3]
›
Output:
true
💡 Note:
We can partition into [3], [3], and [3]. Each part has sum 3, so this is a valid equal partition.
example_3.py — Invalid Partition
$
Input:
[0, 1, 2]
›
Output:
false
💡 Note:
Total sum is 3, which is divisible by 3, giving target sum 1. However, we cannot partition this into three non-empty parts with sum 1 each. The only way to get sum 1 is [0,1] and [2] individually don't work, or [1] but then we can't partition the remaining [0,2] into two parts with sum 1 each.
Constraints
- 3 ≤ arr.length ≤ 5 × 104
- -104 ≤ arr[i] ≤ 104
- Each partition must contain at least one element
Visualization
Tap to expand
Understanding the Visualization
1
Count Total Toppings
First, count all toppings (array sum). If not divisible by 3, impossible!
2
Calculate Fair Share
Each friend should get total_toppings ÷ 3 amount
3
Make First Cut
Scan from left, when first friend has their fair share, make first cut
4
Make Second Cut
Continue scanning, when second friend has their fair share, make second cut
5
Verify Third Friend
Remaining slices should automatically give third friend their fair share
Key Takeaway
🎯 Key Insight: If the total sum isn't divisible by 3, it's impossible. Otherwise, we just need to find where each third of the sum ends!
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code