HARD Arrays & Hashing (with constraints)
41. First Missing Positive
๐ Problem
Given an unsorted integer array nums, return the smallest missing positive integer. You must implement an algorithm that runs in O(n) time and uses O(1) auxiliary space.
๐ง Visual Learning Aid
1 Model the input into the right structure
2 Choose the core technique and invariant
3 Execute step-by-step with a sample
4 Validate complexity and edge cases
JS/TS Refreshers
- โขArray methods (`push`, `pop`, `shift`, `slice`)
- โขObject/Map/Set usage patterns
- โขFunction parameter and return typing
Logical Thinking Concepts
- โขDefine invariants before coding
- โขCheck edge cases first (`[]`, single element, duplicates)
- โขEstimate time/space before implementation
๐ก Approach
- โ First missing positive is in range [1, n+1] where n is array length
- โ Use the array itself as a hash map by marking positions
- โ Place each number in its correct position (number 1 at index 0, etc.)
- โ Time: O(n), Space: O(1)
- โ Using hash set: O(n) time, O(n) space
- โ Sorting: O(n log n) time, O(1) space
๐ ๏ธ Hints & Pitfalls
Hints
- โขFirst missing positive is in range [1, n+1] where n is array length
- โขUse the array itself as a hash map by marking positions
- โขPlace each number in its correct position (number 1 at index 0, etc.)
Common Pitfalls
- โขTime: O(n), Space: O(1)
- โขUsing hash set: O(n) time, O(n) space
- โขSorting: O(n log n) time, O(1) space
๐งช Test Cases
Hidden tests on submit: 5
Test Case 1
Not run Input:
firstMissingPositive(nums: number[]); Expected:
Computed from hidden reference Test Case 2
Not run Input:
firstMissingPositive([...test1]); Expected:
Computed from hidden reference Test Case 3
Not run Input:
firstMissingPositive([...test2]); Expected:
Computed from hidden reference ๐ Code Editor
๐ค Output