[
hath table
2sum
]
Leetcode 0888 Fair Candy Swap
Problem statement
https://leetcode.com/problems/fair-candy-swap/
Solution
First we need to evaluate what is the difference between persons amount of candy, and we need to find two candies such that difference between values is equal to half of this number. We create set of elements of B
and then use idea of 2Sum problem.
Complexity
Time complexity is O(m + n)
, space complexity is O(min(m, n))
, where m
and n
are lengths of bars lists for both persons.
Code
class Solution:
def fairCandySwap(self, A, B):
gain = (sum(B) - sum(A))//2
set_B = set(B)
for elem in A:
if elem + gain in set_B:
return [elem, elem + gain]