Given an array arr
of integers, return true
if we can partition the array into three non-empty parts with equal sums.
Formally, you need to find indices 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])
arr = [0,2,1,-6,6,-7,9,1,2,0,1]
Output: true
(Explanation: The array is partitioned as [0,2,1], [-6,6,-7,9,1], [2,0,1])arr = [0,2,1,-6,6,7,9,-1,2,0,1]
Output: false
arr = [3,3,6,5,-2,2,5,1,-9,4]
Output: true
(Explanation: The array can be partitioned as [3,3], [6,5,-2,2], [5,1,-9,4])def canThreePartsEqualSum(arr):
total_sum = sum(arr)
if total_sum % 3 != 0:
return False
target_sum = total_sum // 3
running_sum, count, n = 0, 0, len(arr)
for num in arr:
running_sum += num
if running_sum == target_sum:
count += 1
running_sum = 0
if count == 2 and running_sum == 0:
return True
return False
# Test Cases
print(canThreePartsEqualSum([0,2,1,-6,6,-7,9,1,2,0,1])) # Expected: True
print(canThreePartsEqualSum([0,2,1,-6,6,7,9,-1,2,0,1])) # Expected: False
print(canThreePartsEqualSum([3,3,6,5,-2,2,5,1,-9,4])) # Expected: True
O(n)
where n
is the length of the array. We traverse the array at most once.O(1)
since we use a constant amount of extra space regardless of the input size.Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?