Skip to content

Commit 392d113

Browse files
committed
Sync LeetCode submission Runtime - 44 ms (54.52%), Memory - 28.7 MB (45.55%)
1 parent d3511b9 commit 392d113

File tree

2 files changed

+63
-0
lines changed

2 files changed

+63
-0
lines changed
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
<p>Given an unsorted integer array <code>nums</code>. Return the <em>smallest positive integer</em> that is <em>not present</em> in <code>nums</code>.</p>
2+
3+
<p>You must implement an algorithm that runs in <code>O(n)</code> time and uses <code>O(1)</code> auxiliary space.</p>
4+
5+
<p>&nbsp;</p>
6+
<p><strong class="example">Example 1:</strong></p>
7+
8+
<pre>
9+
<strong>Input:</strong> nums = [1,2,0]
10+
<strong>Output:</strong> 3
11+
<strong>Explanation:</strong> The numbers in the range [1,2] are all in the array.
12+
</pre>
13+
14+
<p><strong class="example">Example 2:</strong></p>
15+
16+
<pre>
17+
<strong>Input:</strong> nums = [3,4,-1,1]
18+
<strong>Output:</strong> 2
19+
<strong>Explanation:</strong> 1 is in the array but 2 is missing.
20+
</pre>
21+
22+
<p><strong class="example">Example 3:</strong></p>
23+
24+
<pre>
25+
<strong>Input:</strong> nums = [7,8,9,11,12]
26+
<strong>Output:</strong> 1
27+
<strong>Explanation:</strong> The smallest positive integer 1 is missing.
28+
</pre>
29+
30+
<p>&nbsp;</p>
31+
<p><strong>Constraints:</strong></p>
32+
33+
<ul>
34+
<li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li>
35+
<li><code>-2<sup>31</sup> &lt;= nums[i] &lt;= 2<sup>31</sup> - 1</code></li>
36+
</ul>
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
# Approach 3: Cycle Sort
2+
3+
# Time: O(n)
4+
# Space: O(1)
5+
6+
class Solution:
7+
def firstMissingPositive(self, nums: List[int]) -> int:
8+
n = len(nums)
9+
10+
i = 0
11+
while i < n:
12+
correct_idx = nums[i] - 1
13+
if 0 < nums[i] <= n and nums[i] != nums[correct_idx]:
14+
nums[i], nums[correct_idx] = nums[correct_idx], nums[i]
15+
else:
16+
i += 1
17+
18+
# Iterate through nums
19+
# return smallest missing positive integer
20+
for i in range(n):
21+
if nums[i] != i + 1:
22+
return i + 1
23+
24+
# If all elements are at the correct index
25+
# the smallest missing positive number is n + 1
26+
return n + 1
27+

0 commit comments

Comments
 (0)