Skip to the solution
MediumDSA13 min read

How do you rotate an array by k positions?

881 views

The problem

Question presented to candidate: "Given a Python list nums and a non-negative integer k, rotate the list to the right by k steps, in place. For example [1, 2, 3, 4, 5, 6, 7] with k = 3 becomes [5, 6, 7, 1, 2, 3, 4]. Can you do it with O(1) extra space?"

What a strong answer should cover:

  • Reduce k %= n first (k can exceed n) and guard the empty list.
  • The brute force (rotate by one, k times, O(nยทk)) and the extra-array version (O(n) space), then the three-reversal algorithm: O(n) time, O(1) space.
  • Why the reversals work: A B โ†’ rev(B) rev(A) โ†’ B A.
  • Optionally cyclic replacements, and why they may need gcd(n, k) separate cycles.
  • Python specifics: nums[:] = nums[-k:] + nums[:-k] mutates the caller's list but uses O(n) extra space, plain nums = ... only rebinds a local name, collections.deque.rotate(k) exists, and Python's % is never negative for a positive n.

Clarifying questions expected:

  • "Right or left rotation, and can k be larger than n or negative?"
  • "Must it be in place, or may I return a new list?"

Code / implementation expected: Yes โ€” a Python function that rotates nums in place with three reversals.

  • arrays
  • rotation

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

13 min read ยท 11 sections

Python code

Edit the code and run it here. Each printed line with an expected value becomes a test.

PythonRotate right by k with three reversals (k > n, k = 0, empty array)
PythonBrute force vs extra array vs reversal vs cyclic replacements, counting writes
PythonLeft rotation and negative k by normalising k

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 59 of 154 in DSA

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All DSA questions
Up nextMedium

How does a hash table work?

Continue