Problem Description
Given an integer array nums of length n, a partition is defined as an index i (0 <= i < n - 1) that splits the array into two non-empty subarrays, with the left subarray consisting of nums[0..i] and the right subarray consisting of nums[i+1..n-1]. The task is to return the number of partitions such that the difference between the sum of the left subarray and the sum of the right subarray is even.
Key Insights
- The difference between the sum of the left and right subarrays can be written as 2 * (sum of left) - (total sum).
- Notice that 2 * (sum of left) is always even.
- Thus, the parity of the difference depends solely on the parity of the total sum.
- If the total sum is even, then for any partition the difference will be even.
- If the total sum is odd, the difference will always be odd for every partition.
- Therefore, if the total sum is even the answer is the total number of valid partitions (which is n - 1), otherwise the answer is 0.
Space and Time Complexity
Time Complexity: O(n) – to compute the total sum of the array. Space Complexity: O(1) – only constant extra space is used.
Solution
The solution first calculates the total sum of the array. Because the partitioning difference is formulated as 2 * (prefix sum) - (total sum) and 2 * (prefix sum) is always even, the difference is even if and only if the total sum is even. If the sum is even, every possible partition (there are n - 1 partitions) is valid. Otherwise, if the total sum is odd, no partition yields an even difference.