Skip to content

Commit db80c8c

Browse files
committed
[Documentation] Added docs for getting the smallest positive integer.
1 parent 78f03fa commit db80c8c

File tree

1 file changed

+31
-5
lines changed

1 file changed

+31
-5
lines changed
Lines changed: 31 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,44 @@
11
def first_missing_positive(nums):
22
"""
3-
:type nums: List[int]
4-
:rtype: int
3+
Find the first missing positive integer in a list of integers.
4+
5+
This algorithm sorts the array by making swaps
6+
and ignoring elements that are greater than the length
7+
of the array or negative.
8+
9+
If the element is equal to the current index (start) then
10+
it is already in place.
11+
12+
If the element is < 0 or > len() or a duplicate, then pull
13+
in the last element.
14+
15+
Otherwise swap the current element into place with the
16+
element that is occupying it's appropriate place. Do this
17+
until the current value is the correct one for its place or
18+
the start and end have swapped.
19+
20+
Args:
21+
nums: list of integers
22+
23+
Returns:
24+
The first integer greater than 0 that is not
25+
present in the input list.
526
"""
627
start = 0
728
end = len(nums) - 1
829
while start <= end:
9-
i = nums[start] -1
30+
i = nums[start] - 1
31+
# if this element is in position
1032
if i == start:
1133
start += 1
34+
# if the element is negative or out of bounds
35+
# or a duplicate that is already sorted swap the
36+
# current element into the oob and dec the end
1237
elif i < 0 or i > end or nums[start] == nums[i]:
1338
nums[start] = nums[end]
1439
end -= 1
40+
# swap the element to where it should be
1541
else:
16-
nums[start] = nums[i]
17-
nums[i] = i + 1
42+
nums[start], nums[i] = nums[i], nums[start]
43+
1844
return start + 1

0 commit comments

Comments
 (0)