First Missing Positive (LeetCode 41): Solution and Explanation
Given an unsorted integer array that may contain negatives, zeros, duplicates and huge values, return the smallest positive integer that does not appear in it. The solution must run in linear time and use only constant extra space.
Watch it run step by step
Try your own input and write the code →Intuition
Without the constraints, you would put every number into a hash set and then test 1, 2, 3 and so on until one is missing. That is O(n) time but O(n) space. Sorting first and scanning avoids the set but costs O(n log n). The problem demands both linear time and constant space, so neither is allowed.
The first key observation is a bound on the answer. An array of length n can contain at most n distinct positive integers, so if it holds exactly 1 through n, the answer is n + 1, and otherwise some number in 1 through n is missing. That means you only care about values in the range 1 to n. Negatives, zeros and anything larger than n can be ignored completely.
The second observation is that values 1 to n line up perfectly with indices 0 to n - 1. So the array itself can act as the lookup table: try to place each value v at index v - 1. Walk through the array, and while the current element is a value in range that is not already at its home, swap it there. The element that arrives at position i from the swap may itself need moving, so you check position i again instead of advancing. Once everything that can be placed is placed, scan from the left. The first index i whose value is not i + 1 reveals the missing number. Each swap puts one value in its final home, so there are at most n swaps overall.
Approach: Cyclic sort into home positions
- Let
n = len(nums)and start an indexiat 0. - Compute
correct_idx = nums[i] - 1, the home position for the current value. - If
0 < nums[i] <= nandnums[i] != nums[correct_idx], swapnums[i]into its home and stay atito process the newly arrived value. - Otherwise the value is out of range, already home, or a duplicate of what is home, so move on with
i += 1. - After placement, scan indices from 0. The first
iwherenums[i] != i + 1meansi + 1is missing, so return it. - If every position holds its own value, return
n + 1.
Step-by-step example
nums = [3, 4, -1, 1]
- At
i = 0, the value 3 belongs at index 2, which holds -1. Swap them to get [-1, 4, 3, 1] and stay at index 0. - Now -1 is out of range, so advance to
i = 1. The value 4 belongs at index 3, which holds 1. Swap to get [-1, 1, 3, 4]. - Still at
i = 1, the value 1 belongs at index 0, which holds -1. Swap to get [1, -1, 3, 4]. - At
i = 1, -1 is out of range, so advance. Indices 2 and 3 already hold 3 and 4, so the loop finishes. - The scan finds
nums[0] = 1correct, thennums[1] = -1, which is not 2. The function returns 2.
Code: Python, Java, C++
1class Solution:
2 def firstMissingPositive(self, nums: List[int]) -> int:
3 n = len(nums)
4 i = 0
5 while i < n:
6 correct_idx = nums[i] - 1
7 if 0 < nums[i] <= n and nums[i] != nums[correct_idx]:
8 nums[i], nums[correct_idx] = nums[correct_idx], nums[i]
9 else:
10 i += 1
11 for i in range(n):
12 if nums[i] != i + 1:
13 return i + 1
14 return n + 11class Solution {
2 public int firstMissingPositive(int[] nums) {
3 int n = nums.length;
4 int i = 0;
5 while (i < n) {
6 int correctIdx = nums[i] - 1;
7 if (nums[i] > 0 && nums[i] <= n && nums[i] != nums[correctIdx]) {
8 int temp = nums[i];
9 nums[i] = nums[correctIdx];
10 nums[correctIdx] = temp;
11 } else {
12 i++;
13 }
14 }
15 for (i = 0; i < n; i++) {
16 if (nums[i] != i + 1) {
17 return i + 1;
18 }
19 }
20 return n + 1;
21 }
22}1class Solution {
2public:
3 int firstMissingPositive(vector<int>& nums) {
4 int n = nums.size();
5 int i = 0;
6 while (i < n) {
7 int correctIdx = nums[i] - 1;
8 if (nums[i] > 0 && nums[i] <= n && nums[i] != nums[correctIdx]) {
9 swap(nums[i], nums[correctIdx]);
10 } else {
11 i++;
12 }
13 }
14 for (i = 0; i < n; i++) {
15 if (nums[i] != i + 1) {
16 return i + 1;
17 }
18 }
19 return n + 1;
20 }
21};Time and space complexity
O(n)
Although i sometimes stays put, every swap moves a value into its home index where it is never moved again, so there are at most n swaps. Adding the n advances and the final scan keeps the total linear.
O(1)
The array is rearranged in place and only a couple of indices are stored.
Other approaches
Sign marking (time O(n), space O(1))
First replace every value outside 1 to n with n + 1. Then, for each value v in range, make nums[v - 1] negative to mark v as present. The first index still holding a positive number gives the answer. It is also O(n) time and O(1) space and avoids swaps.
Hash set (time O(n), space O(n))
Insert every number into a set, then check 1, 2, 3 and so on until one is absent. It is the simplest correct solution but violates the constant-space requirement.
Common mistakes
- Checking
nums[i] != i + 1instead ofnums[i] != nums[correct_idx]as the swap condition. With duplicates, the value at the home index may already be correct, and swapping identical values forever creates an infinite loop. - Advancing
iafter every swap. The value that just arrived atimight also need to move, so skipping it leaves values out of place. - Indexing with
nums[i] - 1before the range check in languages without short-circuit safety, which reads out of bounds for negatives and large numbers. - Forgetting the
n + 1case. When the array is a permutation of 1 to n, the scan finds nothing and you must return n + 1.
Frequently asked questions
Why is the answer always between 1 and n + 1?
An array of n elements can hold at most n distinct positive values. If it holds all of 1 to n, the answer is n + 1; otherwise one of those values is missing and it is the answer.
Why is the cyclic sort O(n) if i does not always advance?
Each swap places a value at its home index permanently, and there are only n indices, so at most n swaps happen in total. The non-swap steps advance i, which also happens at most n times.
How is First Missing Positive different from Missing Number?
Missing Number guarantees the values are 0 to n with exactly one gap, so a sum or XOR works. Here the array can contain anything, so you need the index-placement trick to stay within O(1) space.