First Missing Positive - Problem

Given an unsorted integer array nums, return the smallest positive integer that is not present in nums.

Important: You must implement an algorithm that runs in O(n) time and uses O(1) auxiliary space.

The problem asks you to find the first missing positive number from 1, 2, 3, ... that doesn't exist in the array.

Input & Output

Example 1 — Basic Case
$ Input: nums = [1,2,0]
Output: 3
💡 Note: The numbers 1 and 2 are present, but 3 is the first missing positive integer.
Example 2 — Negative and Large Numbers
$ Input: nums = [3,4,-1,1]
Output: 2
💡 Note: We have 1, 3, and 4, but 2 is missing. Negative numbers don't affect the result.
Example 3 — All Numbers Present
$ Input: nums = [7,8,9,11,12]
Output: 1
💡 Note: The smallest positive integer 1 is not present in the array.

Constraints

  • 1 ≤ nums.length ≤ 105
  • -231 ≤ nums[i] ≤ 231 - 1

Visualization

Tap to expand
First Missing Positive: Find smallest missing positive integer34-11Input: [3, 4, -1, 1]Check positive integers: 1✓, 2✗, 3✓, 4✓Missing: 2First gap foundOutput: 2
Understanding the Visualization
1
Input Array
Unsorted array with positive, negative, and zero values
2
Process
Identify which positive integers 1,2,3... are missing
3
Output
Return the smallest missing positive integer
Key Takeaway
🎯 Key Insight: Use the array itself as a hash table by placing number n at index n-1, then scan for the first gap
Asked in
Amazon 45 Microsoft 38 Google 32 Facebook 28
289.0K Views
High Frequency
~25 min Avg. Time
8.5K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen