First Missing Positive
Master this topic with zero to advance depth.
First Missing Positive
The missing positive must be in the range [1, n+1]. We can use the array itself to store presence information by placing each number x at index x-1. This is a constant space alternative to a HashSet.
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 constant extra space.
Visual Representation
nums = [3, 4, -1, 1]
Cyclic Sort (Move nums[i] to index nums[i]-1):
1. swap(3, -1) -> [-1, 4, 3, 1]
2. swap(4, 1) -> [-1, 1, 3, 4]
3. swap(-1, 1) -> [1, -1, 3, 4]
Result:
Index 0: 1 (Correct)
Index 1: -1 (Incorrect! Should be 2)
Return: 2Examples
The numbers in the range [1,2] are all in the array. 3 is the smallest missing positive.
1 is in the array, but 2 is missing.
Level I: Brute Force (Sorting)
Intuition
Sort the input array. Since we are looking for the smallest missing positive integer (starting from 1), iterate through the sorted array and keep track of a target (starting at 1). If the current number equals target, increment target. If we find a number greater than target or reach the end, target is the answer.
Detailed Dry Run
| nums | target | Action |
|---|---|---|
| [3,4,-1,1] | 1 | Sort -> [-1,1,3,4] |
| -1 | 1 | Skip (not positive) |
| 1 | 1 | Match! target -> 2 |
| 3 | 2 | 3 > 2, Stop. |
| Result: 2 | - | - |
Level II: Better Solution (HashSet)
Intuition
Store all numbers in a HashSet for O(1) lookups. Iterate from 1 up to N+1 (where N is array size). The first number not present in the set is the smallest missing positive integer.
Detailed Dry Run
| Set | Checking | Found? |
|---|---|---|
| {1, 2, 0} | 1 | Yes |
| {1, 2, 0} | 2 | Yes |
| {1, 2, 0} | 3 | No! Result=3 |
Level III: Optimal Solution (Cyclic Sort)
Intuition
Use the array itself as a 'hash map'. Since the answer must be in the range [1, N+1], try to place every number x in the range [1, N] at index x-1. For example, 1 should be at index 0, 2 at index 1, etc. After one pass of swapping, the first index i where nums[i] != i+1 gives the missing number.
Detailed Dry Run
Cyclic Sort Visualization
nums = [3, 4, -1, 1]
1. nums[0]=3: Swap with nums[2] -> [-1, 4, 3, 1]
2. nums[1]=4: Swap with nums[3] -> [-1, 1, 3, 4]
3. nums[1]=1: Swap with nums[0] -> [1, -1, 3, 4]
4. Done! nums[1] is -1, which is not 1+1=2. Answer: 2Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.