LeetCode Solutions

888. Fair Candy Swap

Time:

Space:

			

class Solution {
 public:
  vector<int> fairCandySwap(vector<int>& A, vector<int>& B) {
    int diff =
        (accumulate(begin(A), end(A), 0) - accumulate(begin(B), end(B), 0)) / 2;
    unordered_set<int> set{begin(B), end(B)};

    for (int a : A)
      if (set.count(a - diff))
        return {a, a - diff};

    throw;
  }
};
			

class Solution {
  public int[] fairCandySwap(int[] A, int[] B) {
    int diff = (IntStream.of(A).sum() - IntStream.of(B).sum()) / 2;
    Set<Integer> set = new HashSet<>();
    for (int b : B)
      set.add(b);

    for (int a : A)
      if (set.contains(a - diff))
        return new int[] {a, a - diff};

    throw new IllegalArgumentException();
  }
}
			

class Solution:
  def fairCandySwap(self, A: List[int], B: List[int]) -> List[int]:
    diff = (sum(A) - sum(B)) // 2
    B = set(B)

    for a in A:
      if a - diff in B:
        return [a, a - diff]