Coding problem · Easy · Basics

Intersection of Two Arrays

Easy Algorithms & data structures

Return the values that appear in both a and b, without duplicates, sorted in ascending order.

Example 1

Input: a = [1,2,2,1], b = [2,2]
Output: [2]

Example 2

Input: a = [4,9,5], b = [9,4,9,8,4]
Output: [4,9]

Hints

Hint 1

Put one array's values in a set.

Hint 2

Keep values of the other array that are in the set, then remove duplicates and sort.

Write and run your solution

Loading the editor… (JavaScript is required to run code in your browser.)

Solution and explanation

Show the solution

Time O(n + m + k log k) · Space O(n)

Build a set from a, collect values of b that are in it into a result set (removing duplicates), then sort.

Reference solution

function intersection(a, b) {
  const inA = new Set(a);
  return [...new Set(b.filter((x) => inA.has(x)))].sort((x, y) => x - y);
}

Was this page helpful?