#3432
Count Partitions with Even Sum Difference
EasyArrayMathPrefix SumPrefix SumArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
Instead of calculating sums for each partition, we can use a prefix sum to efficiently determine the sums of the left and right subarrays. We also note that the difference is even if both sums are either even or odd.
⚙️
Algorithm
6 steps- 1Step 1: Calculate the total sum of the array.
- 2Step 2: Initialize a counter for valid partitions and a variable for the left sum.
- 3Step 3: Loop through the array from index 0 to n-2 (inclusive) to consider each partition point.
- 4Step 4: Update the left sum and calculate the right sum as total_sum - left_sum.
- 5Step 5: Check the parity of left_sum and right_sum. If they are both even or both odd, increment the counter.
- 6Step 6: Return the counter after checking all partitions.
solution.py15 lines
1# Full working Python code
2
3def count_partitions(nums):
4 total_sum = sum(nums)
5 count = 0
6 left_sum = 0
7 for i in range(len(nums) - 1):
8 left_sum += nums[i]
9 right_sum = total_sum - left_sum
10 if (left_sum % 2 == right_sum % 2):
11 count += 1
12 return count
13
14# Example usage
15print(count_partitions([10, 10, 3, 7, 6])) # Output: 4ℹ
Complexity note: This complexity is linear because we only pass through the array a couple of times: once to calculate the total sum and once to check each partition.
- 1The difference between two sums is even if both sums are either even or odd.
- 2Using prefix sums allows us to avoid recalculating sums for each partition.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.