DSA interview question
The advert carousel from the previous problem gets a "skip ahead K adverts" button: the first K adverts move to the end in one go. Rotating by one, K times, is O(n·K), which is too slow when both are large. Copying into a new array is O(n) but uses O(n) memory the controller doesn't have. The elegant answer is the reversal algorithm: reverse the first K elements, reverse the rest, then reverse the whole array. That's O(n) time and O(1) space, and it's worth being able to explain why it works.
Example: [1, 2, 3, 4, 5, 6, 7], K = 2 → [3, 4, 5, 6, 7, 1, 2].
void leftRotate(vector<int>& a, int k); // in place; k may exceed n
void rightRotate(vector<int>& a, int k); // in place (the LeetCode 189 direction)
Input (a, k) | Output | Explanation |
|---|---|---|
([1, 2, 3, 4, 5, 6, 7], 2) left | [3, 4, 5, 6, 7, 1, 2] | |
([1, 2, 3, 4, 5, 6, 7], 0) left | [1, 2, 3, 4, 5, 6, 7] | Nothing to do |
([1, 2, 3, 4, 5, 6, 7], 7) left | [1, 2, 3, 4, 5, 6, 7] | Full cycle |
([1, 2, 3, 4, 5, 6, 7], 9) left | [3, 4, 5, 6, 7, 1, 2] | 9 mod 7 = 2 |
([1, 2], 3) left | [2, 1] | 3 mod 2 = 1 |
([], 3) left | [] | Guard against dividing by zero |
([1, 2, 3, 4, 5, 6, 7], 3) right | [5, 6, 7, 1, 2, 3, 4] | LeetCode 189 example |
(Confirm: k ≥ 0 and may be larger than n; O(1) extra space.)
On Practick another engineer interviews you live for 60 minutes on a question from this bank. They have the full interviewer guide beside the call: the expected answer to every follow-up, hints to give if you stall, and a scoring rubric. You get the model solution once the session settles. It is free: interview someone for an hour and you have earned your own.
Book a free mock interviewAll 474 dsa interview questions
DSA mock interviews · System design interview questions · Free mock interview practice · Browse interviewers · Sign in