PPractick

DSA interview question

Left Rotate an Array by K Places

Easy · Algorithms · Topics: array

The problem

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].

Function signature

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)

Test cases

Input (a, k)OutputExplanation
([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.)

How interviewers phrase it

Clarifying questions to ask

  1. Left or right rotation?
  2. Can k be larger than n, or negative?
  3. Is O(n) extra space allowed?

Follow-ups to expect

  1. "Why does the reversal trick work?"
  2. "Why take k mod n?"
  3. "How do you rotate right instead?"
  4. "What other O(n) approaches exist?"
  5. "Complexity?"

Practise questions like this with a real engineer

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 interview

Related questions

All 474 dsa interview questions

DSA mock interviews · System design interview questions · Free mock interview practice · Browse interviewers · Sign in