Rotate an array to the right
Rotate an integer array to the right by k positions in place. Values shifted past the end must wrap to the front.
Course progress
Problem 36 of 100
Example → approach → runnable solution
Worked example
See the problem in action
Trace a concrete input through to the verified result.
Example input
numbers = [1, 2, 3, 4, 5]; positions = 2
Expected output
4 5 1 2 3
What is happening?
The final two values wrap to the front while the first three shift right, producing 4, 5, 1, 2, 3.
Solution strategy
Build the right mental model
Normalize k, reverse the whole array, then reverse the rotated prefix and remaining suffix. These three reversals place every value correctly without another array.
Core concepts
arrays · reversal
Complexity
Time O(n), space O(1).
Runnable solution
Learn from working code
Compare languages, copy the code, or open it in the compiler.
Complete C# solution for rotate-array-right
using System;
class Program
{
static void Reverse(int[] numbers, int left, int right)
{
while (left < right)
{
int temporary = numbers[left];
numbers[left++] = numbers[right];
numbers[right--] = temporary;
}
}
static void RotateRight(int[] numbers, int positions)
{
if (numbers.Length == 0) return;
positions = ((positions % numbers.Length) + numbers.Length) % numbers.Length;
if (positions == 0) return;
Reverse(numbers, 0, numbers.Length - 1);
Reverse(numbers, 0, positions - 1);
Reverse(numbers, positions, numbers.Length - 1);
}
static void Main()
{
int[] values = { 1, 2, 3, 4, 5 };
RotateRight(values, 2);
Console.WriteLine(string.Join(" ", values));
}
}Knowledge check
Questions students often ask
What is the main idea behind rotate an array to the right?
Normalize k, reverse the whole array, then reverse the rotated prefix and remaining suffix. These three reversals place every value correctly without another array.
What is the time and space complexity of this solution?
Time O(n), space O(1).
Do all language tabs solve the same problem?
Yes. Every program uses the same example and produces the verified output shown on this page. The syntax and a few language-specific data structures differ.