Workspace Kth Permutation
0d
Back to questionsDSA Visualizers: 388 Coding Questions

Kth Permutation visualizer

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.

1 / 5Execution step
Reference example · JavaScript
Inspect reference input
{
  "n": 4,
  "k": 9
}

Algorithm source

JavaScript reference implementation · highlighted trace statement
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
};

Execution canvas

Active Changed
STEP 1

Skip factorial-sized blocks

Inspect the highlighted code and the state below. Click individual cells or nodes to see their values.

Remaining3 items
Output1 items
Rank1 items
Keyboard: Space to play · Left / Right to stepExplore next problem

Worked example and algorithm walkthrough

Topic: Recursion & Backtracking · Constraint search

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

  1. 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
};

Continue learning

Practice related DSA questions in the same topic.