Fair Candy Swap LeetCode

Key takeaways:

  • Fair Candy Swap LeetCode problem involves two friends, Anna and Brian, who want to exchange candy boxes to equalize their total amounts of candy.

  • The problem statement is given two integer arrays A and B, representing the number of candies in Anna's and Brian's candy boxes respectively, and requires an efficient exchange to balance their total candies.

  • The algorithm calculates the total candies for both Anna and Brian, determines the target difference to adjust, and utilizes a set for quick lookups to find the appropriate boxes to swap.

  • The time complexity of this solution is O(N+M)O(N + M).

  • The space complexity is O(M)O(M).

The "Fair Candy Swap" problem presents a scenario where Anna and Brian aim to exchange candy bars to equalize their total candy amounts.

This challenge improves problem-solving and algorithm skills by encouraging efficient and logical thinking. It helps with math skills by balancing candy amounts and showing how to solve practical problems. The problem also highlights the importance of using efficient data structures, such as sets, for optimizing operations like searching and comparison.

These skills are applicable in real-world scenarios involving resource distribution and optimization problems.

Problem statement

Anna and Brian have different total amounts of candies. We are provided with two integer arrays, A and B, where A[i] represents the number of candies in Anna's ithi^{th} candy box and B[j] represents the number of candies in Brian's jthj^{th} candy box.

As friends, they want to swap one candy box each so that their total candy amounts are equal after the exchange. The total amount of candy each person has is the sum of the candies in all their candy boxes.

Return an array where the first element is the number of candies in the box Anna should exchange and the second element is the number of candies in the box Brian should exchange. You can return any one of the possible answers, as there is a guarantee that at least one answer exists.

Constraints:

  • 11 \leq A.length, B.length 103\leq 10^3

  • 11 \leq A[i], B[j] 105\leq 10^5

  • Anna and Brian have a different total number of candies.

  • There exists at least one valid answer.

Examples

canvasAnimation-image
1 of 3

Knowledge test

1

In the given problem, if Anna has candies A = [1, 1] and Brian has candies B = [2, 2], which pair of candies should they swap to equalize their total candy amounts?

A)

[1, 1]

B)

[2, 2]

C)

[2, 1]

D)

[1, 2]

Question 1 of 20 attempted

Solution

This algorithm aims to balance Anna and Brian's total number of candies by finding a pair of candy boxes to swap.

It calculates the difference in their total candies and identifies the target difference to balance the sums. Using a set for quick lookup, it then iterates through Anna's candy boxes to find a matching box in Brian's collection that satisfies the target difference.

The first valid pair found is returned as the answer.

The steps of the algorithm are given below:

  1. Calculate total amounts:

    1. Compute the sum of all candies Anna has (sumA).

    2. Compute the sum of all candies Brian has (sumB).

  2. Calculate the target difference:

    1. Determine the difference between the sums, which needs to be adjusted. This is (sumA - sumB) / 2.

  3. Create a Set for fast lookup:

    1. Convert Brian's list of candies B into a set for O(1)O(1) lookups.

  4. Find the swapping Pair:

    1. Iterate through Anna's candies, and for each candy a in A, compute the required candy b in B such that b = a - diff. Check if this b exists in setB.

Now, let’s look at the following illustration to get a better understanding of the solution:

canvasAnimation-image
1 of 7

Code example

Here is an implementation for the problem:

def fairCandySwap(A, B):
# Step 1: Calculate the total amounts
sumA = sum(A)
sumB = sum(B)
# Step 2: Calculate the target difference
diff = (sumA - sumB) // 2
# Step 3: Create a set for Brian's candies for fast lookup
setB = set(B)
# Step 4: Find the swapping pair
for a in A:
b = a - diff
if b in setB:
return [a, b]
def main():
# Example test cases
test_cases = [
([1, 2, 5], [2, 4]),
([1, 1], [2, 2]),
([1, 1, 1], [2, 3]),
([4, 7], [1, 1, 3]),
([5, 8], [4, 6, 7]),
]
for i, (A, B) in enumerate(test_cases, 1):
print(f"Test Case {i}:")
print("\tA: ", A)
print("\tB: ", B)
result = fairCandySwap(A, B)
print("\tResult: ", result)
print("-" * 100)
main()
Fair Candy Swap

Time complexity

The time complexity of this solution is O(N+M)O(N + M), where NN is the length of A and MM is the length of B. This is due to the summation and the iteration through Anna's candies, each taking linear time. The set lookup operations are O(1)O(1).

Space complexity

The space complexity is O(M)O(M) due to the creation of the set setB from Brian's list of candies.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved