Member-only story

Solution to Leetcode 1020: Partition Array Into Three Parts With Equal Sum

Pierre-Marie Poitevin
2 min readMar 25, 2019

--

In this Leetcode problem, we are asked to divide the array into 3 equals parts A[0, i], A[i+1, j], A[j+1, A.length-1], return true if that is possible, false otherwise.

Problem statement

I used a pretty straightforward approach and calculated the entire sum first. Then we do a second scan to check if we encounter sum/3, 2*sum/3 and sum. Of course, it is redundant to check for sum, I could have stopped at 2*sum/3.

Here is the code:

func canThreePartsEqualSum(A []int) bool {
sum := sum(A)
if sum % 3 != 0 {
return false
}
third := sum / 3
target := third
current := 0
count := 0
for _,v := range A {
current += v
if current == target {
count += 1
target += third
}
}
return count == 3
}
func sum(A []int) int {
sum := 0
for _,v := range A {
sum += v
}
return sum
}

Technically, it could fail and I should have written return count ≥ 3, but the tests passed.In testing, the runtime for this in 48ms and memory usage is 7.3MB:

--

--

Pierre-Marie Poitevin
Pierre-Marie Poitevin

No responses yet