***First Missing Positive (Leetcode 41) (DCP 4)
Problem Link: https://leetcode.com/problems/first-missing-positive/
class Solution:
def firstMissingPositive(self, nums: List[int]) -> int:
n=len(nums)
# Check for 1
for i in nums:
if(i==1):
break
else:
return 1
# Change the 0s, -ves and >n's to 1
# as we have already processed 1 above
for i in range(n):
if(nums[i]==0 or nums[i]<0 or nums[i]>n):
nums[i]=1
for i in range(n):
idx=abs(nums[i])-1
nums[idx]=-1*abs(nums[idx])
for i in range(n):
if(nums[i]>0):
return i+1
else:
return n+1
PreviousContainer with Most Water (Leetcode 11)NextProduct of Array Except Itself (Leetcode 238) (DCP 2)
Last updated