Learn Kth Permutation with a step-by-step Recursion & Backtracking visualizer, JavaScript source code and a worked example. Practice constraint search.
INTERACTIVE EXECUTION STUDIO
LEARN BY DOING
Predict. Execute. Understand.
Follow the source code, inspect live state changes, and predict the next operation before revealing it.
Follow the computed execution on the reference input. Advance one step at a time, inspect the changing values and compare your prediction with the final output.
Example input
{
"n": 4,
"k": 9
}
Execution steps
Skip factorial-sized blocks
Computed output
"2314"
JavaScript reference implementation
const solve = ({
n,k
},s)=>{
let a=Array.from({
length:n
},(_,i)=>i+1),o="",f=1;
for(let i=1;
i<n;
i++)f*=i;
k--;
while(a.length){
let i=Math.floor(k/f);
o+=a.splice(i,1)[0];
k%=f;
s("Skip factorial-sized blocks",{
Remaining:a,Output:[...o],Rank:[k]
});
f=a.length?f/a.length:1
}
return o
};