The Fair Candy Swap interview question features two friends, Alice and Bob, each with an array of candy bar sizes. They want to exchange exactly one candy bar each so that after the exchange, they both have the same total weight of candy. You need to return an array [aliceSize, bobSize] representing the sizes of the candy bars they should swap. The problem guarantees that at least one such pair exists.
This is a popular "Easy" Hash Table and Math interview pattern used by companies like Amazon and Google. It tests your ability to derive a simple algebraic equation from a word problem and then optimize the search for a solution. It evaluates whether you can use a Hash Set to turn an O(N*M) brute-force search into an O(N+M) efficient lookup.
delta = (S_B - S_A) / 2.x + delta exists in Bob's set.Alice: [1, 2], Bob: [2, 3]
delta = (5 - 3) / 2 = 1.{2, 3}.[1, 2].
(Check: Alice: . Bob: . Correct!)Whenever you have an equation with two unknowns ( and ) and two lists of possible values, the most common optimization is to fix and use a Hash Set to find if the required exists in the other list.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Check If N and Its Double Exist | Easy | Solve | |
| Intersection of Two Arrays II | Easy | Solve | |
| Intersection of Two Arrays | Easy | Solve | |
| Rank Transform of an Array | Easy | Solve | |
| Special Array With X Elements Greater Than or Equal X | Easy | Solve |