PPractick

DSA interview question

Rotate a Linked List

Hard · Data structures · Topics: linkedlist, two pointer

The problem

A carousel on a shopping app stores its banners in a singly linked list, and pressing "skip ahead" should rotate the list to the right by k places: the last k banners move to the front, in order. k can be far larger than the list length, because users hold the button, so rotating one step at a time is out. The efficient trick is to temporarily close the list into a ring and then cut it at the right spot.

Example: 1 -> 2 -> 3 -> 4 -> 5, k = 2 → 4 -> 5 -> 1 -> 2 -> 3.

Function signature

Node* rotateRight(Node* head, int k);  // k >= 0; returns the new head

Test cases

Input (list, k)Output listExplanation
(1 -> 2 -> 3 -> 4 -> 5, 2)4 -> 5 -> 1 -> 2 -> 3
(0 -> 1 -> 2, 4)2 -> 0 -> 14 mod 3 = 1
(1 -> 2 -> 3, 3)1 -> 2 -> 3A full rotation changes nothing
(1, 99)1
(empty, 5)(empty)

(Confirm: rotation is to the right; k may exceed the length, up to about 2·10⁹; only links change.)

How interviewers phrase it

Clarifying questions to ask

  1. Rotate right or left?
  2. Can k be larger than the length? (Yes, so reduce it modulo n.)
  3. How should empty lists be handled?

Follow-ups to expect

  1. "Why k mod n?"
  2. "Where do you cut?"
  3. "Why connect the tail to the head?"
  4. "How would a left rotation by k change it?"
  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