Last updated on October 10th, 2024 at 02:11 am
Here, We see First Missing Positive LeetCode Solution. This Leetcode problem is done in many programming languages like C++, Java, JavaScript, Python, etc., with different approaches.
List of all LeetCode Solution
Topics
Array, Hash Table
Level of Question
Hard
First Missing Positive LeetCode Solution
Table of Contents
Problem Statement
Given an unsorted integer array nums, return the smallest missing positive integer.
Example 1: Input: nums = [1,2,0] Output: 3 Explanation: The numbers in the range [1,2] are all in the array. Example 2: Input: nums = [3,4,-1,1] Output: 2 Explanation: 1 is in the array but 2 is missing.
Example 3: Input: nums = [7,8,9,11,12] Output: 1 Explanation: The smallest positive integer 1 is missing.
1. First Missing Positive Leetcode Solution C++
class Solution { public: int firstMissingPositive(vector<int>& nums) { int n=nums.size(); for(int i=0 ; i<n ; i++) { while(nums[i]>0 and nums[i]<=n and nums[i]!=nums[nums[i]-1]) swap(nums[i],nums[nums[i]-1]); } for(int i=0 ; i<n ; i++) if(nums[i] != i+1) return i+1; return n+1; } };
2. First Missing Positive Leetcode Solution Java
class Solution { public int firstMissingPositive(int[] nums) { int n = nums.length; boolean[] exists = new boolean[n]; for (int num : nums) { if (num > 0 && num <= n) exists[num - 1] = true; } for (int i = 0; i < exists.length; i++) { if (!exists[i]) return i + 1; } return n + 1; } }
3. First Missing Positive Leetcode Solution JavaScript
var firstMissingPositive = function(nums) { for (let i = 0; i < nums.length; i++) { let idx = nums[i]-1; if (i == idx || nums[i] == nums[idx]) continue; if (idx >= 0 && idx <= nums.length - 1) { [nums[i], nums[idx]] = [nums[idx], nums[i]]; i--; } } for (let i = 0; i < nums.length; i++) { if (i+1 == nums[i]) continue; else return i+1; } return nums.length + 1; };
4. First Missing Positive Leetcode Solution Python
class Solution(object): def firstMissingPositive(self, nums): unique = set(nums) i = 1 while i in unique: i += 1 return i