Problem Description
Alice and Bob each have boxes of candy represented by two arrays. They want to swap exactly one box each so that after the exchange, both have the same total number of candies. Return the pair of candy counts (one from Alice and one from Bob) that will achieve this equality.
Key Insights
- Compute the sum of candies for both Alice and Bob.
- Let diff = (sumBob - sumAlice) / 2. This represents the extra candy count Bob has per swap.
- For a valid swap, if Alice gives a candy box with count a, then Bob must give a candy box with count a + diff.
- Use a set for Bob’s candies to quickly check for existence.
Space and Time Complexity
Time Complexity: O(n + m), where n is the length of aliceSizes and m is the length of bobSizes. Space Complexity: O(m), as we store Bob's candy sizes in a set.
Solution
We start by calculating the total candies Alice and Bob have. To balance the swap, we derive that for any candy count a in Alice's collection, Bob must have a candy count equal to a + diff, where diff is (sumBob - sumAlice) / 2. Using a set for Bob's candy sizes allows constant time checks for whether a suitable candidate exists. We then iterate through Alice's list and return the first valid pair we find.