Leetcode: Partition Array Into Three Parts With Equal Sum

Identity number which appears exactly once.



Similar Problems:


Given an array A of integers, return true if and only 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 (A[0] + A[1] + … + A[i] = A[i+1] + A[i+2] + ... + A[j-1] = A[j] + A[j-1] + … + A[A.length – 1])

Example 1:

Input: [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: [0,2,1,-6,6,7,9,-1,2,0,1]
Output: false

Example 3:

Input: [3,3,6,5,-2,2,5,1,-9,4]
Output: true
Explanation: 3 + 3 = 6 = 5 - 2 + 2 + 5 + 1 - 9 + 4

Note:

  1. 3 <= A.length <= 50000
  2. -10000 <= A[i] <= 10000

Github: code.dennyzhang.com

Credits To: leetcode.com

Leave me comments, if you have better ways to solve.


  • Solution:
// Blog link: https://code.dennyzhang.com/partition-array-into-three-parts-with-equal-sum
// Basic Ideas: Check the first and the third part
// Complexity: Time O(n), Space O(1)
func canThreePartsEqualSum(A []int) bool {
    sum := 0
    for _, v := range A { sum += v }
    if sum%3 != 0 || len(A) < 3 { return false }
    target := int(sum/3)

    i, j := 0, len(A)-1
    curSum := A[0]

    i++
    for curSum != target && i+1<=j {
        curSum += A[i]
        i++
    }
    if curSum != target { return false }

    curSum = A[j]
    j--
    for curSum != target && i+1<=j {
        curSum += A[j]
        j--
    }
    if curSum != target { return false }

    return true
}
linkedin
github
slack

Share It, If You Like It.

Leave a Reply

Your email address will not be published.