Skip to content
Work Practice Products Coding interviews Machine learning coding Quant developer HFT course Blog Method Why me About Book a call

Coding · Arrays and hashing

Smallest positive integer that is missing

Hard · Target 25 minutes · Arrays and hashing· Type asked at

Given an unsorted array nums of integers, return the smallest positive integer that does not appear in it.

Your solution must run in O(n) time and use only O(1) extra space. You may modify the array.

Examples

InputOutputWhy
nums = [3, 4, -1, 1]21 is present, 2 is not.
nums = [1, 2, 0]31 and 2 are both there.
nums = [7, 8, 9, 11, 12]1Nothing small enough to matter.

Constraints

  • 1 ≤ n ≤ 10⁵
  • −2³¹ ≤ nums[i] ≤ 2³¹ − 1
  • O(n) time, O(1) extra space

Hints

Hint 1

Without the space limit this is one line: put everything in a set and count up from 1. The limit is the whole problem.

Hint 2

With n numbers, the answer cannot be larger than n + 1. So only the values 1 to n matter, and everything else can be ignored.

Hint 3

You need a table indexed 1..n that records "present". You already own an array of length n. Put each value v in slot v − 1.

Where people lose marks

  • Guarding the swap with nums[i] != i + 1 instead of nums[v − 1] != v. On a duplicate the loop never ends.
  • In Python, writing the swap as nums[i], nums[nums[i] - 1] = …. The left side is assigned in order, so the second target is computed from the value just written. Take the index into a variable first.
  • Forgetting that the answer can be n + 1, and returning something inside the array when every slot is correct.
  • Assuming the nested loop is O(n²). Each swap places a value at its final position, so the total number of swaps is at most n.
Console⌘/Ctrl + Enter runs

Write a solution and run it against the real test table.


Keep going

Preparing for a real process? Quant interview preparation, or book a free 20-minute call.