JavaScript simple solution - with inline explanation


  • 0
    D
    /**
     * @param {number[]} nums
     * @return {number}
     */
     
     
    var firstMissingPositive = function(nums) {
        
        if(nums.length == 0){
            return 1;
        }
      
      let N = nums.length;
      
      for(let i = 0; i < N; i++){
        
        // if num is at its true place continue..
        // if it null or undefined.. continue.. it might be a potential answer
        if(!nums[i] || nums[i] == i){
          continue;
        }
        
        // negative numbers are replaced by nulls.. place is made for true numbers there
        if(nums[i] < 0){
            nums[i] = null;
        }
        
        // if number is not in its true position.. swap it to its right position
        if(nums[nums[i]] != nums[i]){
          swap(i, nums[i]);
          i--;
        } else {
          nums[i] = null; // make it null if there's duplicate
        }
      }
    
    
        // iterate N numbers and find the first missing number.. that is the required missing number
        let i = 1;
       while(i <= N){
            if(!nums[i]){
              console.log(i);
              return i;
          }
    
          i++;
       }
    
        
    
      
        // program has come here.. it means all the numbers are present in the array.. so return the N + 1 th number
      return i;
      
      
      function swap(i,j){
        let temp = nums[i];
        nums[i] = nums[j];
        nums[j] = temp;
      }
      
      
        
    };
    
    
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.