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:
- The left subarray contains elements from index
[0, i]
. - 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)
- Partition at index
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.
- Iterate over all possible indices
i
from0
ton-2
. - Compute the sum of the left and right subarrays.
- Check if the difference
(leftSum - rightSum)
is even. - Count the partitions where the condition holds true.
Code:
Complexity:
- Time Complexity: , as for each partition, we compute the left and right sums.
- Space Complexity: , 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.
- Construct a prefix sum array
prefixSum
, whereprefixSum[i]
stores the sum of elements from index0
toi
. - The left sum for partition
i
isprefixSum[i]
. - The right sum for partition
i
istotalSum - prefixSum[i]
, wheretotalSum
is the sum of the entire array. - Check if
(leftSum - rightSum)
is even.
Code:
Complexity:
- Time Complexity: , prefix sum is calculated in , and partition check is also .
- Space Complexity: , 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:
Complexity:
- Time Complexity: , single iteration over the array.
- Space Complexity: , no additional space used.