Problem Description
Given an integer array, remove exactly one index so that after removal the sum of the even-indexed elements equals the sum of the odd-indexed elements (i.e. the array becomes "fair"). Return the count of all such indices where removal makes the array fair.
Key Insights
- Removal of an element shifts the indices of all subsequent elements, affecting their parity (even/odd positions).
- Precompute the total sums of even-indexed and odd-indexed elements.
- Use prefix sums (left sums) to maintain cumulative sums and derive right sums by subtracting from the totals.
- Depending on whether the removed index is even or odd, the right portion of the array will have its elements’ parity flipped.
- A single pass O(n) solution is possible by updating prefix sums on the fly.
Space and Time Complexity
Time Complexity: O(n)
Space Complexity: O(1) (only a few extra integer variables are used)
Solution
The solution iterates over each index and simulates the removal of the element at that index, then calculates the resulting sums for even and odd positions:
- Compute the total sum of elements at even indices (total_even) and at odd indices (total_odd).
- Initialize prefix sums (left_even and left_odd) for elements before the current index.
- For each index i:
- If i is even:
- The new even sum becomes: left_even + (total_odd - left_odd)
- The new odd sum becomes: left_odd + (total_even - left_even - nums[i])
- If i is odd:
- The new even sum becomes: left_even + (total_odd - left_odd - nums[i])
- The new odd sum becomes: left_odd + (total_even - left_even)
- If i is even:
- If the new even sum equals the new odd sum, the removal of index i yields a fair array.
- Update the left prefix sums with nums[i] by checking its parity. This approach only requires one pass over the array, ensuring an efficient solution.