AlgoInsight

DSA problem

First Missing Positive

HardArraysPattern: Index as Hash Key (Cyclic Sort)top75AmazonGoogleMicrosoftAppleFacebookStripe

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.

The crucial observation is that for an array of length n, the answer must lie in the range [1, n + 1]. Any value outside [1, n] (zeros, negatives, or numbers larger than n) is irrelevant and can be ignored.

We use the array itself as a hash table via cyclic sort: we repeatedly place each value v (where 1 <= v <= n) at index v - 1. After this rearrangement, the first index i whose value is not i + 1 reveals that i + 1 is the smallest missing positive. If every position is correct, the answer is n + 1.

Examples

Example 1
Input: nums = [1,2,0]
Output: 3
Explanation: The numbers 1 and 2 are present, so the smallest missing positive is 3.
Example 2
Input: nums = [3,4,-1,1]
Output: 2
Explanation: 1 is present but 2 is not, so the smallest missing positive is 2.
Example 3
Input: nums = [7,8,9,11,12]
Output: 1
Explanation: No positive integer in the range [1,5] is present, so the smallest missing positive is 1.

Constraints

3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.

arrayhash-tablecyclic-sort

Browse all DSA problems