First missing positive
You get a list of integers nums in no particular order. It may hold negative numbers, zeros, repeats, and numbers much larger than its length. Find the smallest positive integer (1, 2, 3, ...) that nums does not contain, and return it.
The limits are the hard part. Your solution must take O(n) time and O(1) extra space, where n is len(nums): a few variables, but no set, dict, sorted copy or second list. You may change nums in place, by moving its items or overwriting them. The tests time your code but cannot measure its memory, so the space rule is yours to keep, as it is in the interview.
nums = [2, -3, 1, 5]Output31 and 2 are in the list; 3 is not.
nums = [4, 1, 2, 3]Output5Every number from 1 to 4 is present, so the answer is the next one.
nums = [7, 8, 0]Output11 is missing, so nothing else matters.
0 ≤ len(nums) ≤ 105
-231 ≤ nums[i] ≤ 231 - 1
O(n) time and O(1) extra space;
numsmay be changed.
Plan it first
Write a line for each before you code, then say them out loud. Compare with the Approach tab afterwards.