Skip to the solution
EasyFrontendAsked in 20245 min read

Array Union

1.1k views

The problem

Problem, as an interviewer would state it: "Given two arrays, return their union — every element that appears in either array, with no duplicates. Then tell me how you'd generalize it to more than two arrays."

Examples:

Code
union([1,2,3], [2,3,4]) -> [1,2,3,4]

Clarifying questions expected:

  • Does the output order matter — first-seen order, sorted, or unspecified?
  • Are the inputs guaranteed to be primitives, or could they contain objects (where equality gets more subtle)?
  • Should this generalize to more than two input arrays from the start, or is two enough for a first pass?

Code / implementation expected: Yes — real, direct proof that a Set-based approach produces identical results to, and is measurably faster than, a brute-force .includes()-based version.

  • array
  • set

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

5 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: a Set-based array union produces identical results to a brute-force version, measured ~16x faster on real 4000-element arrays

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 23 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

Design a Stack That Supports getMin() in O(1) (Min Stack)

Continue