First Missing Positive - Problem
Given an unsorted integer array nums, you need to find the smallest positive integer that is missing from the array. This is a challenging problem that tests your ability to think creatively about array manipulation.

For example, if you have the array [1, 2, 0], the smallest missing positive is 3. If you have [3, 4, -1, 1], the missing positive is 2.

The real challenge here is the constraint: you must solve this in O(n) time using only O(1) auxiliary space. This means you cannot use extra hash tables or arrays that grow with input size!

Input & Output

example_1.py โ€” Basic Case
$ Input: [1,2,0]
โ€บ Output: 3
๐Ÿ’ก Note: The numbers 1 and 2 are present, but 3 is the first positive integer that is missing.
example_2.py โ€” Unordered Array
$ Input: [3,4,-1,1]
โ€บ Output: 2
๐Ÿ’ก Note: The array contains 1, 3, and 4, but is missing 2, which is the smallest positive integer not present.
example_3.py โ€” All Consecutive
$ Input: [7,8,9,11,12]
โ€บ Output: 1
๐Ÿ’ก Note: The smallest positive integer 1 is missing from this array of larger numbers.

Constraints

  • 1 โ‰ค nums.length โ‰ค 5 ร— 104
  • -231 โ‰ค nums[i] โ‰ค 231 - 1
  • Follow up: Could you implement an algorithm that runs in O(n) time and uses constant extra space?

Visualization

Tap to expand
๐Ÿจ Hotel Room Assignment StrategyChaotic RequestsGuest List: [3, 4, -1, 1]Some impossible rooms!Smart OrganizationUse list as room chartPosition-based assignmentRoom Assignment ProcessRoom 1โœ“Room 2โœ—Room 3โœ“Room 4โœ“First Available: Room 2๐Ÿ’ก Key Insight: Array indices ARE the room numbers!Use cyclic sort to place guests optimally, then scan for first gap
Understanding the Visualization
1
Chaos to Order
Initially, guests are requesting random rooms: some want impossible rooms (0, -1), others want rooms beyond capacity
2
Smart Assignment
Instead of creating a separate registry, use the guest list itself as a room chart
3
Cyclic Arrangement
For each valid request, place the guest in their preferred position in the list
4
Find Empty Room
Scan the arranged list - the first position without correct occupant reveals the available room
Key Takeaway
๐ŸŽฏ Key Insight: Transform the array into a position-based hash table where index i represents number i+1. This allows O(n) time with O(1) space by leveraging the constraint that answers are bounded by array length.
Asked in
Google 85 Amazon 72 Meta 65 Microsoft 58 Apple 45
89.5K Views
High Frequency
~25 min Avg. Time
3.4K 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