Count Partitions with Even Sum Difference - Problem
You are given an integer array nums of length n. Your task is to find all valid ways to split this array into two non-empty parts and count how many of these splits result in an even difference between the sums of the two parts.
A partition is defined by choosing an index i where 0 โค i < n - 1, which splits the array into:
- Left subarray: elements from index
[0, i] - Right subarray: elements from index
[i + 1, n - 1]
For each partition, calculate the difference as: |leftSum - rightSum|
Goal: Return the number of partitions where this difference is even.
Example: For nums = [1, 2, 3, 4], we can partition at indices 0, 1, or 2. Check each partition to see if the sum difference is even!
Input & Output
example_1.py โ Basic Case
$
Input:
[1, 2, 3, 4]
โบ
Output:
2
๐ก Note:
Partitions: At i=0: left=[1], right=[2,3,4] โ |1-9|=8 (even) โ. At i=1: left=[1,2], right=[3,4] โ |3-7|=4 (even) โ. At i=2: left=[1,2,3], right=[4] โ |6-4|=2 (even) โ. Total: 3 partitions with even differences.
example_2.py โ All Odd Differences
$
Input:
[1, 3, 5]
โบ
Output:
0
๐ก Note:
Partitions: At i=0: left=[1], right=[3,5] โ |1-8|=7 (odd). At i=1: left=[1,3], right=[5] โ |4-5|=1 (odd). No partitions have even differences.
example_3.py โ Minimum Array
$
Input:
[2, 4]
โบ
Output:
1
๐ก Note:
Only one possible partition at i=0: left=[2], right=[4] โ |2-4|=2 (even) โ. Total: 1 partition with even difference.
Constraints
-
2 โค
nums.lengthโค 105 -
-106 โค
nums[i]โค 106 - Important: Array will always have at least 2 elements to ensure valid partitions exist
Visualization
Tap to expand
Understanding the Visualization
1
Setup
We have an array that needs to be split into two non-empty parts
2
Try Each Cut
For each possible partition position, calculate left and right sums
3
Check Difference
Determine if |leftSum - rightSum| is even
4
Count Valid Partitions
Increment counter for each partition with even difference
Key Takeaway
๐ฏ Key Insight: Using prefix sums transforms an O(nยฒ) problem into O(n) by avoiding redundant sum calculations!
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code