First Missing Positive⚓︎
Description⚓︎
Given an unsorted integer array nums
, return the smallest missing positive integer.
You must implement an algorithm that runs in \(O(n)\) time and uses \(O(1)\) auxiliary space.
Example 1:
- Input:
nums = [1,2,0]
- Output:
3
- Explanation:
The numbers in the range [1,2] are all in the array.
Example 2:
- Input:
nums = [3,4,-1,1]
- Output:
2
- Explanation:
1 is in the array but 2 is missing.
Example 3:
- Input:
nums = [7,8,9,11,12]
- Output:
1
- Explanation:
The smallest positive integer 1 is missing.
Constraints:
1 <= nums.length <= 10^5
-2^31 <= nums[i] <= 2^31 - 1
Solution⚓︎
Step 1: Rearrange the Array
- Iterate through each element in the array using a loop.
- For each element
nums[i]
, if it is a positive integer and within the range[1, n]
(inclusive) and is not already in its correct position (i.e.,nums[nums[i] - 1] != nums[i]
), then swap it with the element at its "correct" position (nums[nums[i] - 1]
). - This swapping continues in a
while
loop until either the current element is negative, out of the range[1, n]
, or already in its correct position. This ensures that, at the end of this step, every positive integerx
that is less than or equal ton
and appears in the array is placed at indexx-1
.
Step 2: Find the Missing Integer
- After rearranging, iterate through the array again.
- Check if
nums[i]
is equal toi + 1
for eachi
. If for anyi
,nums[i] != i + 1
, it meansi + 1
is the smallest missing positive integer, so returni + 1
. - If all positions are correctly occupied, it means the array contains all integers from
1
ton
. Therefore, the smallest missing positive integer isn + 1
.