InterviewPrepKit

Home / Coding / Arrays & Hashing

Find the Difference of Two Arrays

easy Original β†—
Solving tips
  • 'Distinct values' plus 'membership across collections' translates directly to set algebra: build set(nums1) and set(nums2).
  • The answer is the two set differences s1 - s2 and s2 - s1; construction deduplicates for free.
  • Compute BOTH directions (the result is asymmetric) and don't use symmetric difference s1 ^ s2, which loses origin.
  • Target O(n + m) time and space; output order doesn't matter here.

Problem

Given two integer arrays nums1 and nums2, return a list answer of two lists:

  • answer[0]: the distinct values that appear in nums1 but not in nums2.
  • answer[1]: the distinct values that appear in nums2 but not in nums1.

Each inner list may be returned in any order, but must contain no duplicates.

Examples

  • nums1 = [1,2,3], nums2 = [2,4,6] β†’ [[1,3],[4,6]] β€” 1 and 3 are only in nums1; 4 and 6 are only in nums2.
  • nums1 = [1,2,3,3], nums2 = [1,1,2,2] β†’ [[3],[]] β€” 3 appears (twice) only in nums1, listed once; everything in nums2 also appears in nums1.
  • nums1 = [5], nums2 = [5] β†’ [[],[]] β€” the arrays contain the same values.

Constraints

  • 1 <= len(nums1), len(nums2) <= 1000
  • -1000 <= nums1[i], nums2[i] <= 1000

Small enough that O(nΒ·m) squeaks by, but the intended solution is linear with hashing.

Think about it first

Hint 1 Two separate requirements hide in the statement: deduplicate each array, and test membership in the other. Which data structure does both at once?
Hint 2 Once each array is a set, "in nums1 but not nums2" is a single set operation.
Hint 3 Build `s1 = set(nums1)` and `s2 = set(nums2)`; the answer is the two set differences `s1 - s2` and `s2 - s1`, converted back to lists.
Your workspace Not runnable by design β€” this is your interview scratchpad. Saved on this device.