Tags

  • AWS (7)
  • Apigee (3)
  • ArchLinux (5)
  • Array (6)
  • Backtracking (6)
  • BinarySearch (6)
  • C++ (19)
  • CI&CD (3)
  • Calculus (2)
  • DesignPattern (43)
  • DisasterRecovery (1)
  • Docker (8)
  • DynamicProgramming (20)
  • FileSystem (11)
  • Frontend (2)
  • FunctionalProgramming (1)
  • GCP (1)
  • Gentoo (6)
  • Git (15)
  • Golang (1)
  • Graph (10)
  • GraphQL (1)
  • Hardware (1)
  • Hash (1)
  • Kafka (1)
  • LinkedList (13)
  • Linux (27)
  • Lodash (2)
  • MacOS (3)
  • Makefile (1)
  • Map (5)
  • MathHistory (1)
  • MySQL (21)
  • Neovim (10)
  • Network (66)
  • Nginx (6)
  • Node.js (33)
  • OpenGL (6)
  • PriorityQueue (1)
  • ProgrammingLanguage (9)
  • Python (10)
  • RealAnalysis (20)
  • Recursion (3)
  • Redis (1)
  • RegularExpression (1)
  • Ruby (19)
  • SQLite (1)
  • Sentry (3)
  • Set (4)
  • Shell (3)
  • SoftwareEngineering (12)
  • Sorting (2)
  • Stack (4)
  • String (2)
  • SystemDesign (13)
  • Terraform (2)
  • Tree (24)
  • Trie (2)
  • TwoPointers (16)
  • TypeScript (3)
  • Ubuntu (4)
  • Home

    [LeetCode 41] First Missing Positive

    Published Dec 17, 2021 [  Set  ]

    Problem

    Given an unsorted integer array nums, return the smallest missing positive integer.

    You must implement an algorithm that runs in O(n) time and uses constant extra space.

    Example 1:

    Input: nums = [1,2,0]
    Output: 3
    

    Example 2:

    Input: nums = [3,4,-1,1]
    Output: 2
    

    Example 3:

    Input: nums = [7,8,9,11,12]
    Output: 1
    

    Constraints:

    - 1 <= nums.length <= 5 * 105
    - -231 <= nums[i] <= 231 - 1
    

    Javascript

    /**
     * @param {number[]} nums
     * @return {number}
     */
    var firstMissingPositive = function(nums) {
    
    	// update all negative numbers to 0, since they will not affect the final result
    	for(let i = 0; i < nums.length; i++){
    		if(nums[i] < 0) {
    			nums[i] = 0
    		}
    	}
    
        // we will mark index i as negative, indicating i + 1 exists in array, thus using the array as Set
    	for(let i = 0; i < nums.length; i++) {
    		let val = Math.abs(nums[i])
    		if(1 <= val && val <= nums.length) {
    			if(nums[val - 1] > 0) {
    				nums[val - 1] *= -1
    			} else if(nums[val - 1] === 0) {
    				nums[val - 1] = -1 * (nums.length + 1)
    			}
    		}
    	}
    
        // in solution set, we loop from the smallest possible value and check for positive or 0 values
    	for(let i = 1; i < nums.length + 1; i++) {
    		if(nums[i - 1] >= 0) {
    			return i
    		}
    	}
    
    	return nums.length + 1
    };
    

    Reference