24. Rotate Array
easyAsked at RedditRotate an array to the right by k steps. Reddit uses the reverse-then-reverse trick to gauge in-place manipulation — the same skill needed to rotate a fixed-size sliding ranking window without re-allocating.
By Alex Chen, Founder, InterviewChamp.AI · Last verified
Source citations
Public interview reports confirming this problem appears in Reddit loops.
- Glassdoor (2026-Q1)— Reddit infra-team phone screen.
Problem
Given an integer array nums, rotate the array to the right by k steps, where k is non-negative. Try to come up with as many solutions as you can. There are at least three different ways to solve this problem. Could you 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. Use extra array
Copy nums[i] to result[(i + k) % n].
- Time
- O(n)
- Space
- O(n)
function rotate(nums, k) {
const n = nums.length;
k = k % n;
const out = new Array(n);
for (let i = 0; i < n; i++) out[(i + k) % n] = nums[i];
for (let i = 0; i < n; i++) nums[i] = out[i];
}Tradeoff: Linear but uses O(n) memory. Doesn't satisfy the O(1) follow-up.
2. Reverse three times (optimal)
Reverse the whole array. Reverse the first k. Reverse the rest.
- Time
- O(n)
- Space
- O(1)
function rotate(nums, k) {
const n = nums.length;
k = k % n;
const reverse = (l, r) => {
while (l < r) {
[nums[l], nums[r]] = [nums[r], nums[l]];
l++; r--;
}
};
reverse(0, n - 1);
reverse(0, k - 1);
reverse(k, n - 1);
}Tradeoff: O(1) space. The triple-reverse trick is the classic Reddit-favored answer.
Reddit-specific tips
Reddit interviewers want the reverse trick. Bonus signal: explain WHY it works — reversing the whole flips order, reversing the first k re-orders within the front, reversing the back re-orders within the back. Same shape as their ranked-feed window-shift.
Common mistakes
- Forgetting k = k % n (handles k > n).
- Reversing the wrong segments (off-by-one).
- Using slice/concat — O(n) memory.
Follow-up questions
An interviewer at Reddit may pivot to one of these next:
- Cyclic replacements (k = gcd(n,k) cycles).
- Rotate a linked list (LC 61).
- Rotate a matrix (LC 48).
Solve it now
Free. No sign-up. Python and JavaScript run instantly in your browser.
FAQ
Why does the triple-reverse work?
If you label the original as [A B] where B has length k, the target is [B A]. Reverse whole = [B' A']. Reverse first k = [B A']. Reverse rest = [B A].
What if k > n?
k = k % n. Rotating by n is identity.
Practice these live with InterviewChamp.AI
Drill Rotate Array and other Reddit interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →