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<sup>th</sup>
box of candy that Alice has and bobSizes[j]
is the number of candies of the j<sup>th</sup>
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.
For example:
aliceSizes = [1,1], bobSizes = [2,2]
Output: [1,2]
As another example:
aliceSizes = [1,2], bobSizes = [2,3]
Output: [1,2]
And finally:
aliceSizes = [2], bobSizes = [1,3]
Output: [2,3]
Solve this problem in an efficient manner. What is the Big O runtime of your solution? What is the Big O space complexity?
A naive solution would involve iterating through all possible pairs of boxes, one from Alice and one from Bob, and checking if swapping them results in an equal total amount of candy for both. This approach has a time complexity of O(n*m), where n is the number of boxes Alice has and m is the number of boxes Bob has.
def fair_candy_swap_brute_force(aliceSizes, bobSizes):
sum_alice = sum(aliceSizes)
sum_bob = sum(bobSizes)
for a in aliceSizes:
for b in bobSizes:
if sum_alice - a + b == sum_bob - b + a:
return [a, b]
return []
aliceSizes
and m is the length of bobSizes
.To optimize, we can use a set to store the candy box sizes of Bob. This allows us to check in O(1) time whether a particular candy box size is present in Bob's collection. We can calculate the required difference between the total candy of Alice and Bob. Then iterate through Alice's candy sizes, check if Bob has the corresponding candy size that makes total equal for both.
sum_alice
) and the sum of Bob's candies (sum_bob
).diff = (sum_bob - sum_alice) // 2
. The value diff
represents the amount that Bob needs to give to Alice to make the totals equal after the exchange. In other words, bob_gives - alice_gives = diff
or bob_gives = alice_gives + diff
a
, check if a + diff
exists in Bob's candy set. If found, return [a, a + diff]
.def fair_candy_swap_optimal(aliceSizes, bobSizes):
sum_alice = sum(aliceSizes)
sum_bob = sum(bobSizes)
diff = (sum_bob - sum_alice) // 2
bob_set = set(bobSizes)
for a in aliceSizes:
if a + diff in bob_set:
return [a, a + diff]
return []
aliceSizes
and m is the length of bobSizes
. Building the set takes O(m) time, and iterating through Alice's candies takes O(n) time. The lookup in the set takes O(1) on average.bobSizes
, due to the space used by the set.diff
can't be 0, and a non-empty result is possible.