DSA Tracker

Medium

Rotate Array

A medium Arrays problem included in Apna College, Striver A2Z. Below: the roles whose interviews prioritise this topic, and how to practise it.

Topic
Arrays
Sheets
2
Core for
25 roles
Platform
LeetCode

The problem

Given an array and a non-negative integer k, rotate the array to the right by k steps.

Example 1

Input
[1,2,3,4,5,6,7], k=3
Output
[5,6,7,1,2,3,4]

Example 2

Input
[-1,-100,3,99], k=2
Output
[3,99,-1,-100]

Example 3

Input
[1], k=0
Output
[1]

Constraints

  • 1 <= n <= 10^5
  • -2^31 <= arr[i] <= 2^31-1
  • 0 <= k <= 10^5

How to think about it

Updated 2026-09-09

Rotating an array by k steps splits it into two blocks that swap their relative positions: the prefix of length n - k and the suffix of length k. Reversing each section individually orients their contents backwards, and reversing the entire array flips them back into their correct relative order in place.

Approaches, worst first

  1. Auxiliary buffer indexing

    time O(n) · space O(n)

    Create a new array and place each element arr[i] into (i + k) % n. Simple and straightforward to write, but allocates a complete copy of the array instead of rearranging values in place.

  2. Three-step block reversalWrite this one

    time O(n) · space O(1)

    First reduce k modulo n. Reverse the entire array from 0 to n - 1. Then reverse the first k elements from 0 to k - 1, and finally reverse the remaining n - k elements from k to n - 1. Every element moves to its designated spot without extra allocations.

Where people lose marks · 3
  • Neglecting to reduce k modulo n when k >= n, causing an out-of-bounds index boundary during subarray reversal.
  • k = 0 or k % n = 0 must leave the array intact without running invalid slice ranges.
  • A single-element array where reversing boundaries overlap must terminate cleanly.

Full solution

Three-step block reversal: reverse the whole array, then each of the two blocks, all in place. It is O(n) time like the buffer copy but O(1) space, which is exactly the follow-up an interviewer asks after the obvious (i + k) % n version.

Python
def rotate_array(arr: list[int], k: int) -> list[int]:
    n = len(arr)
    k %= n  # k >= n wraps around; k % n == 0 leaves the array untouched

    def reverse(lo: int, hi: int) -> None:
        while lo < hi:
            arr[lo], arr[hi] = arr[hi], arr[lo]
            lo += 1
            hi -= 1

    reverse(0, n - 1)  # whole array: the last k now sit first, but backwards
    reverse(0, k - 1)  # fix the order of the moved block
    reverse(k, n - 1)  # fix the order of the rest
    return arr
JavaScript
function rotateArray(arr, k) {
  const n = arr.length;
  k %= n; // k >= n wraps around; k % n === 0 leaves the array untouched
  const reverse = (lo, hi) => {
    while (lo < hi) {
      [arr[lo], arr[hi]] = [arr[hi], arr[lo]];
      lo++;
      hi--;
    }
  };
  reverse(0, n - 1); // whole array: the last k now sit first, but backwards
  reverse(0, k - 1); // fix the order of the moved block
  reverse(k, n - 1); // fix the order of the rest
  return arr;
}
Try it in the editor

The theory behind it

Arrays — the ground this problem stands on. All Arrays problems

What Arrays is

An array is a row of fixed boxes laid side by side in computer memory, like numbered lockers in a hallway. Because each box occupies identical space and sits directly next to its neighbors, jumping to locker zero or locker ten thousand takes the exact same tiny fraction of time. Every box holds an item of the same type, addressed by an offset number called an index.

When to reach for it

Reach for an array when items arrive in a known sequence and need immediate retrieval by position number. Problems asking for running totals, prefix accumulations, cyclic rotations, or in-place rearrangements signal array mechanics. Whenever constraints require constant-time random lookups or contiguous cache scans across fixed collections, a flat sequence is the default container.

How the pattern works

Visualize a tape with zero-indexed slots stretching from start to end. Keep track of write and read cursors when modifying contents without allocating helper buffers. For running computations, maintain an invariant such as having processed all elements left of the current index while pending elements wait to the right. When modifying entries in place, consider scanning backwards from the end so unread data is not overwritten.

What each operation costs

OperationTime
look up element by indexO(1)
insert or delete at the startO(n)
search an unsorted collection for a valueO(n)
What usually goes wrong with Arrays
  • Reading past the final index by checking index less than or equal to length instead of strictly less than length, triggering index out of bounds exceptions.
  • Modifying length or removing elements during a forward iteration loop, which causes remaining items to shift left and skip validation on the next neighbor.
  • Assuming dynamic resizing is costless inside nested loops, causing repeated memory reallocation copies when appending unknown quantities of items.

Which roles need this problem

Arrays is a core topic for these 25 roles — if you're targeting one of them, this problem is early in your path, not optional.

Secondary for 3 more roles, including Database Engineer, Bioinformatics Engineer, Networking Engineer.

Track this in your role's order

Pick your target role and all 370 problems — including this one — resequence to what that interview actually asks. Free.

Start free

More Arrays problems

Problem set and role mapping as of .