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.
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.
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
Python 3.11+
Python list.copy() is shallow and linear; integers need no nested-object copy here.