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 Array INPUT nums array: 2 i=0 even 1 i=1 odd 6 i=2 even 4 i=3 odd Initial Sums: Even: 2+6=8 Odd: 1+4=5 Goal: Find indices where removal makes evenSum = oddSum Input: nums = [2, 1, 6, 4] ALGORITHM STEPS 1 Compute Total Sums totalEven=8, totalOdd=5 2 Track Prefix Sums prefixEven, prefixOdd 3 For Each Index i Calculate new sums after removal 4 Check Fair Condition newEven == newOdd? count++ Check Each Index: i newE newO Fair? 0 5 6 NO 1 6 6 YES 2 6 3 NO 3 7 1 NO Time: O(n) | Space: O(1) FINAL RESULT Remove index 1 (value=1): Before: 2 1 6 4 After: [2, 6, 4] 2 even 6 odd 4 even New Even Sum: 2 + 4 = 6 New Odd Sum: 6 = 6 6 == 6 : FAIR! Output: 1 Key Insight: When removing element at index i, elements AFTER i shift: odd indices become even and vice versa. Formula: newEvenSum = prefixEven + suffixOdd, newOddSum = prefixOdd + suffixEven This allows O(n) solution using prefix sums instead of O(n^2) brute force approach. TutorialsPoint - Ways to Make a Fair Array | Optimal Solution
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