Skip to the solution
EasyDSA11 min read

How do you find the missing number in 0..n?

871 views

The problem

Question presented to candidate: "You get a list of n distinct integers taken from the range 0 to n, so exactly one value in that range is missing. Write a Python function that returns it, and tell me the time and space cost."

What a strong answer should cover:

  • The sum formula n * (n + 1) // 2 - sum(nums) and why it works (the range is fully known in advance).
  • The XOR alternative and the cancelling property a ^ a == 0.
  • O(n) time and O(1) extra space for both, versus O(n log n) for sorting and O(n) memory for a set.
  • Python specifics: ints never overflow, // keeps the result an int (plain / gives a float), and sum() and enumerate() keep it short.
  • Edge cases: missing value is 0 or n, single element.

Clarifying questions expected:

  • "Are the values distinct, and is exactly one missing?" β€” the sum and XOR tricks depend on it.
  • "Is the range 0..n or 1..n, and how large can n get?" β€” changes the formula and whether it overflows.

Code / implementation expected: Yes β€” a short function in Python; the sum version is two lines.

  • arrays
  • math

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

11 min read Β· 12 sections

Python code

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

PythonSum, XOR and hash set on the standard cases
PythonWhat 32-bit overflow does to the sum formula

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 11 of 154 in DSA

Keep your momentum going.

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

All DSA questions
Up nextEasy

How do you find the best time to buy and sell a stock?

Continue