iq.lab
Python starts when a code cell comes near or you run one
hardHash maps and sets target 40 min

First missing positive

You get a list of integers nums in no particular order. It may hold negative numbers, zeros, repeats, and numbers much larger than its length. Find the smallest positive integer (1, 2, 3, ...) that nums does not contain, and return it.

The limits are the hard part. Your solution must take O(n) time and O(1) extra space, where n is len(nums): a few variables, but no set, dict, sorted copy or second list. You may change nums in place, by moving its items or overwriting them. The tests time your code but cannot measure its memory, so the space rule is yours to keep, as it is in the interview.

Example 1
Inputnums = [2, -3, 1, 5]Output3

1 and 2 are in the list; 3 is not.

Example 2
Inputnums = [4, 1, 2, 3]Output5

Every number from 1 to 4 is present, so the answer is the next one.

Example 3
Inputnums = [7, 8, 0]Output1

1 is missing, so nothing else matters.

Constraints
  • 0 ≤ len(nums) ≤ 105

  • -231 ≤ nums[i] ≤ 231 - 1

  • O(n) time and O(1) extra space; nums may be changed.

Plan it first

Write a line for each before you code, then say them out loud. Compare with the Approach tab afterwards.

⌘+Enter runs 0:00Python starts when a code cell comes near or you run one
Run examples checks the examples. Submit runs every test, including edge cases and, when the problem has one, a speed check on a large input.