Skip to content

268.MissingNumber

Problem Statement

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

Approach
  1. Calculate Sum
    1. sum = n * (n-1)/2 where n is nums.size()+1
    2. forEach the numbers array and subtract values
    3. The sum you have at the end is the result
  2. XOR
  3. SORT

Detailed Reference -> LeetCode Article

Code
class Solution {
public:
    int missingNumber(vector<int>& nums) {
        int n = nums.size()+1;
        long long sum = n * (n-1)/2;
        for(auto a : nums)
            sum -= a;
        return sum;
    }
};