Ways to Make a Fair Array Problem
Description
LeetCode Problem 1664.
You are given an integer array nums. You can choose exactly one index (0-indexed) and remove the element. Notice that the index of the elements may change after the removal.
For example, if nums = [6,1,7,4,1]:
- Choosing to remove index
1results innums = [6,7,4,1]. - Choosing to remove index
2results innums = [6,1,4,1]. - Choosing to remove index
4results innums = [6,1,7,4].
An array is fair if the sum of the odd-indexed values equals the sum of the even-indexed values.
Return the number of indices that you could choose such that after the removal, nums is fair.
Example 1:
Input: nums = [2,1,6,4]
Output: 1
Explanation:
Remove index 0: [1,6,4] -> Even sum: 1 + 4 = 5. Odd sum: 6. Not fair.
Remove index 1: [2,6,4] -> Even sum: 2 + 4 = 6. Odd sum: 6. Fair.
Remove index 2: [2,1,4] -> Even sum: 2 + 4 = 6. Odd sum: 1. Not fair.
Remove index 3: [2,1,6] -> Even sum: 2 + 6 = 8. Odd sum: 1. Not fair.
There is 1 index that you can remove to make nums fair.
Example 2:
Input: nums = [1,1,1]
Output: 3
Explanation: You can remove any index and the remaining array is fair.
Example 3:
Input: nums = [1,2,3]
Output: 0
Explanation: You cannot make a fair array after removing any index.
Constraints:
1 <= nums.length <= 10^51 <= nums[i] <= 10^4
Solution
Approach: Enumeration + Prefix Sums
Removing index i keeps the parity of the elements on its left and flips the parity of the elements on its right.
Keep l[0], l[1]: the sums at even and odd indices to the left of i, and r[0], r[1]: the same sums to the right of i. Start with l = [0, 0] and r = the even and odd sums of the whole array.
Scan from left to right. At index i with value x, first subtract x from r[i % 2], so r covers only the elements after i. After deleting i, the even sum is l[0] + r[1] and the odd sum is l[1] + r[0]; if they are equal, count it. Then add x to l[i % 2].
Complexity: O(n) time and O(1) space, where n is the length of nums.
class Solution:
def waysToMakeFair(self, nums: List[int]) -> int:
s = sum(nums)
r0 = sum(nums[::2])
r = [r0, s - r0]
l = [0, 0]
ans = 0
for i, x in enumerate(nums):
r[i % 2] -= x
if l[0] + r[1] == l[1] + r[0]:
ans += 1
l[i % 2] += x
return ans