Skip to the solution
MediumDSA6 min read

Implement difference(a, b) — elements in a not in b

198 views

The problem

Problem, as an interviewer would state it: "Implement difference(a, b) — returning every element of a that does NOT appear anywhere in b, preserving a's own original relative order, matching lodash's own well-known _.difference behavior."

Examples:

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

Clarifying questions expected:

  • Is this a genuinely ASYMMETRIC operation — elements in a but not b, as opposed to a full, symmetric set difference (in either but not both)?
  • Should the result preserve a's own original relative order?
  • What real, efficient lookup structure should be used to check membership in b, avoiding a naive nested-loop approach?

Code / implementation expected: Yes — real, direct proof of basic asymmetric difference, confirmation a's own order is preserved, and confirmation of the correct, real "b contains everything" edge case.

  • set
  • difference
  • array

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: difference() correctly returns elements unique to a, preserving a's own original relative order via a Set-based O(1) membership check against b

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 121 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 nextMedium

Polyfill Function.prototype.bind (with new support)

Continue