Given an unsorted integer array, find the first missing positive integer.
For example,
Given[1,2,0]return3,
and[3,4,-1,1]return2.
Your algorithm should run inO(n) time and uses constant space.
The Idea: The goal was to achieve this in O(n) time and O(1) space. Using the same array, we can hash the elements of the array to its correct location. e.g. array[0] = array[array\[0]]. We can ignore all negative numbers because we are interested in the first positive. That is, the idea is to search for 1, then 2... and so fourth. For similar reasons, we can ignore values that are greater than the magnitude of the array because they are guaranteed to not be the first positive anyway, since the array can only hold as much as its greatest length.
If these conditions are valid, we swap array[i] with array[array[i]] making it so array[i] hashes to its correct position in the array. Once this process is complete, we are guareenteed to know that all the elements should be moved to their correct location within the array. If they have not otherwise, then its a guareentee they are missing as the first positive.
So we go through another for loop at the end to look for this first instance. I probabily can make this a lot cleaner looking, but it runs in linear time and constant space.
The Idea: Throw all the numbers into a hashset. Find the minimum and then maximum. Then first the first element before or after the minimum until the element is found.
Complexity: O(n) time and O(n) space
import sysclassSolution:deffirstMissingPositive(self,nums):""" :type nums: List[int] :rtype: int """ifnot nums:return1# for find later and terminating condition hashset =set(nums) maxx =max(nums)# find min value after 0 minn = sys.maxsizefor i, num inenumerate(nums):if num < minn and num >0: minn = num# if not found, or 1 doesnt exist then first positive has to be 1if minn == sys.maxsize or1notin hashset:return1# dont assume to look forward after minimum e.g. [1,3,4,-1] -> 2 not 5 elif minn >1and minn -1notin hashset:return minn -1# otherwise try to find after the minimum# find the first missing after minwhile minn <= maxx: minn +=1if minn notin hashset:return minnreturn minn