File: fair-candy-swap/solution.py

Date: 2026-06-06

Time: 16:30

fair-candy-swap/solution.py

Purpose

This file solves LeetCode 888 — Fair Candy Swap. Given two arrays representing candy box sizes for Alice and Bob, find one box from each person to swap so both end up with the same total candy count.

Key Components

Solution.fairCandySwap — the sole method. Takes two lists of integers and returns a two-element list [a, b] where a is the box Alice gives and b is the box Bob gives.

Flow

The algorithm works in three steps:

1. Compute the delta: delta = (sum(aliceSizes) - sum(bobSizes)) // 2. This is the amount by which Alice's chosen box must exceed Bob's chosen box. The derivation: after swapping boxes of size a and b, Alice's new total is sumA - a + b and Bob's is sumB - b + a. Setting them equal gives a - b = (sumA - sumB) / 2.

2. Build a lookup set: bob_set = set(bobSizes) enables O(1) membership checks against Bob's boxes.

3. Linear scan: For each box a in Alice's collection, check if a - delta exists in Bob's set. If so, that's the valid swap pair.

The function returns on the first valid pair found. The problem guarantees exactly one solution exists, so the loop always terminates with a return.

Patterns

Dependencies

Imports: None beyond Python builtins (list, set, sum).

Imported by: fair-candy-swap/testsolution.py and — based on the importedby list — hundreds of other test files across the repo. This is almost certainly an artifact of a shared test harness or import pattern, not direct usage of this solution's logic.

Invariants

Error Handling

None. The function trusts its inputs match the LeetCode contract. No validation, no exceptions. If aliceSizes or bobSizes is empty, or no valid swap exists, the function returns None silently.

Complexity

Topics to Explore

Beliefs