public class LinearTimeMNFinder extends java.lang.Object implements MissingNumberFinder
O(n) time and O(1) space algorithm to find the first missing positive number.
MissingNumberFinder
Constructor and Description |
---|
LinearTimeMNFinder() |
Modifier and Type | Method and Description |
---|---|
int |
findFirstMissingPositive(int[] nums)
First Missing Positive Approach (Reverse of Pigeonhole): you can 'n' balls, you put them into n+1 bins, one bin will remain empty. Phase-1: "approximate" sort to ensure the elements are at their rightful index e.g. |
int |
findMissingNumber(int[] nums)
Complexity: O(n) time and O(1) space. Assumption: no duplicates. Approach: Because we know that 'nums' contains 'n' numbers and that it is missing exactly one number in the range [0..n-1], we can infer that 'n' definitely replaces the missing number in nums. Therefore, if we initialize an integer to 'n' and XOR it with every index and value, we will be left with the missing number. |
public int findFirstMissingPositive(int[] nums)
findFirstMissingPositive
in interface MissingNumberFinder
nums
- input arraypublic int findMissingNumber(int[] nums)
findMissingNumber
in interface MissingNumberFinder
nums
- input array