First missing positive

Input: nums = [1,2,0]
Output: 3
Input: nums = [3,4,-1,1]
Output: 2
Input: nums = [7,8,9,11,12]
Output: 1
  • 1 <= nums.length <= 5 * 105
  • -2^31 <= nums[i] <= 2^31 - 1
loop from 1 to length of nums+1:
check if the number is present in the nums array
if number not present in nums :
return number
class Solution(object):
def firstMissingPositive(self, nums):
val=set(nums)
for i in range(1,len(nums)+2):

if i not in val and i>0:
return i
class Solution(object):
def firstMissingPositive(self, nums):
i=0
while(i<len(nums)):
if nums[i]<=0 or nums[i]>len(nums):
i+=1
else:
if nums[i]==i+1:
i+=1
else:
if nums[nums[i]-1]==nums[i]:
i+=1
else:
temp=nums[nums[i]-1]
nums[nums[i]-1]=nums[i]
nums[i]=temp
j=0
while(j<len(nums)):
if(j+1!=nums[j]):
return(j+1)
j+=1
return(len(nums)+1)

--

--

--

Tech-Enthusiast, Coder,Explorer,Geeky,Software Engineer |A piece of code delivers everything that you need. The world is all about codes.

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Recap: Day 1–8 | 100 Days Full-Stack Challenge

7 things we need to know about React

GitHub Issue, Awesome CMS for your personal blog

Skip Cypress tests using tags

Mocha- A Rich JavaScript Framework.

React — Google Maps Example Project

Destructure the Data in JavaScript

Creating Reusable Components in React: Render Props

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Dhanarajappu

Dhanarajappu

Tech-Enthusiast, Coder,Explorer,Geeky,Software Engineer |A piece of code delivers everything that you need. The world is all about codes.

More from Medium

LeetCode 129. Sum Root to Leaf Numbers

Why coding still matters

Why should we study algorithms? — [Introduction to Algorithms]