AAlgoLoopSpaced repetition for LeetCode
HARDHash Map / SetLeetCode ↗

First Missing Positive

The key idea

Among n numbers, the answer must be one of 1, 2, ..., n, n+1. So the array itself can act as a hash table: put each value v (when 1 <= v <= n) at index v - 1. After that placement, the first index i where nums[i] != i + 1 gives the answer i + 1; if every slot matches, the answer is n + 1.

Problem

Given an unsorted integer array nums, return the smallest positive integer that is not present in nums.

You must implement an algorithm that runs in O(n) time and uses constant extra space.

Note that values that are zero or negative, and any duplicates, are simply irrelevant to which small positive number is missing.

Constraints

Examples

Input: nums = [1,2,0] Output: 3
Input: nums = [3,4,-1,1] Output: 2
Input: nums = [7,8,9,11,12] Output: 1

Complexity

Time: O(n) Space: O(1)

See the full solution

410310
Step-by-step visualization
Start free →

More Hash Map / Set problems