Problem 1664

Abstract / Summary

Given an array with an even number of elements, count ways to split it into two equal-sum subsets by choosing a pivot.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 1664.py

class Solution:
    def waysToMakeFair(self, nums: List[int]) -> int:
        result = 0

        allOdd = allEven = 0 # sum of all odd or even numbers
        for i, n in enumerate(nums):
            if i & 1:
                allOdd  += n
            else:
                allEven += n

        odd = even = 0
        for i, n in enumerate(nums):
            # left side of i
            a = odd
            b = even

            if i & 1:
                odd  += n
            else:
                even += n

            # right side of i
            a += allEven - even
            b += allOdd  - odd

            # fair ?
            if a == b:
                result += 1

        return result
31 lines | 732 bytes | submitted January 18, 2024 | GitHub   18% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 67% (90k+ submissions).

Typical patterns to solve this problem:
  • Array
  • Prefix Sum
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided Solution class implements a method waysToMakeFair that counts the number of indices whose removal makes the remaining array “fair”. An array is considered fair when the sum of elements at even positions equals the sum of elements at odd positions after the removal. The algorithm works in two linear passes over the input list, using only a few integer variables to keep track of prefix and suffix sums.

Key Steps

The method begins by initializing a counter for the result and two accumulators that will hold the total sum of elements located at odd and even indices in the original array.

result = 0
allOdd = allEven = 0
for i, n in enumerate(nums):
    if i & 1:
        allOdd  += n
    else:
        allEven += n

The bitwise expression i & 1 determines the parity of the index: it is true for odd positions and false for even positions. After this loop, allEven contains the sum of all elements at even indices, while allOdd contains the sum of all elements at odd indices.

A second pass computes prefix sums while simultaneously deriving the sums of the left and right parts that would remain after removing the current element. Two variables, odd and even, accumulate the sums of elements seen so far on the left side.

odd = even = 0
for i, n in enumerate(nums):
    # left side of i
    a = odd
    b = even

    if i & 1:
        odd  += n
    else:
        even += n

    # right side of i
    a += allEven - even
    b += allOdd  - odd

    # fair ?
    if a == b:
        result += 1

Inside the loop, a and b start as the sums of the left side (elements before index i). After updating the prefix sums (odd or even), the algorithm adds the contributions from the right side. The right side sums are derived by subtracting the current prefix sums from the total sums computed earlier (allEven - even and allOdd - odd). The condition a == b checks whether the left and right sums are equal after the hypothetical removal of nums[i]. When the condition holds, the result counter is incremented.

Finally, the method returns the total count of such indices.

return result

Edge Cases Handled

When the input list is empty, the first loop does not execute, leaving allOdd and allEven at zero. The second loop also skips, and the method returns 0, correctly indicating that there are no indices to remove.

For a single-element list, the first loop records the element either in allEven (index 0) or allOdd (index 1, which cannot occur). In the second loop, the left side sums a and b start at zero, the prefix sums are updated with the sole element, and the right side contributions become zero because the total minus the prefix equals zero. The equality check then compares 0 with 0, resulting in a count of 1. This matches the definition that removing the only element leaves an empty array, which is trivially fair.

Arrays with an odd or even number of elements are both accommodated because the parity test (i & 1) works uniformly regardless of length. The algorithm correctly updates prefix sums and computes the complementary suffix sums for any index, ensuring that the fairness condition is evaluated accurately for every possible removal.

Performance Optimizations

The implementation avoids recomputing sums for each candidate removal. By pre-computing the total sums of odd and even positions (allOdd, allEven) in the first pass, the algorithm can obtain the sum of the right side in constant time during the second pass through simple subtraction. This eliminates the need for nested loops or repeated scanning of the array.

Using bitwise & to test index parity is marginally faster than the modulo operator, especially in tight loops. The code maintains only a handful of integer variables (result, allOdd, allEven, odd, even, a, b) regardless of input size, which keeps the memory footprint minimal.

Both passes iterate over the list exactly once, resulting in linear time execution relative to the length of nums. The absence of auxiliary data structures such as additional arrays or hash maps contributes to the overall efficiency.

written by openai gpt

ELI5 - Simplified Explanation

Imagine a long line of numbered building blocks sitting on the floor. Some blocks are in spots that count as even, and some are in spots that count as odd. The goal is to pretend that one block is removed, which makes all the blocks behind it shift their positions. When a block shifts, its even or odd status might flip-flop.

The computer does this by first adding up all the odd blocks and all the even blocks into two big piles. Then, the computer walks down the line of blocks one by one. At each spot, it pretends to take that block away. It updates its count of odd and even blocks as if that spot no longer exists.

After removing a block, the computer checks to see if the new pile of odd blocks weighs exactly the same as the new pile of even blocks. If they match perfectly, that spot is considered a fair place to take a block. Every time the computer finds a fair spot, it keeps a tally to see how many there are in total. The code simply finishes the game by counting how many of these fair spots exist in the entire line of blocks.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 8 | μ = 7.63 | σ = 0.91

Complexity Analysis

Time: linear
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Python Java TS
WalkCCC C++ Java
leetcode.ca C++ Python JS Java Go
Progiez C++ Python Java
github black-shadows C++
charles-wangkai Java
everthis JS
fsq C++
halfrost Go
JoshCrozier JS
lkwq007 Python
suxrobGM C#
trung-hn Python
varunu28 Java
wisdompeak C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Java
leetcode.ca C++, Go, Java, JavaScript, Python
Progiez C++, Java, Python
black-shadows C++, C++
charles-wangkai Java
everthis JavaScript
fsq C++
halfrost Go
JoshCrozier JavaScript
lkwq007 Python
suxrobGM C#
trung-hn Python
varunu28 Java
wisdompeak C++
25 links | 15 authors | 7 languages

Videos

4 videos   did my crawler come up with invalid videos ? drop me a line.

Solved On The Same Day

5 solutions   January 18, 2024

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality