First Missing Positive
Problem Statement
You are given an unsorted integer array nums. It can contain zeros, negative numbers, very large numbers and duplicates.
Return the smallest positive integer (1, 2, 3, …) that does not appear in nums.
Your algorithm must run in O(N) time and use only O(1) extra space.
An integer array nums.
The smallest positive integer missing from nums.
1 and 2 are present, so the first missing positive is 3.
1 is present but 2 is not.
Even 1 is missing. The large values do not matter.
- • 1 ≤ nums.length ≤ 10^5
- • −2^31 ≤ nums[i] ≤ 2^31 − 1
- • O(N) time and O(1) extra space.
Pattern Recognition Clues
Recognising these key signals in the problem description immediately identifies the pattern:
Approach Complexity Ladder
For each k from 1, scan the array to see if k is there
Put positives in a set; first k in 1..n+1 not in it
Swap each value v (1..n) into index v − 1, then find the first wrong slot
Try k = 1, then 2, then 3, … For each k, scan the whole array. The first k that is not found is the answer. We never need to go past n + 1.
Recognition rule for this sub-pattern:
Unlock Complete Visual Walkthrough & Optimal C++
The interactive animated dry-run player, optimized C++ implementation, state invariant derivations, and edge-case breakdown for this question are part of Brute2Best Pro. The anchor question of every sub-pattern is completely free.
First anchor question per pattern, Part 1 LLD & Module 1 C++ basics are 100% Free forever.
How this concept connects to System Design & C++ Systems
Top engineering interviews test whether you understand how algorithms like Arrays & Hashing translate into production architectures and low-level memory mechanics.