Skip to the solution
EasyDSA6 min read

Implement intersection of arrays (with duplicates & order)

560 views

The problem

Problem, as an interviewer would state it: "Implement intersection(a, b) — returning every element common to BOTH arrays, respecting real MULTIPLICITY (an item appearing twice in both should appear twice in the result), and preserving array a's own relative order."

Examples:

Code
intersection([1,2,2,3], [2,2,4]); // [2,2]

Clarifying questions expected:

  • If an element appears multiple times in BOTH arrays, does the result need to genuinely reflect that multiplicity, or should it be de-duplicated to a single occurrence?
  • Which array's own relative order should the result preserve — array a's, array b's, or does it not matter?
  • What is the real, correct count when array a has fewer copies of an item than array b does (or vice versa)?

Code / implementation expected: Yes — real, direct proof that multiplicity is respected (not collapsed to a set-style intersection), and that array a's own relative order is preserved in the result.

  • array
  • intersection

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

6 min read · 9 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

JavaScriptReal, direct proof: intersection() respects real multiplicity across both arrays while preserving array a's own relative element order

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 36 of 154 in JavaScript coding

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

Up nextEasy

Implement groupBy(array, iteratee) — lodash style

Continue