impl Solution {
fn first_missing_positive(mut nums: Vec<i32>) -> i32 {
// The length of the input array.
let n = nums.len() as i32;
// Iterate over each element in the array.
for i in 0..n {
// The while loop is used to place the current element at its correct position.
// We keep swapping until:
// 1. The current element is out of the range [1, n].
// 2. The current element is already in its correct position.
// This is checked by comparing the current element with the element at its 'ideal' index.
while nums[i as usize] > 0
&& nums[i as usize] <= n
&& nums[nums[i as usize] as usize - 1] != nums[i as usize]
{
// Swap the current element with the element at its 'ideal' position.
let num = nums[i as usize]; // Store nums[i as usize] in a temporary variable
nums.swap(i as usize, num as usize - 1);
}
}
// After rearranging, iterate through the array again.
for i in 0..n {
// If the value at index i is not i + 1, it means i + 1 is the missing positive integer.
// This is because in the ideal arrangement, each integer x should be at index x - 1.
if nums[i as usize] != i + 1 {
return i + 1;
}
}
// If all numbers are in their correct positions and no positive integer is missing in the range [1, n],
// then the smallest missing positive integer is n + 1.
n + 1
}
}