First Missing Positive

Hard

Topics
ArrayHash Table

Given an unsorted array nums, return the smallest missing positive integer. Aim for O(n) time and O(1) extra space (use the array itself as a hash).

Example 1

102102
in range 1..n and therefore relevant
With 3 slots the answer must lie in 1..4, so only the shaded values matter at all. First gap here: 3.
Cells are the array values; the small numbers underneath are indices.
Input:  nums = [1,2,0]
Output: 3

Example 2

3041-1213
in range 1..n and therefore relevant
Input:  nums = [3,4,-1,1]
Output: 2

Example 3

708192113124
Input:  nums = [7,8,9,11,12]
Output: 1

Constraints

  • 1 <= nums.length <= 10^5
  • -2^31 <= nums[i] <= 2^31 - 1
Editorial — intuition, approach, complexity and pitfalls

Intuition

If space were free this would be easy: drop everything into a hash set, then test 1, 2, 3, ... until one is missing. O(n) time, O(n) space, and worth saying out loud because it is the baseline the real constraint rules out.

Sorting is the other obvious move — sort, then walk looking for the first gap — but that is O(n log n), and the problem wants linear.

So we need a set that costs nothing. The unlock is a counting argument: with n slots, the answer is always in [1, n+1]. It cannot exceed n+1, because to push the first gap past n+1 you would need all of 1..n+1 present, which is n+1 distinct values in n slots. Every value outside [1, n] is therefore irrelevant — it can never be the answer and it never blocks one.

That leaves exactly n interesting values and exactly n array slots, so the array can be the hash table. Put value v at index v-1. Once every value that can be placed is in its home slot, the first index where nums[i] != i+1 names the answer, and if there is no such index the answer is n+1.

💡 The technique is often called index-as-hash: when the value range and the index range are the same size, position encodes membership and the O(n) side table disappears.

Approach

  1. For each index i, repeatedly swap nums[i] toward its home slot while it is in range [1, n] and not already there. The loop condition nums[nums[i]-1] != nums[i] compares values, not indices, which is what makes duplicates terminate instead of swapping forever.
  2. Scan once more for the first i with nums[i] != i+1 and return i+1.
  3. If every slot is correct, return n+1.

Dry Run

nums = [3, 4, -1, 1], so n = 4 and the answer must lie in [1, 5].

i=0: nums[0]=3, in range, home is index 2 which holds -1  -> swap
     [-1, 4, 3, 1]
     nums[0]=-1, out of range -> stop

i=1: nums[1]=4, in range, home is index 3 which holds 1   -> swap
     [-1, 1, 3, 4]
     nums[1]=1, in range, home is index 0 which holds -1   -> swap
     [1, -1, 3, 4]
     nums[1]=-1, out of range -> stop

i=2: nums[2]=3, home is index 2, already correct -> stop
i=3: nums[3]=4, home is index 3, already correct -> stop

final: [1, -1, 3, 4]
scan:  index 0 holds 1 ✓
       index 1 holds -1, wanted 2  -> answer 2

Index 0 did three swaps' worth of work across the run, yet the total swap count is bounded — see the complexity note.

Complexity

  • Time — O(n): the inner while makes the outer loop look quadratic, but each swap places at least one value into its final home slot, and a value in its home slot is never moved again. So there are at most n swaps across the entire run, plus two linear passes. Amortised, every element is touched a constant number of times.
  • Space — O(1): two indices and one temporary for the swap. This is the whole point of the problem: the hash-set solution is O(n) space and the sort is O(log n) to O(n) depending on language, while this is genuinely constant because the input array doubles as the table. Note the trade: it mutates the caller's array, which is a real cost and worth flagging in an interview rather than glossing over — if the caller needs the original order you must copy first, and then you are back to O(n).

Common Pitfalls

  • Writing the loop guard as while nums[i] != i+1. On a value that is out of range, or on a duplicate, that spins forever. The guard must be the conjunction: in range and not already home.
  • Comparing indices instead of values in the guard. nums[nums[i]-1] != nums[i] is what detects "the home slot already holds this value", which is how duplicates like [1, 1] terminate.
  • Caching j = nums[i]-1 before the swap and then reusing it after. The swap changes nums[i], so a stale target index corrupts the next iteration — recompute it each time.
  • Forgetting the n+1 return. For [1, 2, 3] every slot is correct and the answer is 4, not something inside the array.
  • Trying to handle zero and negatives specially. They need no special case; they simply fail the range test and are left where they are as harmless placeholders.
  • Assuming the input is a permutation. It can contain duplicates, zero, negatives and values far above n, and all four are covered by the same range check.

Full Solution — all languages

class Solution:
    def firstMissingPositive(self, nums):
        n = len(nums)
        for i in range(n):
            while 1 <= nums[i] <= n and nums[nums[i] - 1] != nums[i]:
                j = nums[i] - 1
                nums[i], nums[j] = nums[j], nums[i]
        for i in range(n):
            if nums[i] != i + 1:
                return i + 1
        return n + 1
SensAI
Beta
Tap the mic to stop voice mode