SDE & MLE Prep

41. First Missing Positive

Problem

Given an unsorted integer array nums, return the smallest positive integer that does not appear in it.

Example: [3,4,-1,1] → 2; [1,2,0] → 3

Constraints: n ≤ 10⁵; must run in O(n) time with O(1) extra space.

The answer is in [1, n+1]. Use the array as a hash table: cyclic-swap each value v ∈ [1, n] to index v-1. Then the first index i with nums[i] != i+1 gives i+1.

[3, 4, -1, 1]
swap 3 -> idx2:  [-1, 4, 3, 1]
swap 4 -> idx3:  [-1, 1, 3, 4]
swap 1 -> idx0:  [ 1,-1, 3, 4]
scan: idx1 holds -1  -> answer 2

Complexity: O(n) time (each swap fixes one slot), O(1) space.

class Solution:
    def firstMissingPositive(self, nums: List[int]) -> int:
        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