Rotate List

MediumLinked List · Ring & Cut🧩 Linked List TechniquesLeetCode #61 ↗Updated

Problem

You get the head of a singly linked list and a non-negative integer k. Shift the whole list to the right by k places: each step, the last node becomes the new head. Return the head of the rotated list.
Inputhead=[1,2,3,4,5], k=2Output[4,5,1,2,3]
Inputhead=[0,1,2], k=4Output[2,0,1]

0 ≤ n ≤ 500  ·  -100 ≤ Node.val ≤ 100  ·  0 ≤ k ≤ 2·109

Try it yourself

Java
class Solution {
    public ListNode rotateRight(ListNode head, int k) {
        
    }
}
Your code is saved in this browser.Submit on LeetCode ↗
Key insight
Rotating by n changes nothing, so only k % n matters. The answer is just the last k % n nodes moved to the front: link the tail to the head to form a ring, then cut it right after node n - k%n.
PatternLinked List Techniques

Instinct Nodes joined by next pointers and the task is to reverse, splice, merge, reorder or remove in place - grab a dummy head and rewire pointers carefully.

Memory hack Save next, flip, step - never let go of a rope before you've grabbed the next one.

Open the Linked List Techniques guide →

Approaches

Brute ForceRotate One Step at a Time

Time O(n · min(k, n))Space O(1)

Simulate the definition: one right-rotation = detach the last node and put it in front. Doing it k times is hopeless for k = 2·109, so at least reduce to k % n steps; each step still walks the list to find the second-to-last node.

Java
public ListNode rotateRight(ListNode head, int k) {
    if (head == null || head.next == null) return head;
    int n = 0;
    for (ListNode c = head; c != null; c = c.next) n++;
    k %= n;
    for (int step = 0; step < k; step++) {
        ListNode prev = head;
        while (prev.next.next != null) prev = prev.next; // second-to-last
        ListNode last = prev.next;
        prev.next = null;
        last.next = head;
        head = last;
    }
    return head;
}

Direct simulation; quadratic in the worst case (k % n close to n).

At a glance

LevelApproachTimeSpace
Brute ForceRotate One Step at a TimeO(n · min(k, n))O(1)
BetterNode Array & RelinkO(n)O(n)
OptimalClose the Ring, Cut at n − kO(n)O(1)
Common pitfalls
  • Not reducing k modulo n — times out for huge k.
  • Forgetting to break the ring — returns a cyclic list (infinite loop in callers).
  • Off-by-one: the new head is node n-k (0-indexed), the new tail is n-k-1.
Interview tips
  • Ask about k > n and the empty list up front.
  • Explain that a right rotation by k = moving the last k nodes to the front.
  • Mention the ring trick generalises to rotating arrays by reversals.
Pattern
Length + modulo + re-link → any cyclic shift of a linked list.
My notes saved in this browser