15% off all plans & roadmaps Use code
See plansFirst Missing Positive
- LeetCode 41
- Hard
- Array/Matrix Manipulation Patterns
- Array - Cyclic Sort
Updated
TL;DR: Find the smallest positive integer absent from an unsorted array. Place each value from 1 to n into its matching index by swapping in place, then the first slot holding the wrong value gives the answer.
Problem
You are given an unsorted integer array nums. Return the smallest positive integer that does not appear in nums.
Your algorithm must run in O(n) time and use O(1) auxiliary space.
Example 1
Input: nums = [1,2,0] Output: 3 Explanation: The values 1 and 2 both appear in the array.
Example 2
Input: nums = [3,4,-1,1] Output: 2 Explanation: The value 1 appears, but 2 does not.
Example 3
Input: nums = [7,8,9,11,12] Output: 1 Explanation: The smallest positive integer, 1, is absent.
Constraints
1 <= nums.length <= 10^5-2^31 <= nums[i] <= 2^31 - 1
Constraints that matter
- The length can reach 10^5, so any quadratic scan is too slow. A solution must touch each element a small constant number of times.
- The answer is always between 1 and n + 1. Only values in the range 1 to n can fill a slot, so every other value can be ignored.
- Values can be as large as 2^31 - 1 or as small as -2^31. Using a value as an index without a range check causes out-of-bounds access or silent wraparound.
- O(1) extra space rules out a boolean array or a hash set of size n. The array itself must hold the bookkeeping.
Hints
Hint 1
The answer is always at most n + 1.
Hint 2
Try each candidate from 1 upward and check whether it appears anywhere in the array.
Solution
Intuition
The answer is always at most n + 1. With n numbers, the best case is that they fill the slots 1 through n exactly, and then n + 1 is the first gap. So you only ever care about values from 1 to n.
Picture a row of numbered mailboxes where box k should hold letter k. Each swap delivers a letter to its own box, and letters addressed outside 1 to n are skipped over.
The key pattern is cyclic sort. When the value x is in range, it has exactly one home: index x - 1. You can move each value to its home by swapping, which builds a partial sorted layout inside the array you already have.
After you place every reachable value, a single scan finds the gap. The first index whose value is not index + 1 means the number index + 1 was never found. Each swap places one value permanently, so the total work stays linear.
Worked example
Input: nums = [2, 3, 7, 6, 8, -1, -10, 15, 1, 5, 4] Output: 9 Explanation: The array has 11 elements, so the answer lies in the range 1 to 12. The values 1 through 8 all appear, and 9 does not. Negative numbers and values above 11 are ignored, so 9 is the first gap.
Approach 1: Brute force
Try each candidate from 1 upward and check whether it appears anywhere in the array. The first candidate that never appears is the answer. You only need to test candidates from 1 to n + 1, because one of them must be missing.
The cost sits in the membership check. Each candidate triggers a full scan of the array, and the answer can be as large as n + 1. The same scan repeats for every candidate.
Steps
- Let n be the length of nums.
- For each candidate c from 1 to n + 1, do the following.
- Scan the whole array to see whether c appears.
- If c never appears, return c.
- Return n + 1 as a fallback. The loop always returns first, since n values cannot cover n + 1 candidates.
Dry run
Take nums = [2, 3, 7, 6, 8, -1, -10, 15, 1, 5, 4], so n = 11. Candidate 1 is found at index 8 after a scan of 9 elements. Candidate 2 is found at index 0. Candidates 3 through 8 are also found, each after its own scan.
Candidate 9 is checked last. The full scan of all 11 elements finds no 9, so the function returns 9.
Complexity
| Time | O(n^2) |
|---|---|
| Space | O(1) |
Let n be the array length. The loop tries at most n + 1 candidates. Each candidate scans at most n elements, so the work is at most (n + 1) * n, which is O(n^2). The algorithm stores only a loop counter and a flag, so the extra space is O(1).
PythonTested in our runner
class Solution:
def firstMissingPositive(self, nums: List[int]) -> int:
# Try each candidate and scan the array for it
for candidate in range(1, len(nums) + 2):
if candidate not in nums:
return candidate
return len(nums) + 1JavaTested in our runner
import java.util.*;
class Solution {
public int firstMissingPositive(int[] nums) {
int n = nums.length;
for (int c = 1; c <= n + 1; c++) {
boolean found = false;
for (int x : nums) {
if (x == c) {
found = true;
break;
}
}
if (!found) {
return c;
}
}
return n + 1;
}
}C++Tested in our runner
#include <vector>
using namespace std;
class Solution {
public:
int firstMissingPositive(vector<int>& nums) {
int n = nums.size();
for (int c = 1; c <= n + 1; ++c) {
bool found = false;
for (int x : nums) {
if (x == c) {
found = true;
break;
}
}
if (!found) {
return c;
}
}
return n + 1;
}
};JavaScriptTested in our runner
/**
* @param {number[]} nums
* @return {number}
*/
var firstMissingPositive = function(nums) {
const n = nums.length;
for (let c = 1; c <= n + 1; c++) {
if (!nums.includes(c)) {
return c;
}
}
return n + 1;
};GoTested in our runner
func firstMissingPositive(nums []int) int {
n := len(nums)
for c := 1; c <= n+1; c++ {
found := false
for _, x := range nums {
if x == c {
found = true
break
}
}
if !found {
return c
}
}
return n + 1
}C#Tested in our runner
public class Solution {
public int firstMissingPositive(int[] nums) {
int n = nums.Length;
for (int c = 1; c <= n + 1; c++) {
bool found = false;
foreach (int x in nums) {
if (x == c) {
found = true;
break;
}
}
if (!found) {
return c;
}
}
return n + 1;
}
}Approach 2: One-pass hash set
What's slow in the brute force is the membership check. Each candidate triggers a full scan, so the same array is searched n + 1 times. A hash set answers membership in average constant time after one pass to build it.
The insight is to pay O(n) once to load every value into a set. After that, each candidate from 1 to n + 1 costs O(1) on average. This is faster, but the set uses O(n) extra memory, which breaks the space limit of the final problem.
Steps
- Build a hash set containing every value in nums.
- Let n be the length of nums.
- For each candidate c from 1 to n + 1, check whether c is in the set.
- Return the first c that is not in the set.
- Return n + 1 as a fallback.
Dry run
Build the set from nums = [2, 3, 7, 6, 8, -1, -10, 15, 1, 5, 4]. The set holds 11 distinct values. Check 1, present. Check 2 through 8, all present.
Check 9, absent. The function returns 9.
Complexity
| Time | O(n) |
|---|---|
| Space | O(n) |
Let n be the array length. Building the set inserts n values, and each insert is O(1) on average, so that part is O(n). The loop then does at most n + 1 lookups, each O(1) on average, which is also O(n). The set stores up to n values, so the extra space is O(n).
PythonTested in our runner
class Solution:
def firstMissingPositive(self, nums: List[int]) -> int:
# One pass to load every value into a set
seen = set(nums)
for candidate in range(1, len(nums) + 2):
if candidate not in seen:
return candidate
return len(nums) + 1JavaTested in our runner
import java.util.*;
class Solution {
public int firstMissingPositive(int[] nums) {
int n = nums.length;
Set<Integer> seen = new HashSet<>();
for (int x : nums) {
seen.add(x);
}
for (int c = 1; c <= n + 1; c++) {
if (!seen.contains(c)) {
return c;
}
}
return n + 1;
}
}C++Tested in our runner
#include <unordered_set>
#include <vector>
using namespace std;
class Solution {
public:
int firstMissingPositive(vector<int>& nums) {
int n = nums.size();
unordered_set<int> seen(nums.begin(), nums.end());
for (int c = 1; c <= n + 1; ++c) {
if (seen.find(c) == seen.end()) {
return c;
}
}
return n + 1;
}
};JavaScriptTested in our runner
/**
* @param {number[]} nums
* @return {number}
*/
var firstMissingPositive = function(nums) {
const n = nums.length;
const seen = new Set(nums);
for (let c = 1; c <= n + 1; c++) {
if (!seen.has(c)) {
return c;
}
}
return n + 1;
};GoTested in our runner
func firstMissingPositive(nums []int) int {
n := len(nums)
seen := make(map[int]bool, n)
for _, x := range nums {
seen[x] = true
}
for c := 1; c <= n+1; c++ {
if !seen[c] {
return c
}
}
return n + 1
}C#Tested in our runner
public class Solution {
public int firstMissingPositive(int[] nums) {
int n = nums.Length;
var seen = new HashSet<int>(nums);
for (int c = 1; c <= n + 1; c++) {
if (!seen.Contains(c)) {
return c;
}
}
return n + 1;
}
}The Array - Cyclic Sort infographic is part of Pro
A one-page visual of the pattern: when it applies, the steps and the invariant to keep.
Unlock the infographicSolution pattern
Array - Cyclic Sort
Approach 3: Cyclic sort, then scanOptimalArray - Cyclic Sort
The hash set wastes memory because it stores values that could live in the array itself. The array already has n slots, and only the values 1 to n need a slot. If you move each value x to index x - 1, the array becomes a partial lookup table.
The insight is that a swap moves a value to its home. Swap only when the current value is in range and the target slot holds a different value. Each successful swap puts one value into its final place.
Values out of range are skipped by advancing the pointer. After the sweep, scan from index 0 and return the first index where the value is not index + 1.
Why it is correct. Each in-range value is either home or still waiting, and a swap never moves a value already home. When the loop ends, every value from 1 to n in the array sits at its own index. So at the first index i that holds the wrong value, the number i + 1 cannot be anywhere in the array.
Steps
- Set n to the length of nums and set i to 0.
- While i is less than n, let x be nums[i]. If x is between 1 and n and nums[x - 1] is not x, swap nums[i] with nums[x - 1]. Do not advance i after a swap.
- Otherwise, advance i by one. This covers values out of range and values already in place.
- When the loop ends, scan i from 0 to n - 1.
- Return i + 1 at the first index where nums[i] is not i + 1.
- If the scan finds nothing, return n + 1.
Dry run
Start with nums = [2, 3, 7, 6, 8, -1, -10, 15, 1, 5, 4] and n = 11. The table shows each step. The last row shows the array after the sweep.
| Step | i | nums[i] | Action | Array after step |
|---|---|---|---|---|
| 1 | 0 | 2 | Swap with index 1 | [3, 2, 7, 6, 8, -1, -10, 15, 1, 5, 4] |
| 2 | 0 | 3 | Swap with index 2 | [7, 2, 3, 6, 8, -1, -10, 15, 1, 5, 4] |
| 3 | 0 | 7 | Swap with index 6 | [-10, 2, 3, 6, 8, -1, 7, 15, 1, 5, 4] |
| 4 | 0 | -10 | Out of range, advance to 1 | unchanged |
| 5 | 1 | 2 | Already home, advance to 2 | unchanged |
| 6 | 2 | 3 | Already home, advance to 3 | unchanged |
| 7 | 3 | 6 | Swap with index 5 | [-10, 2, 3, -1, 8, 6, 7, 15, 1, 5, 4] |
| 8 | 3 | -1 | Out of range, advance to 4 | unchanged |
| 9 | 4 | 8 | Swap with index 7 | [-10, 2, 3, -1, 15, 6, 7, 8, 1, 5, 4] |
| 10 | 4 | 15 | Above n, advance to 5 | unchanged |
| 11 | 5 to 7 | 6, 7, 8 | Already home, advance to 8 | unchanged |
| 12 | 8 | 1 | Swap with index 0 | [1, 2, 3, -1, 15, 6, 7, 8, -10, 5, 4] |
| 13 | 8 | -10 | Out of range, advance to 9 | unchanged |
| 14 | 9 | 5 | Swap with index 4 | [1, 2, 3, -1, 5, 6, 7, 8, -10, 15, 4] |
| 15 | 9 | 15 | Above n, advance to 10 | unchanged |
| 16 | 10 | 4 | Swap with index 3 | [1, 2, 3, 4, 5, 6, 7, 8, -10, 15, -1] |
| 17 | 10 | -1 | Out of range, i reaches 11 | unchanged |
The scan starts at index 0. Indices 0 to 7 hold 1 to 8. Index 8 holds -10, which is not 9. The function returns 9.
Complexity
| Time | O(n) |
|---|---|
| Space | O(1) |
Let n be the array length. The while loop runs as long as i is below n, and each iteration either advances i or performs a swap. Each swap places one value at its home index x - 1, and a value sitting at home is never moved again, so there are at most n swaps.
Advances are at most n, so the loop does at most 2n iterations. The final scan does at most n checks, so the total time is O(n). The algorithm uses only the variables n, i, and a few temporaries, so the extra space is O(1).
PythonTested in our runner
class Solution:
def firstMissingPositive(self, nums: List[int]) -> int:
n = len(nums)
i = 0
# Move each value in range to its home index value - 1
while i < n:
home = nums[i] - 1
if 0 < nums[i] <= n and nums[i] != nums[home]:
nums[i], nums[home] = nums[home], nums[i]
else:
i += 1
# The first slot holding the wrong value reveals the gap
for i in range(n):
if nums[i] != i + 1:
return i + 1
return n + 1JavaTested in our runner
class Solution {
public int firstMissingPositive(int[] nums) {
int n = nums.length;
int i = 0;
// Move each value in range to its home index value - 1
while (i < n) {
int home = nums[i] - 1;
if (nums[i] > 0 && nums[i] <= n && nums[i] != nums[home]) {
int temp = nums[i];
nums[i] = nums[home];
nums[home] = temp;
} else {
i++;
}
}
// The first slot holding the wrong value reveals the gap
for (int j = 0; j < n; j++) {
if (nums[j] != j + 1) {
return j + 1;
}
}
return n + 1;
}
}C++Tested in our runner
#include <vector>
using namespace std;
class Solution {
public:
int firstMissingPositive(vector<int>& nums) {
int n = nums.size();
int i = 0;
// Move each value in range to its home index value - 1
while (i < n) {
int home = nums[i] - 1;
if (nums[i] > 0 && nums[i] <= n && nums[i] != nums[home]) {
swap(nums[i], nums[home]);
} else {
++i;
}
}
// The first slot holding the wrong value reveals the gap
for (int j = 0; j < n; ++j) {
if (nums[j] != j + 1) {
return j + 1;
}
}
return n + 1;
}
};JavaScriptTested in our runner
/**
* @param {number[]} nums
* @return {number}
*/
var firstMissingPositive = function(nums) {
const n = nums.length;
let i = 0;
// Move each value in range to its home index value - 1
while (i < n) {
const home = nums[i] - 1;
if (nums[i] > 0 && nums[i] <= n && nums[i] !== nums[home]) {
[nums[i], nums[home]] = [nums[home], nums[i]];
} else {
i++;
}
}
// The first slot holding the wrong value reveals the gap
for (let j = 0; j < n; j++) {
if (nums[j] !== j + 1) {
return j + 1;
}
}
return n + 1;
};GoTested in our runner
func firstMissingPositive(nums []int) int {
n := len(nums)
i := 0
// Move each value in range to its home index value - 1
for i < n {
home := nums[i] - 1
if nums[i] > 0 && nums[i] <= n && nums[i] != nums[home] {
nums[i], nums[home] = nums[home], nums[i]
} else {
i++
}
}
// The first slot holding the wrong value reveals the gap
for j := 0; j < n; j++ {
if nums[j] != j+1 {
return j + 1
}
}
return n + 1
}C#Tested in our runner
public class Solution {
public int firstMissingPositive(int[] nums) {
int n = nums.Length;
int i = 0;
// Move each value in range to its home index value - 1
while (i < n) {
int home = nums[i] - 1;
if (nums[i] > 0 && nums[i] <= n && nums[i] != nums[home]) {
int temp = nums[i];
nums[i] = nums[home];
nums[home] = temp;
} else {
i++;
}
}
// The first slot holding the wrong value reveals the gap
for (int j = 0; j < n; j++) {
if (nums[j] != j + 1) {
return j + 1;
}
}
return n + 1;
}
}Common mistakes
if nums[i] != nums[nums[i]]without subtracting 1. This compares against the wrong slot. Usenums[i] - 1as the home index.while nums[i] != i + 1with no range check on the value. Values like 0, -10 or 15 make the index invalid or wrap silently in Python. Check0 < x <= nfirst.swapfollowed byi += 1in the same branch. The value that moved into slot i may still be misplaced, so i must stay put after a swap.- Swapping when
nums[i]already equalsnums[home], such as two copies of 5. This loops forever. Compare the value at the home slot before swapping. - Returning
ninstead ofn + 1when every slot holds the right value. The array then holds 1 through n exactly, so the answer is n + 1. - Reaching for
sort(nums)as the first move. Sorting costs O(n log n), which breaks the required O(n) bound, even though it gives a correct answer.
Edge cases
- nums = [1]: the array holds 1 in its home slot, so the scan finds nothing and the answer is 2.
- nums = [2]: the value 2 is in range but not at home. The swap check fails for index 0, and the answer is 1.
- nums = [-1, -10]: every value is out of range, so no swap happens and the answer is 1.
- nums = [1, 1]: the duplicate 1 must not trigger an infinite swap. The second copy stays put and the answer is 2.
- nums = [1, 2, 3, 4]: every slot is full and correct, so the scan finds nothing and the answer is 5.
- nums = [0, 2147483647]: zero and the maximum int are out of range. They are skipped, and the answer is 1.
Follow-ups interviewers ask
- What if the array is already sorted?
- A sorted array lets you skip the swaps. Walk the array once and track the next expected value, starting at 1. Skip values below the expected value and duplicates. When a value is larger than expected, that expected value is the answer. This is O(n) time and O(1) extra space, and the input is not modified. Binary search does not solve this directly, because gaps and duplicates break the simple rule that value minus index is constant.
- Can you solve it without modifying the input array?
- Cyclic sort rearranges nums, so it changes the caller's data. A read-only version needs extra memory. A bitset with one bit per value from 1 to n + 1 uses n / 8 bytes and runs in O(n) time. That is still O(n) extra space, counted in bits. Under the strict O(1) space rule, you must accept the in-place mutation, or restore the array afterward with the same swaps in reverse.
- What if the array does not fit in memory?
- Process the data in blocks. Pick a value range, such as 1 to a few million, and count how many values fall inside it using a bitset that fits in memory. Stream the file once per block. The first block with a missing value contains the answer. You can also use an external sort on the file, then scan the sorted output for the first gap.
First Missing Positive FAQ
What is the time complexity of First Missing Positive?
The optimal cyclic sort solution runs in O(n) time. Each element is swapped into its home index at most once, so the swaps total at most n. The final scan adds another n steps. The hash set version is also O(n) on average, and the brute force version is O(n^2).
Why use cyclic sort for First Missing Positive?
The answer is always in the range 1 to n + 1, and each value in that range has a single home index. Cyclic sort moves values to their homes using only swaps inside the array. This avoids the O(n) extra space that a hash set needs.
Can First Missing Positive be solved in O(1) extra space?
Yes. The cyclic sort version uses only a few index variables and a temporary for swaps. It does change the input array, so the space is O(1) only if you accept that mutation. A read-only solution needs extra space for a bitset or a set.
Why does Python need a range check before indexing?
Python accepts negative indices and silently wraps them. The value -1 would read nums[-1], which is the last element, and the code would give a wrong answer without raising an error. Check 0 < value <= n before using the value as an index.
Why is the answer never bigger than n + 1?
The array holds n values. To cover every value from 1 to n + 1 would require n + 1 distinct positive values, which is more than the array can hold. So at least one value in the range 1 to n + 1 is missing.
Asked at
See which companies ask this — Pro
Related problems
- Find the Duplicate Number · same technique: Array - Cyclic Sort
- Find All Duplicates in an Array · same technique: Array - Cyclic Sort
- Missing Number · same technique: Array - Cyclic Sort
- Find All Numbers Disappeared in an Array · same technique: Array - Cyclic Sort
- Split Array Largest Sum · same pattern: Array/Matrix Manipulation Patterns
- Longest Substring Without Repeating Characters · same pattern: Array/Matrix Manipulation Patterns
- Group Anagrams · same pattern: Array/Matrix Manipulation Patterns
- Longest Consecutive Sequence · same pattern: Array/Matrix Manipulation Patterns
- Top K Frequent Elements · same pattern: Array/Matrix Manipulation Patterns
- Task Scheduler · same pattern: Array/Matrix Manipulation Patterns