Introduction
Candy swap is a problem of Hashing and Array where we have to find the amount of candies we need to swap between two friends to make the total amount between them the same. Concepts related to Array and Hashing should be clear in your head if you have to master Data Structures and Algorithms.
We will see different approaches from brute force to an efficient one, which will help you build the logic more easily.
Without any delays, let's move to our problem statement.
Problem Statement
There are two friends Alice and Bob, and both are very fond of candies. They have a different total number of candies. You are given two integer arrays, of which one array contains the total number of candies that Alice has, and another array contains the total number of candies that Bob has.
As they are best friends, they would like to exchange one candy box each so that after the exchange, they both have the same number of candies. The total number of candies a person has is the sum of candies in each box.
We have to return the array, where the first index of the array will contain the number of candies that Alice must exchange, and the second index of the array will include the number of candies that Bob must exchange.
Note:
- There can be multiple answers; return any one of them.
- At least one answer will be there.
Let me make you more precise with the help of an example.
Input:
Alice = [1,1] , Bob = [2,2]
Output:
[1,2]
In this example, Alice has in total two candies(1+1=2), and Bob has in total four candies(2+2=4), which is not the same. To make the total number of candies the same, we have to swap Alice and Bob.
If we swap Alice having candy at index=0 and Bob having candy at index=0, then Alice will have three candies in total, and Bob will also have three candies in total, which is the same amount.
After swapping the arrays will become:
Alice = [2,1] , Bob = [1,2]
Therefore, the result array will be [1,2].
If the problem statement is clear, then let's move towards the approach.
Building of Approach
The building of the logic will be clear through this pictorial representation.
A = Alice
B = Bob
Therefore, our target is to find a candy pair whose difference is exactly x/2.
If B > A, logic is precisely the same.
Note: Please try to solve Fair Candy Swap by yourself before heading towards the solution.