Skip to content
Problem 2215 · LeetCode 2215(opens in a new tab)

Find the Difference of Two Arrays

EasyArrays

nums1 and nums2 are two arrays of whole numbers. Build an answer made of two lists. The first holds every value that appears in nums1 but nowhere in nums2. The second holds every value that appears in nums2 but nowhere in nums1.

Each value is listed once, even if it appears several times in its array. The values inside each list can be in any order.

Example 1

Input:  nums1 = [6,2,9,2], nums2 = [9,5,7]
Output: [[6,2],[5,7]]
Why:    9 is in both; 6 and 2 only in nums1, 5 and 7 only in nums2
2 more examples and the constraints

Example 2

Input:  nums1 = [4,4,1], nums2 = [1,4,8,8]
Output: [[],[8]]
Why:    every value of nums1 is in nums2; 8 is listed once

Example 3

Input:  nums1 = [-3], nums2 = [3]
Output: [[-3],[3]]
Why:    no value is shared

Constraints

  • 1 ≤ length of nums1, length of nums2 ≤ 1,000
  • −1,000 ≤ nums1[i], nums2[i] ≤ 1,000

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Scan the other arrayO(n·m)
  2. Two hash setsO(n + m)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for 1,000 values in each arrayVerdict
Scan the other arrayO(n·m)
Passes at this size; quadratic
Two hash setsO(n + m)
Best; linear

n = length of nums1, m = length of nums2.

Edge cases to test

  • Same values on both sides. [3,3] and [3] give [[],[]]: both lists can be empty.
  • Duplicates. [8,8] against [1] gives [[8],[1]]: a repeated value is listed once.
  • Nothing shared. Every distinct value of each array is returned.
  • Negative numbers. −3 and 3 are different values; nothing special happens.

Common mistakes

  • Listing a repeated value more than once.
  • Returning only the first list and forgetting the second direction.
  • Expecting the values in input order; a set gives them back in any order, which is allowed.

How to talk through it

  1. 1Clarify. Should repeated values be listed once? Does the order inside each list matter?
  2. 2Give the simple version. Scan the other array for each value; say it is O(n·m).
  3. 3Name the fix. A hash set makes each lookup O(1) and removes duplicates for free.
  4. 4Code it. Two sets, then two filters, one per direction.
  5. 5Test out loud. Run identical arrays, an array with repeats and arrays with nothing shared.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?