Skip to content

First Missing Positive

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.

InputOutputWhy
[1,2,0]31 and 2 present, 3 missing
[3,4,-1,1]21 present, 2 missing
[7,8,9,11,12]11 missing immediately
  • 1 <= nums.length <= 10^5
  • -2^31 <= nums[i] <= 2^31 - 1
ApproachTimeSpaceNotes
Index as HashO(n)O(1)Uses negative marking; modifies input
Cycle SortO(n)O(1)Places elements at correct positions
Hash Set (not allowed)O(n)O(n)Conceptually simple but violates constraint
★ Recommended
⏱ Time O(n) Three linear passes 💾 Space O(1) In-place marking

The key insight: the answer must be in the range [1, n+1]. This means the array’s n slots are exactly enough to encode presence of every candidate value. We use negative sign as a boolean flag at the index corresponding to each value.

Three phases:

  1. Clean: replace irrelevant values (≤0 or >n) with n+1 so they don’t interfere with marking
  2. Mark: for each value v = abs(nums[i]) where 1 ≤ v ≤ n, negate nums[v-1] to mark “v is present”
  3. Scan: find first index i where nums[i] > 0 → return i+1

Input: [3,4,-1,1], n = 4

Phase 1 — replace -1 (≤0) with n+1=5: [3,4,5,1]

Phase 2 — mark:

iabs(nums[i])mark indexarray after
032[3,4,-5,1]
143[3,4,-5,-1]
25 > nskip[3,4,-5,-1]
310[-3,4,-5,-1]

Phase 3 — scan [-3,4,-5,-1]: index 1 has positive 4 → return 2

Animated walkthrough

Index-as-Hash marking phase on [3,4,-1,1]

Watch how each value's presence is encoded by negating the slot at index (value-1). Use Next or Autoplay.

Step 1 of 6
Waiting to begin...
Array state
Memory / lookup state

function firstMissingPositive(nums):
n = len(nums)
# Phase 1: replace non-positives and > n
for i in range(n):
if nums[i] <= 0 or nums[i] > n:
nums[i] = n + 1
# Phase 2: mark presence
for i in range(n):
v = abs(nums[i])
if 1 <= v <= n:
nums[v-1] = -abs(nums[v-1])
# Phase 3: find first unmarked
for i in range(n):
if nums[i] > 0:
return i + 1
return n + 1
first_missing_positive_index_hash.py
from typing import List
def first_missing_positive(nums: List[int]) -> int:
n = len(nums)
# Phase 1: replace non-positives and values > n with n+1
for i in range(n):
if nums[i] <= 0 or nums[i] > n:
nums[i] = n + 1
# Phase 2: mark presence using negative signs
for i in range(n):
v = abs(nums[i])
if 1 <= v <= n:
nums[v - 1] = -abs(nums[v - 1])
# Phase 3: find first unmarked index
for i in range(n):
if nums[i] > 0:
return i + 1
return n + 1
print(first_missing_positive([1, 2, 0])) # 3
print(first_missing_positive([3, 4, -1, 1])) # 2
print(first_missing_positive([7, 8, 9, 11, 12])) # 1
🎯 Interview Favourite
⏱ Time O(n) Each element moved at most once 💾 Space O(1) In-place

Place each number at its “correct” position: value v belongs at index v-1. Keep swapping until every element is either in its correct slot or out of range. Then scan for the first mismatch.

Input: [3,4,-1,1]

inums[i]correct idxactionarray
032swap(0,2)[-1,4,3,1]
0-1invalidskip[-1,4,3,1]
143swap(1,3)[-1,1,3,4]
110swap(1,0)[1,-1,3,4]
1-1invalidskip[1,-1,3,4]
232 ✓skip[1,-1,3,4]
343 ✓skip[1,-1,3,4]

Scan: index 0: nums[0]=1=1 ✓, index 1: nums[1]=-1≠2 → return 2

function firstMissingPositive(nums):
n = len(nums)
i = 0
while i < n:
j = nums[i] - 1 # correct index for nums[i]
if 1 <= nums[i] <= n and nums[j] != nums[i]:
swap(nums[i], nums[j])
else:
i += 1
for i in range(n):
if nums[i] != i + 1:
return i + 1
return n + 1
first_missing_positive_cycle_sort.py
from typing import List
def first_missing_positive(nums: List[int]) -> int:
n = len(nums)
i = 0
# Place each number at its correct index (value v at index v-1)
while i < n:
j = nums[i] - 1
if 1 <= nums[i] <= n and nums[j] != nums[i]:
nums[i], nums[j] = nums[j], nums[i]
else:
i += 1
# Find first index where value doesn't match expected
for i in range(n):
if nums[i] != i + 1:
return i + 1
return n + 1
print(first_missing_positive([1, 2, 0])) # 3
print(first_missing_positive([3, 4, -1, 1])) # 2
print(first_missing_positive([7, 8, 9, 11, 12])) # 1
✓ Simple

A third approach demonstrating an alternative technique for solving this problem. This implementation optimizes either time or space complexity compared to the previous approaches.

⏱ Time O(n) Optimized complexity 💾 Space O(1) Efficient space usage
function approach3():
// Implementation approach goes here
first_missing_positive_space_optimized.py
"""
Solution for First Missing Positive
"""
def solve():
"""Implementation for approach 3 of First Missing Positive"""
pass
if __name__ == "__main__":
print("Solution ready")