Array Rotation
Linear Time Algorithm
Data Structures
Programming Techniques
Algorithm Optimization

Algorithm to rotate an array in linear time

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

Rotating an array means shifting its elements by k positions while preserving relative order. The classic in-place linear-time solution is the reversal algorithm, which runs in O(n) time and uses O(1) extra space.

Right Rotation With Three Reversals

To rotate right by k positions:

  1. reverse the whole array
  2. reverse the first k elements
  3. reverse the remaining elements

For example, starting with:

text
[1, 2, 3, 4, 5, 6, 7]

Rotate right by 3:

  • reverse all: [7, 6, 5, 4, 3, 2, 1]
  • reverse first 3: [5, 6, 7, 4, 3, 2, 1]
  • reverse rest: [5, 6, 7, 1, 2, 3, 4]

That is the final rotated array.

Python Implementation

Here is a complete in-place implementation:

python
1from typing import List
2
3
4def reverse_segment(arr: List[int], left: int, right: int) -> None:
5    while left < right:
6        arr[left], arr[right] = arr[right], arr[left]
7        left += 1
8        right -= 1
9
10
11def rotate_right(arr: List[int], k: int) -> None:
12    n = len(arr)
13    if n == 0:
14        return
15
16    k %= n
17    if k == 0:
18        return
19
20    reverse_segment(arr, 0, n - 1)
21    reverse_segment(arr, 0, k - 1)
22    reverse_segment(arr, k, n - 1)
23
24
25data = [1, 2, 3, 4, 5, 6, 7]
26rotate_right(data, 3)
27print(data)

This is linear time because each element is touched only a constant number of times across the three reversal passes.

Left Rotation Variant

Left rotation is the mirror image. One clean implementation is:

python
1def rotate_left(arr: List[int], k: int) -> None:
2    n = len(arr)
3    if n == 0:
4        return
5
6    k %= n
7    if k == 0:
8        return
9
10    reverse_segment(arr, 0, k - 1)
11    reverse_segment(arr, k, n - 1)
12    reverse_segment(arr, 0, n - 1)
13
14
15data = [1, 2, 3, 4, 5, 6, 7]
16rotate_left(data, 2)
17print(data)

That produces:

text
[3, 4, 5, 6, 7, 1, 2]

Why Not Use Extra Arrays

If extra memory is allowed, many high-level languages offer simpler syntax such as slicing:

python
1def rotated_copy(arr, k):
2    if not arr:
3        return []
4    k %= len(arr)
5    return arr[-k:] + arr[:-k]

This is still linear time, but it allocates additional memory. The in-place reversal algorithm is preferred when the constraint explicitly says:

  • linear time
  • constant extra space

That is the main reason the reversal method appears so often in interview and systems-programming questions.

Another Linear-Time Option: Juggling

There is also a juggling algorithm based on cycle decomposition and the greatest common divisor. It is linear and in-place as well, but it is usually harder to read and easier to get wrong.

For most practical discussions, the reversal algorithm is the best tradeoff between:

  • performance
  • simplicity
  • ease of verification

So unless you have a very specific reason to prefer cycle-based movement, reversal is usually the clearer answer.

Edge Cases Matter

A robust rotation implementation should handle:

  • empty arrays
  • one-element arrays
  • 'k = 0'
  • 'k larger than the array length'
  • negative or invalid input rules if the API allows them

This is why normalizing k with k %= n is so important. Rotating by the array length should do nothing, and rotating by a larger number should wrap around correctly.

Quick Test Harness

A small test makes off-by-one mistakes easier to catch:

python
1def expected_right(arr, k):
2    if not arr:
3        return []
4    k %= len(arr)
5    return arr[-k:] + arr[:-k] if k else arr[:]
6
7
8cases = [
9    ([], 3),
10    ([1], 99),
11    ([1, 2, 3, 4], 0),
12    ([1, 2, 3, 4], 4),
13    ([1, 2, 3, 4], 5),
14]
15
16for arr, k in cases:
17    actual = arr[:]
18    rotate_right(actual, k)
19    assert actual == expected_right(arr, k)
20
21print("All tests passed")

Common Pitfalls

The most common pitfall is forgetting to reduce k modulo the array length before rotating.

Another mistake is mixing up the left-rotation and right-rotation reversal orders. The steps are similar, but not identical.

A third issue is using slicing or temporary arrays when the problem explicitly requires constant extra space.

Finally, developers sometimes get the segment boundaries wrong during reversal, especially around k - 1 and the split between the two parts.

Summary

  • The reversal algorithm rotates an array in linear time with constant extra space.
  • Right rotation uses three reversals: whole array, first k, then the rest.
  • Left rotation uses the mirrored three-reversal pattern.
  • Normalize k with modulo arithmetic before rotating.
  • The reversal method is usually the clearest in-place solution for this problem.

Course illustration
Course illustration

All Rights Reserved.