KatInterview

823. Split Array With Same Average

HardSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem asks if we can partition an array nums into two non-empty subarrays, A and B, such that their averages are equal.

Solution

Split Array With Same Average in Python

class Solution:
    def splitArraySameAverage(self, nums: List[int]) -> bool:
        n = len(nums)
        if n == 1:
            return False
        
        total_sum = sum(nums)
        
        # Helper function to generate sums for each subset size
        def get_sums_by_len(arr):
            m = len(arr)
            sums = [set() for _ in range(m + 1)]
            sums[0].add(0)
            
            for num in arr:
                for k in range(m, 0, -1):
                    for s in sums[k-1]:
                        sums[k].add(s + num)
            return sums

        m = n // 2
        left_half = nums[:m]
        right_half = nums[m:]

        left_sums = get_sums_by_len(left_half)
        right_sums = get_sums_by_len(right_half)

        # We only need to check for subset lengths up to n/2.
        # If a solution with length k > n/2 exists, its complement has length n-k < n/2
        # and will be found by this loop.
        for k in range(1, n // 2 + 1):
            # Check if target sum is an integer
            if (total_sum * k) % n == 0:
                target_sum = (total_sum * k) // n
                
                # Try to form target_sum with k elements
                for k1 in range(k + 1):
                    k2 = k - k1
                    # Check if k1 and k2 are valid lengths
                    if k1 <= len(left_half) and k2 <= len(right_half):
                        for s1 in left_sums[k1]:
                            s2_needed = target_sum - s1
                            if s2_needed in right_sums[k2]:
                                return True
        
        return False

Split Array With Same Average in Java

class Solution {
    public boolean splitArraySameAverage(int[] nums) {
        int n = nums.length;
        if (n == 1) {
            return false;
        }
        int totalSum = 0;
        for (int x : nums) {
            totalSum += x;
        }

        int m = n / 2;
        List<Set<Integer>> leftSums = getSumsByLen(nums, 0, m);
        List<Set<Integer>> rightSums = getSumsByLen(nums, m, n);

        // We only need to check for subset lengths up to n/2.
        // If a solution with length k > n/2 exists, its complement has length n-k < n/2
        // and will be found by this loop.
        for (int k = 1; k <= n / 2; k++) {
            // Check if target sum is an integer
            if ((totalSum * k) % n == 0) {
                int targetSum = (totalSum * k) / n;
                // Try to form target_sum with k elements
                for (int k1 = 0; k1 <= m; k1++) {
                    int k2 = k - k1;
                    // Check if k2 is a valid length for a subset of right_half
                    if (k2 >= 0 && k2 <= n - m) {
                        for (int s1 : leftSums.get(k1)) {
                            int s2Needed = targetSum - s1;
                            if (rightSums.get(k2).contains(s2Needed)) {
                                return true;
                            }
                        }
                    }
                }
            }
        }
        
        // Special case for k > n/2. The logic for k <= n/2 should cover this
        // because if a partition (A, B) exists with len(A) > n/2, then len(B) < n/2,
        // and we would find B. However, for total correctness, especially if n is odd,
        // and len(A) = len(B) is not possible, we should check all k from 1 to n-1
        // or prove n/2 is sufficient. The proof holds, so this is correct. 
        // But if we want to be fully explicit about the logic without relying on the proof of symmetry,
        // a check for k=n/2 in right sums might be needed.
        // Let's re-verify the logic. If A is of size k, its sum must be S*k/n. If B is complement, size n-k, sum S-S*k/n = S*(n-k)/n.
        // average is (S*k/n)/k = S/n, and (S*(n-k)/n)/(n-k) = S/n. The condition is symmetric.
        // So k <= n/2 is sufficient.

        return false;
    }

    // Helper function to generate sums for each subset size for a subarray
    private List<Set<Integer>> getSumsByLen(int[] arr, int start, int end) {
        int len = end - start;
        List<Set<Integer>> sums = new ArrayList<>();
        for (int i = 0; i <= len; i++) {
            sums.add(new HashSet<>());
        }
        sums.get(0).add(0);

        for (int i = start; i < end; i++) {
            int num = arr[i];
            for (int k = len; k >= 1; k--) {
                for (int s : sums.get(k - 1)) {
                    sums.get(k).add(s + num);
                }
            }
        }
        return sums;
    }
}

Split Array With Same Average in C++

class Solution {
public:
    bool splitArraySameAverage(vector<int>& nums) {
        int n = nums.size();
        int total_sum = 0;
        for (int x : nums) {
            total_sum += x;
        }

        // Helper function to generate sums for each subset size
        auto get_sums_by_len = [](const vector<int>& arr) {
            int m = arr.size();
            vector<unordered_set<int>> sums(m + 1);
            sums[0].insert(0);
            for (int num : arr) {
                for (int k = m; k >= 1; --k) {
                    for (int s : sums[k - 1]) {
                        sums[k].insert(s + num);
                    }
                }
            }
            return sums;
        };

        int m = n / 2;
        vector<int> left_half(nums.begin(), nums.begin() + m);
        vector<int> right_half(nums.begin() + m, nums.end());

        vector<unordered_set<int>> left_sums = get_sums_by_len(left_half);
        vector<unordered_set<int>> right_sums = get_sums_by_len(right_half);

        // We only need to check for subset lengths up to n/2.
        // If a solution with length k > n/2 exists, its complement has length n-k < n/2
        // and will be found by this loop.
        for (int k = 1; k <= n / 2; ++k) {
            // Check if target sum is an integer
            if ((total_sum * k) % n == 0) {
                int target_sum = (total_sum * k) / n;
                // Try to form target_sum with k elements
                for (int k1 = 0; k1 <= m; ++k1) {
                    int k2 = k - k1;
                    // Check if k2 is a valid length for a subset of right_half
                    if (k2 >= 0 && k2 <= n - m) {
                        for (int s1 : left_sums[k1]) {
                            int s2_needed = target_sum - s1;
                            if (right_sums[k2].count(s2_needed)) {
                                return true;
                            }
                        }
                    }
                }
            }
        }

        return false;
    }
};

Split Array With Same Average in TypeScript

function splitArraySameAverage(nums: number[]): boolean {
    const n = nums.length;
    if (n === 1) {
        return false;
    }

    const totalSum = nums.reduce((acc, val) => acc + val, 0);

    // Helper function to generate sums for each subset size
    const getSumsByLen = (arr: number[]): Set<number>[] => {
        const m = arr.length;
        const sums: Set<number>[] = Array.from({ length: m + 1 }, () => new Set());
        sums[0].add(0);

        for (const num of arr) {
            for (let k = m; k >= 1; k--) {
                for (const s of sums[k - 1]) {
                    sums[k].add(s + num);
                }
            }
        }
        return sums;
    };

    const m = Math.floor(n / 2);
    const leftHalf = nums.slice(0, m);
    const rightHalf = nums.slice(m);

    const leftSums = getSumsByLen(leftHalf);
    const rightSums = getSumsByLen(rightHalf);

    // We only need to check for subset lengths up to n/2.
    // If a solution with length k > n/2 exists, its complement has length n-k < n/2
    // and will be found by this loop.
    for (let k = 1; k <= Math.floor(n / 2); k++) {
        // Check if target sum is an integer
        if ((totalSum * k) % n === 0) {
            const targetSum = (totalSum * k) / n;

            // Try to form targetSum with k elements
            for (let k1 = 0; k1 <= m; k1++) {
                const k2 = k - k1;
                // Check if k2 is a valid length for a subset of right_half
                if (k2 >= 0 && k2 <= n - m) {
                    for (const s1 of leftSums[k1]) {
                        const s2Needed = targetSum - s1;
                        if (rightSums[k2].has(s2Needed)) {
                            return true;
                        }
                    }
                }
            }
        }
    }

    return false;
}

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.