Given an unsorted integer array nums, return the smallest missing positive integer. You must implement an algorithm that runs in O(n) time and uses O(1) auxiliary space.
nums = [3,4,-1,1]2nums = [1,2,0]3The answer is in [1, n+1]. We use the array as a hash — value v goes to index v-1. After cyclic placement, if nums[i] = i+1 for all i then [1..n] are all present and the answer is n+1. Otherwise the first mismatch reveals the missing number. Each element is moved at most once across all iterations — total swaps ≤ n.
Sorting is O(n log n), and a hash set uses O(n) space. Both break the rules.
The answer is always between 1 and n plus 1. So use the array itself as the hash: every number x belongs at index x −1. Swap numbers into their home, ignoring anything out of range. Then the first index that does not hold its own number gives the answer.
The answer is in 1 to n plus 1, so the array can be its own hash. Place each x at index x −1, then find the first misfit.
Run the animation above on your own input, or watch the 1:37 video explanation of First Missing Positive with a dry run and Java code.