Skip to contentKEEP THE CRAFTTHE SANCTUARY

Cyclic Sort

Place each integer v in 1..n at index v-1, stopping when a duplicate already occupies its home. Use the resulting mismatches to identify missing values.

1 practice exercise1 interview problem

Recognize it when A length-n array contains integers restricted to 1..n, with missing or repeated values.

Checking your account…

Cyclic Sort Code Labs

Derive the Home from the Value

For an array of length n, these Labs accept integers in 1..n. Value 1 belongs at index 0, and value n belongs at index n-1. This direct address is why placement can avoid comparison sorting. It is also a precondition: subtracting one from an arbitrary negative value does not produce a safe destination.

Reconsider What a Swap Brings Back

At the current index, compute the home of its value. If that home holds a different value, exchange them. One home is now correct, but the value returned to the cursor may still belong elsewhere, so the cursor does not advance. This is the cycle being followed; it is not a full pass that swaps each position only once.

Trace Cyclic Placements

Reference
def cyclic_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 cyclic_trace(values). Values are 1..n; return the array after each swap toward home index value-1.

Public tests

  • Follow displaced values until settled

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

Trace Cyclic Placements

def cyclic_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

Follow a Three-Swap Cycle

Predict cyclic_trace([2,4,1,3]). The trace records copied arrays after exchanges, so each row below identifies a real statement that creates one snapshot.

Step Executed statement State Why
1 home=values[index]-1 index=0; home=1; values=[2,4,1,3] Value 2 directly names its home at index 1.
2 values[index],values[home]=values[home],values[index]; trace.append(values.copy()) values=[4,2,1,3]; trace=[[4,2,1,3]] Home 1 is filled; index stays 0 to handle incoming 4.
3 values[index],values[home]=values[home],values[index]; trace.append(values.copy()) home=3; values=[3,2,1,4] The next exchange settles 4 without losing the displaced 3.
4 values[index],values[home]=values[home],values[index]; trace.append(values.copy()) home=2; values=[1,2,3,4] Settling 3 brings 1 to its own index and ends this cycle.
5 else: index+=1 index=4; trace has 3 snapshots Every remaining home already has its value, so advancing finishes the scan.
Print Output
print(cyclic_trace([2,4,1,3])) [[4, 2, 1, 3], [3, 2, 1, 4], [1, 2, 3, 4]]

Equal Occupants End the Cycle

With duplicates, not every index can hold its own value. For [1,1], the second 1 finds its home already occupied by 1. Swapping equal occupants would change nothing, so the equality guard advances instead. Each successful exchange fills a home; each nonexchange advances the cursor. Together these facts bound the core placement work by O(n).

Find All Missing Values

Reference
def find_missing(values):
    values=values.copy();index=0
    while index<len(values):
        home=values[index]-1
        if values[index]!=values[home]:values[index],values[home]=values[home],values[index]
        else:index+=1
    return [index+1 for index,value in enumerate(values) if value!=index+1]
Practice

Implement find_missing(values). Values are in 1..n and may repeat; return absent values after cyclic placement.

Public tests

  • Treat duplicate occupancy as settled

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

Find All Missing Values

def find_missing(values):
    values=values.copy();index=0
    while index<len(values):
        home=values[index]-1
        if values[index]!=values[home]:values[index],values[home]=values[home],values[index]
        else:index+=1
    return [index+1 for index,value in enumerate(values) if value!=index+1]

After placement, a mismatch at index i means that i+1 is absent. Report the expected occupant, not the displaced value currently stored there. Duplicates account for those mismatches without requiring a separate frequency map.

Account for Copies and Preserve the Contract

Both Labs copy the caller’s list before placing values. That choice preserves input order outside the function and costs O(n) space. The trace additionally copies n cells after each exchange, so a linear placement algorithm can produce quadratic diagnostic output. An implementation that mutates its input can keep only the index and home as working state, but must explicitly permit that mutation.

Explain the Interview Selection Boundary

Choose this pattern for a guaranteed bounded 1-based domain when placement or missing values matter. Use the guarded index-mapping variant when irrelevant negative or oversized values may appear; use a set when mutation is forbidden and extra storage is acceptable. General comparison sorting remains appropriate for arbitrary ordered values and costs O(n log n).

Template To Memorize

Learn this shape by heart; most problems in this family change only one or two lines of it.

Cyclic sort: send each number home

Each value v belongs at index v - 1; swap until it gets there.

Values are in the range 1..n (or 0..n) and you look for missing or duplicated values in O(1) extra space.

Trigger words

  • values 1..n
  • missing number
  • first missing positive
  • all duplicates in 1..n
  • index as a mark
def find_missing(nums):              # values are 1..n
    i = 0
    while i < len(nums):
        home = nums[i] - 1
        if 0 <= home < len(nums) and nums[i] != nums[home]:
            nums[i], nums[home] = nums[home], nums[i]
        else:
            i += 1
    missing = []
    for i, num in enumerate(nums):
        if num != i + 1:
            missing.append(i + 1)
    return missing

Spot it when

  • 'Find all missing / duplicate numbers'.
  • 'First missing positive'.

Remember

  • Each swap puts one value in its final place, so there are at most n swaps: O(n).
  • If you must not change the input, mark seen values another way (a set, or negative signs on a copy).

How problems bend it

  • Duplicates: After placing, every index i with nums[i] != i + 1 holds a duplicate value.
  • Mark instead of swap: Flip nums[abs(v) - 1] negative to mark v as seen.

Python Version Note

Complexity & Invariants

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

OperationAverageWorstInterview note
Place bounded values and find missing positionsO(n)O(n)Every successful swap settles a home, so there are at most n swaps; the final scan is linear.

Space

O(n) for the Labs' copied array, plus O(n) possible missing-value output.

Assumptions

  • cyclic_trace copies the entire array after each swap, making its diagnostic time and output O(n²) in the worst case.
  • Both existing Labs first copy values; the placement loop alone can use O(1) extra space when mutation is allowed.
  • Python list.copy() is shallow and linear; integers need no nested-object copy here.

Invariants Worth Saying Aloud

  1. Each completed swap fills a home with its own value.
  2. The cursor stays in place after a swap because the incoming value has not been checked.
  3. When the destination already holds the same value, advancing prevents a duplicate from causing repeated no-op swaps.

When To Use Or Avoid Cyclic Sort

Use It When

  • The range 1..n is guaranteed and equal values may share one home.
  • Reordering is allowed, or an explicit copy fits the space budget.

Choose Another Tool When

  • Values lie outside 1..n without a guard; value-1 may be an invalid or negative index.
  • The task needs a stable order or sorting arbitrary comparable values; comparison sorting has a broader contract.

Common Pitfalls

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

Using a value as a zero-based index

Value n belongs at n-1; indexing n is outside a length-n list.

Prevent it: Translate v to v-1 after establishing the 1..n domain.

Avoid

home=values[index]
occupant=values[home]

Use instead

home=values[index]-1
occupant=values[home]

Swapping equal duplicate occupants forever

A misplaced duplicate can have a different cursor and home even though both slots already contain the same value. A swap then makes no progress.

Prevent it: Compare the values at the two slots, not just whether their indices differ.

Avoid

should_swap=index!=home

Use instead

should_swap=values[index]!=values[home]

Reporting the displaced value as missing

At a mismatched position, the stored value is present elsewhere; the missing value is the intended occupant.

Prevent it: Convert the mismatched index back to its 1-based value.

Avoid

missing=value

Use instead

missing=index+1

Reviewed References

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