Alice and Bob have candy bars of different sizes. Alice has A
array of candy bars, and Bob has B
array of candy bars. They want to swap exactly one candy bar each so that after the swap, they both have the same total amount of candy.
Return an integer array ans
where ans[0]
is the candy bar from Alice’s collection that she should swap, and ans[1]
is the candy bar from Bob’s collection that she should receive. If there are multiple answers, you may return any one of them. It is guaranteed that at least one answer exists.
A
and B
arrays have lengths that are between 1 and 10^4.A
and B
ranges from 1 to 10^4.To solve the problem:
The target solution should ideally:
Here’s the C++ implementation to solve the problem:
#include <vector>
#include <unordered_set>
#include <numeric>
std::vector<int> fairCandySwap(std::vector<int>& A, std::vector<int>& B) {
// Calculate the sum of both arrays
int sumA = std::accumulate(A.begin(), A.end(), 0);
int sumB = std::accumulate(B.begin(), B.end(), 0);
// Calculating the difference
int diff = (sumA - sumB) / 2;
// Store B's elements in a set for O(1) lookups
std::unordered_set<int> setB(B.begin(), B.end());
// Find a pair to swap
for (int a : A) {
if (setB.count(a - diff)) {
return {a, a - diff};
}
}
// If no valid pair is found, though guaranteed there is one.
return {};
}
std::accumulate
, the total sum of candy bars for both Alice and Bob is computed.This efficient approach ensures the solution is both time and space-optimal.
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?