Bird
Raised Fist0
Interview PrepbacktrackinghardAmazonGoogleFacebook

Permutation Sequence (Kth)

Choose your preparation mode3 modes available
Steps
setup

Initialize factorial array

Create a factorial array of size n with all elements initialized to 1. This array will store factorial values from 0! to (n-1)!.

💡 Precomputing factorials allows quick calculation of how many permutations start with each number at each position.
Line:factorial = [1] * n
💡 Factorials represent the number of permutations possible for the remaining positions.
📊
Permutation Sequence (Kth) - Watch the Algorithm Execute, Step by Step
Watching this step-by-step reveals how the factorial number system helps directly compute the kth permutation without generating all permutations.
Step 1/13
·Active fillAnswer cell
setup
1
0
1
1
1
2
Result: ""
fill_row
1
0
1
1
i
2
2
Result: ""
setup
1
0
2
1
3
2
Result: ""
setup
1
0
2
1
k
3
2
Result: ""
compare
1
0
idx
2
1
i
3
2
Result: ""
move_left
k
1
0
idx
2
1
i
3
2
Result: ""
delete
k
1
0
3
1
Result: "2"
compare
idx
1
0
i
3
1
Result: "2"
move_left
idx
1
0
i
3
1
Result: "2"
delete
k
3
0
Result: "21"
compare
idx
3
0
Result: "21"
delete
Result: "213"
record
Result: "213"

Key Takeaways

The factorial number system partitions permutations into blocks, allowing direct calculation of the kth permutation without generating all permutations.

This insight is hard to see from code alone because the math behind factorial indexing is abstract without visualization.

At each step, the algorithm selects a digit by dividing k by the factorial of remaining positions, then updates k to the remainder, progressively narrowing down the permutation.

Seeing k and idx update step-by-step clarifies how the algorithm zooms into the correct permutation.

Removing chosen numbers from the list ensures no repeats and reduces the problem size, which is visually clear when watching the array shrink.

This concrete example shows how the numbers list changes, which is less obvious when reading code.