Magicsheet logo

Rotate List

Medium
29.7%
Updated 6/1/2025

Rotate List

What is this problem about?

The Rotate List interview question asks you to rotate a singly linked list to the right by k places. Rotating right by k means the last k nodes move to the front. For example, rotating 1→2→3→4→5 by 2 gives 4→5→1→2→3. The rotation must be done in-place by relinking nodes, not by copying values.

Why is this asked in interviews?

This problem is asked at Apple, Microsoft, Meta, Nvidia, Amazon, LinkedIn, Oracle, Google, Bloomberg, and Adobe because it tests linked list manipulation under a rotational constraint. It requires computing the list length (to handle k ≥ n via modulo), finding the new tail position, and relinking the list into a ring and then cutting it at the correct point. It builds on the "find k-th from end" pattern but with ring formation.

Algorithmic pattern used

The pattern is ring formation and cutting. Traverse the list to find its length n and the tail node. Compute effective rotation: k = k % n (if 0, return head unchanged). The new tail is at position n - k - 1 from the start (0-indexed). Connect the tail of the list to the head (form a ring), advance to position n - k - 1, set the new head as new_tail.next, and set new_tail.next = None.

Example explanation

List: 1 → 2 → 3 → 4 → 5, k = 2.

Length n = 5. Effective k = 2 % 5 = 2. New tail position: 5 - 2 - 1 = 2 (0-indexed) → node with value 3.

Form ring: 5 → 1 (link tail to head). Traverse to position 2 (node 3): new_tail = 3. New head = new_tail.next = 4. Set new_tail.next = None: 3 → None.

Result: 4 → 5 → 1 → 2 → 3.

Common mistakes candidates make

  • Not reducing k modulo n — if k equals n, the list should be returned unchanged.
  • Off-by-one in the new tail position — the new tail is at n - k - 1, not n - k.
  • Forgetting to set the new tail's next to None, leaving a cycle in the list.
  • Not handling an empty list or single-node list.

Interview preparation tip

For the Rotate List coding problem, the linked list and two-pointer interview pattern with ring formation is the approach. Practice finding the new tail index n - k - 1 carefully — it is the most error-prone step. Morgan Stanley and Nvidia interviewers often focus on k > n edge cases — always compute k % n first. Draw the before/after pointer diagram for a 5-node list rotated by 2 to internalize the index math.

Similar Questions