InterviewPrepKit

Home / Coding / Algorithm & Data Structure / Bit Manipulation

Missing Number

easy Original ↗ 00:00

Problem

You are given an array nums of n distinct integers drawn from the range [0, n] (that range holds n + 1 values, so exactly one is absent). Return the single number in [0, n] that does not appear in nums.

Examples

  • [3, 0, 1]2n = 3, the full range is 0..3; 2 is missing.
  • [0, 1]2n = 2, the full range is 0..2; 2 is missing.
  • [9, 6, 4, 2, 3, 5, 7, 0, 1]8n = 9; every value 0..9 is present except 8.

Constraints

  • n == len(nums), 0 <= nums[i] <= n, and all nums[i] are distinct.
  • 1 <= n <= 10^4

Follow-up: O(n) time, O(1) extra space, and without any risk of integer overflow.

Think about it first

Hint 1 The array should contain every value in `0..n` but one. Put the present values in a set and find the one index in `0..n` that isn't there — correct, but O(n) space.
Hint 2 The numbers `0..n` have a known total, `n(n + 1) / 2`. Subtract the actual sum of `nums` and the missing value falls out — O(1) space, though the sum can overflow a fixed-width integer.
Hint 3 XOR is self-cancelling: `x ^ x = 0` and `x ^ 0 = x`. XOR together all the indices `0..n` and all the values in `nums`. Every present number shows up as both an index and a value and cancels itself; the missing number appears only as an index and survives — no overflow risk.

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug