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
Partition Counting Visualization1234Example: [1, 2, 3, 4] partitioned at index 1Left: 1+2 = 3Right: 3+4 = 7Difference: |3-7| = 4 (even) โœ“Algorithm Summary1. Calculate total sum of array elements2. For each partition position i (0 to n-2):โ€ข Maintain running left sumโ€ข Calculate right sum = total - left sum3. Check if |left - right| is even4. Count valid partitions5. Time: O(n), Space: O(1)Fast!
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!
Asked in
Google 25 Amazon 20 Meta 15 Microsoft 12
28.5K Views
Medium Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen