Concept – Array Rotation in DSA
Array Rotation in DSA involves shifting the elements of an array either to the left or right by a specified number of positions.
Example:
Consider an array,
A = [1, 2, 3, 4, 5].
- Left Rotation by 2:
- Result:
[3, 4, 5, 1, 2]
- Result:
- Right Rotation by 2:
- Result:
[4, 5, 1, 2, 3]
- Result:
Approach:
- Naive Approach (One by One Rotation):
- For a left rotation, move the first element to the end and shift all others one position left.
- Repeat this process
d
times ford
rotations.
- Efficient Approach (Reversal Algorithm):
- Left Rotation:
- Reverse the first
d
elements. - Reverse the remaining
n-d
elements. - Reverse the entire array.
- Reverse the first
- Right Rotation:
- Reverse the entire array.
- Reverse the first
d
elements. - Reverse the remaining
n-d
elements.
- Left Rotation:
Time Complexity:
- Naive Approach: O(n×d)
- Reversal Algorithm: O(n)
Visual Explanation
Example Array: A = [1, 2, 3, 4, 5]
Left Rotation by 2 using Reversal Algorithm:
- Step 1: Reverse the first
d=2
elements.- Reverse
[1, 2]
→[2, 1]
- Array becomes:
[2, 1, 3, 4, 5]
- Reverse
- Step 2: Reverse the remaining
n-d=3
elements.- Reverse
[3, 4, 5]
→[5, 4, 3]
- Array becomes:
[2, 1, 5, 4, 3]
- Reverse
- Step 3: Reverse the entire array.
- Reverse
[2, 1, 5, 4, 3]
→[3, 4, 5, 1, 2]
- Final rotated array:
[3, 4, 5, 1, 2]
- Reverse
Right Rotation by 2 using Reversal Algorithm:
- Step 1: Reverse the entire array.
- Reverse
[1, 2, 3, 4, 5]
→[5, 4, 3, 2, 1]
- Array becomes:
[5, 4, 3, 2, 1]
- Reverse
- Step 2: Reverse the first
d=2
elements.- Reverse
[5, 4]
→[4, 5]
- Array becomes:
[4, 5, 3, 2, 1]
- Reverse
- Step 3: Reverse the remaining
n-d=3
elements.- Reverse
[3, 2, 1]
→[1, 2, 3]
- Final rotated array:
[4, 5, 1, 2, 3]
- Reverse