|
1 | 1 | #Question: Given a list of ints, find the smallest missing positive number
|
2 | 2 | #Solution: Sort the list as you go through by placing every term on its index + 1th place.
|
3 | 3 | #Difficulty: Hard
|
| 4 | +#Time Complexity: O(n) |
| 5 | +#Space Complexity: O(1) |
4 | 6 |
|
5 | 7 | from typing import List
|
6 | 8 |
|
7 | 9 | def firstMissingPositive(nums: List[int]) -> int:
|
8 |
| - i, j = 0, len(nums) |
9 |
| - while i < j: |
| 10 | + i, j = 0, len(nums) |
| 11 | + while i < j: |
10 | 12 |
|
11 |
| - #If the current number is equal to its index + 1, skip over as its already sorted |
12 |
| - #ie if the number 5 is in the 4th index/ 5th place |
13 |
| - if nums[i] == i+1: i += 1 |
| 13 | + #If the current number is equal to its index + 1, skip over as its already sorted |
| 14 | + #for example if the number 5 is in the 4th index/ 5th place |
| 15 | + if nums[i] == i+1: i += 1 |
14 | 16 |
|
15 |
| - #Regular case, ie a number not in the correct place |
16 |
| - elif nums[i] > 0 and nums[i] <= j and nums[i] != nums[nums[i]-1]: |
17 |
| - nums[nums[i]-1], nums[i] = nums[i], nums[nums[i]-1] |
| 17 | + #Regular case, ie a number not in the correct place |
| 18 | + #In othe words, if a number n is within our range and the number in the nth position isnt equal to this number, swap the two |
| 19 | + elif nums[i] > 0 and nums[i] <= j and nums[nums[i]-1] != nums[i]: |
| 20 | + nums[nums[i]-1], nums[i] = nums[i], nums[nums[i]-1] |
18 | 21 |
|
19 |
| - #Case if the number is a duplicate, or out of our range (1 to j). So place it at the end |
20 |
| - else: |
21 |
| - j -= 1 |
22 |
| - nums[j], nums[i] = nums[i], nums[j] |
| 22 | + #Case if the number is a duplicate, or out of our range (1 to j). So place it at the end |
| 23 | + else: |
| 24 | + j -= 1 |
| 25 | + nums[j], nums[i] = nums[i], nums[j] |
23 | 26 |
|
24 |
| - return j + 1 |
| 27 | + return j + 1 |
25 | 28 |
|
26 | 29 | def main():
|
27 | 30 | print(firstMissingPositive([1, 5, 4, 3, 2, 7, 0]))
|
|
0 commit comments