⬅ Previous Topic
Left Rotate an Array by One PlaceNext Topic ⮕
Move Zeroes in Array to End⬅ Previous Topic
Left Rotate an Array by One PlaceNext Topic ⮕
Move Zeroes in Array to EndTopic Contents
Given an array arr
of integers and an integer k
, your task is to rotate the array to the left by k
positions.
In a left rotation, each element of the array is shifted to the left by one index, and the first elements are moved to the end in order.
The goal is to perform this rotation efficiently using an optimal in-place algorithm with O(n) time and O(1) extra space.
arr
of size n
and a value k
.k
using k = k % n
to handle overflow.k
elements.n - k
elements.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))
Case | Time Complexity | Explanation |
---|---|---|
Best Case | O(n) | In all cases, the reversal algorithm performs three full reversals of parts of the array, resulting in linear time complexity. |
Average Case | O(n) | Regardless of the value of k, the algorithm always reverses the same number of elements in total, leading to consistent linear time. |
Average Case | O(n) | Even in the worst case (e.g., k = n - 1), the three-reversal strategy still results in traversing each element once, so the complexity is linear. |
O(1)
Explanation: The algorithm operates in-place and uses only a constant number of temporary variables to perform reversals. No additional data structures are needed.
We will left rotate the array by 3
places using the reversal algorithm.
Step 1: Reverse the first 3
elements.
Step 2: Reverse the remaining 4
elements.
Step 3: Reverse the entire array.
⬅ Previous Topic
Left Rotate an Array by One PlaceNext Topic ⮕
Move Zeroes in Array to EndYou 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.