Algorithm Steps
- Given an array
arr
of sizen
and a valuek
. - Normalize
k
usingk = k % n
to handle overflow. - Reverse the first
k
elements. - Reverse the remaining
n - k
elements. - Reverse the entire array to get the final rotated form.
Left Rotate Array by K Places - Optimal Approach (Reversal Algorithm) Code
Python
JavaScript
Java
C++
C
def reverse(arr, start, end):
while start < end:
arr[start], arr[end] = arr[end], arr[start]
start += 1
end -= 1
def left_rotate(arr, k):
n = len(arr)
k = k % n
reverse(arr, 0, k - 1)
reverse(arr, k, n - 1)
reverse(arr, 0, n - 1)
return arr
# Sample Input
arr = [1, 2, 3, 4, 5, 6, 7]
k = 2
print("Rotated Array:", left_rotate(arr, k))
Detailed Step by Step Example
We will left rotate the array by 3
places using the reversal algorithm.
{ "array": [10,20,30,40,50,60,70], "showIndices": true }
Step 1: Reverse the first 3
elements.
{ "array": [10,20,30,40,50,60,70], "showIndices": true, "labels": { "0": "start", "2": "end" }, "highlightIndices": [0,1,2] }
{ "array": [30,20,10,40,50,60,70], "showIndices": true, "labels": { "0": "start", "2": "end" } }
Step 2: Reverse the remaining 4
elements.
{ "array": [30,20,10,40,50,60,70], "showIndices": true, "labels": { "3": "start", "6": "end" }, "highlightIndices": [3,4,5,6] }
{ "array": [30,20,10,70,60,50,40], "showIndices": true, "labels": { "3": "start", "6": "end" } }
Step 3: Reverse the entire array.
{ "array": [30,20,10,70,60,50,40], "showIndices": true, "labels": { "0": "start", "6": "end" }, "highlightIndices": [0,1,2,3,4,5,6] }
{ "array": [40,50,60,70,10,20,30], "showIndices": true, "labels": { "0": "start", "6": "end" } }
Final Rotated Array:
{ "array": [40,50,60,70,10,20,30], "showIndices": true, "highlightIndicesGreen": [4,5,6] }