Skip to main content
Back to problems
Leetcode
Medium
Arrays
Hash Maps
Sorting
Amazon
Intersection of Two Arrays II

Return the intersection of two integer arrays, including duplicates as many times as they appear in both arrays.

Acceptance 0%
Problem Statement

Problem

Given two integer arrays, build an array containing every value that appears in both arrays. If a number occurs multiple times in both arrays, include it in the result the minimum number of times it appears in either array.

The order of elements in the returned array does not matter.

Goal

Compute the multiset intersection of the two arrays efficiently.

Notes

  • A value can appear more than once in the output if it appears more than once in both inputs.
  • You may return the result in any order unless a specific platform variant requires otherwise.

Input Format

  • Two integer arrays nums1 and nums2.
  • Each array may contain duplicate values.
  • No additional special input structure is required.

Output Format

  • Return an integer array containing the intersection of nums1 and nums2 with duplicates preserved.
  • Any order is acceptable.

Constraints

  • 0 <= nums1.length, nums2.length
  • Array values are integers.
  • The solution should be efficient for large inputs; an O(n+m)O(n + m) or O(nlogn+mlogm)O(n \log n + m \log m) approach is typically expected.
Examples
Sample cases returned by the problem API.

Example 1

Input

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

Output

[2,2]

Explanation

The value 2 appears twice in both arrays, so it is included twice in the result.

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. Each is included once because that is the minimum frequency across the two arrays.

Premium problem context

Unlock deeper context for this problem

Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.

Guided hints
Editorial and discussion links
Concept map and variants
Sign in to unlock
Track your progress
Sign in to bookmark this problem, save notes, and manage its revision plan.