Intersection of Two Arrays
Easy
Topics
Given two integer arrays a and b, return the values that appear in both. Each value appears once in the result, however many times it occurs in the inputs.
Return the values in ascending order.
LeetCode names the arguments nums1 and nums2 and accepts any order. The harness here calls them a and b, and asks for ascending order so the judge has a single answer to compare against.
Example 1
Input: a = [1,2,2,1], b = [2,2] Output: [2] Explanation: 2 is the only shared value, and it appears once in the result despite occurring twice in both inputs.
Example 2
Input: a = [4,9,5], b = [9,4,9,8,4] Output: [4,9] Explanation: Both 4 and 9 are shared, returned ascending.
Example 3
Input: a = [1,2,3], b = [4,5,6] Output: [] Explanation: Nothing is shared, so the result is empty.
Constraints
- 1 <= a.length, b.length <= 1000
- 0 <= a[i], b[i] <= 1000
Editorial — intuition, approach, complexity and pitfalls
Intuition
Membership is the only question being asked of b, so turn b into something that answers membership in constant time and then filter a through it. Scanning b once per element of a works and is quadratic, which the limits here tolerate but the habit does not deserve.
The word unique is doing real work. Filtering a directly would emit 2 twice for a = [1,2,2,1], so the duplicates have to be removed — either by collecting results into a set, or by reducing a to a set before filtering.
Making both inputs sets first is the clearest statement of the problem: the answer is the intersection of two sets, and the uniqueness falls out instead of being patched in.
The ascending order asked for here is a sort at the end. If the inputs were already sorted, two cursors advancing through them together would produce the answer in order with no extra memory — which is the version worth knowing, since it generalises to inputs too large to hold.
Approach
- Put the values of
binto a set. - Walk
a, keeping the values that are in that set, and collect them into a second set so each is kept once. - Sort the collected values ascending and return them.
- For the sorted-input variant: sort both arrays, run a cursor through each, advance the smaller one, and on a match record the value and advance both past all copies of it.
Walkthrough
a = [4,9,5], b = [9,4,9,8,4]
set of b: {4, 8, 9}
walk a
4 in set -> keep
9 in set -> keep
5 not in set
kept {4, 9}, sorted -> [4, 9]
why a set and not a list of kept values
a = [1,2,2,1], b = [2,2]
set of b: {2}
walk a: 1 no, 2 YES, 2 YES, 1 no
a list would hold [2, 2]; the answer is [2].Complexity
- Time — O(m + n log n): both arrays are scanned once; the sort is over the shared values only.
- Space — O(m + n): a set for b and a set for the shared values.
Common Pitfalls
- Emitting a value once per occurrence in
a. The result holds each value once. - Returning in input order. This statement asks for ascending.
- Confusing this with Intersection of Two Arrays II, where multiplicities are kept and the answer for
[1,2,2,1]and[2,2]is[2,2]. - Mutating an input array by sorting it when the caller still needs the original order.
- Using a list for the membership test, which turns a linear scan into a quadratic one.
Full Solution — all languages
class Solution:
def intersection(self, a, b):
in_b = set(b)
# Collecting into a set is what makes each value appear once, however
# many times it occurs in a.
shared = {x for x in a if x in in_b}
return sorted(shared)import java.util.*;
class Solution {
public int[] intersection(int[] a, int[] b) {
Set<Integer> inB = new HashSet<>();
for (int x : b) inB.add(x);
TreeSet<Integer> shared = new TreeSet<>();
for (int x : a) {
if (inB.contains(x)) shared.add(x);
}
int[] out = new int[shared.size()];
int i = 0;
for (int x : shared) out[i++] = x;
return out;
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: vector<int> intersection(vector<int>& a, vector<int>& b) {
unordered_set<int> inB(b.begin(), b.end());
set<int> shared;
for (int x : a) {
if (inB.count(x)) shared.insert(x);
}
return vector<int>(shared.begin(), shared.end());
}
};/**
* @param {number[]} a
* @param {number[]} b
* @return {number[]}
*/ var intersection = function(a, b) {
const inB = new Set(b);
const shared = new Set();
for (const x of a) {
if (inB.has(x)) shared.add(x);
}
return [...shared].sort((x, y) => x - y);
};