First Missing Positive
Hard
Topics
Given an unsorted array nums, return the smallest missing positive integer. Aim for O(n) time and O(1) extra space (use the array itself as a hash).
Example 1
1..4, so only the shaded values matter at all. First gap here: 3.Input: nums = [1,2,0] Output: 3
Example 2
Input: nums = [3,4,-1,1] Output: 2
Example 3
Input: nums = [7,8,9,11,12] Output: 1
Constraints
- 1 <= nums.length <= 10^5
- -2^31 <= nums[i] <= 2^31 - 1
Editorial — intuition, approach, complexity and pitfalls
Intuition
If space were free this would be easy: drop everything into a hash set, then test 1, 2, 3, ... until one is missing. O(n) time, O(n) space, and worth saying out loud because it is the baseline the real constraint rules out.
Sorting is the other obvious move — sort, then walk looking for the first gap — but that is O(n log n), and the problem wants linear.
So we need a set that costs nothing. The unlock is a counting argument: with n slots, the answer is always in [1, n+1]. It cannot exceed n+1, because to push the first gap past n+1 you would need all of 1..n+1 present, which is n+1 distinct values in n slots. Every value outside [1, n] is therefore irrelevant — it can never be the answer and it never blocks one.
That leaves exactly n interesting values and exactly n array slots, so the array can be the hash table. Put value v at index v-1. Once every value that can be placed is in its home slot, the first index where nums[i] != i+1 names the answer, and if there is no such index the answer is n+1.
💡 The technique is often called index-as-hash: when the value range and the index range are the same size, position encodes membership and the O(n) side table disappears.
Approach
- For each index
i, repeatedly swapnums[i]toward its home slot while it is in range[1, n]and not already there. The loop conditionnums[nums[i]-1] != nums[i]compares values, not indices, which is what makes duplicates terminate instead of swapping forever. - Scan once more for the first
iwithnums[i] != i+1and returni+1. - If every slot is correct, return
n+1.
Dry Run
nums = [3, 4, -1, 1], so n = 4 and the answer must lie in [1, 5].
i=0: nums[0]=3, in range, home is index 2 which holds -1 -> swap
[-1, 4, 3, 1]
nums[0]=-1, out of range -> stop
i=1: nums[1]=4, in range, home is index 3 which holds 1 -> swap
[-1, 1, 3, 4]
nums[1]=1, in range, home is index 0 which holds -1 -> swap
[1, -1, 3, 4]
nums[1]=-1, out of range -> stop
i=2: nums[2]=3, home is index 2, already correct -> stop
i=3: nums[3]=4, home is index 3, already correct -> stop
final: [1, -1, 3, 4]
scan: index 0 holds 1 ✓
index 1 holds -1, wanted 2 -> answer 2Index 0 did three swaps' worth of work across the run, yet the total swap count is bounded — see the complexity note.
Complexity
- Time — O(n): the inner
whilemakes the outer loop look quadratic, but each swap places at least one value into its final home slot, and a value in its home slot is never moved again. So there are at mostnswaps across the entire run, plus two linear passes. Amortised, every element is touched a constant number of times. - Space — O(1): two indices and one temporary for the swap. This is the whole point of the problem: the hash-set solution is O(n) space and the sort is O(log n) to O(n) depending on language, while this is genuinely constant because the input array doubles as the table. Note the trade: it mutates the caller's array, which is a real cost and worth flagging in an interview rather than glossing over — if the caller needs the original order you must copy first, and then you are back to O(n).
Common Pitfalls
- Writing the loop guard as
while nums[i] != i+1. On a value that is out of range, or on a duplicate, that spins forever. The guard must be the conjunction: in range and not already home. - Comparing indices instead of values in the guard.
nums[nums[i]-1] != nums[i]is what detects "the home slot already holds this value", which is how duplicates like[1, 1]terminate. - Caching
j = nums[i]-1before the swap and then reusing it after. The swap changesnums[i], so a stale target index corrupts the next iteration — recompute it each time. - Forgetting the
n+1return. For[1, 2, 3]every slot is correct and the answer is 4, not something inside the array. - Trying to handle zero and negatives specially. They need no special case; they simply fail the range test and are left where they are as harmless placeholders.
- Assuming the input is a permutation. It can contain duplicates, zero, negatives and values far above
n, and all four are covered by the same range check.
Full Solution — all languages
class Solution:
def firstMissingPositive(self, nums):
n = len(nums)
for i in range(n):
while 1 <= nums[i] <= n and nums[nums[i] - 1] != nums[i]:
j = nums[i] - 1
nums[i], nums[j] = nums[j], nums[i]
for i in range(n):
if nums[i] != i + 1:
return i + 1
return n + 1import java.util.*;
class Solution {
public int firstMissingPositive(int[] nums) {
int n = nums.length;
for (int i = 0; i < n; i++) {
while (nums[i] >= 1 && nums[i] <= n && nums[nums[i] - 1] != nums[i]) {
int j = nums[i] - 1;
int t = nums[i];
nums[i] = nums[j];
nums[j] = t;
}
}
for (int i = 0; i < n; i++) if (nums[i] != i + 1) return i + 1;
return n + 1;
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: int firstMissingPositive(vector<int>& nums) {
int n = (int)nums.size();
for (int i = 0; i < n; i++) {
while (nums[i] >= 1 && nums[i] <= n && nums[nums[i] - 1] != nums[i]) swap(nums[i], nums[nums[i] - 1]);
}
for (int i = 0; i < n; i++) if (nums[i] != i + 1) return i + 1;
return n + 1;
}
};/**
* @param {number[]} nums
* @return {number}
*/ var firstMissingPositive = function(nums) {
const n = nums.length;
for (let i = 0; i < n; i++) {
while (nums[i] >= 1 && nums[i] <= n && nums[nums[i] - 1] !== nums[i]) {
const j = nums[i] - 1;
const t = nums[i];
nums[i] = nums[j];
nums[j] = t;
}
}
for (let i = 0; i < n; i++) if (nums[i] !== i + 1) return i + 1;
return n + 1;
};