InterviewPrepKit

Home / Coding / Algorithm & Data Structure / Arrays & Hashing

Find the Difference of Two Arrays

easy Original ↗ 00:00

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

The arrays are small enough that an O(n·m) solution passes, but the intended solution is linear using hashing.

Think about it first

Hint 1 The statement has two requirements: 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.

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug