150NeetCode 150

148.Missing Number

EasyBlind 75Bit Manipulation ยท 5/7

Problem

Given an array nums containing n distinct numbers taken from the range [0, n], return the only number in the range that is missing from the array.

Follow-up: can you solve it using only O(1) extra space and O(n) time?

Examples

Input:  nums = [3, 0, 1]
Output: 2
Explanation: n = 3, so the range is [0, 3]. 2 is the only number not in nums.
Input:  nums = [0, 1]
Output: 2
Explanation: n = 2, so the range is [0, 2]. 2 is missing.
Input:  nums = [9, 6, 4, 2, 3, 5, 7, 0, 1]
Output: 8

Constraints

  • n == nums.length
  • 1 <= n <= 10^4
  • 0 <= nums[i] <= n
  • All the numbers of nums are unique.

๐Ÿ’ก Key Insight

We know exactly which numbers should be present: 0, 1, ..., n. Combine the expected set and the actual array with an operation that cancels matching values โ€” subtraction of sums (n(n+1)/2 - sum(nums)) or XOR (x ^ x = 0). Everything cancels except the missing number, using O(1) space.

Brute Force

TimeO(nยฒ)SpaceO(1).

Intuition

Check each candidate 0..n one by one, scanning the array to see if it is present. The first candidate not found is the answer.

Algorithm

  1. For candidate from 0 to n:
    • Scan nums; if candidate is not found, return it.
  2. (Unreachable) return -1.

Visualization

nums = [3, 0, 1]
candidate 0 โ†’ found โœ“
candidate 1 โ†’ found โœ“
candidate 2 โ†’ not found โ†’ return 2

Code

java
class Solution {
    public int missingNumber(int[] nums) {
        int n = nums.length;
        for (int candidate = 0; candidate <= n; candidate++) {
            boolean found = false;
            for (int num : nums) {
                if (num == candidate) {
                    found = true;
                    break;
                }
            }
            if (!found) {
                return candidate;
            }
        }
        return -1; // not reached for valid input
    }
}

Complexity

  • Time: O(nยฒ) โ€” up to n + 1 candidates, each with an O(n) scan.
  • Space: O(1).

Complexity Comparison

Approach Time Space
Brute Force O(nยฒ) O(1)
Hash Set O(n) O(n)
Gauss Sum O(n) O(1)
XOR O(n) O(1)

Common Pitfalls

  • Forgetting that the range is [0, n] (size n + 1), not [1, n] โ€” the missing number can be 0 or n.
  • In the XOR solution, forgetting to include n itself โ€” then an input like [0, 1] would wrongly return 0 instead of 2.
  • Overflow in the sum formula for large n (n(n+1)/2 exceeds int around n โ‰ˆ 65,000) โ€” fine here, but use long or XOR in general.
  • Sorting first and scanning for a gap works but costs O(n log n) and mutates the input.