The First Missing Positive interview question is a famous "Hard" level array problem. You are given an unsorted integer array, and you need to find the smallest positive integer () that is not present in the array. The catch is that you must solve it in time and extra space.
This is a staple question at high-tier companies like Amazon, Meta, and Netflix. It tests whether a candidate can use the input array itself as a hash map. It evaluates your ability to perform In-place array manipulation and handle edge cases like negative numbers, zeros, and large values. It's a true test of algorithmic creativity under strict constraints.
The optimal solution uses the Cycle Sort / Bucket Sort pattern (specifically, placing each number at index ).
nums[i] is either out of range or already at the correct index (nums[i] == nums[nums[i] - 1]).nums[i] != i + 1 tells you that is the first missing positive.Array: [3, 4, -1, 1]
[-1, 4, 3, 1].[-1, 1, 3, 4].[1, -1, 3, 4].nums[i] != nums[nums[i]-1], which leads to an infinite loop if the array has duplicates.Master the "Value as Index" technique. It is the most common way to achieve space in problems involving numbers within a restricted range (). Practice this alongside the "Negation Marking" trick.