Ways to Make a Fair Array
Ways to Make a Fair Array is a medium arrays & hashing problem solved with the prefix sum strategy pattern.
The best approach, optimal (running left and right sums), runs in O(n) time and O(1) space.
Below are 3 approaches in Java, Python, C++ and JavaScript, from brute force (rebuild every array) up.
Problem
You are given an integer array nums. You will remove exactly one element from it. The elements after the removed one slide one place to the left to close the gap, so their indexes drop by one.
Call an array fair when the sum of its elements at even indexes equals the sum of its elements at odd indexes.
Return the number of indexes i such that removing nums[i] leaves a fair array.
Examples
Example 1
- Input
nums = [2, 5, 3, 4, 1]- Output
1- Why
- Removing index 2 (the 3) leaves [2, 5, 4, 1]. The even indexes hold 2 and 4, which add up to 6, and the odd indexes hold 5 and 1, also 6. No other removal balances the two sums.
Example 2
- Input
nums = [5, 5, 5]- Output
3- Why
- Whichever 5 you remove, the array becomes [5, 5], with 5 at index 0 and 5 at index 1. All three removals work.
Example 3
- Input
nums = [1, 2, 3]- Output
0- Why
- Removing index 0 gives [2, 3], index 1 gives [1, 3] and index 2 gives [1, 2]. None of them has equal sums.
Constraints
1 <= nums.length <= 10^51 <= nums[i] <= 10^4
Solve it here
Write your solution in Java, Python, C++ or JavaScript and run it against the examples, right in the page. Submit runs the hidden tests too and, with a free account, records the solve in your revision log.
Your own testcases: Run checks these, and the expected output comes from our reference solution.
My submissions
Nothing yet. Every Run and Submit you make while signed in shows up here.
| When | Result | Tests | Runtime | Your time | Type |
|---|
Run checks the testcases above (3 examples, or your own). Submit also runs 17 hidden tests and saves the solve to your log. Signed in, every Run and Submit is saved under My submissions; your draft stays in this browser.
Animated walkthrough
A narrated, step-by-step animation that builds the solution from the idea up. Press play, or step through it at your own pace.
Concepts first, then the problem and every approach, step by step.
Space to play or pause · ← → to jump a step · click or drag the bar to seek
Solutions
Try it yourself first. Then compare: each approach lists its idea, the steps, its time and space, and the code in Java, Python, C++ and JavaScript.
| Approach | Time | Space |
|---|---|---|
| Brute force (rebuild every array) | O(n²) | O(1) |
| Prefix sums by parity | O(n) | O(n) |
| Optimal (running left and right sums) | O(n) | O(1) |
1Brute force (rebuild every array)
O(n²)n removals, and each one walks over the other n - 1 elements.O(1)Only the two sums and counters; the new array is never stored.Try every index as the one to remove. Walk over the rest of the array, giving each remaining element its new index: the same index for elements before the removed one, one less for elements after it. Add each element to the even or odd sum by that new index, and count the removals where the two sums match.
- Set count = 0.
- For each i from 0 to n - 1: set even = odd = 0 and idx = 0.
- For each j != i: add nums[j] to even if idx is even, else to odd, then add one to idx.
- If even == odd, add one to count.
- Return count.
class Solution {
public int waysToMakeFair(int[] nums) {
int n = nums.length, count = 0;
for (int i = 0; i < n; i++) {
int even = 0, odd = 0, idx = 0;
for (int j = 0; j < n; j++) {
if (j == i) continue;
if (idx % 2 == 0) even += nums[j];
else odd += nums[j];
idx++;
}
if (even == odd) count++;
}
return count;
}
}class Solution:
def waysToMakeFair(self, nums: List[int]) -> int:
n = len(nums)
count = 0
for i in range(n):
even = odd = idx = 0
for j in range(n):
if j == i:
continue
if idx % 2 == 0:
even += nums[j]
else:
odd += nums[j]
idx += 1
if even == odd:
count += 1
return countclass Solution {
public:
int waysToMakeFair(vector<int>& nums) {
int n = nums.size(), count = 0;
for (int i = 0; i < n; i++) {
int even = 0, odd = 0, idx = 0;
for (int j = 0; j < n; j++) {
if (j == i) continue;
if (idx % 2 == 0) even += nums[j];
else odd += nums[j];
idx++;
}
if (even == odd) count++;
}
return count;
}
};function waysToMakeFair(nums) {
const n = nums.length;
let count = 0;
for (let i = 0; i < n; i++) {
let even = 0, odd = 0, idx = 0;
for (let j = 0; j < n; j++) {
if (j === i) continue;
if (idx % 2 === 0) even += nums[j];
else odd += nums[j];
idx++;
}
if (even === odd) count++;
}
return count;
}2Prefix sums by parity
O(n)One pass builds the prefix arrays and one pass checks every removal in O(1).O(n)Two prefix arrays of length n + 1.Build two prefix arrays: evenPre[i] is the sum of nums[k] for even k < i, and oddPre[i] the same for odd k. Removing index i keeps the parity of everything before it and flips everything after it. So the new even sum is evenPre[i] plus the odd sum after i, which is oddPre[n] - oddPre[i + 1], and the new odd sum is oddPre[i] plus evenPre[n] - evenPre[i + 1]. Each removal is now checked in constant time.
- Fill evenPre and oddPre of length n + 1: copy the previous values, then add nums[i] to the one matching the parity of i.
- For each i: newEven = evenPre[i] + (oddPre[n] - oddPre[i + 1]) and newOdd = oddPre[i] + (evenPre[n] - evenPre[i + 1]).
- Count the indexes where newEven == newOdd.
class Solution {
public int waysToMakeFair(int[] nums) {
int n = nums.length;
int[] evenPre = new int[n + 1], oddPre = new int[n + 1];
for (int i = 0; i < n; i++) {
evenPre[i + 1] = evenPre[i] + (i % 2 == 0 ? nums[i] : 0);
oddPre[i + 1] = oddPre[i] + (i % 2 == 1 ? nums[i] : 0);
}
int count = 0;
for (int i = 0; i < n; i++) {
int newEven = evenPre[i] + (oddPre[n] - oddPre[i + 1]);
int newOdd = oddPre[i] + (evenPre[n] - evenPre[i + 1]);
if (newEven == newOdd) count++;
}
return count;
}
}class Solution:
def waysToMakeFair(self, nums: List[int]) -> int:
n = len(nums)
even_pre = [0] * (n + 1)
odd_pre = [0] * (n + 1)
for i in range(n):
even_pre[i + 1] = even_pre[i] + (nums[i] if i % 2 == 0 else 0)
odd_pre[i + 1] = odd_pre[i] + (nums[i] if i % 2 == 1 else 0)
count = 0
for i in range(n):
new_even = even_pre[i] + (odd_pre[n] - odd_pre[i + 1])
new_odd = odd_pre[i] + (even_pre[n] - even_pre[i + 1])
if new_even == new_odd:
count += 1
return countclass Solution {
public:
int waysToMakeFair(vector<int>& nums) {
int n = nums.size();
vector<int> evenPre(n + 1, 0), oddPre(n + 1, 0);
for (int i = 0; i < n; i++) {
evenPre[i + 1] = evenPre[i] + (i % 2 == 0 ? nums[i] : 0);
oddPre[i + 1] = oddPre[i] + (i % 2 == 1 ? nums[i] : 0);
}
int count = 0;
for (int i = 0; i < n; i++) {
int newEven = evenPre[i] + (oddPre[n] - oddPre[i + 1]);
int newOdd = oddPre[i] + (evenPre[n] - evenPre[i + 1]);
if (newEven == newOdd) count++;
}
return count;
}
};function waysToMakeFair(nums) {
const n = nums.length;
const evenPre = new Array(n + 1).fill(0), oddPre = new Array(n + 1).fill(0);
for (let i = 0; i < n; i++) {
evenPre[i + 1] = evenPre[i] + (i % 2 === 0 ? nums[i] : 0);
oddPre[i + 1] = oddPre[i] + (i % 2 === 1 ? nums[i] : 0);
}
let count = 0;
for (let i = 0; i < n; i++) {
const newEven = evenPre[i] + (oddPre[n] - oddPre[i + 1]);
const newOdd = oddPre[i] + (evenPre[n] - evenPre[i + 1]);
if (newEven === newOdd) count++;
}
return count;
}3Optimal (running left and right sums)
O(n)One pass for the totals and one pass over the removals, each step O(1).O(1)Four running sums and a counter.The prefix arrays are only ever read at i and at n, so four running numbers are enough. Keep leftEven and leftOdd for the part before i (starting at 0), and rightEven and rightOdd for the part from i on (starting at the totals). At index i, first take nums[i] out of the right side, since it is being removed. Then the new even sum is leftEven + rightOdd and the new odd sum is leftOdd + rightEven. Before moving on, put nums[i] into the left side.
- Compute rightEven and rightOdd, the sums at even and odd indexes of the whole array. Set leftEven = leftOdd = 0.
- For each i: subtract nums[i] from rightEven if i is even, else from rightOdd.
- If leftEven + rightOdd == leftOdd + rightEven, add one to count.
- Add nums[i] to leftEven if i is even, else to leftOdd.
- Return count.
class Solution {
public int waysToMakeFair(int[] nums) {
int rightEven = 0, rightOdd = 0;
for (int i = 0; i < nums.length; i++) {
if (i % 2 == 0) rightEven += nums[i];
else rightOdd += nums[i];
}
int leftEven = 0, leftOdd = 0, count = 0;
for (int i = 0; i < nums.length; i++) {
if (i % 2 == 0) rightEven -= nums[i];
else rightOdd -= nums[i];
if (leftEven + rightOdd == leftOdd + rightEven) count++;
if (i % 2 == 0) leftEven += nums[i];
else leftOdd += nums[i];
}
return count;
}
}class Solution:
def waysToMakeFair(self, nums: List[int]) -> int:
right_even = right_odd = 0
for i, v in enumerate(nums):
if i % 2 == 0:
right_even += v
else:
right_odd += v
left_even = left_odd = count = 0
for i, v in enumerate(nums):
if i % 2 == 0:
right_even -= v
else:
right_odd -= v
if left_even + right_odd == left_odd + right_even:
count += 1
if i % 2 == 0:
left_even += v
else:
left_odd += v
return countclass Solution {
public:
int waysToMakeFair(vector<int>& nums) {
int rightEven = 0, rightOdd = 0;
for (int i = 0; i < (int) nums.size(); i++) {
if (i % 2 == 0) rightEven += nums[i];
else rightOdd += nums[i];
}
int leftEven = 0, leftOdd = 0, count = 0;
for (int i = 0; i < (int) nums.size(); i++) {
if (i % 2 == 0) rightEven -= nums[i];
else rightOdd -= nums[i];
if (leftEven + rightOdd == leftOdd + rightEven) count++;
if (i % 2 == 0) leftEven += nums[i];
else leftOdd += nums[i];
}
return count;
}
};function waysToMakeFair(nums) {
let rightEven = 0, rightOdd = 0;
for (let i = 0; i < nums.length; i++) {
if (i % 2 === 0) rightEven += nums[i];
else rightOdd += nums[i];
}
let leftEven = 0, leftOdd = 0, count = 0;
for (let i = 0; i < nums.length; i++) {
if (i % 2 === 0) rightEven -= nums[i];
else rightOdd -= nums[i];
if (leftEven + rightOdd === leftOdd + rightEven) count++;
if (i % 2 === 0) leftEven += nums[i];
else leftOdd += nums[i];
}
return count;
}Edge cases to test
- A single element: removing it leaves an empty array, where both sums are 0, so the answer is 1
- Two elements: the remaining single element sits at index 0 and the odd sum is 0, so neither removal works (all values are at least 1)
- All elements equal: an array of odd length works for every removal, one of even length for none
- Removing index i shifts every later element one place left, so their parity flips; forgetting the flip gives wrong counts
- Sums reach 10^5 * 10^4 = 10^9, which still fits in a 32-bit int
Hints
Hint 1
After removing index i, elements before i keep their index, and elements after i move one place left, so even becomes odd and odd becomes even.
Hint 2
The new even sum is the even sum before i plus the odd sum after i. The new odd sum is the odd sum before i plus the even sum after i.
Hint 3
Keep running sums for the part to the left of i, and start with the totals for the right part. Moving i one step to the right only changes one number on each side.
FAQ
What is the best time complexity for Ways to Make a Fair Array?
Optimal (running left and right sums) runs in O(n) time and O(1) extra space. One pass for the totals and one pass over the removals, each step O(1).
Which pattern does Ways to Make a Fair Array use?
It is a arrays & hashing problem that uses the prefix sum strategy pattern. Other problems with the same pattern: Subarray Sum Equals K, Subarray with given XOR, Range Sum Query - Immutable.
Is there a brute force solution for Ways to Make a Fair Array?
Yes. Brute force (rebuild every array) takes O(n²) time and O(1) space. Try every index as the one to remove.
Which edge cases should I test for Ways to Make a Fair Array?
A single element: removing it leaves an empty array, where both sums are 0, so the answer is 1; Two elements: the remaining single element sits at index 0 and the odd sum is 0, so neither removal works (all values are at least 1); All elements equal: an array of odd length works for every removal, one of even length for none; Removing index i shifts every later element one place left, so their parity flips; forgetting the flip gives wrong counts; Sums reach 10^5 10^4 = 10^9, which still fits in a 32-bit int.