Introduction
The Rotate Array problem involves shifting the elements of an array by k positions.
Given an array arr[] of size n and an integer k, the task is to rotate the array to the right by k steps.
In right rotation:
- the last elements move to the beginning
- remaining elements shift toward the right
This is an important array manipulation problem that helps in understanding array reversal, modular arithmetic, and in-place transformations.
Example:
Input: arr[] = [1, 2, 3, 4, 5, 6]k = 2
Output: [5, 6, 1, 2, 3, 4] Explanation:
After rotating by 2 positions:
5 and 6 move to the front
Input: arr[] = [10, 20, 30, 40, 50]
k = 3
Output: [30, 40, 50, 10, 20]
Explanation:
Last 3 elements shift to the beginning.
Remaining elements move to the right.
Constraints
1 <= n <= 10^5
0 <= k <= 10^5
-10^9 <= arr[i] <= 10^9Approach 1 : Brute Force (Using Extra Array)
Explanation
The simplest way to rotate the array is:
- Create another array
- Place each element at its new rotated position
- Copy elements back if required
The new index after rotation is calculated using:
newIndex = (i + k) % nThis approach is simple but requires extra space
Steps
- Create a new array of size n.
- Traverse the original array.
- Calculate rotated index using modulo operation.
- Place elements at correct rotated positions.
- Return rotated array.
Dry Run
Input Array: [1, 2, 3, 4, 5, 6]k = 2
n = 6
Move 1 to index (0 + 2) % 6 = 2
Move 2 to index (1 + 2) % 6 = 3
Move 3 to index (2 + 2) % 6 = 4
Move 4 to index (3 + 2) % 6 = 5
Move 5 to index (4 + 2) % 6 = 0
Move 6 to index (5 + 2) % 6 = 1
Final Result:
[5, 6, 1, 2, 3, 4]
Brute Force Code
Complexity Analysis
Time Complexity: O(n)Explanation:
Every element is moved once.
Space Complexity: O(n)
Explanation:
An extra array is used for rotation.
Approach 2 : Optimized Solution (Array Reversal Technique)
Explanation
We can rotate the array in-place using the Reversal Algorithm.
For right rotation by k:
- Reverse entire array
- Reverse first k elements
- Reverse remaining elements
This avoids extra space usage.
Steps
- Calculate:
- k=k%n.
- Reverse the entire array.
- Reverse first k elements.
- Reverse remaining n-k elements.
- Final array becomes rotated.
Dry Run
Input Array: [1, 2, 3, 4, 5, 6]k = 2
Reverse entire array:
[6, 5, 4, 3, 2, 1]
Reverse first 2 elements:
[5, 6, 4, 3, 2, 1]
Reverse remaining elements:
[5, 6, 1, 2, 3, 4]
Final Result:
[5, 6, 1, 2, 3, 4]
Optimized Code