Skip to contentKEEP THE CRAFTTHE SANCTUARY

In-place Index Mapping

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-place Index Mapping Code Labs

Decide Which Values Can Matter

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.

Learn the Placement Mechanism First

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.

Trace Home-Index Placement

Reference
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 trace
Practice

Implement placement_trace(values). Values are in 1..n. Return the array after each swap that moves a value toward index value-1.

Public tests

  • Settle values or detect duplicates

Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor

Trace Home-Index Placement

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 trace

Guard Before Touching a Home

The 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.

Find the First Missing Positive

Reference
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)+1
Practice

Implement first_missing_positive(values). Return the smallest missing positive using in-place index mapping; mutation is allowed.

Public tests

  • Ignore invalid and duplicate values

Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor

Find the First Missing Positive

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)+1

Place Relevant Values and Skip the Rest

Predict 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.
Print 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.

Separate Storage from Diagnostic Output

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.

State the Interview Tradeoff

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 Version Note

Complexity & Invariants

Interview bounds depend on the stated representation, input model, and real Python operations.

OperationAverageWorstInterview note
Find the first missing positive in a mutable listO(n)O(n)Each successful swap fills a home; the placement and final mismatch scan are linear.

Space

O(1) extra space for first_missing_positive; placement_trace copies input and snapshots.

Assumptions

  • placement_trace requires all values in 1..n and can spend O(n²) time and output space on full-array snapshots.
  • first_missing_positive mutates its argument; copying first would add O(n) working space.
  • Python and short-circuits left to right; this makes the range guard protect the following index operation.

Invariants Worth Saying Aloud

  1. A swap places a relevant value v at index v-1.
  2. The range check runs before reading values[home].
  3. Equal destination occupants cause an advance, so duplicates cannot force repeated swaps.

When To Use Or Avoid In-place Index Mapping

Use It When

  • Mutation is allowed and the answer concerns the bounded relevant domain 1..n.
  • An O(n) set is too much working storage and a direct home-index encoding is available.

Choose Another Tool When

  • The caller requires the original list order and a copy is not allowed.
  • Values are arbitrary identifiers without a bounded index mapping; use a set or dictionary.

Common Pitfalls

These are the mistakes most likely to survive a happy-path example and fail a boundary case.

Reading the home before the range guard

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.

Avoid

eligible=values[home]!=value and 1<=value<=len(values)

Use instead

eligible=1<=value<=len(values) and values[home]!=value

Using different indices as the swap guard

Two positions can contain the same duplicate. Exchanging them repeatedly changes no home.

Prevent it: Test whether the destination already holds the current value.

Avoid

should_swap=index!=home

Use instead

should_swap=values[home]!=value

Returning n when every home is occupied

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.

Avoid

answer=len(values)

Use instead

answer=len(values)+1

Reviewed References

Official Python documentation supports language behavior. Canonical problem pages provide additional practice context.