File tree Expand file tree Collapse file tree 3 files changed +55
-0
lines changed 
Hard/FirstMissingPositive Expand file tree Collapse file tree 3 files changed +55
-0
lines changed Original file line number Diff line number Diff line change 1+ 
2+ # First Missing Positive  
3+ [ Leetcode Link] ( https://leetcode.com/problems/first-missing-positive/ ) 
4+ 
5+ ## Problem:  
6+ 
7+ Given an unsorted integer array, find the smallest missing positive integer.
8+ 
9+ ## Example:  
10+ 
11+ ``` 
12+ Input: [1,2,0] 
13+ Output: 3 
14+ ``` 
15+ ``` 
16+ Input: [3,4,-1,1] 
17+ Output: 2 
18+ ``` 
19+ ``` 
20+ Input: [7,8,9,11,12] 
21+ Output: 1 
22+ ``` 
23+ 
24+ ## Note:  
25+ 
26+ Your algorithm should run in ** O(n) time**  and uses ** constant extra space O(1)** .
Original file line number Diff line number Diff line change 1+ from  typing  import  List 
2+ 
3+ class  Solution :
4+  def  firstMissingPositive (self , nums : List [int ]) ->  int :
5+  # mark negatives and zeros with number larger than len(nums) 
6+  for  i  in  range (len (nums )):
7+  if  nums [i ] <=  0 :
8+  nums [i ] =  len (nums )+ 1 
9+  print ("after marking useless numbers:" , nums )
10+  # use negative to mark positive integer has appeared 
11+  for  i  in  range (len (nums )):
12+  absolute  =  abs (nums [i ])
13+  if  absolute  <=  len (nums ):
14+  # in case of duplicate (to prevent more than one negation) 
15+  nums [absolute - 1 ] =  - nums [absolute - 1 ] if  nums [absolute - 1 ] >  0  else  nums [absolute - 1 ]
16+  print ("After marking positions:" , nums )
17+  # first positive position + 1 is the first missing positive, if none, then len(nums) + 1 is the first missing 
18+  for  i  in  range (len (nums )):
19+  if  nums [i ] >  0 :
20+  return  i + 1 
21+  return  len (nums )+ 1 
22+ 
23+ 
24+ # test driver 
25+ sol  =  Solution ()
26+ input  =  [4 , 0 , 1 , 2 , 0 ]
27+ print ("Input:" , input )
28+ print ("Output:" , sol .firstMissingPositive (input ))
Original file line number Diff line number Diff line change @@ -73,6 +73,7 @@ Languages used: Java and Python
7373 -  [ Maximum Score Words Formed by Letters] ( Hard/MaximumScoreWords ) 
7474 -  [ Reducing Dishes] ( Hard/ReducingDishes ) 
7575 -  [ Longest Consecutive Sequence] ( Hard/LongestConsecutiveSequence ) 
76+  -  [ First Missing Positive] ( Hard/FirstMissingPositive ) 
7677
7778--- 
7879
                                 You can’t perform that action at this time. 
               
                  
0 commit comments