LeetCode 888: Fair Candy Swap Solution
Master LeetCode problem 888 (Fair Candy Swap), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
888. Fair Candy Swap
Problem Explanation
Explanation:
To solve this problem, we need to find two boxes, one from Alice and one from Bob, such that after swapping candies between these boxes, both Alice and Bob will have the same total amount of candies. We can represent this problem as a mathematical equation where we need to find x and y such that: sum(alice) - x + y = sum(bob) - y + x This equation simplifies to: x = y + (sum(alice) - sum(bob)) / 2 We can iterate over one of the arrays and for each element, check if the corresponding value exists in the other array. We can also use a set to store all elements of one array for faster lookups.
:
Solution Code
import java.util.*;
class Solution {
public int[] fairCandySwap(int[] aliceSizes, int[] bobSizes) {
int sumAlice = 0, sumBob = 0;
for (int size : aliceSizes) {
sumAlice += size;
}
for (int size : bobSizes) {
sumBob += size;
}
Set<Integer> bobSet = new HashSet<>();
for (int size : bobSizes) {
bobSet.add(size);
}
for (int size : aliceSizes) {
int target = size + (sumBob - sumAlice) / 2;
if (bobSet.contains(target)) {
return new int[]{size, target};
}
}
return new int[2];
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 888 (Fair Candy Swap)?
This page provides optimized solutions for LeetCode problem 888 (Fair Candy Swap) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 888 (Fair Candy Swap)?
The time complexity for LeetCode 888 (Fair Candy Swap) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 888 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 888 in Java, C++, or Python.