Show problems as
Classic problem #350EasyArrayHash TableTwo PointersBinary SearchSorting

Intersection of Two Arrays II

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

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

Two service vans each carry a bin of spare parts. nums1 lists the catalogue number of every part in the first bin and nums2 does the same for the second bin; a bin may hold several copies of the same part.

A dispatcher wants the list of parts the two vans have in common, counted with copies: if one van carries three copies of part 8 and the other carries two, then part 8 belongs in the answer twice, because only two matching pairs can be made.

Return that list. Its entries may be given in any order.

Examples

Example 1

Input
nums1 = [3, 8, 3, 0, 8, 8], nums2 = [8, 3, 8]
Output
[3, 8, 8]

The first bin holds three copies of part 8 and the second holds two, so part 8 is reported twice. Part 3 appears twice in the first bin and once in the second, so it is reported once. Part 0 is missing from the second bin.

Example 2

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

Only two pairs of part 7 can be made, so the answer lists it twice.

Example 3

Input
nums1 = [4], nums2 = [9]
Output
[]

The bins share no catalogue number, so the answer is empty.

Constraints

  • 1 <= nums1.length, nums2.length <= 1000
  • 0 <= nums1[i], nums2[i] <= 1000
  • The result may be returned in any order.

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 intersect(nums1: list[int], nums2: list[int]) -> list[int]:
Java
public int[] intersect(int[] nums1, int[] nums2)