Skip to content
Work Free practice Coding course Blog Method Results Why me About Enquire Book a call

Coding · Arrays and hashing

Smallest positive integer that is missing

Hard · Target 25 minutes · Arrays and hashing · Type asked atHudson River TradingCitadel

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.

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.