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) {
    vector<vector<int>> ans(2);
    unordered_set<int> set1{begin(nums1), end(nums1)};
    unordered_set<int> set2{begin(nums2), end(nums2)};

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

    for (const int num : set2)
      if (!set1.count(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
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]