Skip to content
Problem 41 · LeetCode 41(opens in a new tab)

First Missing Positive

HardArrays

You are given an unsorted array of whole numbers, nums. It can hold negatives, zeros, duplicates and huge values. Return the smallest positive whole number (1, 2, 3, ...) that does not appear in it.

Your solution must run in O(n) time and use only O(1) extra memory. Changing nums itself is allowed.

Example 1

Input:  nums = [4, 1, -3, 2, 7]
Output: 3
Why:    1 and 2 are there, 3 is not
2 more examples and the constraints

Example 2

Input:  nums = [2, 3, 5, 1]
Output: 4
Why:    1, 2 and 3 are there, 4 is missing

Example 3

Input:  nums = [-4, 0, 9]
Output: 1
Why:    no positive number below 9 shows up

Constraints

  • 1 ≤ length of nums ≤ 100,000
  • Each value fits in a 32-bit signed integer: −2,147,483,648 to 2,147,483,647

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Hash set, count upO(n)
  2. Put each number at its indexO(n)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for 100,000 numbersVerdict
Hash set, count upO(n)
Fast, but uses O(n) memory
Put each number at its indexO(n)
Best; O(1) extra space

n = length of nums. Set lookups cost more than plain array reads, so the in-place version is also faster in practice.

Edge cases to test

  • Every slot filled. [5, 4, 3, 2, 1] holds 1 to 5, so the answer is 6, which is n + 1.
  • No positives. [-4, 0, 9] has no 1, so the answer is 1.
  • Duplicates. [1, 1] gives 2. Without the nums[v − 1] != v check the two 1s swap forever.
  • Extreme values. [−2,147,483,648, 2,147,483,647] gives 1. Skip out-of-range values before using them as an index.
  • One element. [1] gives 2 and [2] gives 1.

Common mistakes

  • Checking only nums[i] != i + 1 before swapping, which loops forever on duplicates.
  • Moving i forward after one swap, so the value just swapped into i never gets placed.
  • Forgetting that the answer can be n + 1 when the array holds exactly 1 to n.

How to talk through it

  1. 1Clarify. Can I change the input? Are there duplicates, zeros and negatives?
  2. 2Give the set version. Count up from 1 against a set: O(n) time but O(n) space.
  3. 3Bound the answer. With n numbers the answer is at most n + 1, so only values 1 to n matter.
  4. 4Reuse the array. Swap each value v to index v − 1, then scan for the first slot that is wrong.
  5. 5Test out loud. Run a full 1 to n, a duplicate case and an all-negative case.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?