Require the total to divide by three, then scan for two completed target-sum parts before the final element; the remaining suffix must form the third.
Complexity
O(n) time and O(1) space.
Check whether an array can be split into three nonempty contiguous parts with equal sums.
Require the total to divide by three, then scan for two completed target-sum parts before the final element; the remaining suffix must form the third.
O(n) time and O(1) space.
package main
func canThreePartsEqualSum(arr []int) bool {
total := 0
for _, value := range arr {
total += value
}
if total%3 != 0 {
return false
}
target, current, parts := total/3, 0, 0
for index := 0; index < len(arr)-1; index++ {
current += arr[index]
if current == target {
parts++
current = 0
if parts == 2 {
return true
}
}
}
return false
}
class Solution:
def canThreePartsEqualSum(self, arr: list[int]) -> bool:
total = sum(arr)
if total % 3: return False
target, current, parts = total // 3, 0, 0
for value in arr[:-1]:
current += value
if current == target:
parts, current = parts + 1, 0
if parts == 2: return True
return False
function canThreePartsEqualSum(arr: number[]): boolean {
const total = arr.reduce((sum, value) => sum + value, 0); if (total % 3 !== 0) return false;
const target = total / 3; let parts = 0; let sum = 0;
for (let index = 0; index < arr.length - 1; index += 1) { sum += arr[index]; if (sum === target) { parts += 1; sum = 0; if (parts === 2) return true; } }
return false;
}