⬅ Previous Topic
Remove Duplicates from Sorted ArrayNext Topic ⮕
Left Rotate an Array by K Places⬅ Previous Topic
Remove Duplicates from Sorted ArrayNext Topic ⮕
Left Rotate an Array by K PlacesTopic Contents
Given an array of integers, your task is to left rotate the array by 1
position. This means that each element moves one place to the left, and the first element is moved to the end of the array.
The operation should be performed in-place using an optimal solution, without using extra space for a new array.
If the array is empty or contains only one element, it should remain unchanged after rotation.
arr
of size n
.first
.first
to the last index of the array.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))
Case | Time Complexity | Explanation |
---|---|---|
Best Case | O(n) | Every element (except the first) needs to be shifted one position to the left, which takes linear time regardless of input. |
Average Case | O(n) | In all scenarios, the array is traversed once to shift elements, resulting in linear time complexity. |
Average Case | O(n) | Even in the worst case, each element is moved exactly once, making the operation linear in the number of elements. |
O(1)
Explanation: Only one temporary variable is used to store the first element. No additional space is required proportional to input size.
Let's left rotate the array by one position.
Store the first element 10
in a temporary variable.
Move 20
from index 1 to index 0.
Move 30
from index 2 to index 1.
Move 40
from index 3 to index 2.
Move 50
from index 4 to index 3.
Set 10
to index 4.
Array after left rotation: [20, 30, 40, 50, 10]
⬅ Previous Topic
Remove Duplicates from Sorted ArrayNext Topic ⮕
Left Rotate an Array by K PlacesYou can support this website with a contribution of your choice.
When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.