09 Sept 2026Go / Python / TypeScriptEasy

Fair Candy Swap

Find one candy-size exchange that makes two people's total candy amounts equal.

Compute the required size difference, store one person's sizes in a set, and find a pair satisfying the balance equation.

complexity

O(n + m) expected time and O(m) space.

solution files

  • Go fair-candy-swap/solution.go
  • Python fair-candy-swap/solution.py
  • TypeScript fair-candy-swap/solution.ts

Solution files

Gofair-candy-swap/solution.go
package main

func fairCandySwap(aliceSizes []int, bobSizes []int) []int {
	aliceTotal, bobTotal := 0, 0
	bobSet := map[int]bool{}
	for _, value := range aliceSizes {
		aliceTotal += value
	}
	for _, value := range bobSizes {
		bobTotal += value
		bobSet[value] = true
	}
	difference := (aliceTotal - bobTotal) / 2
	for _, alice := range aliceSizes {
		if bobSet[alice-difference] {
			return []int{alice, alice - difference}
		}
	}
	return nil
}
Pythonfair-candy-swap/solution.py
class Solution:
    def fairCandySwap(self, aliceSizes: list[int], bobSizes: list[int]) -> list[int]:
        difference = (sum(aliceSizes) - sum(bobSizes)) class=class="syntax-string">"syntax-comment">// class="syntax-number">2
        bob_set = set(bobSizes)
        for alice in aliceSizes:
            if alice - difference in bob_set: return [alice, alice - difference]
        return []
TypeScriptfair-candy-swap/solution.ts
function fairCandySwap(aliceSizes: number[], bobSizes: number[]): number[] {
  const aliceTotal = aliceSizes.reduce((sum, value) => sum + value, class="syntax-number">0);
  const bobTotal = bobSizes.reduce((sum, value) => sum + value, class="syntax-number">0);
  const bobSet = new Set(bobSizes);
  const difference = (aliceTotal - bobTotal) / class="syntax-number">2;
  for (const alice of aliceSizes) if (bobSet.has(alice - difference)) return [alice, alice - difference];
  return [];
}