Fair Candy Swap - Problem
Alice and Bob are sharing their Halloween candy collections! They have different amounts of candy in total, but being good friends, they want to make it fair.
You're given two arrays:
aliceSizes[]- wherealiceSizes[i]is the number of candies in Alice's i-th boxbobSizes[]- wherebobSizes[j]is the number of candies in Bob's j-th box
Goal: Find exactly one box from Alice and one box from Bob to swap so that after the exchange, both friends have the same total number of candies.
Return: An array [alice_box_size, bob_box_size] representing the sizes of boxes they should exchange.
Note: It's guaranteed that at least one valid answer exists!
Input & Output
example_1.py โ Basic Case
$
Input:
aliceSizes = [1, 2], bobSizes = [2, 3]
โบ
Output:
[1, 2]
๐ก Note:
Alice has 1+2=3 candies, Bob has 2+3=5 candies. If Alice gives her box of 1 candy and receives Bob's box of 2 candies: Alice will have 3-1+2=4 candies, Bob will have 5-2+1=4 candies. Both have equal amounts!
example_2.py โ Larger Numbers
$
Input:
aliceSizes = [1, 2, 5], bobSizes = [2, 4]
โบ
Output:
[5, 4]
๐ก Note:
Alice has 1+2+5=8 candies, Bob has 2+4=6 candies. If Alice gives her box of 5 candies and receives Bob's box of 4 candies: Alice will have 8-5+4=7 candies, Bob will have 6-4+5=7 candies. Perfect balance!
example_3.py โ Multiple Solutions
$
Input:
aliceSizes = [2, 2], bobSizes = [1, 1]
โบ
Output:
[2, 1]
๐ก Note:
Alice has 4 candies, Bob has 2 candies. Any exchange of Alice's 2-candy box for Bob's 1-candy box results in both having 3 candies. Multiple valid answers exist, any one is acceptable.
Constraints
- 1 โค aliceSizes.length, bobSizes.length โค 104
- 1 โค aliceSizes[i], bobSizes[i] โค 105
- Alice and Bob have different total amounts of candy
- There will always be at least one valid answer
Visualization
Tap to expand
Understanding the Visualization
1
Identify the Imbalance
Alice has 15 candies, Bob has 9 candies. Total difference is 6 candies.
2
Calculate Required Exchange
To balance, Alice needs to give 3 more than she receives: diff = (15-9)/2 = 3
3
Find the Perfect Match
If Alice gives 4 candies, she needs to receive 4-3=1 candy from Bob
4
Verify Balance
After swap: Alice = 15-4+1 = 12, Bob = 9-1+4 = 12 โ
Perfect balance!
Key Takeaway
๐ฏ Key Insight: The mathematical relationship `needed_bob_box = alice_box - (alice_total - bob_total)/2` directly gives us the required exchange partner, making hash table lookup the optimal O(n+m) solution!
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code