Fair Candy Swap - Problem

Alice and Bob have a different total number of candies. You are given two integer arrays aliceSizes and bobSizes where aliceSizes[i] is the number of candies of the i-th box of candy that Alice has and bobSizes[j] is the number of candies of the j-th box of candy that Bob has.

Since they are friends, they would like to exchange one candy box each so that after the exchange, they both have the same total amount of candy. The total amount of candy a person has is the sum of the number of candies in each box they have.

Return an integer array answer where answer[0] is the number of candies in the box that Alice must exchange, and answer[1] is the number of candies in the box that Bob must exchange. If there are multiple answers, you may return any one of them. It is guaranteed that at least one answer exists.

Input & Output

Example 1 — Basic Exchange
$ Input: aliceSizes = [1,1], bobSizes = [2,2]
Output: [1,2]
💡 Note: Alice has total 2, Bob has total 4. If Alice gives 1 and gets 2, she has 1+2=3. If Bob gives 2 and gets 1, he has 4-2+1=3. Both end up with 3 candies.
Example 2 — Multiple Options
$ Input: aliceSizes = [1,2], bobSizes = [2,3]
Output: [1,2]
💡 Note: Alice sum=3, Bob sum=5. Alice gives 1, gets 2 → Alice: 3-1+2=4. Bob gives 2, gets 1 → Bob: 5-2+1=4. Equal totals achieved.
Example 3 — Larger Arrays
$ Input: aliceSizes = [2,1,1], bobSizes = [1,2,3]
Output: [1,3]
💡 Note: Alice sum=4, Bob sum=6. Alice gives 1, gets 3 → Alice: 4-1+3=6. Bob gives 3, gets 1 → Bob: 6-3+1=4. Wait, that's not equal. Let me recalculate: Alice gives 1, gets 2 → Alice: 4-1+2=5. Bob gives 2, gets 1 → Bob: 6-2+1=5.

Constraints

  • 1 ≤ aliceSizes.length, bobSizes.length ≤ 104
  • 1 ≤ aliceSizes[i], bobSizes[i] ≤ 105
  • Alice and Bob have different total amounts of candy
  • At least one valid exchange exists

Visualization

Tap to expand
Fair Candy Swap: Equal ExchangeAlice Before: [1, 1]11Total = 2Bob Before: [2, 2]22Total = 4Alice gives 1Bob gives 2Alice After: [2, 1]21Total = 3Bob After: [1, 2]12Total = 3✓ Fair Exchange Complete: Both have 3 candies
Understanding the Visualization
1
Input
Alice has [1,1] (total=2), Bob has [2,2] (total=4)
2
Exchange
Alice gives 1 candy box, Bob gives 2 candy box
3
Result
Both end up with total=3 candies
Key Takeaway
🎯 Key Insight: Use the mathematical relationship that Alice must give exactly (her_total - his_total) / 2 more than she receives to balance the exchange.
Asked in
Google 15 Amazon 8 Facebook 5
28.0K Views
Medium Frequency
~15 min Avg. Time
980 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen