Problem 42
First Missing Positive
Hard · 30 pts · Array, Hash Table
Problem
You are given an unsorted array of N integers, which may contain negative numbers, zeros, duplicates and very large values. Find the smallest positive integer (1, 2, 3, ...) that does not appear in the array. The answer is always between 1 and N + 1, because N numbers can cover at most the values 1 to N. A hash set works; the classic O(1)-memory solution places each value v in the range 1 to N at index v - 1 by swapping, and then finds the first index i where A[i] is not i + 1.
Input
First line: integer N. Second line: N space-separated integers.
Output
Print the smallest missing positive integer.
Constraints
1 <= N <= 100000; -1000000000 <= A[i] <= 1000000000
Example input
3 1 2 0
Example output
3
Explanation
The array is 1 2 0. The positive integers 1 and 2 both appear, but 3 does not, so the answer is 3.