Alice and Bob have candy bars of different sizes. They would like to swap one candy bar each so that after the swap, they both have the same total amount of candy.
You are given two integer arrays A
and B
where A[i]
and B[i]
are the sizes of the candy bars that Alice and Bob have, respectively. Return an integer array ans
where ans[0]
is the size of the candy bar Alice must exchange, and ans[1]
is the size of the candy bar Bob must exchange. If there are multiple answers, you may return any one of them. It is guaranteed that at least one answer exists.
Example 1:
Input: A = [1,1], B = [2,2]
Output: [1,2]
Example 2:
Input: A = [1,2], B = [2,3]
Output: [1,2]
Example 3:
Input: A = [2], B = [1,3]
Output: [2,3]
Example 4:
Input: A = [1,2,5], B = [2,4]
Output: [5,4]
Constraints:
A
and Bob’s B
candy bars.delta
is given by (sumA - sumB) / 2
.B
, trying to find a corresponding element a
in A
such that the equality condition holds.
a - b = delta
, then swapping these elements ensures equal sums.import java.util.HashSet;
import java.util.Set;
public class Solution {
public int[] fairCandySwap(int[] A, int[] B) {
int sumA = 0;
int sumB = 0;
for (int a : A) {
sumA += a;
}
for (int b : B) {
sumB += b;
}
int delta = (sumA - sumB) / 2;
Set<Integer> setA = new HashSet<>();
for (int a : A) {
setA.add(a);
}
for (int b : B) {
int a = b + delta;
if (setA.contains(a)) {
return new int[]{a, b};
}
}
return new int[0]; // This line is never reached.
}
}
n
is the length of A
and m
is the length of B
.A
elements: O(n).B
to find the correct swap: O(m).A
.This approach ensures the solution is efficient and meets the problem constraints.
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?