KatInterview

924. Fair Candy Swap

EasySolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

Method: Hash Set

This problem asks us to find a pair of candy boxes, one from Alice (x) and one from Bob (y), to swap such that their total candy amounts become equal. This can be solved efficiently using a mathematical observation and a hash set.

Solution

Fair Candy Swap in Python

class Solution:
    def fairCandySwap(self, aliceSizes: List[int], bobSizes: List[int]) -> List[int]:
        # Calculate the sum of candies for Alice and Bob.
        sumA = sum(aliceSizes)
        sumB = sum(bobSizes)
        
        # For a fair swap, the following must be true:
        # sumA - x + y = sumB - y + x
        # Rearranging the equation to solve for y:
        # 2y = 2x + sumB - sumA
        # y = x + (sumB - sumA) // 2
        delta = (sumB - sumA) // 2
        
        # Convert bobSizes to a set for O(1) average time complexity lookups.
        setB = set(bobSizes)
        
        # Iterate through aliceSizes to find a candy box x.
        for x in aliceSizes:
            # Calculate the required candy box y for Bob.
            y = x + delta
            # Check if Bob has a candy box of size y.
            if y in setB:
                # If found, return the pair [x, y].
                return [x, y]
        
        # The problem guarantees an answer exists, so this part is technically unreachable.

Fair Candy Swap in Java

class Solution {
    public int[] fairCandySwap(int[] aliceSizes, int[] bobSizes) {
        // Calculate the sum of candies for Alice.
        int sumA = 0;
        for (int x : aliceSizes) {
            sumA += x;
        }
        
        // Calculate the sum for Bob and store his candy sizes in a HashSet for efficient lookup.
        int sumB = 0;
        Set<Integer> setB = new HashSet<>();
        for (int y : bobSizes) {
            sumB += y;
            setB.add(y);
        }
        
        // The equation for a fair swap is: sumA - x + y = sumB - y + x
        // Rearranging for y: 2y = 2x + sumB - sumA => y = x + (sumB - sumA) / 2
        int delta = (sumB - sumA) / 2;
        
        // Iterate through Alice's candy boxes.
        for (int x : aliceSizes) {
            // Calculate the size of the box Bob needs to give in return.
            int y = x + delta;
            
            // Check if Bob has a box of that size.
            if (setB.contains(y)) {
                // If he does, we've found our answer.
                return new int[]{x, y};
            }
        }
        
        // The problem guarantees an answer exists, so this is unreachable.
        return new int[0];
    }
}

Fair Candy Swap in C++

class Solution {
public:
    vector<int> fairCandySwap(vector<int>& aliceSizes, vector<int>& bobSizes) {
        // Calculate the sum of candies for Alice and Bob.
        long sumA = 0;
        for (int x : aliceSizes) {
            sumA += x;
        }
        
        long sumB = 0;
        // Use an unordered_set for efficient lookups of Bob's candy sizes.
        unordered_set<int> setB;
        for (int y : bobSizes) {
            sumB += y;
            setB.insert(y);
        }
        
        // We need sumA - x + y = sumB - y + x
        // Which simplifies to y = x + (sumB - sumA) / 2
        int delta = (sumB - sumA) / 2;
        
        // Iterate through Alice's candy sizes.
        for (int x : aliceSizes) {
            // Calculate the required candy size for Bob.
            int y = x + delta;
            // Check if Bob has this candy size using the hash set.
            if (setB.count(y)) {
                // If found, this is the answer.
                return {x, y};
            }
        }
        
        // According to the problem statement, a solution always exists.
        // This line is theoretically unreachable.
        return {}; 
    }
};

Fair Candy Swap in TypeScript

function fairCandySwap(aliceSizes: number[], bobSizes: number[]): number[] {
    // Calculate sum for Alice and Bob.
    const sumA = aliceSizes.reduce((sum, val) => sum + val, 0);
    const sumB = bobSizes.reduce((sum, val) => sum + val, 0);
    
    // Create a Set of Bob's candy sizes for O(1) average time lookups.
    const setB = new Set(bobSizes);
    
    // We need to find x (from aliceSizes) and y (from bobSizes) such that:
    // sumA - x + y = sumB - y + x
    // Rearranging gives: y = x + (sumB - sumA) / 2
    const delta = (sumB - sumA) / 2;
    
    // Iterate through Alice's sizes.
    for (const x of aliceSizes) {
        const y = x + delta;
        // If the required y exists in Bob's set, we found the solution.
        if (setB.has(y)) {
            return [x, y];
        }
    }
    
    // The problem guarantees an answer exists, so this part should not be reached.
    return [];
};

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.