Title: Rotate an Array by K Positions (Left and Right)
Array rotation is one of those small, deceptively simple problems that shows up everywhere, from circular buffer implementations to sliding window puzzles to the warm-up round of coding interviews. In this guide, you will learn how to rotate an array by K positions in both directions using a clean, in-place algorithm that runs in linear time with constant extra memory.
Along the way we will tackle the edge cases that trip up most first attempts, such as a k value larger than the array length, negative shifts, and empty inputs. By the end you will have a reusable template for every rotation question an interviewer can throw at you.
Understanding the Problem
Rotating an array means shifting every element by a fixed number of positions, with the elements that fall off one end wrapping around to the other end. A right rotation by k moves each element k steps toward higher indices, and a left rotation by k moves each element k steps toward lower indices.
For example, right rotating {1, 2, 3, 4, 5} by 2 gives {4, 5, 1, 2, 3}, while left rotating the same array by 2 gives {3, 4, 5, 1, 2}. The challenge is to perform this rotation without allocating a second array and in a single linear pass.
Approach: The Three-Reversal Technique
The elegant trick for rotating in place is to reverse the array in three carefully chosen chunks. Here are the steps for a right rotation by shift:
- Handle the trivial cases, a
nullarray or one of length zero, by returning immediately. - Compute
nas the array length, then normalisekusing((k % n) + n) % nso that over-sized and negative shifts both land in the valid range from0ton - 1. - If the normalised
shiftis zero, the array is already in the desired state and no work is needed. - Reverse the entire array from index
0to indexn - 1. - Reverse the first
shiftelements, meaning the slice from index0toshift - 1. - Reverse the remaining elements, meaning the slice from index
shiftton - 1. - For a left rotation by
k, delegate to the right rotation usingn - shiftas the effective count, which keeps a single implementation at the core.
Java Program: Rotate an Array by K Positions
import java.util.Arrays;
public class RotateArray {
// Rotate the array to the right by k positions in place
public static void rotateRight(int[] array, int k) {
if (array == null || array.length == 0) {
return;
}
int n = array.length;
// Normalise k so a value larger than n still works
int shift = ((k % n) + n) % n;
if (shift == 0) {
return;
}
reverse(array, 0, n - 1);
reverse(array, 0, shift - 1);
reverse(array, shift, n - 1);
}
// Rotate the array to the left by k positions in place
public static void rotateLeft(int[] array, int k) {
if (array == null || array.length == 0) {
return;
}
int n = array.length;
// A left rotation by k is a right rotation by n - k
int shift = ((k % n) + n) % n;
rotateRight(array, n - shift);
}
// Reverse the sub array from index start to end inclusive
private static void reverse(int[] array, int start, int end) {
while (start < end) {
int temp = array[start];
array[start] = array[end];
array[end] = temp;
start++;
end--;
}
}
public static void main(String[] args) {
int[] numbers = {10, 20, 30, 40, 50, 60, 70};
int k = 3;
int[] rightCopy = numbers.clone();
rotateRight(rightCopy, k);
System.out.println("Original Array : " + Arrays.toString(numbers));
System.out.println("Right Rotation by " + k + ": " + Arrays.toString(rightCopy));
int[] leftCopy = numbers.clone();
rotateLeft(leftCopy, k);
System.out.println("Left Rotation by " + k + " : " + Arrays.toString(leftCopy));
}
}Explanation of the Program
The RotateArray class exposes two public entry points, rotateRight and rotateLeft, backed by a shared private helper, reverse. The design means every rotation ultimately runs through the same three-reversal pipeline, so bug fixes stay in one spot.
- The guard
array == null || array.length == 0is checked first so that short-circuit evaluation stops before touchingarray.lengthon anullreference. - The expression
((k % n) + n) % nis the usual Java trick for a non-negative modulo result. Plaink % ncan return a negative value whenkis negative, which would hand bad indices toreverse. - Each call to
reversewalks astartpointer up and anendpointer down, swapping the elements they land on until the two pointers meet. Three such passes rotate the array because reversing twice around the pivot point effectively slides the tail of the array to its head. rotateLeftis a one-liner on top ofrotateRight, converting a left shift ofkinto a right shift ofn - shift. This is both a code reuse win and a nice interview talking point.- The
mainmethod clones the input before each rotation so the two demonstrations do not interfere with each other.
Step-by-Step Trace
Let us right rotate the small input [A, B, C, D, E] by k = 2. Here n = 5 and the normalised shift is 2, so three reversals will produce the target output [D, E, A, B, C].
| Step | Call | Range | Array before | Array after |
|---|---|---|---|---|
| 1 | reverse(0, 4) | Whole array | [A, B, C, D, E] | [E, D, C, B, A] |
| 2 | reverse(0, 1) | First shift items | [E, D, C, B, A] | [D, E, C, B, A] |
| 3 | reverse(2, 4) | Remaining items | [D, E, C, B, A] | [D, E, A, B, C] |
After the three reversals complete, the last shift elements of the original array sit at the front, and every other element has slid shift positions to the right. That is the loop invariant that makes the three-reversal technique work.
Examples
Example 1: Right Rotation by 2
A right rotation moves each element toward higher indices, with the overflow wrapping to the start.
int[] arr = {1, 2, 3, 4, 5};
rotateRight(arr, 2);
// Output: [4, 5, 1, 2, 3]Example 2: Left Rotation by 2
A left rotation moves each element toward lower indices, with elements that fall off the front wrapping to the end.
int[] arr = {1, 2, 3, 4, 5};
rotateLeft(arr, 2);
// Output: [3, 4, 5, 1, 2]Example 3: Shift Larger Than the Array
When k is bigger than n, the modulo normalisation shrinks the shift into the valid range. Here 5 % 3 gives an effective shift of 2.
int[] arr = {7, 8, 9};
rotateRight(arr, 5);
// shift becomes 5 % 3 = 2
// Output: [8, 9, 7]Common Mistakes to Avoid
A handful of mistakes come up again and again when candidates attempt this problem under interview pressure. Watch for these:
- Not normalising k against n – passing
k = 7on an array of length5callsreversewith out of range indices and throwsArrayIndexOutOfBoundsException. Reducekmodulonbefore using it. - Negative shifts via plain k % n – a negative
kyields a negative modulo in Java and silently corrupts the array. Use((k % n) + n) % nso the shift is always non-negative. - Confusing left and right directions – swapping the direction without adjusting the count applies the correct magnitude to the wrong side. Remember that a left rotation by
kequals a right rotation byn - k. - Allocating a new array for in-place requirements – building a copy array fails the common
O(1)extra space constraint. The three-reversal technique mutates the input directly and keeps extra memory to a handful of pointers. - Off-by-one in the reverse bounds – using
ninstead ofn - 1orshiftinstead ofshift - 1leaves one element in the wrong place. Pass inclusive end indices and verify them with a two element dry run before trusting the code.
Edge Cases to Test
Enumerate these boundary inputs before you declare victory on any rotation solution:
- Empty array
- Single-element array
kequal to zerokequal to the array lengthkgreater than the array length- Negative
kvalue nullarray reference- Two-element array with
k = 1
Additional Considerations
Time complexity is O(n). Each of the three reverse calls visits at most n elements, and the modulo arithmetic is constant time. Space complexity is O(1) because the only extra variables are a few integer pointers and a temp swap variable.
An alternative approach uses a secondary array and the formula result[(i + shift) % n] = array[i]. It is a single pass and arguably easier to explain, but it costs O(n) extra memory and fails the usual in-place constraint. A third approach, cyclic replacement, achieves O(1) space with a single pass but is harder to code correctly under interview pressure because it relies on tracking visited positions when gcd(n, shift) is greater than one.
For negative values of k, the modulo normalisation is doing real work. In Java, -3 % 5 evaluates to -3, not 2, so the + n and outer % n are what rescue the computation. Treat the normalisation line as a defensive barrier at the top of every rotation helper you write.
Interview Follow-up Questions
Expect the interviewer to pivot from the base problem to one of these variations once you ship a working rotation:
- What if you cannot modify the input array? – allocate a new array of the same length and copy element at index
ito position(i + shift) % nin a single linear pass. - What if the array is wrapped in a circular buffer type? – rotation collapses to a pointer move on the read head, dropping the cost to
O(1)time and zero data movement. - What if k could be as large as Integer.MAX_VALUE? – the modulo trick still works, but prefer
Math.floorMod(k, n)when the sign ofkis unpredictable, since it already returns a non-negative result. - What if the array holds generic objects instead of ints? – the three-reversal algorithm is identical, just swap generic references through a
T temp; the time and space bounds are unchanged. - What if you need to rotate a two-dimensional grid by k rows and k columns? – apply the three-reversal trick along each axis in turn, giving
O(m * n)time and stillO(1)extra memory, which is the standard solution for the matrix rotation family of interview questions.
Conclusion
Rotating an array by K positions is a small algorithm with an outsized role in both interviews and real systems, from queue implementations to left-right swap puzzles to streaming data windows. The three-reversal technique keeps the solution linear in time, constant in extra memory, and short enough to type under pressure.
Try adapting the code to your own data types, step through the trace with pen and paper on a fresh input, and you will have a reliable tool for every rotation problem you meet. You can learn more about array techniques here: Arrays.



