#1664

Ways to Make a Fair Array

Medium
ArrayPrefix SumPrefix SumArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(1)
💡

Intuition

Time O(n)Space O(1)

The optimal approach uses prefix sums to keep track of the even and odd indexed sums as we iterate through the array, allowing us to calculate the sums in constant time after the initial setup.

⚙️

Algorithm

5 steps
  1. 1Step 1: Calculate the total sums of even and odd indexed elements in the original array.
  2. 2Step 2: Initialize variables to keep track of the current even and odd sums as we iterate through the array.
  3. 3Step 3: For each index, calculate the new even and odd sums if the current index is removed, using the prefix sums.
  4. 4Step 4: If the adjusted sums are equal, increment the counter.
  5. 5Step 5: Return the counter after checking all indices.
solution.py20 lines
1# Full working Python code
2
3def ways_to_make_fair(nums):
4    total_even = sum(nums[i] for i in range(0, len(nums), 2))
5    total_odd = sum(nums[i] for i in range(1, len(nums), 2))
6    current_even = 0
7    current_odd = 0
8    count = 0
9    for i in range(len(nums)):
10        if i % 2 == 0:
11            total_even -= nums[i]
12        else:
13            total_odd -= nums[i]
14        if current_even + total_odd == current_odd + total_even:
15            count += 1
16        if i % 2 == 0:
17            current_even += nums[i]
18        else:
19            current_odd += nums[i]
20    return count

Complexity note: The optimal solution runs in linear time because we only traverse the array a constant number of times, maintaining a running total of even and odd indexed sums.

  • 1The parity of indices changes after removing an element, affecting the sums.
  • 2Using prefix sums allows for efficient recalculation of sums after each removal.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.