First Missing Positive LeetCode Solution

Here, We see First Missing Positive problem Solution. This Leetcode problem is done in many programming languages like C++, Java, JavaScript, Python, etc., with different approaches.

First Missing Positive LeetCode Solution

First Missing Positive LeetCode Solution

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.

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; } };
Code language: C++ (cpp)

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; } }
Code language: Java (java)

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; };
Code language: JavaScript (javascript)

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
Code language: Python (python)