Skip to main content

Count Partitions with Even Sum Difference | Leetcode | Explanation and Solution

Partitioning arrays is a common problem in algorithm challenges, and counting partitions with an even sum difference is one of the interesting variations. 

Problem Statement

You are given an integer array nums of length n. A partition is defined as an index i where:

  1. The left subarray contains elements from index [0, i].
  2. The right subarray contains elements from index [i + 1, n - 1].

You need to find the number of such partitions where the difference between the sum of the left and right subarrays is even.

Example 1:

  • Input: nums = [10,10,3,7,6]
  • Output: 4
  • Explanation:
    • Partition at index 0: Left = [10], Right = [10, 3, 7, 6], Difference = -16 (even)
    • Partition at index 1: Left = [10, 10], Right = [3, 7, 6], Difference = 4 (even)
    • Partition at index 2: Left = [10, 10, 3], Right = [7, 6], Difference = 10 (even)
    • Partition at index 3: Left = [10, 10, 3, 7], Right = [6], Difference = 24 (even)

Example 2:

  • Input: nums = [1,2,2]
  • Output: 0
  • Explanation: No partition results in an even difference.

Example 3:

  • Input: nums = [2,4,6,8]
  • Output: 3

Approach 1: Brute Force

In this approach, we manually calculate the left and right subarray sums for each possible partition.

  1. Iterate over all possible indices i from 0 to n-2.
  2. Compute the sum of the left and right subarrays.
  3. Check if the difference (leftSum - rightSum) is even.
  4. Count the partitions where the condition holds true.

Code:

class Solution {
public:
    int countPartitions(vector<int>& nums) {
        int n = nums.size();
        int count = 0;

        for (int i = 0; i < n - 1; ++i) {
            int leftSum = 0, rightSum = 0;
            for (int j = 0; j <= i; ++j) {
                leftSum += nums[j];
            }
            for (int j = i + 1; j < n; ++j) {
                rightSum += nums[j];
            }
            if ((leftSum - rightSum) % 2 == 0) {
                ++count;
            }
        }

        return count;
    }
};

Complexity:

  • Time Complexity: O(n2)O(n^2), as for each partition, we compute the left and right sums.
  • Space Complexity: O(1)O(1), no additional space is used.

This approach works but is inefficient for large arrays.


Approach 2: Using Prefix Sum

To optimize the process, we can use a prefix sum array to calculate the sum of any subarray in constant time.

  1. Construct a prefix sum array prefixSum, where prefixSum[i] stores the sum of elements from index 0 to i.
  2. The left sum for partition i is prefixSum[i].
  3. The right sum for partition i is totalSum - prefixSum[i], where totalSum is the sum of the entire array.
  4. Check if (leftSum - rightSum) is even.

Code:

class Solution {
public:
    int countPartitions(vector<int>& nums) {
        int n = nums.size();
        vector<int> prefixSum(n, 0);
        prefixSum[0] = nums[0];

        for (int i = 1; i < n; ++i) {
            prefixSum[i] = prefixSum[i - 1] + nums[i];
        }

        int totalSum = prefixSum[n - 1];
        int count = 0;

        for (int i = 0; i < n - 1; ++i) {
            int leftSum = prefixSum[i];
            int rightSum = totalSum - leftSum;
            if ((leftSum - rightSum) % 2 == 0) {
                ++count;
            }
        }

        return count;
    }
};

Complexity:

  • Time Complexity: O(n)O(n), prefix sum is calculated in O(n)O(n), and partition check is also O(n)O(n).
  • Space Complexity: O(n)O(n), for the prefix sum array.

Approach 3: Optimized Space

Instead of using a prefix sum array, we can keep track of the left sum and right sum using simple variables. This reduces the space complexity.

Code:

class Solution {
public:
    int countPartitions(vector<int>& nums) {
        int n = nums.size();
        int totalSum = 0;
        for (int num : nums) {
            totalSum += num;
        }

        int leftSum = 0, count = 0;

        for (int i = 0; i < n - 1; ++i) {
            leftSum += nums[i];
            int rightSum = totalSum - leftSum;
            if ((leftSum - rightSum) % 2 == 0) {
                ++count;
            }
        }

        return count;
    }
};

Complexity:

  • Time Complexity: O(n)O(n), single iteration over the array.
  • Space Complexity: O(1)O(1), no additional space used.

Popular posts from this blog

Maximum Difference Between Even and Odd Frequency | LeetCode

We are given a string consisting of lowercase English letters. Our task is to find the maximum difference between the frequency of two characters in the string such that: One of the characters has an even frequency . The other character has an odd frequency . The difference is calculated as:  odd_frequency - even_frequency We need to return the maximum possible difference between the odd and even frequencies. Example Walkthrough Let's take a couple of examples to better understand the problem: Example 1: Input:  s = "aaaaabbc" Frequencies: 'a' → 5 (odd) 'b' → 2 (even) 'c' → 1 (odd) Here, the maximum odd frequency is 5 (for 'a') and the maximum even frequency is 2 (for 'b'). Therefore, the result is: maxOdd - maxEven = 5 - 2 = 3 Example 2: Input:  s = "abcabcab" Frequencies: 'a' → 3 (odd) 'b' → 2 (even) 'c' → 2 (even) The maximum odd frequency is 3 (for 'a') and the maximum even fr...

Top 10 Beginner-Friendly LeetCode Questions and Their Solutions

If you're new to solving coding problems on LeetCode, it can feel overwhelming. Where do you start? Which problems are suitable for beginners? Don’t worry! In this blog post, I’ll guide you through   10 beginner-friendly LeetCode questions   that are perfect for getting started on your coding journey. These problems will help you build confidence, improve your problem-solving skills, and lay a solid foundation in data structures and algorithms. Why Start with Beginner-Friendly Problems? Before diving into advanced topics like dynamic programming or graph theory, it’s essential to: Build a strong foundation in basic programming concepts. Understand how to approach a coding problem methodically. Gain familiarity with LeetCode’s platform and its problem structure. The following problems are simple yet impactful, designed to introduce you to common techniques like loops, arrays, strings, and basic math operations. 10 Beginner-Friendly LeetCode Problems 1.  Two Sum (Easy) Prob...

Count Mentions Per User | Leetcode | Problem Explanation and Solution Approaches

Tracking mentions in messages is a common task in communication-based applications. This blog post breaks down a complex problem, "Count Mentions Per User," and walks through how to solve it efficiently with a clear understanding of all rules and constraints. Problem Statement You are given: An integer numberOfUsers representing the total number of users. An array events where each element is of size n x 3 and describes either a "MESSAGE" or an "OFFLINE" event. Each event can be one of the following types: MESSAGE Event : ["MESSAGE", "timestamp", "mentions_string"] Indicates that users are mentioned in a message at a specific timestamp. The mentions_string can contain: id<number> : Mentions a specific user (e.g., id0 , id1 ). ALL : Mentions all users (online or offline). HERE : Mentions only users who are online at the time. OFFLINE Event : ["OFFLINE", "timestamp", "id<number>"] In...