Skip to content
Problem 350 · LeetCode 350(opens in a new tab)

Intersection of Two Arrays II

EasyArrays

You are given two lists of whole numbers, nums1 and nums2. Return the numbers they share, counting repeats: a value goes into the answer as many times as it appears in both lists, which is the smaller of its two counts.

The answer can be in any order.

Example 1

Input:  nums1 = [3, 1, 3, 5], nums2 = [3, 3, 7]
Output: [3, 3]
Why:    3 appears twice in each list
2 more examples and the constraints

Example 2

Input:  nums1 = [6, 2, 8], nums2 = [8, 6, 8, 6, 1]
Output: [6, 8]
Why:    nums1 has one 6 and one 8, so each counts once

Example 3

Input:  nums1 = [1, 2], nums2 = [3, 4]
Output: []
Why:    no value is in both lists

Constraints

  • 1 ≤ length of nums1, length of nums2 ≤ 1,000
  • 0 ≤ every number ≤ 1,000

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Brute forceO(n·m)
  2. Sort + two pointersO(n log n)
  3. Count, then matchO(n + m)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for 1,000 numbers in each listVerdict
Brute forceO(n·m)
Mention it, then move on
Sort + two pointersO(n log n)
Best if already sorted
Count, then matchO(n + m)
Best; two passes, done

n = length of nums1, m = length of nums2.

Edge cases to test

  • Nothing in common. [1, 2] and [3, 4] give an empty list, not an error.
  • Repeats on one side only. [2, 2, 2, 2] and [2, 2] give [2, 2]: the smaller count wins.
  • Zero is a value. [0, 0, 1] and [0, 1000, 0, 0] give [0, 0]; a count of 0 is not the same as a missing key in every language.
  • One number each. [5] and [5] give [5]; [5] and [6] give [].

Common mistakes

  • Using a set, which drops repeats and returns [3] instead of [3, 3].
  • Not lowering the count after a match, so a value is added more times than nums1 has it.
  • In the brute force, letting two numbers pair with the same copy in nums2.

How to talk through it

  1. 1Clarify. Do repeats count? Does the order of the answer matter? Are the lists sorted?
  2. 2Give the brute force. Scan nums2 for an unused copy of each number; say it is O(n·m).
  3. 3Count copies. A map from value to copies left makes each match O(1) and handles repeats.
  4. 4Answer the follow-ups. Sorted input: two pointers. Small nums1: count it. Huge nums2: stream it through the count.
  5. 5Test out loud. Run the repeats case [2, 2, 2, 2] with [2, 2] and the no-overlap case.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?