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 INPUT Unsorted Array nums[] 1 idx: 0 2 idx: 1 0 idx: 2 Input Values: nums = [1, 2, 0] Find smallest positive integer NOT in array Constraints: O(n) time, O(1) space Use Hash Set approach ALGORITHM STEPS 1 Build Hash Set Add all nums to set HashSet = {0, 1, 2} O(n) to build 2 Start from 1 Check positive ints 3 Lookup Each O(1) per lookup 1 in set? YES 2 in set? YES 3 in set? NO OK OK X 4 Return Missing First not found = 3 FINAL RESULT Missing Positive Found! 3 Output: return 3 Verification: 1 exists in [1,2,0] 2 exists in [1,2,0] 3 NOT in [1,2,0] --> Answer! Key Insight: Hash Set enables O(1) lookup for each positive integer. We only need to check integers from 1 to n+1 because at most n distinct positives exist. The answer is always in range [1, n+1] where n = array length. TutorialsPoint - First Missing Positive | Hash Set Lookup Approach
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