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
- Normalize
k = k % n. - Reverse the first
kelements: indices0tok - 1. - Reverse the remaining
n - kelements: indiceskton - 1. - Reverse the entire array: indices
0ton - 1. - 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.