← Back to libraryQuestion 87 of 273
⌨️Java CodingIntermediate

Rotate an Array by K Positions

📌 Definition:

Rotate an array to the right by k steps (e.g. [1,2,3,4,5], k=2 -> [4,5,1,2,3]).

📖 Detailed Explanation:

The elegant O(1)-space trick is the reversal algorithm: reverse the whole array, then reverse the first k elements, then reverse the remaining n-k. Take k modulo n first so large k values wrap. O(n) time.

💻 Solutions:
public static void rotate(int[] a, int k) {
    int n = a.length; k %= n;
    reverse(a, 0, n - 1);
    reverse(a, 0, k - 1);
    reverse(a, k, n - 1);
}
private static void reverse(int[] a, int i, int j) {
    while (i < j) { int t = a[i]; a[i++] = a[j]; a[j--] = t; }
}
function rotate(a, k) {
  const n = a.length; k %= n;
  const reverse = (i, j) => { while (i < j) { [a[i], a[j]] = [a[j], a[i]]; i++; j--; } };
  reverse(0, n - 1); reverse(0, k - 1); reverse(k, n - 1);
  return a;
}
def rotate(a, k):
    n = len(a)
    k %= n
    a[:] = a[-k:] + a[:-k] if k else a
    return a
🔑 Key Points:
  • k %= n to handle k > n
  • Reverse whole, then first k, then rest
  • O(n) time, O(1) space
  • Extra-array copy is the simpler O(n)-space variant
🌍 Real-World Example:

Rotation models circular buffers and round-robin scheduling; the reverse-thrice trick is a classic O(1)-space insight.

🎯 Scenario-Based Interview Question:

For k = 7 on a length-5 array, a candidate's code shifts out of bounds. Fix?