Count Partitions with Even Sum Difference - Problem

You are given an integer array nums of length n. A partition is defined as an index i where 0 <= i < n - 1, splitting the array into two non-empty subarrays such that:

  • Left subarray contains indices [0, i]
  • Right subarray contains indices [i + 1, n - 1]

Return the number of partitions where the difference between the sum of the left and right subarrays is even.

Input & Output

Example 1 — Basic Case
$ Input: nums = [1,2,3,4]
Output: 3
💡 Note: Partition at i=0: left=[1], right=[2,3,4], difference=|1-9|=8 (even). Partition at i=1: left=[1,2], right=[3,4], difference=|3-7|=4 (even). Partition at i=2: left=[1,2,3], right=[4], difference=|6-4|=2 (even). All 3 partitions have even differences, so count = 3.
Example 2 — Different Result
$ Input: nums = [1,2,3]
Output: 2
💡 Note: Partition at i=0: left=[1], right=[2,3], difference=|1-5|=4 (even). Partition at i=1: left=[1,2], right=[3], difference=|3-3|=0 (even). Both partitions have even differences, so count = 2.
Example 3 — All Odd Differences
$ Input: nums = [1,2]
Output: 0
💡 Note: Only one partition at i=0: left=[1], right=[2], difference=|1-2|=1 (odd). No partitions with even difference, so count = 0.

Constraints

  • 2 ≤ nums.length ≤ 105
  • -106 ≤ nums[i] ≤ 106

Visualization

Tap to expand
Count Partitions with Even Sum Difference INPUT Array: nums 1 i=0 2 i=1 3 i=2 4 i=3 Possible Partitions: [1] | [2,3,4] at i=0 [1,2] | [3,4] at i=1 [1,2,3] | [4] at i=2 Input Values: nums = [1, 2, 3, 4] n = 4 ALGORITHM STEPS 1 Calculate Total Sum total = 1+2+3+4 = 10 2 For each partition i: leftSum, rightSum = total-left 3 Check difference parity (left - right) % 2 == 0? 4 Count valid partitions Increment count if even Partition Analysis i Left Right Diff Even? 0 1 9 -8 OK 1 3 7 -4 OK 2 6 4 2 NO FINAL RESULT Valid Partitions Found: Partition at i=0 [1] | [2,3,4] --> diff = -8 Partition at i=1 [1,2] | [3,4] --> diff = -4 Partition at i=2 (Invalid) [1,2,3] | [4] --> diff = 2 (odd) OUTPUT 2 Key Insight: The difference (left - right) is even when both sums have the same parity (both even or both odd). Since left + right = total, if total is even, both parts must have same parity. O(n) time, O(1) space. TutorialsPoint - Count Partitions with Even Sum Difference | Optimal Solution
Asked in
Google 25 Microsoft 18 Amazon 15 Meta 12
33.8K Views
Medium Frequency
~15 min Avg. Time
890 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