Skip to main content
PreparationZone Logo
PreparationZone
Back to Fundamentals

Fundamentals · Medium · Free

Rotate an array by k steps — juggling or reversal method.

FresherFundamentalsData Structures & Algorithms
Model answer

Rotate array by k

Reverse whole array, reverse first k, reverse rest—O(n) in-place.

java
void rotate(int[] a, int k) {
  k %= a.length;
  reverse(a, 0, a.length - 1);
  reverse(a, 0, k - 1);
  reverse(a, k, a.length - 1);
}
Also juggling algorithm—reversal is easiest to code live.