Find the Difference of Two Arrays (LeetCode 2215): Solution and Explanation
Given two integer arrays, return two lists: the distinct values of nums1 that never appear in nums2, and the distinct values of nums2 that never appear in nums1. Each list may be in any order.
Intuition
The question only cares about which values exist in each array, not how many times they appear or where. That points straight at a set: once both arrays are turned into sets, repeated values collapse to one copy each.
Think of the two sets as a Venn diagram. Every distinct value falls into exactly one region: only in nums1, in both, or only in nums2. The answer is the two outer regions, and the shared middle is thrown away.
To place a value, you ask one question: is it in the other set? A hash set answers that in O(1), so walking set1 and then set2 classifies everything in linear time. Scanning the other array instead would make every check O(n) and the whole thing quadratic.
Approach: Two hash sets
- Build
set1fromnums1andset2fromnums2. Duplicates disappear here. - For each value in
set1, add it toonly1ifset2does not contain it. - For each value in
set2, add it toonly2ifset1does not contain it. - Return
[only1, only2].
Step-by-step example
nums1 = [1,2,3], nums2 = [2,4,6]
- Build the sets:
set1 = {1,2,3}andset2 = {2,4,6}. - 1 is not in set2, so
only1 = [1]. - 2 is in set2, so it is shared and skipped.
- 3 is not in set2, so
only1 = [1,3]. - Now walk set2: 2 is in set1 and is skipped, 4 and 6 are not, so
only2 = [4,6]. - Return
[[1,3],[4,6]].
Code: Python, Java, C++
1class Solution:
2 def findDifference(self, nums1: List[int], nums2: List[int]) -> List[List[int]]:
3 set1, set2 = set(nums1), set(nums2)
4 only1 = []
5 for x in set1:
6 if x not in set2:
7 only1.append(x)
8 only2 = []
9 for x in set2:
10 if x not in set1:
11 only2.append(x)
12 return [only1, only2]1class Solution {
2 public List<List<Integer>> findDifference(int[] nums1, int[] nums2) {
3 Set<Integer> set1 = new HashSet<>(), set2 = new HashSet<>();
4 for (int x : nums1) set1.add(x);
5 for (int x : nums2) set2.add(x);
6 List<Integer> only1 = new ArrayList<>();
7 for (int x : set1) {
8 if (!set2.contains(x)) {
9 only1.add(x);
10 }
11 }
12 List<Integer> only2 = new ArrayList<>();
13 for (int x : set2) {
14 if (!set1.contains(x)) {
15 only2.add(x);
16 }
17 }
18 return Arrays.asList(only1, only2);
19 }
20}1class Solution {
2public:
3 vector<vector<int>> findDifference(vector<int>& nums1, vector<int>& nums2) {
4 unordered_set<int> set1(nums1.begin(), nums1.end());
5 unordered_set<int> set2(nums2.begin(), nums2.end());
6 vector<int> only1, only2;
7 for (int x : set1) {
8 if (!set2.count(x)) {
9 only1.push_back(x);
10 }
11 }
12 for (int x : set2) {
13 if (!set1.count(x)) {
14 only2.push_back(x);
15 }
16 }
17 return {only1, only2};
18 }
19};Time and space complexity
O(n + m)
Building the sets takes one pass over each array, and each distinct value is checked once against the other set in O(1) on average.
O(n + m)
The two sets hold up to n + m distinct values, plus the output lists.
Other approaches
Set difference operators (time O(n + m), space O(n + m))
In Python, [list(set1 - set2), list(set2 - set1)] does the same work in one line. It is idiomatic, but it hides the membership checks that the explicit loops show.
Presence array (time O(n + m + R), space O(R))
Values are limited to [-1000, 1000], so two boolean arrays of size 2001 indexed by value + 1000 can replace the hash sets. It avoids hashing, but it only works because the value range is small.
Nested scans (time O(n * m), space O(n + m))
For each value, scan the other array to see if it appears. It needs no extra structure but costs O(n * m), and you still need a way to drop duplicates from the output.
Common mistakes
- Looping over the original arrays instead of the sets, which puts a repeated value like 3 in
[1,2,3,3]into the answer twice. - Checking membership with
x in nums2on a list, which is a linear scan and turns the solution quadratic. - Swapping the two lists.
answer[0]is the values unique to nums1,answer[1]the values unique to nums2.
Frequently asked questions
Does the order of values in the answer matter?
No. Each inner list may be returned in any order, so iterating a hash set directly is fine. Only the order of the two inner lists is fixed.
Why convert both arrays to sets instead of only one?
You need fast lookups in both directions, and you need each output list to contain distinct values. Two sets give you both at once.
What is the time and space complexity?
O(n + m) time on average and O(n + m) extra space for the two sets, where n and m are the array lengths.