First Missing Positive
hard
arrays
in-place
cyclic-sort
Given an unsorted integer array nums, return the smallest missing positive integer.
The classic optimal solution runs in linear time and uses constant extra space by reusing the input array itself as bookkeeping.
Input / output
- Input:
nums: int[] - Output:
int
Examples
nums = [1,2,0]returns3.nums = [3,4,-1,1]returns2.nums = [7,8,9,11,12]returns1.
Constraints
1 <= nums.length <= 100000-2^31 <= nums[i] <= 2^31 - 1
Follow-up
Can you solve it in O(n) time and O(1) extra space, and explain why values outside the range 1..n can be ignored?
Examples
Example 1
Input: nums = [1,2,0]
Output: 3
Example 2
Input: nums = [3,4,-1,1]
Output: 2
Example 3
Input: nums = [7,8,9,11,12]
Output: 1
🔒 5 hidden
Running will execute all 8 cases, including 5 hidden ones.