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], bobSizes = [1,3]
Output: [2,3]
💡 Note: Alice sum=2, Bob sum=4. Alice gives 2, gets 3 → Alice: 2-2+3=3. Bob gives 3, gets 2 → Bob: 4-3+2=3. Both end up with 3 candies.

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 - Hash Set Optimization INPUT Alice's Boxes 1 1 Total: 2 Bob's Boxes 2 2 Total: 4 Input Arrays: aliceSizes = [1, 1] bobSizes = [2, 2] Sum Alice: 2 Sum Bob: 4 ALGORITHM STEPS 1 Calculate Sums sumA=2, sumB=4 2 Find Difference delta = (4-2)/2 = 1 3 Build HashSet bobSet = {2} 4 Find Match For a in Alice: check if (a+delta) in bobSet Hash Set Lookup: a=1: need b = 1+1 = 2 Is 2 in bobSet? OK! Found: [1, 2] FINAL RESULT After Exchange: 1 Alice gives 2 Bob gives Alice New 2-1+2 = 3 Bob New 4-2+1 = 3 = Output: [1, 2] Both have 3 candies - OK! Time: O(n+m), Space: O(m) Key Insight: If Alice gives candy 'a' and receives 'b', for equal totals: sumA - a + b = sumB - b + a Solving: b = a + (sumB - sumA)/2. Use HashSet for O(1) lookup of valid 'b' values in Bob's boxes. TutorialsPoint - Fair Candy Swap | Hash Set Optimization Approach
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