Given an unsorted integer array
You must implement an algorithm that runs in
Output: 3
Explanation: The numbers in the range [1,2] are all in the array.
Output: 2
Explanation: 1 is in the array but 2 is missing.
Output: 1
Explanation: The smallest positive integer 1 is missing.
Constraints:
1 <= nums.length <= 105 -231 <= nums[i] <= 231 - 1
Contents
Solution 1 - Use the hint of lowest possible positive is 1 and highest possible positive is N+1, use a marking process to identify the smallest one
In this approach, we will use the hint from problem statement, that is smallest positive value possible is
So, we can conclude that the smallest positive values must be in the range of
Implementation steps:
-
In the first step, loop through input array
nums , and mark out-of-bounds numbers, such as 0, negative integers, or number that are greater thanN withN + 1 . -
In the next step, take
nums[i] as index and if that is within the range of array length, change the number at thatindex to negative. By doing so we are marking that the number does exist in the array between1 andN . For example, say if the array is[4, -1, 9, 6, 8] , array length is 5, and the number at index 0 is 4, since 4 is within the bounds of array length, we will mark the corresponding indexed element to negative, i.e. 3rd indexed element[4, -1, 9, .-6 , 8] -
Once we mark the array elements, now we will loop through the array one more time and when the first positive integer is found at index
i , i+1 will be the smallest positive value possible. -
If there is no smallest found after marking the elements, for example if the array has 1....N elements, then the smallest number will be
N+1 .
Complexity Analysis:
Time complexity: Above code runs in O(n) time where
Space complexity: O(1), since we are modifying input array itself and not using any extra data type.
Above implementations source code can be found at