First Missing Positive

HardCyclic sortLeetCode 41 ↗World 2-14
0:00 / 0:00

Find the smallest missing positive in O(n) time and O(1) space: swap each value into its own seat, then the first wrong seat is the answer.

▼

The problem

LeetCode 41 (Hard). Given an unsorted integer array nums, return the smallest positive integer that is not in nums, in O(n) time and O(1) extra space.

Examples (LeetCode's): [1,2,0] → 3, [3,4,-1,1] → 2 (the walkthrough) and [7,8,9,11,12] → 1.

TRY IT ON LEETCODE ▶

The solution

def first_missing_positive(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

Transcript

First Missing Positive. Given an unsorted array of integers, return the smallest positive number that's missing from it. The catch: linear time, and only constant extra space.

One, two, zero gives three. Three, four, minus one, one gives two: two is missing. Seven, eight, nine, eleven, twelve: even one is missing, so the answer is one.

The easy ways break the rules. Sorting first costs n log n time. A hash set of every value runs in linear time, but needs n extra space.

Here's the key. With n numbers, the answer is between one and n plus one. Going past that would need n plus one different values, and there are only n. So only one to n matter, and the array itself can be the hash table. Think of a hotel with rooms one to n. Value v belongs in room v. Zero, negatives and numbers bigger than n have no room, so they stay put.

Let's walk three, four, minus one, one. Three goes to room three, and minus one comes back. Minus one has no room, so we move on. Four goes to room four, and one comes back. One goes to room one, and minus one comes back again. Three and four are already home. Now scan: room one holds one. Room two holds minus one. The answer is two.

In code: for each slot, while its number fits and its room doesn't already hold that number, swap it home. That second check stops duplicates, like two ones, from swapping forever. Then scan. The first slot i that doesn't hold i plus one gives i plus one. If every room is right, it's n plus one.

The while loop looks costly, but each swap sends a number home for good, so there are at most n swaps in all. Order n time, order one extra space. Flipping signs to mark seen values works too.

Skip what has no room, send each number home, then find the first wrong room. That's First Missing Positive.