Algo-Sim › Arrays & Hashing

First Missing Positive

Hard · Arrays & Hashing · step through it in Java, Python and C++ on your own input

Ignore values outside 1..n, swap the rest home to index v − 1, and the first index without its own number is the answer.

Problem

Given an unsorted integer array nums, return the smallest positive integer that does not appear in it. The solution must run in O(n) time and use only O(1) extra space.

Constraints

Edge cases to test

Follow-up questions

Why is the answer always between 1 and n + 1?
n slots can hold at most the values 1..n, so one of 1..n + 1 must be missing. That bound is what lets the array itself act as the hash table.
Why does the swap loop stay O(n)?
Every swap puts one value at its home index for good, so there are at most n swaps in total across all iterations.

Solution

Java

public int firstMissingPositive(int[] nums) {
    int n = nums.length, i = 0;
    while (i < n) {
        int v = nums[i];
        if (v >= 1 && v <= n && nums[v - 1] != v) {
            nums[i] = nums[v - 1]; nums[v - 1] = v;
        } else {
            i++;
        }
    }
    for (int j = 0; j < n; j++) {
        if (nums[j] != j + 1) return j + 1;
    }
    return n + 1;
}

Python

def first_missing_positive(nums):
    n, i = len(nums), 0
    while i < n:
        v = nums[i]
        if 1 <= v <= n and nums[v - 1] != v:
            nums[i], nums[v - 1] = nums[v - 1], v
        else:
            i += 1
    for j in range(n):
        if nums[j] != j + 1: return j + 1
    return n + 1

C++

#include <bits/stdc++.h>
using namespace std;

class Solution {
  public:
    int firstMissingPositive(vector<int> &nums) {
        int n = nums.size(), i = 0;
        while (i < n) {
            int v = nums[i];
            if (v >= 1 && v <= n && nums[v - 1] != v) {
                nums[i] = nums[v - 1];
                nums[v - 1] = v;
            } else {
                i++;
            }
        }
        for (int j = 0; j < n; j++) {
            if (nums[j] != j + 1) return j + 1;
        }
        return n + 1;
    }
};

More Arrays & Hashing problems