Python 3.11+
Python and short-circuits left to right; this makes the range guard protect the following index operation.
Verify in Python docs(opens in a new tab)Map relevant positive values to array indices, guard out-of-range values before indexing, and use duplicate-aware swaps to find the first missing positive in O(n) time.
1 practice exercise2 interview problems
Recognize it when The smallest missing positive must be found in a mutable integer array.
Checking your account…
In a length-n integer array, the first missing positive lies in 1..n+1. Only 1..n need homes in the array; a negative integer, zero, or a larger value cannot fill one of those homes. This is the selection rule that extends bounded cyclic placement to arbitrary integer input.
The diagnostic placement_trace Lab uses the simpler 1..n contract and copies input. Follow each value to index value-1, exchanging only unequal occupants. Keeping the cursor after an exchange checks the incoming value before moving on. Duplicates make the occupant comparison essential.
def placement_trace(values):
values=values.copy(); trace=[]; index=0
while index<len(values):
home=values[index]-1
if values[index]!=values[home]:
values[index],values[home]=values[home],values[index]; trace.append(values.copy())
else: index+=1
return traceImplement placement_trace(values). Values are in 1..n. Return the array after each swap that moves a value toward index value-1.
Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor
def placement_trace(values):
values=values.copy(); trace=[]; index=0
while index<len(values):
home=values[index]-1
if values[index]!=values[home]:
values[index],values[home]=values[home],values[index]; trace.append(values.copy())
else: index+=1
return traceThe first_missing_positive Lab adds a range condition before values[home]. Python evaluates and from left to right, so an irrelevant value never reaches that index access. This order matters: negative indices are valid Python syntax and can silently inspect an unrelated tail element.
def first_missing_positive(values):
index=0
while index<len(values):
value=values[index]
home=value-1
if 1<=value<=len(values) and values[home]!=value:
values[index],values[home]=values[home],values[index]
else: index+=1
for index,value in enumerate(values):
if value!=index+1: return index+1
return len(values)+1Implement first_missing_positive(values). Return the smallest missing positive using in-place index mapping; mutation is allowed.
Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor
def first_missing_positive(values):
index=0
while index<len(values):
value=values[index]
home=value-1
if 1<=value<=len(values) and values[home]!=value:
values[index],values[home]=values[home],values[index]
else: index+=1
for index,value in enumerate(values):
if value!=index+1: return index+1
return len(values)+1Predict first_missing_positive([2,-3,1,5]). The negative value and oversized 5 do not have valid homes in this four-element list.
| Step | Executed statement | State | Why |
|---|---|---|---|
| 1 | value=values[index]; home=value-1 |
index=0; value=2; home=1 |
2 is relevant and its home contains a different value. |
| 2 | values[index],values[home]=values[home],values[index] |
values=[-3,2,1,5]; index=0 |
The exchange settles 2, then leaves the cursor to inspect -3. |
| 3 | else: index+=1 |
index=2; values=[-3,2,1,5] |
-3 fails the range check and 2 already occupies its home. |
| 4 | values[index],values[home]=values[home],values[index] |
home=0; values=[1,2,-3,5]; index=2 |
The relevant 1 is placed without trying to index the irrelevant -3. |
| 5 | else: index+=1 |
index=4; values=[1,2,-3,5] |
Both -3 and 5 are outside 1..4, so placement finishes. |
| 6 | if value!=index+1: return index+1 |
scan index=2; value=-3; return=3 |
Homes for 1 and 2 are correct; the next absent occupant is 3. |
| Output | |
|---|---|
print(first_missing_positive([2,-3,1,5])) |
3 |
After placement, inspect indices from zero upward. The first mismatch at i identifies i+1 as the smallest missing positive. If every home is correct, return n+1; returning n would name a value already present. Empty input therefore returns 1 without a special placement step.
first_missing_positive reorders the caller’s array and keeps O(1) extra working state. Its swaps fill homes, so the loop and final scan take O(n). placement_trace instead preserves the caller by copying and saves another full copy after each swap; those snapshots can consume O(n²) time and space. A trace is useful evidence but is not the constant-space implementation.
Use this guarded mapping when the relevant integer domain is bounded and mutation is part of the contract. Use cyclic sort directly if the entire input is guaranteed to lie in 1..n. If order must be preserved, a set gives a simpler O(n) expected-time solution with O(n) storage, or copying before placement explicitly pays the same storage cost.
Python 3.11+
Python and short-circuits left to right; this makes the range guard protect the following index operation.
Verify in Python docs(opens in a new tab)Interview bounds depend on the stated representation, input model, and real Python operations.
| Operation | Average | Worst | Interview note |
|---|---|---|---|
| Find the first missing positive in a mutable list | O(n) | O(n) | Each successful swap fills a home; the placement and final mismatch scan are linear. |
O(1) extra space for first_missing_positive; placement_trace copies input and snapshots.
These are the mistakes most likely to survive a happy-path example and fail a boundary case.
An oversized positive value can raise IndexError before the expression decides that it is irrelevant.
Prevent it: Put the bounded-domain condition on the left side of and.
eligible=values[home]!=value and 1<=value<=len(values)eligible=1<=value<=len(values) and values[home]!=valueWhere you will hit this: Mark Seen Indices(opens in a new tab)
Two positions can contain the same duplicate. Exchanging them repeatedly changes no home.
Prevent it: Test whether the destination already holds the current value.
should_swap=index!=homeshould_swap=values[home]!=valueWhere you will hit this: Mark Seen Indices(opens in a new tab)
If 1..n are all present, n is not missing; the next positive is n+1.
Prevent it: Use the one-past-domain answer after the mismatch scan finds nothing.
answer=len(values)answer=len(values)+1Where you will hit this: Find All Duplicates in an Array(opens in a new tab)
Official Python documentation supports language behavior. Canonical problem pages provide additional practice context.
python-docs · checked 2026-07-27