First Missing Positive
Given an unsorted integer array nums, return the smallest positive integer (starting from 1) that does not appear in the array. You must run in O(n) time and use O(1) auxiliary space.
Open official problem prompt ↗Find the smallest positive integer absent from the array without allocating extra memory proportional to n.
Like a coat check where ticket k must hang on hook k: after everyone hangs their coat on its matching hook, the first empty hook whose number is a valid ticket tells you which ticket never showed up.
- Input
- nums = [3, 4, -1, 1]
- Output
- 2
- Why
- 1 is present but 2 is missing, and 2 is the smallest such positive integer.
1 <= nums.length <= 10^5-2^31 <= nums[i] <= 2^31 - 1Must be O(n) time and O(1) extra space