661/670

661. Find the Difference of Two Arrays

Easy

You are given two integer arrays, nums1 and nums2. Compute what each array has that the other lacks:

  • the first list holds every distinct value that occurs in nums1 but never in nums2,
  • the second list holds every distinct value that occurs in nums2 but never in nums1.

Return the pair [list1, list2]. To keep the answer unique, each list must be sorted in increasing order (that canonical order is what the judge compares against).

Example 1:

Input: nums1 = [1, 2, 3], nums2 = [2, 4, 6]

Output: [[1, 3], [4, 6]]

Explanation: From nums1, the values 1 and 3 never appear in nums2 (2 does). From nums2, the values 4 and 6 never appear in nums1.

Example 2:

Input: nums1 = [1, 2, 3, 3], nums2 = [1, 1, 2, 2]

Output: [[3], []]

Explanation: Only 3 is unique to nums1 — and it is reported once even though it occurs twice. Every value of nums2 also appears in nums1, so the second list is empty.

Constraints:

  • 1 ≤ nums1.length, nums2.length ≤ 1000
  • -1000 ≤ nums1[i], nums2[i] ≤ 1000

Hints:

For each value of nums1, you need to answer two questions: is it in nums2, and have I already reported it? Scanning nums2 for every element works, but it is O(n · m).

Convert both arrays to sets. The answer is just the two set differences — set1 minus set2 and set2 minus set1 — sorted. Membership tests against a hash set are O(1).

▶ Run checks these sample cases. Submit also runs hidden edge cases.

Input: nums1 = [1, 2, 3], nums2 = [2, 4, 6]

Expected output: [[1, 3], [4, 6]]