Skip to the solution
MediumDSAAsked in 20246 min read

Find missing number

2.2k views

The problem

Problem, as an interviewer would state it: "Given an array of n distinct numbers taken from 0..n, exactly one number is missing. Find it. Discuss edge cases, runtime, and alternative approaches."

Examples:

Code
findMissing([3, 0, 1]); // 2
findMissing([0, 1]);    // 2
findMissing([1]);       // 0

Clarifying questions expected:

  • Is the input guaranteed to be distinct, in range, and missing exactly one value?
  • Can I modify the array, and what space budget do I have?
  • How large can n be (does the arithmetic stay exact)?

Code / implementation expected: Yes — real, direct proof of each approach, and of the input assumptions each one silently depends on.

  • 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

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: sum, XOR and Set agree exhaustively for every size and gap up to n = 60 and at one million, with the numeric limits shown

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

Custom Set class with hash

Continue