Ways to Make a Fair Array - Problem

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 1 results in nums = [6,7,4,1].
  • Choosing to remove index 2 results in nums = [6,1,4,1].
  • Choosing to remove index 4 results in nums = [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.

Input & Output

Example 1 — Basic Case
$ Input: nums = [2,1,6,4]
Output: 1
💡 Note: Only removing index 1 makes the array fair. After removing nums[1]=1, we get [2,6,4]. Even indices sum: 2+4=6, Odd indices sum: 6. Since 6=6, it's fair.
Example 2 — Multiple Solutions
$ Input: nums = [1,1,1]
Output: 3
💡 Note: Removing any element results in [1,1]. Even sum = 1, Odd sum = 1. All three removals work.
Example 3 — No Solution
$ Input: nums = [1,2,3]
Output: 0
💡 Note: No removal makes the array fair. Remove 1→[2,3] (2≠3), Remove 2→[1,3] (1≠3), Remove 3→[1,2] (1≠2).

Constraints

  • 1 ≤ nums.length ≤ 105
  • 1 ≤ nums[i] ≤ 104

Visualization

Tap to expand
Ways to Make a Fair ArrayInput: [2, 1, 6, 4]2164idx 0idx 1idx 2idx 3Current sums:Even positions (0,2): 2 + 6 = 8Odd positions (1,3): 1 + 4 = 5Try removing index 1:2X64After removal [2,6,4]:Even positions: 2 + 4 = 6Odd positions: 66 = 6 ✓ FAIR!Answer: 1 (only index 1 removal works)
Understanding the Visualization
1
Input Array
Array with elements at even and odd positions
2
Try Removal
Remove element and check if remaining array is fair
3
Count Solutions
Count how many removals result in fair arrays
Key Takeaway
🎯 Key Insight: When removing an element, all subsequent elements shift positions, changing the even/odd balance
Asked in
Google 12 Facebook 8 Amazon 6
32.4K Views
Medium Frequency
~25 min Avg. Time
856 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