23. Rotate Array
easyAsked at OlaRotate an array to the right by k steps in-place.
By Alex Chen, Founder, InterviewChamp.AI · Last verified
Problem
Given an integer array nums, rotate the array to the right by k steps, where k is non-negative. Try to do it in-place with O(1) extra space.
Constraints
1 <= nums.length <= 10^5-2^31 <= nums[i] <= 2^31 - 10 <= k <= 10^5
Examples
Example 1
nums = [1,2,3,4,5,6,7], k = 3[5,6,7,1,2,3,4]Example 2
nums = [-1,-100,3,99], k = 2[3,99,-1,-100]Approaches
1. Copy with shift
Allocate a copy and write each element to (i+k)%n.
- Time
- O(n)
- Space
- O(n)
const n = nums.length, copy = [...nums];
for (let i=0;i<n;i++) nums[(i+k)%n] = copy[i];Tradeoff:
2. Triple reverse
Reverse the whole array, then reverse the first k and the last n-k. In-place.
- Time
- O(n)
- Space
- O(1)
function rotate(nums, k) {
k = k % nums.length;
const rev = (a, l, r) => { while (l < r) { [a[l], a[r]] = [a[r], a[l]]; l++; r--; } };
rev(nums, 0, nums.length - 1);
rev(nums, 0, k - 1);
rev(nums, k, nums.length - 1);
}Tradeoff:
Ola-specific tips
Ola uses this to test in-place tricks; relate it to shifting a circular driver-shift schedule by a number of hours without reallocating arrays.
Solve it now
Free. No sign-up. Python and JavaScript run instantly in your browser.
Practice these live with InterviewChamp.AI
Drill Rotate Array and other Ola interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →