Alice and Bob have a different total number of candies. To be fair, each of them should exchange one of their own candies so that each person ends up with the same total amount of candies. The problem is to determine a pair of candies that they can swap to achieve this fair distribution.
Given two integer arrays A
and B
where A[i] and B[i] represent the size of the i-th
candy from Alice’s and Bob’s collection respectively, return an integer array [x, y]
such that:
x
is from Alice’s collection A
.y
is from Bob’s collection B
.If there are multiple answers, you may return any one of them.
The solution should fit in O(N) time complexity, where N is the size of the input arrays.
A
and B
?A
and B
have negative values or zeroes?A
or B
are empty?The key to solving this problem is to use the fact that the sum of candies in Alice’s collection minus the sum of candies in Bob’s collection is a key factor in finding the fair swap.
sumA
) and Bob (sumB
).Determine the difference delta
such that if Alice gives away x
and receives y
, it will balance out the total candies for both:
[ \text{sumA} - x + y = \text{sumB} - y + x ]
From this, we derive:
[ 2(y - x) = \text{sumB} - \text{sumA} ]
Therefore,
[ y = x + \left(\frac{\text{sumB} - \text{sumA}}{2}\right) ]
x
, compute y
and check if y
exists in Bob’s set.def fairCandySwap(A, B):
sumA = sum(A)
sumB = sum(B)
delta = (sumB - sumA) // 2
setB = set(B)
for x in A:
y = x + delta
if y in setB:
return [x, y]
N
and M
are the lengths of A and B respectively.Thus, the total time complexity is O(N + M).
This approach satisfies the time complexity requirement and ensures a valid solution for the problem.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?