Algorithm Steps
- Given an array
arr
of sizen
. - Store the first element in a temporary variable
first
. - Shift all elements of the array one position to the left (from index 1 to n-1).
- Assign
first
to the last index of the array. - The array is now left-rotated by one place.
Left Rotate an Array by One Place - Optimal Solution Code
Python
JavaScript
Java
C++
C
def left_rotate_by_one(arr):
if not arr:
return arr
first = arr[0]
for i in range(1, len(arr)):
arr[i - 1] = arr[i]
arr[-1] = first
return arr
# Sample Input
arr = [10, 20, 30, 40, 50]
print("After Left Rotation:", left_rotate_by_one(arr))
Detailed Step by Step Example
Let's left rotate the array by one position.
{
"array": [10,20,30,40,50],
"showIndices": true
}
Store the first element 10
in a temporary variable.
Shift index 1
Move 20
from index 1 to index 0.
{
"array": [20,20,30,40,50],
"showIndices": true,
"highlightIndices": [0],
"labels": { "0": "updated" }
}
Shift index 2
Move 30
from index 2 to index 1.
{
"array": [20,30,30,40,50],
"showIndices": true,
"highlightIndices": [1],
"labels": { "1": "updated" }
}
Shift index 3
Move 40
from index 3 to index 2.
{
"array": [20,30,40,40,50],
"showIndices": true,
"highlightIndices": [2],
"labels": { "2": "updated" }
}
Shift index 4
Move 50
from index 4 to index 3.
{
"array": [20,30,40,50,50],
"showIndices": true,
"highlightIndices": [3],
"labels": { "3": "updated" }
}
Place the first element at the end
Set 10
to index 4.
{
"array": [20,30,40,50,10],
"showIndices": true,
"highlightIndices": [4],
"labels": { "4": "rotated" }
}
Final Result:
Array after left rotation: [20, 30, 40, 50, 10]