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

Next Permutation visualizer

Learn Next Permutation with a step-by-step Arrays visualizer, JavaScript source code and a worked example. Practice optimization and matrix.

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 / 3Execution step
Reference example · JavaScript
Inspect reference input
[
  1,
  3,
  2
]

Algorithm source

JavaScript reference implementation · highlighted trace statement
const solve = (a,s)=>{
let i=a.length-2;
while(i>=0&&a[i]>=a[i+1])i--;
if(i>=0){
let j=a.length-1;
while(a[j]<=a[i])j--;
[a[i],a[j]]=[a[j],a[i]];
s("Swap pivot with successor",{
Array:a
},[i,j])
}
let l=i+1,r=a.length-1;
while(l<r){
[a[l],a[r]]=[a[r],a[l]];
s("Reverse suffix",{
Array:a
},[l,r]);
l++;
r--
}
return a
};

Execution canvas

Active Changed
STEP 1

Swap pivot with successor

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

Array3 items
Keyboard: Space to play · Left / Right to stepExplore next problem

Worked example and algorithm walkthrough

Topic: Arrays · Optimization and matrix

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

[
  1,
  3,
  2
]

Execution steps

  1. Swap pivot with successor
  2. Reverse suffix

Computed output

[
  2,
  1,
  3
]
JavaScript reference implementation
const solve = (a,s)=>{
  let i=a.length-2;
  while(i>=0&&a[i]>=a[i+1])i--;
  if(i>=0){
    let j=a.length-1;
    while(a[j]<=a[i])j--;
    [a[i],a[j]]=[a[j],a[i]];
    s("Swap pivot with successor",{
      Array:a
    },[i,j])
  }
  let l=i+1,r=a.length-1;
  while(l<r){
    [a[l],a[r]]=[a[r],a[l]];
    s("Reverse suffix",{
      Array:a
    },[l,r]);
    l++;
    r--
  }
  return a
};

Continue learning

Practice related DSA questions in the same topic.