← Questions
First missing positive integer in an unsorted list
0
I was asked this
No reports yet. Sign in to say where you were asked it.
Given an unsorted list of integers that may include negatives, zeros, duplicates and values far larger than the list's length, return the smallest positive integer that does not appear in it. A linear-time solution with extra memory is a fine start; the target is linear time and constant extra space.
Interface
Unless you agree on a different interface with the interviewer, assume:
-
first_missing_positive(nums: list[int]) -> int— the smallest integer>= 1not innums. You may rearrange or overwritenums.
Example
first_missing_positive([7, 1, 0, 2, -5]) -> 3
first_missing_positive([2, 3, 4]) -> 1 # 1 is missing, however large the rest are
first_missing_positive([1, 1, 2, 2, 3]) -> 4
Constraints
-
1 <= len(nums) <= 10^5; values are 32-bit signed integers. - Target: O(n) time, O(1) extra space.
Clarifying questions
- May I modify the input list?
- Does "constant extra space" allow overwriting the input?
- Can values be at the 32-bit limits, so negating or adding might overflow?
- Is a sort, O(n log n), acceptable as a first step?
What a strong answer covers
- The bound: for a list of length
nthe answer is in1..n+1, so values outside[1, n]never matter. - A hash-set solution first, O(n) time and space.
- Cyclic placement: swap each value
vin[1, n]into indexv - 1until it is home or a duplicate is already there, then scan for the first indexiwithnums[i] != i + 1. Each swap places one value for good, so the total is O(n). - The duplicate check that prevents an endless swap loop, and an alternative that marks presence by negating
nums[v - 1]after clearing non-positives. - Tests: all negatives,
[1..n]complete, duplicates, a single element.
Follow-ups
- The input is read-only. What is the best you can do in time and space?
- Return the
ksmallest missing positive integers. - The numbers arrive as a stream too large to store. How would you find the answer, or an approximation?
No official answer yet. Write yours on the right and run it.
Nothing published yet.
Sign in to submit your code; every attempt is kept here.
Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding
