LeetCode 548: Split Array with Equal Sum

Problem Description

Explanation:

This problem asks us to split an array into three non-empty subarrays with equal sums. We need to return true if it is possible, otherwise false.

To solve this problem, we can iterate over all possible positions to split the array into three parts. For each position, we calculate the sum of each part and check if they are equal. If they are equal, we return true.

We can optimize the solution by pre-calculating the prefix sums of the array, which allows us to calculate the sum of any subarray in constant time. :

Solutions

class Solution {
    public boolean splitArray(int[] nums) {
        int n = nums.length;
        int[] prefixSum = new int[n];
        prefixSum[0] = nums[0];
        
        for (int i = 1; i < n; i++) {
            prefixSum[i] = prefixSum[i - 1] + nums[i];
        }
        
        for (int j = 3; j < n - 3; j++) {
            HashSet<Integer> set = new HashSet<>();
            for (int i = 1; i < j - 1; i++) {
                if (prefixSum[i - 1] == prefixSum[j - 1] - prefixSum[i]) {
                    set.add(prefixSum[i - 1]);
                }
            }
            for (int k = j + 2; k < n - 1; k++) {
                int sum3 = prefixSum[n - 1] - prefixSum[k];
                int sum4 = prefixSum[k] - prefixSum[j];
                if (set.contains(sum3) && sum3 == sum4) {
                    return true;
                }
            }
        }
        
        return false;
    }
}

Loading editor...