Sponsored
Sponsored
In this approach, we first calculate the total number of candies Alice and Bob have, respectively. Let this be sumA for Alice and sumB for Bob. If Alice swaps a candy box with x candies and Bob swaps a box with y candies, the condition to balance their total candies after swap can be derived as: sumA - x + y = sumB - y + x. Simplifying this, we get y = x + (sumB - sumA) / 2. Using this equation, we can loop through one person's candy sizes array and for each candy size, compute the necessary size from the other person's array and check if it exists using a set for quick lookup.
Time Complexity: O(n + m), where n is the length of aliceSizes and m is the length of bobSizes. This is because we iterate over each list once and use constant time checks for the existence of an element in Bob's collection.
Space Complexity: O(m), due to the additional space used for storing Bob's candy sizes in a set.
1#include <vector>
2#include <unordered_set>
3
4std::vector<int> fairCandySwap(std::vector<int>& aliceSizes, std::vector<int>& bobSizes) {
5 int sumA = 0, sumB = 0;
6 for (int x : aliceSizes) sumA += x;
7 for (int y : bobSizes) sumB += y;
8 int delta = (sumB - sumA) / 2;
9 std::unordered_set<int> setB(bobSizes.begin(), bobSizes.end());
10 for (int x : aliceSizes) {
11 if (setB.count(x + delta)) {
12 return {x, x + delta};
13 }
}
return {}; // This line should not be reached
}
The C++ code works in a similar way to the C solution. It uses STL features to manage the sums and uses an unordered set for fast lookup of Bob's candy sizes. The difference (delta) is calculated and used to determine if a valid swap exists.
This approach involves first sorting both the candy size arrays of Alice and Bob. The idea is to use a two-pointer technique to find a suitable pair of candy boxes such that swapping them would balance Alice's and Bob's total candies. Once both lists are sorted, use two pointers, starting at the beginnings of Alice's and Bob's lists, and adjust them based on the comparison of their sums to find the correct swap.
Time Complexity: O(n log n + m log m), due to the sorting step. The subsequent linear scan is O(n + m).
Space Complexity: O(1), with only a few additional variables used.
After sorting the candy sizes, this Python solution makes use of a single pass with two pointers to find the valid swap. The sort guarantees that once a valid swap is found, it is also optimal due to sorted order ensuring smaller and larger elements follow a linear order.