Skip to content

2215. Find the Difference of Two Arrays 👍

  • Time: $O(|\texttt{nums1}| + |\texttt{nums2}|)$
  • Space: $O(|\texttt{nums1}| + |\texttt{nums2}|)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
class Solution {
 public:
  vector<vector<int>> findDifference(vector<int>& nums1, vector<int>& nums2) {
    const unordered_set<int> set1{nums1.begin(), nums1.end()};
    const unordered_set<int> set2{nums2.begin(), nums2.end()};
    vector<vector<int>> ans(2);

    for (const int num : set1)
      if (!set2.contains(num))
        ans[0].push_back(num);

    for (const int num : set2)
      if (!set1.contains(num))
        ans[1].push_back(num);

    return ans;
  }
};
1
2
3
4
5
6
7
8
9
class Solution {
  public List<List<Integer>> findDifference(int[] nums1, int[] nums2) {
    Set<Integer> set1 = Arrays.stream(nums1).boxed().collect(Collectors.toSet());
    Set<Integer> set2 = Arrays.stream(nums2).boxed().collect(Collectors.toSet());
    Arrays.stream(nums1).forEach(set2::remove);
    Arrays.stream(nums2).forEach(set1::remove);
    return Arrays.asList(new ArrayList<>(set1), new ArrayList<>(set2));
  }
}
1
2
3
4
5
6
class Solution:
  def findDifference(self, nums1: list[int],
                     nums2: list[int]) -> list[list[int]]:
    set1 = set(nums1)
    set2 = set(nums2)
    return [set1 - set2, set2 - set1]