Show problems as
Classic problem #349EasyArrayHash TableTwo PointersBinary SearchSorting

Intersection of Two Arrays

Real-world version: Shared Scan Codes
Tracked in this browser only
Read Intersection of Two Arrays on LeetCode(opens in a new tab)

The statement here is our own: the same inputs, outputs and technique.

Two handheld scanners ran along the same loading dock for a shift. Their logs arrive as the integer arrays nums1 and nums2, where every entry is the bay code of one scan. A scanner may well have hit the same bay several times, so a code can repeat inside a log.

Collect the bay codes that turn up in both logs. Each such code belongs in the answer once, however many times it was scanned, and the answer may come back in whatever arrangement you find convenient. When the two scanners never touched a common bay, the answer is empty.

Examples

Example 1

Input
nums1 = [7, 3, 7, 12], nums2 = [12, 7, 7]
Output
[7, 12]

Bays 7 and 12 appear on both logs; the repeats of 7 collapse into a single entry.

Example 2

Input
nums1 = [0, 5], nums2 = [5, 0, 0]
Output
[0, 5]

Bay code 0 is a real code, so it counts just like any other shared bay.

Example 3

Input
nums1 = [1, 2, 3], nums2 = [40, 50]
Output
[]

The two scanners covered disjoint stretches of the dock, so nothing is shared.

Constraints

  • 1 <= nums1.length, nums2.length <= 1000
  • 0 <= nums1[i], nums2[i] <= 1000

The values you return may be in any order.

The signature

The editor starts with this. It matches the parent problem's shape, so a solution that works here works on a standard judge unchanged.

Python
def intersection(nums1: list[int], nums2: list[int]) -> list[int]:
Java
public int[] intersection(int[] nums1, int[] nums2)