Problem Description
Given an unsorted integer array nums, return the smallest positive integer that is not present in the array. The solution must run in O(n) time and use O(1) auxiliary space.
Key Insights
- The missing positive number must be in the range [1, n+1] where n is the length of the array.
- Use the array indices to place numbers in their correct positions (i.e., number i should be at index i-1) with in-place swapping.
- After rearrangement, scan the array: the first index where the number is not equal to index+1 indicates the missing positive integer.
Space and Time Complexity
Time Complexity: O(n) as each number is swapped at most once. Space Complexity: O(1) since the rearrangement occurs in-place.
Solution
The approach involves reordering the array so that each positive integer in the range [1, n] is placed at the index corresponding to its value minus one. This means for any valid number i, nums[i-1] should be i. We iterate through the array and perform in-place swaps to achieve this order. After this process, another pass through the array reveals the first position where the number does not match the expected value (i+1), which is the smallest missing positive. If every position is correct, then the missing value is n+1.