First Missing Positive
To solve this coding challenge of finding the smallest positive integer that is not present in the given unsorted integer array
, we need to implement an algorithm that operates in O(n) time complexity and uses O(1) auxiliary space. Let's break down the solution in a very detailed manner.
nums
Explanation
-
Objective
: Find the smallest missing positive integer in an unsorted array
nums
- Constraints : The search should be confined to O(n) time and O(1) auxiliary space. This is crucial as it guides our approach to the problem.
- Understanding the Problem :
- Given a list of integers, some may be negative, some positive.
- We need to find the smallest positive integer that is not present in the list.
-
For example, given
[3,4,-1,1]
2
-
Rearrange the array
: Iterate over the list to place each number
nums[i]
- Identify the first missing positive : Iterate over the rearranged list to find the first index where the value does not match the index + 1.
- Rearranging :
- Loop through each element in the array.
-
For each element
nums[i]
nums[i] - 1
- Repeat this process until all elements are either out of the valid range or at their correct positions.
- Finding the Missing Positive :
- Loop through the rearranged array.
-
If
nums[i]
i + 1
i + 1
-
If no mismatch is found, then the missing integer is
n + 1
- Initialization :
-
Start with the input array
nums
-
Calculate the length of the array
length_of_nums
- Rearranging the Elements :
-
Iterate with index
i
0
length_of_nums - 1
-
For each
nums[i]
length_of_nums
nums[nums[i] - 1] != nums[i]
nums[i] - 1
-
This ensures that by the end of the loop, all valid positive integers up to
n
- Finding the Missing Positive :
- After rearranging, iterate over the modified array.
-
Check each position
i
-
If
nums[i]
i + 1
i + 1
-
If no such index is found, return
length_of_nums + 1
length_of_nums
Initial Thoughts:
Ordinarily, one might sort the array or use additional storage to track the presence of integers. However, due to the O(n) time and O(1) space constraints, these approaches are not feasible. Instead, we need to rearrange the array elements such that each positive integeri
i-1
Plan:
Detailed Steps in Pseudocode:
Pseudocode:
function find_first_missing_positive(nums):
# Rearrange the elements in the array
length_of_nums = length of nums
for i from 0 to length_of_nums - 1:
# While the current element is in the valid range and not in its correct spot
while 1 <= nums[i] <= length_of_nums and nums[nums[i] - 1] != nums[i]:
# Swap the element to its correct position
temp = nums[nums[i] - 1]
nums[nums[i] - 1] = nums[i]
nums[i] = temp
# Identify the first missing positive integer
for i from 0 to length_of_nums - 1:
# If the current element is not in the correct position
if nums[i] != i + 1:
return i + 1
# If all elements are in the correct position
return length_of_nums + 1