Intersection of Two Arrays

Easy · Arrays & Hashing · Array · Hash Table · Two Pointers · Sorting

Problem

You are given two integer arrays nums1 and nums2.

Return an array of the values that appear in both arrays. Each value in the result must be unique, even if it appears several times in the inputs, and the result may be in any order.

Examples

Input: nums1 = [3,1,3,8], nums2 = [8,3,3]
Output: [3,8]

3 and 8 are common; 3 is listed once even though it repeats.

Input: nums1 = [5,6], nums2 = [7]
Output: []

No value is shared.

Input: nums1 = [0,2,4,6], nums2 = [6,5,4,0]
Output: [0,4,6]

0, 4 and 6 appear in both arrays. Any order is accepted.

Constraints

Approaches

Follow-up

What if a value should appear as many times as it occurs in both arrays? Count with a dictionary instead of a set and decrement on each match. And if nums2 is too large for memory? Stream it in chunks against a set of the smaller array, or sort both on disk and merge.

Related problems

Start free on Cariara · Coding problems · System design studio

Starting Python
No results yet.

          
↑↓ move ↵ open esc close

Labs

Loading labs…

Run with your own input

Starting Python

Loading Python…