Fair Candy Swap (LeetCode 888): Solution and Explanation

Easy
Array
Hash Table
Binary Search
Sorting

Alice and Bob each trade one candy box so that their totals end up equal. Find which two boxes to swap.

Intuition

If Alice gives a box of size a and gets back b, her total becomes sumA - a + b and Bob's becomes sumB - b + a. Setting them equal gives b - a = (sumB - sumA) / 2.

So the gap delta = (sumB - sumA) / 2 is fixed by the totals alone. Each of Alice's boxes names exactly one size Bob would need to hand back, a + delta.

The whole problem turns into a membership question: does Bob own a box of size a + delta? Sorting Bob's boxes makes each question a binary search.

Approach: Delta from the sums, then binary search

  1. Compute sumA, sumB and delta = (sumB - sumA) / 2.
  2. Sort bobSizes.
  3. For each a in aliceSizes, set target = a + delta and binary search for it in bobSizes.
  4. On the first hit return [a, target].

Step-by-step example

aliceSizes = [35,17,4,24,10], bobSizes = [63,21]
  1. sumA = 90 and sumB = 84, so both must end at 87 and delta = (84 - 90) / 2 = -3.
  2. Sorted Bob: [21, 63].
  3. a = 35 needs 32. The search checks 21, then 63, and the window empties. Not there.
  4. a = 17 needs 14 and a = 4 needs 1. Neither is in Bob's boxes.
  5. a = 24 needs 21, and bob[0] = 21 matches.
  6. Return [24, 21]. Alice ends with 90 - 24 + 21 = 87 and Bob with 84 - 21 + 24 = 87.

Code: Python, Java, C++

1class Solution:
2    def fairCandySwap(self, aliceSizes: List[int], bobSizes: List[int]) -> List[int]:
3        delta = (sum(bobSizes) - sum(aliceSizes)) // 2
4        bobSizes.sort()
5        for a in aliceSizes:
6            target = a + delta
7            lo, hi = 0, len(bobSizes) - 1
8            while lo <= hi:
9                mid = (lo + hi) // 2
10                if bobSizes[mid] == target:
11                    return [a, target]
12                if bobSizes[mid] < target:
13                    lo = mid + 1
14                else:
15                    hi = mid - 1
16        return []
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O((n + m) log m)

Sorting Bob's m boxes costs O(m log m), and each of Alice's n boxes runs one O(log m) binary search.

Space

O(1)

Apart from the in-place sort, only the sums, delta and the search bounds are stored.

Other approaches

Hash set of Bob's boxes (time O(n + m), space O(m))

Put every size Bob owns into a set, then check a + delta for each of Alice's boxes in O(1).

Sort both and walk two pointers (time O(n log n + m log m), space O(1))

Sort both arrays and move a pointer on each side: if bob[j] - alice[i] is below delta advance j, if above advance i, until it equals delta.

Try every pair (time O(n * m), space O(1))

Check every (a, b) pair for b - a == delta. Simple, but up to 10^8 pairs at the limits.

Common mistakes

  • Getting the sign of delta backwards. Bob's box must be larger than Alice's by (sumB - sumA) / 2, which is negative when Alice holds more.
  • Recomputing both sums for every candidate pair. The sums never change, so compute delta once.
  • Searching Alice's boxes instead of Bob's. Either works if you flip the sign, but mixing the two gives the wrong pair.

Frequently asked questions

Why is sumB - sumA always even?

An answer is guaranteed, and any valid swap satisfies 2 * (b - a) = sumB - sumA. So the difference of the totals is twice an integer.

What if several swaps work?

LeetCode accepts any of them. Every test on this page is built so that exactly one swap balances the totals, so the first hit is the only answer.

Is the hash set version better?

It is O(n + m) instead of O((n + m) log m) and just as short. Binary search uses no extra memory, which is why it is shown here.