First Missing Positive – Solution & Complexity
Solution Walkthrough
Step 1: Understand what actually matters
- The answer must be in the range
1..n+1for an array of lengthn. - Negative numbers, zeros, and values larger than
ncannot directly block the first missing positive.
- The answer must be in the range
Step 2: Start with a set-based brute-force solution
- Insert every value into a hash set.
- Then scan upward from
1until you find the first positive missing from the set. - This is easy to reason about, but it costs
O(n)extra space.
Step 3: Place each value where it belongs
- Value
1belongs at index0, value2at index1, and so on. - If we keep swapping each in-range value into its correct slot, the first index that disagrees with this rule reveals the answer.
- Value
Step 4: Use cyclic placement for O(1) extra space
- While a value is in the range
1..nand not already in its correct slot, swap it into positionvalue - 1. - After that placement phase, scan left to right for the first index whose value is wrong.
- While a value is in the range
Step 5: Dry run / placement trace
Trace
nums = [3,4,-1,1].step array explanation start [3,4,-1,1]3belongs at index2swap [-1,4,3,1]put 3into its slotskip [-1,4,3,1]-1is out of range, so move onswap [-1,1,3,4]4belongs at index3swap [1,-1,3,4]then 1belongs at index0scan [1,-1,3,4]index 1should contain2, so the answer is2Step 6: Common mistakes and follow-ups
- Forgetting to keep swapping until the current slot is either invalid or correct.
- Accessing
nums[correct]before checking that the value is in the range1..n. - Using a clone in a context where the interviewer asked specifically for true
O(1)extra space. - Follow-up: can you solve the same problem with sign marking after first normalizing out-of-range values?
Step 7: Edge cases to test mentally
- Arrays containing only negatives should return
1. [1,2,3]should return4.- Duplicates like
[1,1]still return2. - A single
[1]should return2, while a single[2]should return1.
- Arrays containing only negatives should return
Step 8: Final full solution and complexity
Cyclic placement visits each index a constant number of times, so the optimal approach runs in
O(n)time withO(1)extra space beyond the returned integer.