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), andsum()andenumerate()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.