Similar Problems
Similar Problems not available
Fair Candy Swap - Leetcode Solution
LeetCode: Fair Candy Swap Leetcode Solution
Difficulty: Easy
Topics: hash-table binary-search sorting array
The Fair Candy Swap problem on LeetCode is a problem that can be solved using various techniques. The problem statement is as follows:
Alice and Bob have candy bars of different sizes: A[i] and B[j]. They would like to exchange one candy bar each so that after the exchange, they both have the same total amount of candy. The total amount of candy a person has is the sum of the candy bars they have. 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 an answer exists.
Solution: To solve this problem, we need to find the values of A[i] and B[j] such that A[i] - B[j] = (sum(A)-sum(B))/2. This will ensure that after swapping the candy bars, both Alice and Bob have the same total amount of candy.
First, we need to calculate the sum of candy bars of Alice and Bob. We can iterate through the arrays and sum up the elements. Then we can find the difference d = (sum(A) - sum(B)) / 2.
Next, we can iterate through the array A and for each element a in A, we can check if b = a - d exists in array B. If it exists, we can return a and b as the answer.
Here is the detailed solution:
-
Calculate the sum of candy bars of Alice and Bob.
-
Calculate the difference d = (sum(A) - sum(B)) / 2.
-
Iterate through the array A and for each element a in A, check if b = a - d exists in array B.
-
If b exists in array B, return a and b as the answer.
Here is the Python code for the solution:
def fair_candy_swap(A, B): sum_a = sum(A) sum_b = sum(B) diff = (sum_a - sum_b) // 2 set_b = set(B) for a in A: b = a - diff if b in set_b: return [a, b]
Test the function
A = [1,2,5] B = [2,4] print(fair_candy_swap(A, B)) # Output: [5, 2]
In this example, the sum of candy bars of Alice is 1+2+5=8 and Bob is 2+4=6. The difference d is (8-6)/2=1. We then iterate through the array A and check if 5-1=4 exists in array B. Since it does exist, we return [5,2] as the answer.
Fair Candy Swap Solution Code
1