#888

Fair Candy Swap

Easy
ArrayHash TableBinary SearchSortingHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal solution uses a mathematical approach to find the required swap without checking every pair. We calculate the difference in total candies and use a set for quick lookups.

⚙️

Algorithm

4 steps
  1. 1Step 1: Calculate the total number of candies for Alice and Bob.
  2. 2Step 2: Calculate the difference between the two totals and divide by 2.
  3. 3Step 3: Store all of Bob's candy sizes in a set for O(1) lookups.
  4. 4Step 4: For each box in Alice's sizes, check if there exists a box in Bob's sizes that satisfies the swapping condition.
solution.py8 lines
1def fairCandySwap(aliceSizes, bobSizes):
2    totalAlice = sum(aliceSizes)
3    totalBob = sum(bobSizes)
4    diff = (totalAlice - totalBob) // 2
5    bobSet = set(bobSizes)
6    for a in aliceSizes:
7        if a - diff in bobSet:
8            return [a, a - diff]

Complexity note: The time complexity is O(n) because we only loop through Alice's sizes once and use a set for fast lookups.

  • 1Understanding the total difference in candies helps to find the required swap efficiently.
  • 2Using a set allows for quick lookups, reducing the need for nested loops.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.