296/670

296. Intersection of Two Arrays

Easy

You are given two integer arrays, nums1 and nums2. Return every distinct value that appears in both arrays — each common value exactly once, no matter how many times it occurs in either array.

To make the answer unique, return the values sorted in increasing order. If the arrays share nothing, return an empty list (printed as an empty line).

Example 1:

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

Output: [2]

Explanation: The only value present in both arrays is 2. It occurs twice in each, but the answer lists distinct values, so it appears once.

Example 2:

Input: nums1 = [4, 9, 5], nums2 = [9, 4, 9, 8, 4]

Output: [4, 9]

Explanation: Both 4 and 9 appear in each array. Sorted ascending, the answer is [4, 9].

Constraints:

  • 1 ≤ nums1.length, nums2.length ≤ 10⁴
  • -10⁹ ≤ nums1[i], nums2[i] ≤ 10⁹

Hints:

For each candidate from nums1, scanning all of nums2 works but costs O(n·m). What structure answers "is this value in the other array?" in O(1)?

Turn nums1 into a hash set, then walk nums2 keeping every value found in the set. Collect into a second set so duplicates can't sneak into the answer — then sort it.

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

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

Expected output: [2]