Leetcode 41 : First Missing Positive Integer
Question : Given an unsorted integer array, find the smallest missing positive integer. Example : Input: [1,2,0] Output: 3 Input: [3,4,-1,1] Output: 2 Input: [7,8,9,11,12] Output: 1 Idea : In 1st phase, scan from left to right and mark numbers which are less than 0 and greater than n as n+1. As all the given numbers are in the range [1,n] we can use n+1. Now all the numbers in the array are…
The problem at hand is to determine the smallest missing positive integer from an unsorted array of integers. The array may contain both negative numbers and numbers greater than the array's length, as well as positive integers within the range of 1 to the array's length.
The solution begins with a first phase where the array is scanned from left to right. If any element is found to be less than zero or greater than the array's length, it is replaced with the value of n+1, where n is the array's length. This ensures that all numbers in the array are then positive and fall within the range of 1 to n+1.
The second phase involves iterating through the array again. Each number within the range of 1 to n is used to mark its corresponding index as negative. This is achieved by taking the absolute value of the current number, subtracting one to get the index, and then negating the value at that index. If the number is greater than n, it is ignored as it does not need to be marked as missing.
In the third and final phase, the array is scanned once more. The first positive number encountered is identified as the smallest missing positive integer. This is because the absence of a number within the range of 1 to n would result in its corresponding index being marked negative. If no positive numbers are found, it implies that all numbers from 1 to n are present, and thus, the smallest missing positive integer is n+1.
The code provided follows this logic closely. It first handles the modification of array elements based on their value in the first phase, then marks the indices corresponding to the numbers in the second phase. Finally, it identifies the first positive number in the third phase to return the smallest missing positive integer. The time complexity of the algorithm is O(n) as it iterates through the array a constant number of times.
The auxiliary space used is O(1) since the solution modifies the input array in place without requiring additional space that scales with the input size.
This method is efficient and leverages the input array itself for marking purposes, thereby avoiding the need for extra space. The approach effectively handles edge cases where all numbers are greater than the array's length or when all numbers are within the range, ensuring a comprehensive solution to the problem.
Written by urgent.news from Dev.to's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.