🌟 Introduction
Array rotation is a common problem in Data Structures and Algorithms (DSA), often asked in coding interviews. The task is simple: given an array, shift its elements by k positions either to the left or to the right.
For example
👉 Input: arr = [1, 2, 3, 4, 5], k = 2
👉 Left Rotation: [3, 4, 5, 1, 2]
👉 Right Rotation: [4, 5, 1, 2, 3]
This problem helps you understand array manipulation, modular arithmetic, and in-place algorithms.
🧩 Types of Array Rotation
There are mainly two types of rotation:
Left Rotation: Each element is shifted to the left by one, and the first element goes to the end.
Example:
[1, 2, 3, 4, 5]→[2, 3, 4, 5, 1]
Right Rotation: Each element is shifted to the right by one, and the last element comes to the front.
Example:
[1, 2, 3, 4, 5]→[5, 1, 2, 3, 4]
⚙️ Approaches to Solve the Problem
1️⃣ Naive Approach (Using Extra Space)
Store elements of the array in a temporary array after rotation.
Copy them back to the original array.
⏱️ Time Complexity: O(n)
💾 Space Complexity: O(n)
2️⃣ Juggling Algorithm (Efficient)
Based on finding GCD (Greatest Common Divisor) of
nandk.Rotate elements in sets determined by GCD.
⏱️ Time Complexity: O(n)
💾 Space Complexity: O(1)
3️⃣ Reversal Algorithm (Most Popular)
For left rotation by k:
Reverse first
kelements.Reverse remaining
n-kelements.Reverse the whole array.
For right rotation by k:
Reverse last
kelements.Reverse first
n-kelements.Reverse the whole array.
⏱️ Time Complexity: O(n)
💾 Space Complexity: O(1)
💻 Code Implementations
✅ C++ Code
#include <bits/stdc++.h>using namespace std;
void reverseArray(vector<int>& arr, int start, int end) {
while (start < end) {
swap(arr[start], arr[end]);
start++;
end--;
}
}
void leftRotate(vector<int>& arr, int k) {
int n = arr.size();
k = k % n;
reverseArray(arr, 0, k-1);
reverseArray(arr, k, n-1);
reverseArray(arr, 0, n-1);
}
int main() {
vector<int> arr = {1, 2, 3, 4, 5};
int k = 2;
leftRotate(arr, k);
for (int x : arr) cout << x << " ";
}
Join the conversation! Your thoughts help the community grow.