First Missing Positive - Problem
Given an unsorted integer array
For example, if you have the array
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!
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
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.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code