First Missing Positive

HardArrays · Cyclic Sort (Index as Hash)🧩 Array ManipulationLeetCode #41 ↗Updated

Problem

Given an unsorted integer array nums, find the smallest positive integer that does not appear in it. The required solution runs in O(n) time using O(1) auxiliary space.
Input[1,2,0]Output3
Input[3,4,-1,1]Output2
Input[7,8,9,11,12]Output1

1 ≤ n ≤ 105  ·  -231 ≤ nums[i] ≤ 231-1  ·  must be O(n) time, O(1) extra space

Try it yourself

Java
class Solution {
    public int firstMissingPositive(int[] nums) {
        
    }
}
Your code is saved in this browser.Submit on LeetCode ↗
Key insight
The answer is always in [1, n+1] (n slots can hold at most 1..n). So only values 1..n matter, and the array itself can act as the hash set: put value v at index v-1.
PatternArray Manipulation

Instinct "In place", "O(1) extra space" or "one pass" over an array? Think write pointer, reversal, prefix/suffix passes or using indices as storage.

Memory hack Read fast, write slow, reverse to rotate, and let the index be the hash.

Open the Array Manipulation guide →

Approaches

Brute ForceCheck 1, 2, 3, … by Scanning

Time O(n2)Space O(1)

Try candidates i = 1..n+1 in order; for each, scan the whole array. The first candidate not found is the answer — at most n+1 candidates are needed.

Java
public int firstMissingPositive(int[] nums) {
    int n = nums.length;
    for (int i = 1; i <= n + 1; i++) {
        boolean found = false;
        for (int num : nums) {
            if (num == i) { found = true; break; }
        }
        if (!found) return i;
    }
    return -1; // unreachable
}

Constant space, but quadratic time.

At a glance

LevelApproachTimeSpace
Brute ForceCheck 1, 2, 3, … by ScanningO(n2)O(1)
BetterHash Set LookupO(n)O(n)
OptimalCyclic Sort (In-Place Placement)O(n)O(1)
Common pitfalls
  • Swap guard nums[i] != i+1 instead of nums[nums[i]-1] != nums[i] — loops forever on duplicates.
  • Forgetting to return n+1 when 1..n are all present.
  • Indexing with an out-of-range value — check 1 ≤ v ≤ n before swapping.
Interview tips
  • State the [1, n+1] bound first — it is what makes O(1) space possible.
  • Argue the amortised O(n): each swap places one value at its final index.
  • Ask whether mutating the input is allowed before going in-place.
Pattern
Cyclic sort / index-as-hash → values lie in 1..n and you need O(1) space presence checks.
My notes saved in this browser