Fair Candy Swap — LeetCode 888 Python Solution

EasyArrayHash TableBinary SearchSorting
Problem
#888
Reading time
2 min

The problem

Alice and Bob have a different total number of candies. You are given two integer arrays aliceSizes and bobSizes where aliceSizes[i] is the number of candies of the ith box of candy that Alice has and bobSizes[j] is the number of candies of the jth box of candy that Bob has.

Example

Input
aliceSizes = [1,1], bobSizes = [2,2]
Output
[1,2]

Python solution

Python
class Solution:
    def fairCandySwap(self, aliceSizes: List[int], bobSizes: List[int]) -> List[int]:
        diff = (sum(aliceSizes) - sum(bobSizes)) >> 1
        s = set(bobSizes)
        for a in aliceSizes:
            if (b := (a - diff)) in s:
                return [a, b]

Complexity

MeasureComplexity
TimeO(m + n)
SpaceO(n) auxiliary

Pattern: Binary Search

Halve the search space each step — over an array, or over the answer itself. LeetCode 888. Fair Candy Swap is filed here because LeetCode tags it Binary Search, which is the vocabulary this hub collects.

The binary search guide has the Python template for the pattern and the 254 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 888. Fair Candy Swap?
LeetCode 888. Fair Candy Swap is rated Easy on LeetCode.
What is the time complexity of LeetCode 888. Fair Candy Swap?
The Python solution on this page runs in O(m + n).
What is the space complexity of LeetCode 888. Fair Candy Swap?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 888. Fair Candy Swap cover?
LeetCode 888. Fair Candy Swap is tagged Array, Hash Table, Binary Search and Sorting on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview