Skip to content

Commit 6b71ab4

Browse files
committed
[Feature] Added first missing positive algorithm.
1 parent 1362587 commit 6b71ab4

File tree

2 files changed

+32
-0
lines changed

2 files changed

+32
-0
lines changed
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
def first_missing_positive(nums):
2+
"""
3+
:type nums: List[int]
4+
:rtype: int
5+
"""
6+
start = 0
7+
end = len(nums) - 1
8+
while start <= end:
9+
i = nums[start] -1
10+
if i == start:
11+
start += 1
12+
elif i < 0 or i > end or nums[start] == nums[i]:
13+
nums[start] = nums[end]
14+
end -= 1
15+
else:
16+
nums[start] = nums[i]
17+
nums[i] = i + 1
18+
return start + 1

tests/test_first_missing_positive.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
import unittest
2+
from algorithms.math.first_missing_positive import first_missing_positive
3+
4+
class TestFirstMissingPositive(unittest.TestCase):
5+
6+
def test_in_order(self):
7+
self.assertEqual(6,first_missing_positive([1,2,3,4,5]))
8+
self.assertEqual(6,first_missing_positive([0,1,2,3,4,5]))
9+
10+
def test_with_negatives(self):
11+
self.assertEqual(7,first_missing_positive([-1,0,-3,6,-5,2,5,3,4,-9,0,1]))
12+
13+
def test_filled_with_zeros(self):
14+
self.assertEqual(3,first_missing_positive([0,0,0,1,0,0,0,0,0,2,0,0,0,0]))

0 commit comments

Comments
 (0)