The example shows this is an intersection with duplicates: 2 appears twice in both arrays, so it appears twice in the answer. A Set can't do that; you need counts. Build a Map from value to how many times it occurs in the second array. Then walk the first array: if the count for the element is above zero, add it to the result and decrease the count. Each match uses one occurrence up, so a value is reported the smaller of its two counts. That's O(n + m) time and O(m) space, against O(n × m) for nested loops with includes. If both arrays are already sorted, two pointers do it with no extra memory. For the matrix follow-up, ask what's meant: common to every row of one matrix (keep the minimum count per value across rows) or common to two matrices (flatten both and do the same thing).
Find common elements between two arrays — e.g. arr1 = [1, 2, 2, 4, 5], arr2 = [3, 2, 4, 2] → [2, 2, 4]. Follow-up: extend to matrices instead of two arrays.
Answer it out loud, in your own words. Then compare.
Interviewers listen for how you get there, not only where you land. The answer opens once you have tried.
left holds how many of each value the second array still has to offer. Walking the first array, a value with a positive count is common: push it and take one away. When the count reaches zero, further copies in the first array no longer match. The result follows the order of the first array. Map compares keys the way includes does, so NaN matches NaN, and the number 1 is not the string '1'.
// Count what's in the second array. Walk the first: an element is common while the count for// it is above zero, and each match uses one up. So duplicates match as many times as both have.function common(a, b) {const left = new Map();for (const x of b) left.set(x, (left.get(x) ?? 0) + 1);const out = [];for (const x of a) {const n = left.get(x);if (n > 0) {out.push(x);left.set(x, n - 1);}}return out;}
passes 6 checks run on every build, against the native method where there is one
- the example: duplicates match as often as both arrays have them
- a value repeated more on one side counts the smaller number
- order follows the first array
- nothing in common, and empty arrays
- strings, NaN, and no mixing of 1 with '1'
- the inputs are not changed
If both arrays are sorted, move two pointers: advance the one at the smaller value, and when the values are equal take it and advance both. That's O(n + m) time with no map, and duplicates work naturally. For more than two arrays, fold the two-array step across them: the running result is intersected with each next array in turn, so the final counts are the minimum across all of them.
// Two more shapes of the same question.// Sorted input: two pointers, no extra memory besides the result.function commonSorted(a, b) {const out = [];let i = 0;let j = 0;while (i < a.length && j < b.length) {if (a[i] < b[j]) i++;else if (a[i] > b[j]) j++;else {out.push(a[i]);i++;j++;}}return out;}// Any number of arrays: fold the two-array version across them.function common(first, ...rest) {if (first === undefined) return [];return rest.reduce((acc, next) => {const left = new Map();for (const x of next) left.set(x, (left.get(x) ?? 0) + 1);return acc.filter((x) => {const n = left.get(x);if (!(n > 0)) return false;left.set(x, n - 1);return true;});}, [...first]);}
passes 10 checks run on every build, against the native method where there is one
- the example: duplicates match as often as both arrays have them
- a value repeated more on one side counts the smaller number
- order follows the first array
- nothing in common, and empty arrays
- strings, NaN, and no mixing of 1 with '1'
- the inputs are not changed
- common across three or more arrays
- one array is common with itself; none gives []
- commonSorted: same answer on sorted input
- commonSorted: strings in sorted order work too
"Extend to matrices" usually means elements common to every row: start with the counts of the first row and, for each later row, lower every count to what that row has, deleting values that are absent. Stopping early when nothing is left avoids reading the rest. The other reading, common to two matrices, ignores position, so both are flattened and treated as two long arrays. Both are linear in the number of cells.
// The follow-up, "matrices instead of arrays". Two readings; ask which one is meant.function countsOf(list) {const counts = new Map();for (const x of list) counts.set(x, (counts.get(x) ?? 0) + 1);return counts;}// 1. Elements common to EVERY row of one matrix. Keep, for each value, the smallest count seen// in any row; a value missing from a row drops out. O(cells) time.function commonInRows(matrix) {if (matrix.length === 0) return [];const keep = countsOf(matrix[0]);for (let r = 1; r < matrix.length && keep.size > 0; r++) {const row = countsOf(matrix[r]);for (const [value, n] of keep) {const m = Math.min(n, row.get(value) ?? 0);if (m === 0) keep.delete(value);else keep.set(value, m);}}// Report in the order of the first row.const out = [];for (const x of matrix[0]) {const n = keep.get(x);if (n > 0) {out.push(x);keep.set(x, n - 1);}}return out;}// 2. Elements common to two matrices: position doesn't matter, so flatten and reuse the idea.function commonInMatrices(a, b) {const left = countsOf(b.flat());return a.flat().filter((x) => {const n = left.get(x);if (!(n > 0)) return false;left.set(x, n - 1);return true;});}
passes 9 checks run on every build, against the native method where there is one
- commonInRows: values present in every row
- commonInRows: the smallest count across rows wins
- commonInRows: a value missing from one row drops out
- commonInRows: one row, no rows, an empty row
- commonInRows: stops reading rows once nothing is left in common
- commonInRows: order of the first row
- commonInMatrices: position doesn't matter, counts do
- commonInMatrices: rows of different lengths
- the inputs are not changed
Shared tags, permissions, cart items
Comparing two lists for overlap is everyday code: tags two posts share, permissions a role and a route both list, items in two carts. With quantities it's this multiset version.
Set.prototype.intersection
For values without duplicates the platform now has it built in: new Set(a).intersection(new Set(b)). It can't keep repeated values, which is why this question needs counts.
lodash.intersection
The library function returns unique shared values across any number of arrays, in the order of the first: the set version of the intermediate stage.
Using a
Set, which returns[2, 4]and loses the second 2.a.filter((x) => b.includes(x)): O(n × m), and it returns a value as many times as the first array has it, even if the second has it once.Mutating the input (splicing matched items out of the second array) without saying so.
Sorting the caller's arrays in place to use two pointers.
Assuming the answer's order without asking: first array's order, second's, or sorted.
A plain object as the counter, which turns the number 1 and the string '1' into the same key.
What if one array is far larger than the other?
Build the map from the smaller one, so memory is O(min(n, m)). If the large one is sorted, binary search each element of the small one in it: O(m log n).
What if the arrays hold objects?
A Map compares objects by identity, so two equal-looking objects don't match. Map each to a key first (an id, or a stable serialisation) and count the keys.
What if the data doesn't fit in memory?
Sort both on disk and stream them through the two-pointer merge, which needs only the current element of each.
How would you return each common value once?
Use sets: new Set(a).intersection(new Set(b)), or filter one set by membership in the other.
- developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map
- developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set/intersection
- developer.mozilla.org/en-US/docs/Web/JavaScript/Equality_comparisons_and_sameness#same-value-zero_equality
- developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flat
- lodash.com/docs/4.17.15#intersection