Explorer
JavaScript

Rotate the array to the left by K positions.

Problem Statement

Given an array of integers, left rotate the array by K positions.

Examples

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

Output: [4, 5, 6, 7, 1, 2, 3]

Explanation: Rotated left by 3.

Constraints

Standard constraints

Complexity

Time Complexity: O(N)

Space Complexity: O(1)

Hints

šŸ’” Hint 1: Notice that rotating by k places is equivalent to rotating by k % n places. šŸ’” Hint 2: You can achieve O(1) extra space using the reversal algorithm! šŸ’” Hint 3: Reverse the first k elements, reverse the remaining n - k elements, and then reverse the whole array.

Editorial & Approach

Problem Overview & Intuition

Rotating an array of size N by K places can be solved in O(N) time and O(1) space using the reversal algorithm. By reversing sub-segments [0, k-1] and [k, n-1], and then the whole array, elements cycle into their target positions.

Step-by-Step Approach

  1. Normalize k = k % n.
  2. Reverse the first k elements: indices 0 to k - 1.
  3. Reverse the remaining n - k elements: indices k to n - 1.
  4. Reverse the entire array: indices 0 to n - 1.
  5. Return arr.

Optimal Implementation (JavaScript)

function leftRotateByK(arr, k) {
  const n = arr.length;
  if (n <= 1) return arr;
  k = k % n;
  if (k === 0) return arr;

  function reverse(start, end) {
    while (start < end) {
      [arr[start], arr[end]] = [arr[end], arr[start]];
      start++;
      end--;
    }
  }

  reverse(0, k - 1);
  reverse(k, n - 1);
  reverse(0, n - 1);
  return arr;
}

Complexity Analysis

Time Complexity O(N) — each element is reversed twice.
Space Complexity O(1) — done completely in-place.

Edge Cases & Corner Traps Handled

  • k is 0 or multiple of n: array remains unchanged.
  • k > n: modulo operator handles large k seamlessly.
  • Array of size 1: returns without modification.

Left Rotate Array by K Places

Easy
Given an array of integers, left rotate the array by K positions.
Example Scenarios
1Example 1
Input: arr = [1, 2, 3, 4, 5, 6, 7], k = 3
Output: [4, 5, 6, 7, 1, 2, 3]
Explanation:

Rotated left by 3.

Constraints
•Standard constraints
Editor
Loading Editor...
arr =
[1, 2, 3, 4, 5, 6, 7]
k =
3
Output:Click "Run" above to execute and verify your code here.
[4,5,6,7,1,2,3]