Partition Array Into Three Parts With Equal Sum Problem
Description
LeetCode Problem 1013.
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 + 1 < j with (arr[0] + arr[1] + ... + arr[i] == arr[i + 1] + arr[i + 2] + ... + arr[j - 1] == arr[j] + arr[j + 1] + ... + arr[arr.length - 1])
Example 1:
Input: arr = [0,2,1,-6,6,-7,9,1,2,0,1]
Output: true
Explanation: 0 + 2 + 1 = -6 + 6 - 7 + 9 + 1 = 2 + 0 + 1
Example 2:
Input: arr = [0,2,1,-6,6,7,9,-1,2,0,1]
Output: false
Example 3:
Input: arr = [3,3,6,5,-2,2,5,1,-9,4]
Output: true
Explanation: 3 + 3 = 6 = 5 - 2 + 2 + 5 + 1 - 9 + 4
Constraints:
3 <= arr.length <= 5 * 10^4-10^4 <= arr[i] <= 10^4
Solution
Approach: Greedy Cuts
If the array splits into three parts with equal sums, each part sums to total / 3. So first, if total is not divisible by 3, the answer is false.
Otherwise let target = total / 3 and scan from the left with a running sum run. Each time run reaches target, cut off a part there (parts++) and start a new part from 0. Cutting as early as possible is safe: if any valid split exists, its first cut can be moved to the earliest prefix that sums to target without breaking the rest.
At the end, the answer is parts >= 3, not parts == 3. With zeros, or values that cancel out, we can find more than three cuts, e.g. [0,0,0,0] gives four. That is still fine: keep the first two parts, and merge everything after them into the third part, which sums to total - 2 * target = target and is not empty.
Complexity: O(n) time and O(1) extra space.
class Solution:
def canThreePartsEqualSum(self, arr: List[int]) -> bool:
total = sum(arr)
if total % 3 != 0:
return False
target = total // 3
parts = run = 0 # parts cut off so far, and the sum of the current part
for x in arr:
run += x
if run == target:
parts += 1
run = 0
# More than 3 cuts is fine: everything after the second part sums to target.
return parts >= 3