</>

268. Missing Number

Easy NeetCode 150
Bit Manipulation Time O(n) Space O(1)
↗ Open on LeetCode Source: Standard solution only

Quick review

Pattern
Bit Manipulation
Time
O(n)
Space
O(1)

Standard Solution (C++)

SummaryGiven an array containing n distinct numbers drawn from 0..n, return the single value in that range that is absent.

Approach

Key idea: XOR every index from 0..n together with every array element. Each present value cancels with its index, leaving only the missing number.

Steps:

  • Start with result = n (covers the top index since the array has only n elements).
  • XOR each index i and each nums[i] into the result.
  • The remaining value is the missing number.
class Solution {
public:
    int missingNumber(vector<int>& nums) {
        int result = nums.size();
        for (int i = 0; i < (int)nums.size(); ++i) {
            result ^= i ^ nums[i];
        }
        return result;
    }
};
Time O(n) Space O(1)

A canonical reference solution. Problem statement © LeetCode — see the official link above.

▶ Run it — editable in-browser playground with a sample driver C++

Your solution plus an auto-generated main() and sample input so Run produces output. The driver and inputs are unverified — edit freely; Reset restores this starting point.

C++ ▶ Runnable Auto-generated driver with sample input — unverified.

Runs in a free public sandbox (Wandbox). Output and timing include network latency; don't paste secrets.

Related — same pattern