Difference Between Two Arrays

easy array hash set

Problem

Given two arrays a and b, return a pair of lists: distinct values present in a but not in b, and distinct values present in b but not in a. Build a hash set from each array and filter against the other.

Inputa = [1, 2, 3], b = [2, 4, 6]
Output[[1, 3], [4, 6]]
2 is in both, so it's excluded from both halves.

def array_difference(a, b):
    A, B = set(a), set(b)
    only_a = list(A - B)
    only_b = list(B - A)
    return [only_a, only_b]
function arrayDifference(a, b) {
  const A = new Set(a), B = new Set(b);
  const onlyA = [...A].filter(x => !B.has(x));
  const onlyB = [...B].filter(x => !A.has(x));
  return [onlyA, onlyB];
}
class Solution {
    public List<List<Integer>> arrayDifference(int[] a, int[] b) {
        Set<Integer> A = new HashSet<>(), B = new HashSet<>();
        for (int x : a) A.add(x);
        for (int x : b) B.add(x);
        List<Integer> onlyA = new ArrayList<>();
        for (int x : A) if (!B.contains(x)) onlyA.add(x);
        List<Integer> onlyB = new ArrayList<>();
        for (int x : B) if (!A.contains(x)) onlyB.add(x);
        return List.of(onlyA, onlyB);
    }
}
vector<vector<int>> arrayDifference(vector<int>& a, vector<int>& b) {
    unordered_set<int> A(a.begin(), a.end()), B(b.begin(), b.end());
    vector<int> onlyA;
    for (int x : A) if (!B.count(x)) onlyA.push_back(x);
    vector<int> onlyB;
    for (int x : B) if (!A.count(x)) onlyB.push_back(x);
    return { onlyA, onlyB };
}
Time: O(|a| + |b|) Space: O(|a| + |b|)