Skip to contentKEEP THE CRAFTTHE SANCTUARY

Fisher-Yates Shuffle

Finalize one suffix position per uniform draw from the remaining prefix. Use inclusive bounds and a real swap, preserve the caller when the contract requires a copy, and derive equal permutation probability.

1 practice exercise1 interview problem

Recognize it when The task needs a random permutation of all input positions.

Checking your account…

Fisher-Yates Shuffle Code Labs

Choose Uniformly from the Unshuffled Prefix

Fisher-Yates processes positions from the end toward the front. For position i, it chooses uniformly from every index zero through i that has not yet been finalized.

Swap One Final Position per Step

Swap the chosen item into position i, then never touch that suffix position again. The remaining prefix contains exactly the items still available for earlier positions.

Trace Fisher-Yates Swaps

Reference
def shuffle_trace(values,draws):
    values=values.copy();trace=[]
    for offset,index in enumerate(range(len(values)-1,0,-1)):
        chosen=draws[offset];values[index],values[chosen]=values[chosen],values[index];trace.append([index,chosen,values.copy()])
    return trace
Practice

Implement shuffle_trace(values,draws). Moving right to left, draws provides j in [0,i]; return [i,j,state] after each swap.

Public tests

  • Finalize one suffix position each step

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

Trace Fisher-Yates Swaps

def shuffle_trace(values,draws):
    values=values.copy();trace=[]
    for offset,index in enumerate(range(len(values)-1,0,-1)):
        chosen=draws[offset];values[index],values[chosen]=values[chosen],values[index];trace.append([index,chosen,values.copy()])
    return trace

Freeze the Last Position Before the Next Swap

Predict both states of the existing trace Lab. Each row copies the entire current array, so this teaching trace deliberately stores more than the ordinary linear shuffle.

Step Executed statement State Why
Protect caller values=values.copy();trace=[] working list=["a","b","c"] The Lab reorders a separate top-level list.
Finalize index 2 chosen=draws[offset];values[index],values[chosen]=values[chosen],values[index];trace.append([index,chosen,values.copy()]) i=2, j=1, state=["a","c","b"] b moves to its final position; future choices cannot touch index 2.
Finalize index 1 chosen=draws[offset];values[index],values[chosen]=values[chosen],values[index];trace.append([index,chosen,values.copy()]) i=1, j=0, state=["c","a","b"] Only the two remaining prefix items exchange positions.
Complete return trace two snapshots; empty-input trace=[] The remaining index 0 is forced, so no final random draw is needed.
Print Output
print(shuffle_trace(["a","b","c"],[1,0])) [[2, 1, ['a', 'c', 'b']], [1, 0, ['c', 'a', 'b']]]
print(shuffle_trace([],[])) []

Uniformity concerns the set of remaining original positions. Finite deterministic draw lists test exact swaps; a chosen random source must separately meet the probability premise. Python random.shuffle mutates its argument, while this Lab returns copied ordering.

Use Inclusive Random Bounds Correctly

The draw must include both zero and i. Excluding i or choosing from the entire array each time makes permutation probabilities unequal.

Shuffle with Deterministic Draws

Reference
def shuffled(values,draws):
    output=values.copy()
    for offset,index in enumerate(range(len(output)-1,0,-1)):
        chosen=draws[offset];output[index],output[chosen]=output[chosen],output[index]
    return output
Practice

Implement shuffled(values,draws). Return a shuffled copy using supplied inclusive draws. Supply one integer draw j in [0,i] for each descending index i from len(values)-1 through 1, in that order; empty or singleton input needs no draws.

Public tests

  • Keep the caller input unchanged

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

Shuffle with Deterministic Draws

def shuffled(values,draws):
    output=values.copy()
    for offset,index in enumerate(range(len(output)-1,0,-1)):
        chosen=draws[offset];output[index],output[chosen]=output[chosen],output[index]
    return output

Separate In Place and Copying Contracts

Classic Fisher-Yates mutates in place with O(1) auxiliary space. Copy first when caller input must remain unchanged, and inject the random source or draws for deterministic tests.

Explain It in an Interview

Say: “At step i, each remaining item has equal probability of taking final position i. One uniform inclusive draw and swap finalizes it.” State O(n) time, mutation policy, RNG quality, and why repeated arbitrary swaps are biased.

Python Version Note

Python 3.11+

The code uses standard Python syntax and containers supported by the browser Judge. The Fisher-Yates Shuffle proof does not depend on a minor Python release.

Verify in Python docs(opens in a new tab)

Complexity & Invariants

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

OperationAverageWorstInterview note
In-place shuffleO(n)O(n)One bounded-cost draw and swap per suffix position.
Displayed swap traceO(n^2)O(n^2)Each of n-1 iterations copies the full n-item state into the trace.

Space

O(1) in-place algorithm state; O(n) copying shuffle result; O(n^2) returned full-state trace.

Assumptions

  • Draw legality and independence are premises, not certified by one deterministic example.
  • Duplicate values represent distinct input positions; several positional permutations can print the same value sequence.

Invariants Worth Saying Aloud

  1. Positions above i are finalized and never touched again.
  2. Indexes 0 through i contain exactly the remaining eligible original positions.
  3. A copy separates top-level element ordering from caller-owned input.

When To Use Or Avoid Fisher-Yates Shuffle

Use It When

  • Use the right-to-left shuffle with a uniform draw from 0 through i.
  • Use Python random.shuffle for an in-place shuffle when an implementation is not the interview task.

Choose Another Tool When

  • Do not perform arbitrary whole-array swaps and assume the distribution is uniform.
  • Do not promise all permutations under an arbitrary finite-state RNG; the proof assumes ideal independent uniform draws.

Common Pitfalls

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

Omitting the self-swap option

At i=2, every remaining item including the one already there needs probability 1/3. range(i) forbids leaving it in place.

Prevent it: Include i with range(i+1) or randrange(i+1).

Avoid

choices=list(range(index))

Use instead

choices=list(range(index+1))

Overwriting one swap operand before reading it

Assigning values[i] first destroys the old value needed for values[j], producing duplicate items.

Prevent it: Use simultaneous tuple assignment.

Avoid

values[i]=values[j]
values[j]=values[i]

Use instead

values[i],values[j]=values[j],values[i]

Aliasing caller input when a copy is required

output=values names the same list. A correct swap still rearranges the caller and violates the copy contract.

Prevent it: Copy the top-level list before swapping.

Avoid

output=values

Use instead

output=values.copy()

Reviewed References

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