Leetcode: Split Array with Equal Sum

Split Array with Equal Sum



Similar Problems:


Given an array with n integers, you need to find if there are triplets (i, j, k) which satisfies following conditions:

0 < i, i + 1 < j, j + 1 < k < n – 1
Sum of subarrays (0, i – 1), (i + 1, j – 1), (j + 1, k – 1) and (k + 1, n – 1) should be equal.
where we define that subarray (L, R) represents a slice of the original array starting from the element indexed L to the element indexed R.
Example:

Input: [1,2,1,2,1,2,1]
Output: True
Explanation:
i = 1, j = 3, k = 5. 
sum(0, i - 1) = sum(0, 0) = 1
sum(i + 1, j - 1) = sum(2, 2) = 1
sum(j + 1, k - 1) = sum(4, 4) = 1
sum(k + 1, n - 1) = sum(6, 6) = 1

Note:

  1. 1 <= n <= 2000.
  2. Elements in the given array will be in range [-1,000,000, 1,000,000].

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/split-array-with-equal-sum
// Basic Ideas:
// Split the list with 4 groups of equal values
//
// Complexity: Time O(n*n), Space O(n)
func splitArray(nums []int) bool {
    if len(nums) < 7 { return false }

    sums := make([]int, len(nums))
    for i, _ := range nums {
        if i == 0 {
            sums[i] = nums[i]
        } else {
            sums[i] = nums[i]+sums[i-1]
        }
    }

    for j:= 3; j<len(nums)-3; j++ {
        m := map[int]bool{}
        for i:=1; i<j-1; i++ {
            if sums[i]-nums[i] == sums[j]-sums[i]-nums[j] {
                m[sums[i]-nums[i]] = true
            }
        }
        for k:=j+2; k<len(nums)-1; k++ {
            if sums[len(nums)-1]-sums[k] == sums[k]-sums[j]-nums[k] {
                if m[sums[len(nums)-1]-sums[k]] == true {
                    return true
                }
            }
        }
    }
    return false
}
linkedin
github
slack

Share It, If You Like It.

Leave a Reply

Your email address will not be published.