LC 268. Missing Number

Nilanjan Deb · April 1, 2020

This is a very easy question. I sorted them first then traversing over it and when encounter a difference not equal to one simply return the corresponding number. I hope it is easy to implement. Don’t forget about corner Cases.

This is my CPP solution.

class Solution {
public:
    int missingNumber(vector<int>& nums) {
        if(nums.size()==0){
            return 0;
        }
        if(nums.size()==1 && nums[0] == 0){
            return 1;
        }
        sort(nums.begin(),nums.end());
        int pos = 0;
        for(int i=0;i<nums.size()-1;i++){
            if(nums[i+1]-nums[i]!=1){
                pos = i+1;
            }
        }
        if(nums[0]==0 && pos==0){
            return nums.size();
        }
        return pos;
    }
};

Time Complexity O(nlogn); Space Complexity O(1);



Dicussion Forum