Fair Candy Swap — LeetCode 888 Python Solution
- Problem
- #888
- Pattern
- Binary Search
- Reading time
- 2 min
- Source
- leetcode.com
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
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
| Measure | Complexity |
|---|---|
| Time | O(m + n) |
| Space | O(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.