Workspace Rotate Array By K
0d
Back to questionsDSA Visualizers: 388 Coding Questions

Rotate Array by K visualizer

Learn Rotate Array by K with a step-by-step Arrays visualizer, JavaScript source code and a worked example. Practice fundamentals.

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
{
  "a": [
    1,
    2,
    3,
    4,
    5
  ],
  "k": 2
}

Algorithm source

JavaScript reference implementation · highlighted trace statement
const solve = ({
a,k
},s)=>{
function rev(l,r){
while(l<r){
[a[l],a[r]]=[a[r],a[l]];
s("Reverse segment",{
Array:a
},[l,r]);
l++;
r--
}
}
rev(0,a.length-1);
rev(0,k-1);
rev(k,a.length-1);
return a
};

Execution canvas

Active Changed
STEP 1

Reverse segment

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

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

Worked example and algorithm walkthrough

Topic: Arrays · Fundamentals

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

{
  "a": [
    1,
    2,
    3,
    4,
    5
  ],
  "k": 2
}

Execution steps

  1. Reverse segment

Computed output

[
  4,
  5,
  1,
  2,
  3
]
JavaScript reference implementation
const solve = ({
  a,k
},s)=>{
  function rev(l,r){
    while(l<r){
      [a[l],a[r]]=[a[r],a[l]];
      s("Reverse segment",{
        Array:a
      },[l,r]);
      l++;
      r--
    }
  }
  rev(0,a.length-1);
  rev(0,k-1);
  rev(k,a.length-1);
  return a
};

Continue learning

Practice related DSA questions in the same topic.