Fair Candy Swap (LeetCode 888): Solution and Explanation
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
- Compute
sumA,sumBanddelta = (sumB - sumA) / 2. - Sort
bobSizes. - For each
ainaliceSizes, settarget = a + deltaand binary search for it inbobSizes. - On the first hit return
[a, target].
Step-by-step example
aliceSizes = [35,17,4,24,10], bobSizes = [63,21]
- sumA = 90 and sumB = 84, so both must end at 87 and delta = (84 - 90) / 2 = -3.
- Sorted Bob: [21, 63].
- a = 35 needs 32. The search checks 21, then 63, and the window empties. Not there.
- a = 17 needs 14 and a = 4 needs 1. Neither is in Bob's boxes.
- a = 24 needs 21, and bob[0] = 21 matches.
- 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 []1class Solution {
2 public int[] fairCandySwap(int[] aliceSizes, int[] bobSizes) {
3 int sumA = 0, sumB = 0;
4 for (int x : aliceSizes) sumA += x;
5 for (int x : bobSizes) sumB += x;
6 int delta = (sumB - sumA) / 2;
7 Arrays.sort(bobSizes);
8 for (int a : aliceSizes) {
9 int target = a + delta;
10 int lo = 0, hi = bobSizes.length - 1;
11 while (lo <= hi) {
12 int mid = (lo + hi) / 2;
13 if (bobSizes[mid] == target) {
14 return new int[]{a, target};
15 }
16 if (bobSizes[mid] < target) {
17 lo = mid + 1;
18 } else {
19 hi = mid - 1;
20 }
21 }
22 }
23 return new int[0];
24 }
25}1class Solution {
2public:
3 vector<int> fairCandySwap(vector<int>& aliceSizes, vector<int>& bobSizes) {
4 int sumA = accumulate(aliceSizes.begin(), aliceSizes.end(), 0);
5 int sumB = accumulate(bobSizes.begin(), bobSizes.end(), 0);
6 int delta = (sumB - sumA) / 2;
7 sort(bobSizes.begin(), bobSizes.end());
8 for (int a : aliceSizes) {
9 int target = a + delta;
10 int lo = 0, hi = (int)bobSizes.size() - 1;
11 while (lo <= hi) {
12 int mid = (lo + hi) / 2;
13 if (bobSizes[mid] == target) {
14 return {a, target};
15 }
16 if (bobSizes[mid] < target) {
17 lo = mid + 1;
18 } else {
19 hi = mid - 1;
20 }
21 }
22 }
23 return {};
24 }
25};Time and space complexity
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.
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.