Cyclic Sort
LC #41Hard
First Missing Positive
Cyclic Sort
AmazonGoogleMetaProblem
Find the smallest missing positive integer in an unsorted array. Must be O(n) time and O(1) space.
arrayhash-mapcyclic-sort
Constraints
- ›1 ≤ n ≤ 10⁵
- ›-2³¹ ≤ nums[i] ≤ 2³¹ − 1
- ›O(n) time and O(1) space required
Example
Input
nums = [3, 4, -1, 1]Output
2Why
1 is present, 2 is missing. Negatives and out-of-range are irrelevant