Rotate Array
Java coding interview problem for Array Coding: Rotate Array.
Array rotation is one of the most frequently asked array interview questions.
This problem tests your understanding of:
- Array Index Manipulation
- Modulo Operation
- In-place Algorithms
- Reversal Technique
- Space Optimization
- Time Complexity
Array rotation concepts are used in many advanced problems:
- Circular Buffers
- Scheduling Algorithms
- Sliding Window Problems
- Data Streaming
- Memory Management
What is Array Rotation?
Array rotation means shifting the elements of an array in a specific direction.
There are two common types:
- Left Rotation
- Right Rotation
Left Rotation
In left rotation,
elements move towards the left.
Example:
Input:
[1,2,3,4,5]
Rotate left by 2 positions.
Step 1:
[2,3,4,5,1]
Step 2:
[3,4,5,1,2]
Output:
[3,4,5,1,2]
Right Rotation
In right rotation,
elements move towards the right.
Example:
Input:
[1,2,3,4,5]
Rotate right by 2 positions.
Step 1:
[5,1,2,3,4]
Step 2:
[4,5,1,2,3]
Output:
[4,5,1,2,3]
Why is This Question Asked in Interviews?
Interviewers ask array rotation problems because they evaluate:
- Array manipulation skills
- Understanding of indexes
- Modulo arithmetic
- Space optimization
- In-place operations
This problem is commonly asked by:
- Amazon
- Microsoft
- Oracle
- Meta
- Apple
Real-World Applications
Array rotation concepts appear in many systems.
Circular Buffer
A queue implemented using a fixed-size array uses rotation logic.
Example:
Memory Slots
[0][1][2][3][4]
When reaching the end:
Return to index 0
Operating System Scheduling
Processes are rotated in:
Round Robin Scheduling
Image Processing
Pixels can be shifted or rotated during transformations.
Data Streaming
Moving windows use rotation concepts.
Gaming
Player turns rotate:
Player 1
↓
Player 2
↓
Player 3
Problem Statement
Given an integer array,
rotate the array by k positions.
Example 1 — Right Rotation
Input:
array = [1,2,3,4,5]
k = 2
Output:
[4,5,1,2,3]
Example 2 — Left Rotation
Input:
array = [1,2,3,4,5]
k = 2
Output:
[3,4,5,1,2]
Example 3
Input:
[10,20,30,40]
k = 1
Right Rotation:
[40,10,20,30]
Understanding Array Rotation
Consider:
[1,2,3,4,5]
Right rotate by 2.
Elements moved:
4 → position 0
5 → position 1
Remaining:
1,2,3
Final:
[4,5,1,2,3]
Mathematical Concept
Array indexes are zero-based.
For right rotation:
New position:
(newIndex)
=
(oldIndex + k) % n
Where:
k= rotation countn= array length
Example:
Array length:
n = 5
Rotate:
k = 2
For element at index 3:
(3 + 2) % 5
Result:
0
Element moves to index 0.
Handling Large Rotation Values
Example:
Array:
[1,2,3,4,5]
Rotate:
k = 12
Since:
12 % 5 = 2
Rotating 12 times is equal to rotating 2 times.
Always normalize:
k = k % n;
Array Rotation Visualization
Input:
[1,2,3,4,5]
Right rotate by 2:
Before:
1 2 3 4 5
Take last two:
4 5
Move to front:
4 5 1 2 3
Dry Run
Input:
[10,20,30,40,50]
k = 3
Right rotation.
First rotation:
[50,10,20,30,40]
Second rotation:
[40,50,10,20,30]
Third rotation:
[30,40,50,10,20]
Answer:
[30,40,50,10,20]
Approach 1 — Using Extra Array (Simple Approach)
The easiest approach is using an additional array.
For right rotation:
- Move each element to its new position.
- Copy the result back.
Algorithm
- Create a new array of same size.
- Calculate new index.
- Place each element.
- Return rotated array.
Java Program
import java.util.Arrays;
public class RotateArrayExtraSpace {
public static int[] rotateRight(
int[] numbers,
int k) {
int n = numbers.length;
k = k % n;
int[] result =
new int[n];
for (int i = 0; i < n; i++) {
int newIndex =
(i + k) % n;
result[newIndex] =
numbers[i];
}
return result;
}
public static void main(String[] args) {
int[] numbers =
{1,2,3,4,5};
System.out.println(
Arrays.toString(
rotateRight(numbers,2)));
}
}
Output
[4, 5, 1, 2, 3]
Step-by-Step Explanation
Original:
[1,2,3,4,5]
Length:
n = 5
Rotation:
k = 2
For element:
1
Index:
0
New index:
(0+2)%5
Result:
2
Place:
result[2]=1
For element:
4
Index:
3
New index:
(3+2)%5
Result:
0
Place:
result[0]=4
Final:
[4,5,1,2,3]
Advantages
- Very easy to understand.
- No complex logic.
- Works for left and right rotation.
- Good beginner approach.
Drawbacks
- Requires extra memory.
- Not optimal for large arrays.
Approach 2 — Using Reversal Algorithm (Optimal)
The reversal algorithm rotates an array in-place.
It uses three steps.
For right rotation by k:
Example:
[1,2,3,4,5]
k = 2
Step 1:
Reverse entire array:
[5,4,3,2,1]
Step 2:
Reverse first k elements:
[4,5,3,2,1]
Step 3:
Reverse remaining elements:
[4,5,1,2,3]
Result:
[4,5,1,2,3]
Approach 2 — Using Reversal Algorithm (Optimal)
The Reversal Algorithm is the most popular optimal solution for rotating an array.
It rotates the array in-place without using extra memory.
This approach is commonly asked in interviews because it demonstrates:
- Array manipulation
- Multiple reversals
- Two pointer technique
- Space optimization
Right Rotation Using Reversal
Example:
Input:
[1,2,3,4,5]
k = 2
Step 1 — Reverse Entire Array
Before:
1 2 3 4 5
After:
5 4 3 2 1
Step 2 — Reverse First k Elements
Reverse:
5 4
Result:
4 5 3 2 1
Step 3 — Reverse Remaining Elements
Reverse:
3 2 1
Result:
4 5 1 2 3
Final:
[4,5,1,2,3]
Algorithm
For right rotation:
- Normalize
k.
k = k % n;
- Reverse complete array.
- Reverse first
kelements. - Reverse remaining elements.
Java Program
import java.util.Arrays;
public class RotateArrayReversal {
public static void rotateRight(
int[] numbers,
int k) {
int n = numbers.length;
k = k % n;
reverse(numbers, 0, n - 1);
reverse(numbers, 0, k - 1);
reverse(numbers, k, n - 1);
}
private static void reverse(
int[] numbers,
int start,
int end) {
while (start < end) {
int temp = numbers[start];
numbers[start] = numbers[end];
numbers[end] = temp;
start++;
end--;
}
}
public static void main(String[] args) {
int[] numbers =
{1,2,3,4,5};
rotateRight(numbers, 2);
System.out.println(
Arrays.toString(numbers));
}
}
Output
[4, 5, 1, 2, 3]
Step-by-Step Explanation
Input:
[1,2,3,4,5]
k:
2
Reverse complete array:
[5,4,3,2,1]
Reverse first two:
[4,5,3,2,1]
Reverse remaining:
[4,5,1,2,3]
Complexity Analysis
Time:
O(n)
Why?
Each element participates in a constant number of swaps.
Space:
O(1)
No additional array is created.
Advantages
- Optimal solution.
- In-place operation.
- Constant memory.
- Preferred interview solution.
Drawbacks
- Logic is harder initially.
- Requires understanding reversal technique.
Approach 3 — Using Cyclic Replacement
Cyclic replacement rotates elements by moving each element directly to its final position.
This avoids reversing the array.
Idea
For right rotation:
New Index
=
(Current Index + k) % n
Move elements one cycle at a time.
Example
Input:
[1,2,3,4,5]
k:
2
Move:
1 → index 2
2 → index 3
3 → index 4
4 → index 0
5 → index 1
Result:
[4,5,1,2,3]
Java Program
import java.util.Arrays;
public class RotateArrayCyclic {
public static void rotateRight(
int[] numbers,
int k) {
int n = numbers.length;
k = k % n;
int count = 0;
int start = 0;
while (count < n) {
int current = start;
int previous = numbers[start];
do {
int next =
(current + k) % n;
int temp =
numbers[next];
numbers[next] =
previous;
previous = temp;
current = next;
count++;
} while (current != start);
start++;
}
}
public static void main(String[] args) {
int[] numbers =
{1,2,3,4,5};
rotateRight(numbers,2);
System.out.println(
Arrays.toString(numbers));
}
}
Output
[4,5,1,2,3]
Advantages
- O(1) extra space.
- Direct movement.
- Useful for advanced discussions.
Drawbacks
- More difficult implementation.
- Easy to introduce bugs.
- Less readable than reversal algorithm.
Approach 4 — Using Collections.rotate()
Java provides a built-in method:
Collections.rotate()
for rotating lists.
Algorithm
- Convert array into List.
- Call
Collections.rotate(). - Convert back.
Java Program
import java.util.*;
public class RotateArrayCollections {
public static void main(String[] args) {
Integer[] numbers =
{1,2,3,4,5};
List<Integer> list =
Arrays.asList(numbers);
Collections.rotate(list, 2);
System.out.println(list);
}
}
Output
[4, 5, 1, 2, 3]
Step-by-Step Explanation
Original:
[1,2,3,4,5]
Call:
Collections.rotate(list,2)
Moves last two elements:
4,5
to the front.
Result:
[4,5,1,2,3]
Advantages
- Very simple.
- Production-friendly.
- Reduces implementation errors.
Drawbacks
- Works with collections.
- Requires boxing for primitive arrays.
- Less useful for algorithm interviews.
Approach 5 — Using Java Streams
Streams can create a rotated array by combining:
- Array slicing
- Stream concatenation
Java Program
import java.util.Arrays;
import java.util.stream.IntStream;
public class RotateArrayStreams {
public static int[] rotateRight(
int[] numbers,
int k) {
int n = numbers.length;
k = k % n;
return IntStream.concat(
Arrays.stream(numbers, n - k, n),
Arrays.stream(numbers, 0, n - k)
).toArray();
}
public static void main(String[] args) {
int[] numbers =
{1,2,3,4,5};
System.out.println(
Arrays.toString(
rotateRight(numbers,2)));
}
}
Output
[4,5,1,2,3]
Left Rotation Implementation
Left rotation by k can be converted into right rotation:
Formula:
Right Rotation
=
n - k
Example:
Array:
[1,2,3,4,5]
Left rotate:
2
Equivalent:
Right rotate 3
Result:
[3,4,5,1,2]
Left Rotation Using Reversal
For left rotation:
- Reverse first
kelements. - Reverse remaining elements.
- Reverse entire array.
Example:
[1,2,3,4,5]
k = 2
Reverse first two:
[2,1,3,4,5]
Reverse remaining:
[2,1,5,4,3]
Reverse entire:
[3,4,5,1,2]
Comparison of All Approaches
| Approach | Time | Space | Interview Rating |
|---|---|---|---|
| Extra Array | O(n) | O(n) | ⭐⭐⭐ |
| Reversal Algorithm | O(n) | O(1) | ⭐⭐⭐⭐⭐ |
| Cyclic Replacement | O(n) | O(1) | ⭐⭐⭐⭐ |
| Collections.rotate() | O(n) | O(1) | ⭐⭐⭐ |
| Streams | O(n) | O(n) | ⭐⭐⭐ |
Common Interview Mistakes
Mistake 1
Forgetting:
k = k % n;
Example:
k = 100
array size = 5
Equivalent:
100 % 5 = 0
Mistake 2
Wrong rotation direction.
Clarify:
- Left rotation?
- Right rotation?
Mistake 3
Incorrect index calculation.
Remember:
(index + k) % n
Mistake 4
Ignoring empty arrays.
Handle:
numbers == null
numbers.length == 0
Mistake 5
Using extra arrays when memory is limited.
Use:
Reversal Algorithm
Edge Cases
| Input | Output |
|---|---|
[1] |
[1] |
[1,2,3], k=0 |
Same array |
k > array length |
Use k % n |
| Empty array | Handle exception |
| Negative values | Works correctly |
Interview Follow-up Questions
Q1. Rotate array left by k positions.
Q2. Rotate array right by k positions.
Q3. Rotate without extra space.
Q4. Rotate a linked list.
Q5. Rotate a matrix by 90 degrees.
Q6. Implement circular queue.
Q7. What is the optimal approach?
Q8. Why does reversal work?
Q9. Can rotation be done in one pass?
Q10. How would you rotate billions of elements?
Related Problems
- Reverse an Array
- Move Zeroes
- Rotate Matrix
- Circular Queue
- Sliding Window
- Cyclic Replacement
- Rearrange Array Elements
- Next Permutation
Key Takeaways
- Array rotation is a fundamental array manipulation problem.
- Always normalize rotation:
k = k % n;
- Extra Array approach is easiest.
- Reversal Algorithm is the best interview solution.
- Cyclic Replacement provides another O(1) space solution.
- Choose the approach based on:
- Memory constraints
- Input size
- Code readability
Frequently Asked Interview Questions
Q1. Which approach is best?
The Reversal Algorithm is the preferred interview solution.
Complexity:
Time: O(n)
Space: O(1)
Q2. Why does reversal work?
Reversing sections rearranges the array segments into their rotated positions without additional storage.
Q3. Why use modulo?
Because rotating by array length returns the original array.
Example:
[1,2,3]
rotate 3 times
=
same array
Q4. Which approach is easiest?
Extra Array approach.
Q5. Which approach is best for production?
Depends:
- Simple code → Collections.rotate()
- Performance → Reversal Algorithm
- Streaming scenarios → Cyclic approach
Interview Tip
When asked:
"Rotate an array by k positions."
Clarify:
- Left or right rotation?
- Can you modify the original array?
- Is extra memory allowed?
Then present:
- Extra Array (basic)
- Reversal Algorithm (optimal)
- Cyclic Replacement (advanced)
The ability to explain multiple solutions and their trade-offs demonstrates strong understanding of arrays, indexing, and algorithm optimization.