15% off all plans & roadmaps Use code

See plans

First Missing Positive

Updated

TL;DR: Find the smallest positive integer absent from an unsorted array. Place each value from 1 to n into its matching index by swapping in place, then the first slot holding the wrong value gives the answer.

Problem

You are given an unsorted integer array nums. Return the smallest positive integer that does not appear in nums.

Your algorithm must run in O(n) time and use O(1) auxiliary space.

Example 1

Input: nums = [1,2,0]
Output: 3
Explanation: The values 1 and 2 both appear in the array.

Example 2

Input: nums = [3,4,-1,1]
Output: 2
Explanation: The value 1 appears, but 2 does not.

Example 3

Input: nums = [7,8,9,11,12]
Output: 1
Explanation: The smallest positive integer, 1, is absent.

Constraints

  • 1 <= nums.length <= 10^5
  • -2^31 <= nums[i] <= 2^31 - 1

Constraints that matter

  • The length can reach 10^5, so any quadratic scan is too slow. A solution must touch each element a small constant number of times.
  • The answer is always between 1 and n + 1. Only values in the range 1 to n can fill a slot, so every other value can be ignored.
  • Values can be as large as 2^31 - 1 or as small as -2^31. Using a value as an index without a range check causes out-of-bounds access or silent wraparound.
  • O(1) extra space rules out a boolean array or a hash set of size n. The array itself must hold the bookkeeping.

View on LeetCode

Hints

Hint 1

The answer is always at most n + 1.

Hint 2

Try each candidate from 1 upward and check whether it appears anywhere in the array.

Solution

Intuition

The answer is always at most n + 1. With n numbers, the best case is that they fill the slots 1 through n exactly, and then n + 1 is the first gap. So you only ever care about values from 1 to n.

Picture a row of numbered mailboxes where box k should hold letter k. Each swap delivers a letter to its own box, and letters addressed outside 1 to n are skipped over.

The key pattern is cyclic sort. When the value x is in range, it has exactly one home: index x - 1. You can move each value to its home by swapping, which builds a partial sorted layout inside the array you already have.

After you place every reachable value, a single scan finds the gap. The first index whose value is not index + 1 means the number index + 1 was never found. Each swap places one value permanently, so the total work stays linear.

Watch the pattern animation

Worked example

Input: nums = [2, 3, 7, 6, 8, -1, -10, 15, 1, 5, 4]
Output: 9
Explanation: The array has 11 elements, so the answer lies in the range 1 to 12. The values 1 through 8 all appear, and 9 does not. Negative numbers and values above 11 are ignored, so 9 is the first gap.

Approach 1: Brute force

Try each candidate from 1 upward and check whether it appears anywhere in the array. The first candidate that never appears is the answer. You only need to test candidates from 1 to n + 1, because one of them must be missing.

The cost sits in the membership check. Each candidate triggers a full scan of the array, and the answer can be as large as n + 1. The same scan repeats for every candidate.

Steps

  1. Let n be the length of nums.
  2. For each candidate c from 1 to n + 1, do the following.
  3. Scan the whole array to see whether c appears.
  4. If c never appears, return c.
  5. Return n + 1 as a fallback. The loop always returns first, since n values cannot cover n + 1 candidates.

Dry run

Take nums = [2, 3, 7, 6, 8, -1, -10, 15, 1, 5, 4], so n = 11. Candidate 1 is found at index 8 after a scan of 9 elements. Candidate 2 is found at index 0. Candidates 3 through 8 are also found, each after its own scan.

Candidate 9 is checked last. The full scan of all 11 elements finds no 9, so the function returns 9.

Complexity

TimeO(n^2)
SpaceO(1)

Let n be the array length. The loop tries at most n + 1 candidates. Each candidate scans at most n elements, so the work is at most (n + 1) * n, which is O(n^2). The algorithm stores only a loop counter and a flag, so the extra space is O(1).

PythonTested in our runner

class Solution:
    def firstMissingPositive(self, nums: List[int]) -> int:
        # Try each candidate and scan the array for it
        for candidate in range(1, len(nums) + 2):
            if candidate not in nums:
                return candidate
        return len(nums) + 1

Approach 2: One-pass hash set

What's slow in the brute force is the membership check. Each candidate triggers a full scan, so the same array is searched n + 1 times. A hash set answers membership in average constant time after one pass to build it.

The insight is to pay O(n) once to load every value into a set. After that, each candidate from 1 to n + 1 costs O(1) on average. This is faster, but the set uses O(n) extra memory, which breaks the space limit of the final problem.

Steps

  1. Build a hash set containing every value in nums.
  2. Let n be the length of nums.
  3. For each candidate c from 1 to n + 1, check whether c is in the set.
  4. Return the first c that is not in the set.
  5. Return n + 1 as a fallback.

Dry run

Build the set from nums = [2, 3, 7, 6, 8, -1, -10, 15, 1, 5, 4]. The set holds 11 distinct values. Check 1, present. Check 2 through 8, all present.

Check 9, absent. The function returns 9.

Complexity

TimeO(n)
SpaceO(n)

Let n be the array length. Building the set inserts n values, and each insert is O(1) on average, so that part is O(n). The loop then does at most n + 1 lookups, each O(1) on average, which is also O(n). The set stores up to n values, so the extra space is O(n).

PythonTested in our runner

class Solution:
    def firstMissingPositive(self, nums: List[int]) -> int:
        # One pass to load every value into a set
        seen = set(nums)
        for candidate in range(1, len(nums) + 2):
            if candidate not in seen:
                return candidate
        return len(nums) + 1

The Array - Cyclic Sort infographic is part of Pro

A one-page visual of the pattern: when it applies, the steps and the invariant to keep.

Unlock the infographic

Solution pattern

Array - Cyclic Sort

Part of Array/Matrix Manipulation Patterns

Approach 3: Cyclic sort, then scanOptimalArray - Cyclic Sort

The hash set wastes memory because it stores values that could live in the array itself. The array already has n slots, and only the values 1 to n need a slot. If you move each value x to index x - 1, the array becomes a partial lookup table.

The insight is that a swap moves a value to its home. Swap only when the current value is in range and the target slot holds a different value. Each successful swap puts one value into its final place.

Values out of range are skipped by advancing the pointer. After the sweep, scan from index 0 and return the first index where the value is not index + 1.

Why it is correct. Each in-range value is either home or still waiting, and a swap never moves a value already home. When the loop ends, every value from 1 to n in the array sits at its own index. So at the first index i that holds the wrong value, the number i + 1 cannot be anywhere in the array.

Steps

  1. Set n to the length of nums and set i to 0.
  2. While i is less than n, let x be nums[i]. If x is between 1 and n and nums[x - 1] is not x, swap nums[i] with nums[x - 1]. Do not advance i after a swap.
  3. Otherwise, advance i by one. This covers values out of range and values already in place.
  4. When the loop ends, scan i from 0 to n - 1.
  5. Return i + 1 at the first index where nums[i] is not i + 1.
  6. If the scan finds nothing, return n + 1.

Dry run

Start with nums = [2, 3, 7, 6, 8, -1, -10, 15, 1, 5, 4] and n = 11. The table shows each step. The last row shows the array after the sweep.

Stepinums[i]ActionArray after step
102Swap with index 1[3, 2, 7, 6, 8, -1, -10, 15, 1, 5, 4]
203Swap with index 2[7, 2, 3, 6, 8, -1, -10, 15, 1, 5, 4]
307Swap with index 6[-10, 2, 3, 6, 8, -1, 7, 15, 1, 5, 4]
40-10Out of range, advance to 1unchanged
512Already home, advance to 2unchanged
623Already home, advance to 3unchanged
736Swap with index 5[-10, 2, 3, -1, 8, 6, 7, 15, 1, 5, 4]
83-1Out of range, advance to 4unchanged
948Swap with index 7[-10, 2, 3, -1, 15, 6, 7, 8, 1, 5, 4]
10415Above n, advance to 5unchanged
115 to 76, 7, 8Already home, advance to 8unchanged
1281Swap with index 0[1, 2, 3, -1, 15, 6, 7, 8, -10, 5, 4]
138-10Out of range, advance to 9unchanged
1495Swap with index 4[1, 2, 3, -1, 5, 6, 7, 8, -10, 15, 4]
15915Above n, advance to 10unchanged
16104Swap with index 3[1, 2, 3, 4, 5, 6, 7, 8, -10, 15, -1]
1710-1Out of range, i reaches 11unchanged

The scan starts at index 0. Indices 0 to 7 hold 1 to 8. Index 8 holds -10, which is not 9. The function returns 9.

Complexity

TimeO(n)
SpaceO(1)

Let n be the array length. The while loop runs as long as i is below n, and each iteration either advances i or performs a swap. Each swap places one value at its home index x - 1, and a value sitting at home is never moved again, so there are at most n swaps.

Advances are at most n, so the loop does at most 2n iterations. The final scan does at most n checks, so the total time is O(n). The algorithm uses only the variables n, i, and a few temporaries, so the extra space is O(1).

PythonTested in our runner

class Solution:
    def firstMissingPositive(self, nums: List[int]) -> int:
        n = len(nums)
        i = 0
        # Move each value in range to its home index value - 1
        while i < n:
            home = nums[i] - 1
            if 0 < nums[i] <= n and nums[i] != nums[home]:
                nums[i], nums[home] = nums[home], nums[i]
            else:
                i += 1
        # The first slot holding the wrong value reveals the gap
        for i in range(n):
            if nums[i] != i + 1:
                return i + 1
        return n + 1

Common mistakes

  • if nums[i] != nums[nums[i]] without subtracting 1. This compares against the wrong slot. Use nums[i] - 1 as the home index.
  • while nums[i] != i + 1 with no range check on the value. Values like 0, -10 or 15 make the index invalid or wrap silently in Python. Check 0 < x <= n first.
  • swap followed by i += 1 in the same branch. The value that moved into slot i may still be misplaced, so i must stay put after a swap.
  • Swapping when nums[i] already equals nums[home], such as two copies of 5. This loops forever. Compare the value at the home slot before swapping.
  • Returning n instead of n + 1 when every slot holds the right value. The array then holds 1 through n exactly, so the answer is n + 1.
  • Reaching for sort(nums) as the first move. Sorting costs O(n log n), which breaks the required O(n) bound, even though it gives a correct answer.

Edge cases

  • nums = [1]: the array holds 1 in its home slot, so the scan finds nothing and the answer is 2.
  • nums = [2]: the value 2 is in range but not at home. The swap check fails for index 0, and the answer is 1.
  • nums = [-1, -10]: every value is out of range, so no swap happens and the answer is 1.
  • nums = [1, 1]: the duplicate 1 must not trigger an infinite swap. The second copy stays put and the answer is 2.
  • nums = [1, 2, 3, 4]: every slot is full and correct, so the scan finds nothing and the answer is 5.
  • nums = [0, 2147483647]: zero and the maximum int are out of range. They are skipped, and the answer is 1.

Follow-ups interviewers ask

What if the array is already sorted?
A sorted array lets you skip the swaps. Walk the array once and track the next expected value, starting at 1. Skip values below the expected value and duplicates. When a value is larger than expected, that expected value is the answer. This is O(n) time and O(1) extra space, and the input is not modified. Binary search does not solve this directly, because gaps and duplicates break the simple rule that value minus index is constant.
Can you solve it without modifying the input array?
Cyclic sort rearranges nums, so it changes the caller's data. A read-only version needs extra memory. A bitset with one bit per value from 1 to n + 1 uses n / 8 bytes and runs in O(n) time. That is still O(n) extra space, counted in bits. Under the strict O(1) space rule, you must accept the in-place mutation, or restore the array afterward with the same swaps in reverse.
What if the array does not fit in memory?
Process the data in blocks. Pick a value range, such as 1 to a few million, and count how many values fall inside it using a bitset that fits in memory. Stream the file once per block. The first block with a missing value contains the answer. You can also use an external sort on the file, then scan the sorted output for the first gap.

First Missing Positive FAQ

What is the time complexity of First Missing Positive?

The optimal cyclic sort solution runs in O(n) time. Each element is swapped into its home index at most once, so the swaps total at most n. The final scan adds another n steps. The hash set version is also O(n) on average, and the brute force version is O(n^2).

Why use cyclic sort for First Missing Positive?

The answer is always in the range 1 to n + 1, and each value in that range has a single home index. Cyclic sort moves values to their homes using only swaps inside the array. This avoids the O(n) extra space that a hash set needs.

Can First Missing Positive be solved in O(1) extra space?

Yes. The cyclic sort version uses only a few index variables and a temporary for swaps. It does change the input array, so the space is O(1) only if you accept that mutation. A read-only solution needs extra space for a bitset or a set.

Why does Python need a range check before indexing?

Python accepts negative indices and silently wraps them. The value -1 would read nums[-1], which is the last element, and the code would give a wrong answer without raising an error. Check 0 < value <= n before using the value as an index.

Why is the answer never bigger than n + 1?

The array holds n values. To cover every value from 1 to n + 1 would require n + 1 distinct positive values, which is more than the array can hold. So at least one value in the range 1 to n + 1 is missing.

Asked at

See which companies ask this — Pro

Practise it