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);
}
function intersection(a: number[], b: number[]): number[] {
const inA = new Set(a);
return [...new Set(b.filter((x) => inA.has(x)))].sort((x, y) => x - y);
}
def intersection(a: list[int], b: list[int]) -> list[int]:
return sorted(set(a) & set(b))
<?php
function intersection(array $a, array $b): array
{
$out = array_values(array_unique(array_intersect($a, $b)));
sort($out);
return $out;
}
class Solution {
public int[] intersection(int[] a, int[] b) {
java.util.Set<Integer> inA = new java.util.HashSet<>();
for (int x : a) inA.add(x);
java.util.TreeSet<Integer> both = new java.util.TreeSet<>();
for (int x : b) if (inA.contains(x)) both.add(x);
return both.stream().mapToInt(Integer::intValue).toArray();
}
}
More Basics problems
- Reverse a String · Easy
- Count the Vowels · Easy
- Capitalize Each Word · Easy
- Longest Word in a Sentence · Easy
- Run-Length Encoding · Easy
- Is It a Pangram? · Easy