Problem: Rotate Array
The Rotate Array problem involves performing left rotations on an array of size `n` such
that each element is shifted `d` units to the left.
SOLUTION
1. Efficient Approach
Instead of performing rotations repeatedly, we calculate the effective rotations and
rearrange the array using slicing or indexing techniques. This improves efficiency.
Python Implementation:
def right_rotate_array(n, d, arr):
# Compute the effective number of rotations
d = d % n # Handles cases where d >= n
# Perform the rotation using slicing
rotated_array = arr[-d:] + arr[:-d]
# Print the result as a space-separated string
print(" ".join(map(str, rotated_array)))
# Input reading
n, d = map(int, input().split()) # Read n and d
arr = list(map(int, input().split())) # Read the array
# Perform right rotations
right_rotate_array(n, d, arr)
C++ Implementation:
#include <iostream>
#include <vector>
using namespace std;
// Function to perform right rotation
void rightRotateArray(int n, int d, vector<int>& arr) {
d = d % n; // Handles cases where d >= n
vector<int> rotatedArray(arr.end() - d, arr.end()); // Get the last d elements
rotatedArray.insert(rotatedArray.end(), arr.begin(), arr.end() - d); // Append the rest
// Print the rotated array
for (int num : rotatedArray) {
cout << num << " ";
}
cout << endl;
}
int main() {
int n, d;
cin >> n >> d; // Read n and d
vector<int> arr(n);
for (int i = 0; i < n; i++) {
cin >> arr[i];
}
// Perform right rotations
rightRotateArray(n, d, arr);
return 0;
}
Comparison of Methods:
Language Time Complexity Space Complexity Best Use Case
Python O(n) O(n) Slicing-based
approach for quick
implementation.
C++ O(n) O(n) STL-based approach
for efficient memory
handling.
Sample Input/Output Explanation
Example 1
Input:
94
123456789
Explanation:
Array: [1, 2, 3, 4, 5, 6, 7, 8, 9]
Right Rotate by 4:
o Last 4 elements [6, 7, 8, 9] move to the front.
o Remaining elements [1, 2, 3, 4, 5] follow.
Result: [6, 7, 8, 9, 1, 2, 3, 4, 5]
Output:
678912345
Example 2
Input:
52
12345
Explanation:
Array: [1, 2, 3, 4, 5]
Right Rotate by 2:
o Last 2 elements [4, 5] move to the front.
o Remaining elements [1, 2, 3] follow.
Result: [4, 5, 1, 2, 3]
Output:
45123
Example 3
Input:
60
10 20 30 40 50 60
Explanation:
Array: [10, 20, 30, 40, 50, 60]
Right Rotate by 0: No change to the array.
Result: [10, 20, 30, 40, 50, 60]
Output:
10 20 30 40 50 60