Skip to content

Commit a47b7b5

Browse files
committed
added First Missing Positive (hard)
1 parent 86510e6 commit a47b7b5

File tree

3 files changed

+55
-0
lines changed

3 files changed

+55
-0
lines changed
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
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)**.
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
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))

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff 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

0 commit comments

Comments
 (0)