Left Rotate an Array by D Places — Easy Problem & Solution

Rotate the array arr to the left by d positions and return the result. A left rotation by one moves arr[0] to the end. d may be larger than the array length.

  • Difficulty: Easy
  • Topics: Arrays, Two Pointers
  • Asked at: TCS, Infosys, Wipro, Accenture
  • Time limit: 2 s
  • Memory limit: 256 MB
  • Languages: JavaScript, TypeScript, Python, Java, C++, C, C#, Go, Kotlin, Swift, Rust, PHP and Ruby

Problem statement

Rotate the array arr to the left by d positions and return the result. A left rotation by one moves arr[0] to the end.

d may be larger than the array length.

Example 1

Input: arr = [1,2,3,4,5,6,7], d = 2
Output: [3,4,5,6,7,1,2]
Explanation: The first two elements move to the back.

Example 2

Input: arr = [1,2,3], d = 4
Output: [2,3,1]
Explanation: Rotating by 4 is the same as rotating by 4 mod 3 = 1.

Example 3

Input: arr = [5,5,5], d = 0
Output: [5,5,5]

Constraints

  • 1 <= arr.length <= 100000
  • 0 <= d <= 1000000000
  • 1 <= arr[i] <= 1000000

How to solve Left Rotate an Array by D Places

A left rotation by d splits the array at index d % n and swaps the two blocks. Reducing d modulo n first is what makes a huge d free.

Approach

  1. Compute shift = d % n.
  2. The result is arr[shift..n-1] followed by arr[0..shift-1].
  3. For the in-place version: reverse arr[0..shift-1], reverse arr[shift..n-1], then reverse the whole array.

Why it works

Rotating by n is the identity, so the group of rotations is cyclic of order n and only the residue matters. The three-reversal trick works because reversing a block twice — once alone and once inside the full reversal — restores its order while moving it to the other side.

Complexity

  • Time — O(n)
  • Space — O(n) here; O(1) with the reversal algorithm

Pitfalls

  • Rotating one step at a time d times is O(n·d) and times out for large d.
  • Skipping the modulo indexes past the end as soon as d >= n.

Reference solution

Python

from typing import List

def rotateLeft(arr: List[int], d: int) -> List[int]:
    n = len(arr)
    shift = d % n
    return arr[shift:] + arr[:shift]

JavaScript

var rotateLeft = function(arr, d) {
    var n = arr.length;
    var shift = d % n;
    var out = [];
    for (var i = 0; i < n; i++) out.push(arr[(i + shift) % n]);
    return out;
};

Also on the editorial tab: C, C#, C++, Go, Java, Kotlin, PHP, Ruby, Rust, Swift, TypeScript.

All 667 arrays problems · the whole catalogue