Skip to the solution
MediumDSAAsked in 20245 min read

Array subset check

764 views

The problem

Problem, as an interviewer would state it: "Write isSubset(sub, sup) that returns whether every element of sub appears in sup. Discuss edge cases, runtime, and what subset should mean when there are duplicates."

Examples:

Code
isSubset([1, 2], [3, 2, 1]); // true
isSubset([1, 4], [1, 2, 3]); // false

Clarifying questions expected:

  • Set semantics (only presence matters) or multiset semantics (counts matter, so [1,1] is not a subset of [1])?
  • Is the empty array a subset of everything?
  • How are NaN, objects, and 1 versus "1" compared?

Code / implementation expected: Yes — real, direct proof against a brute-force reference, in both semantics.

  • js-coding
  • utility
  • algorithm

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: set and multiset subset checks match brute force on 20,000 random pairs, NaN is handled, and a Set beats nested includes

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

Implement Promise.allSettled()

Continue