Find the Difference of Two Arrays (LeetCode 2215): Solution and Explanation

Easy
Array
Hash table

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

  1. Build set1 from nums1 and set2 from nums2. Duplicates disappear here.
  2. For each value in set1, add it to only1 if set2 does not contain it.
  3. For each value in set2, add it to only2 if set1 does not contain it.
  4. Return [only1, only2].

Step-by-step example

nums1 = [1,2,3], nums2 = [2,4,6]
  1. Build the sets: set1 = {1,2,3} and set2 = {2,4,6}.
  2. 1 is not in set2, so only1 = [1].
  3. 2 is in set2, so it is shared and skipped.
  4. 3 is not in set2, so only1 = [1,3].
  5. Now walk set2: 2 is in set1 and is skipped, 4 and 6 are not, so only2 = [4,6].
  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]
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

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.

Space

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 nums2 on 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.