Algo-Sim › Matrix & Bit Manipulation

Missing Number

Easy · Matrix & Bit Manipulation · step through it in Java, Python and C++ on your own input

n distinct numbers from 0..n, one missing. XOR the indices, the values and n: everything present cancels in pairs.

Problem

The array nums holds n distinct numbers taken from the range 0..n, so exactly one number of that range is missing. Return it.

Constraints

Edge cases to test

Follow-up questions

What about the sum formula?
n(n + 1)/2 − sum works but can overflow 32 bits for big n; XOR can’t overflow.
What if two numbers are missing?
XOR gives a ^ b; split by its lowest set bit as in Single Number III. Or use the sum and the sum of squares.

Solution

Java

public int missingNumber(int[] nums) {
    int missing = nums.length;
    for (int i = 0; i < nums.length; i++) {
        missing ^= i ^ nums[i];
    }
    return missing;
}

Python

def missing_number(nums):
    missing = len(nums)
    for i, num in enumerate(nums):
        missing ^= i ^ num
    return missing

C++

#include <bits/stdc++.h>
using namespace std;

class Solution {
  public:
    int missingNumber(vector<int> &nums) {
        int missing = int(nums.size());
        for (int i = 0; i < int(nums.size()); i++) {
            missing ^= i ^ nums[i];
        }
        return missing;
    }
};

More Matrix & Bit Manipulation problems