First Missing Positive solution explained

The smallest missing positive integer in an array of length n is always between 1 and n + 1, so the array's own indices can serve as the lookup table. Move each value v in the range 1 to n to index v - 1 by swapping, then scan for the first index i that does not hold i + 1; the answer is i + 1, or n + 1 if every slot matches. That runs in O(n) time with O(1) extra space.

By Published 7 min read

What you are asked to find

You get an unsorted list of integers that may include negatives, zeros, duplicates and very large values. Return the smallest integer greater than zero that is not in the list. The usual version adds the real challenge: do it in linear time while using only constant extra memory, which rules out both sorting and a hash set.

Arrays and answers worked out for this page
ArrayAnswerReason
[5, 2, -1, 1]31 and 2 are present, 3 is not
[2, 3, 4]11 itself is missing
[1, 2, 3]41 to n all present, so the answer is n + 1
[6, 9, 8]1Every value is larger than n
[1, 1, 0, 2, 2]3Duplicates and zero do not help fill 3
[]1Nothing is present
Arrays and answers worked out for this page. Scroll sideways on a small screen.

Why interviewers like it

The problem is listed as hard mostly because of the space limit. Without it, a set solves it in a few lines. With it, you need the insight that the answer is bounded by n + 1, and then the nerve to treat the input array as your own scratch space. Interviewers are checking whether you can find that bound by reasoning, and whether your in-place loop terminates and handles duplicates.

Follow-ups

  • You may not modify the input. Then you need O(n) extra space, a set or a boolean array of size n + 1, or O(n log n) time with a sorted copy.
  • Find all missing numbers from 1 to n. Same placement pass, then report every index whose value is wrong.
  • Find the duplicate and the missing number together. After placement, the slot that holds the wrong value gives both: its value is the duplicate and its index plus one is missing.
  • The input is a stream too large to store. A bitmap over 1 to n, or several passes over ranges, trades memory for passes.

Simple version with a set

Put every value in a set, then count up from 1 until you reach a number that is not in it. The loop stops after at most n + 1 checks because only n values exist. This is O(n) time and O(n) space, and it is the answer to give first. Then say what the space limit forces you to change.

def first_missing_with_set(nums):
    present = set(nums)
    candidate = 1
    while candidate in present:
        candidate += 1
    return candidate
Hash set and a counter. O(n) time, O(n) space.

Sending each value to its home index

Since only 1 to n matter, give each of those values a home: value v belongs at index v - 1. Walk the array. While the current slot holds a value in range that is not already at home, swap it to its home. The value that comes back may also need moving, hence the while loop. Values out of range, and duplicates whose home is already correct, stay where they are. Afterward, the first index i whose value is not i + 1 tells you that i + 1 is missing.

def first_missing_positive(nums):
    n = len(nums)
    for i in range(n):
        # Keep moving nums[i] to its home slot (value v belongs at index v - 1)
        # until the value here is out of range or already has a copy at home.
        while 1 <= nums[i] <= n and nums[nums[i] - 1] != nums[i]:
            home = nums[i] - 1
            nums[i], nums[home] = nums[home], nums[i]
    for i in range(n):
        if nums[i] != i + 1:
            return i + 1
    return n + 1
In-place placement. O(n) time, O(1) extra space; reorders the input.

The nested loop looks quadratic but is not. Every swap puts at least one value into its final home, and a value at home is never moved again, so there are at most n swaps in total across the whole run. The guard nums[nums[i] - 1] != nums[i] is what stops an endless loop on duplicates: if the home already holds the same value, there is nothing to gain by swapping.

Marking with signs, in JavaScript

A second constant-space approach uses the sign of each slot as a seen flag. First replace every value that cannot be the answer, zero, negatives and anything above n, with n + 1, so all values are positive. Then, for each value v in range, make the slot at index v - 1 negative. Read absolute values, since a slot may already have been flipped. The first slot that is still positive marks the missing number.

function firstMissingPositive(nums) {
  const n = nums.length;
  // Step 1: values that can never be the answer become n + 1.
  for (let i = 0; i < n; i++) {
    if (nums[i] <= 0 || nums[i] > n) nums[i] = n + 1;
  }
  // Step 2: for each value v in 1..n, mark index v - 1 by making it negative.
  for (let i = 0; i < n; i++) {
    const v = Math.abs(nums[i]);
    if (v <= n && nums[v - 1] > 0) nums[v - 1] = -nums[v - 1];
  }
  // Step 3: the first index still positive was never marked.
  for (let i = 0; i < n; i++) {
    if (nums[i] > 0) return i + 1;
  }
  return n + 1;
}
Three passes: clean, mark, scan. O(n) time, O(1) extra space.

Both in-place versions overwrite the caller's array. If that matters, say so and offer to restore it: the sign version can flip signs back, the swap version cannot recover the original order.

Cost comparison

n values in the input
ApproachTimeExtra spaceChanges the input
Hash setO(n)O(n)No
Sort, then scanO(n log n)O(1) to O(n)Yes, unless you copy
Swap values homeO(n)O(1)Yes
Sign markingO(n)O(1)Yes, values replaced
n values in the input. Scroll sideways on a small screen.

Edge cases

  • Empty array: the answer is 1.
  • Only negatives and zeros: the answer is 1.
  • A complete run 1 to n in any order: the answer is n + 1.
  • Duplicates of a value in range, which must not cause an infinite swap loop.
  • Values far above n, including the largest integer your language allows.

Mistakes to avoid

  • Checking nums[i] != i + 1 as the swap condition instead of comparing with the value at home, which loops forever on duplicates.
  • Swapping with an index computed after nums[i] has already changed. In Python the tuple assignment above is safe because home is saved first; inline index expressions are not.
  • In the sign version, reading nums[i] instead of its absolute value after earlier marks.
  • Forgetting the n + 1 case when every slot is correct.
  • Calling the swap loop O(n²) and abandoning a correct idea, or calling it O(n) without the at-most-n-swaps argument.

Talking it through

Fictional example

Getting from a set to constant space
Candidate
With a set this is easy: add everything and count up from one. But that's linear space.
Candidate
The answer can't be bigger than n plus one, because n values can fill at most the slots one to n. So I only care about values in that range, and I have exactly n slots to track them.
Candidate
I'll swap each in-range value to index value minus one, skipping it if the home already holds the same number. Every swap settles one value for good, so it's linear overall.
Candidate
Then the first index that doesn't hold index plus one gives the answer, or n plus one if they all match.

Majority Element is another array question where a constant-space trick replaces a hash map. Sort Colors also rearranges values in place by swapping them toward where they belong, and Move Zeroes is a gentler in-place exercise. When a hash map is the right tool, Two Sum is the classic example. See the coding problems hub for more.

Practicing with Natively

First Missing Positive is easy to half-remember. When you practice it, Natively can read the problem from a screenshot on Mac or Windows and set out the bound and the placement loop in its overlay, so you can see where your version differs. It also transcribes spoken mock interviews, which helps you check whether you justified the linear running time out loud. More on Natively for coding interviews.

Questions people ask

How do you solve First Missing Positive in O(1) space?

Place each value v between 1 and n at index v - 1 by swapping, skipping duplicates whose home already holds v. Then return the first i + 1 where nums[i] is not i + 1, or n + 1 if all match.

Why is the answer at most n + 1?

An array of n values can contain at most the n numbers 1 to n. If all of them are present the answer is n + 1; otherwise one of 1 to n is missing.

Is the swapping solution really O(n)?

Yes. Each swap moves at least one value into its final slot, and a value in its final slot is never moved again, so there are at most n swaps overall.

Can I solve First Missing Positive without changing the array?

Not in O(n) time and O(1) space. Without modifying it, use a hash set for O(n) time and space, or sort a copy for O(n log n) time.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP