Description

Rotate List
Given the head of a linked list, rotate the list to the right by k places.

Example 1:

Input: head = [1,2,3,4,5], k = 2
Output: [4,5,1,2,3]

Example 2:

Input: head = [0,1,2], k = 4
Output: [2,0,1]

Constraints:

  • The number of nodes in the list is in the range [0, 500].
  • -100 <= Node.val <= 100
  • 0 <= k <= 2 * 109

Brute Force Approach

Shift the entire list to the right by node at a time, repeating the entire process times. In each iteration, traverse to the second-to-last node, detach the last node, attach it to the front as the new head, and update references.

public ListNode rotateRightBruteForce(ListNode head, int k) {
    if (head == null || head.next == null || k == 0) return head;
 
    for (int i = 0; i < k; i++) {
        ListNode prev = null;
        ListNode curr = head;
        while (curr.next != null) {
            prev = curr;
            curr = curr.next;
        }
        prev.next = null;
        curr.next = head;
        head = curr;
    }
    return head;
}
 
  • Time Complexity: — Traverses the list up to times; causes Time Limit Exceeded (TLE) when is large.
  • Space Complexity: — Uses a constant number of pointer variables.

Optimized Approach (The Ring Method)

Connect the end of the list back to the head to form a circular ring, then cut the ring at the correct offset.

Mental Model Steps:

  1. Form the Ring: Traverse to the end to get length and connect cur.next = head.
  2. Find Split Point: Reduce via . Advancing steps from the tail lands cur directly on the new tail node.
  3. Break the Ring: Set head = cur.next, then disconnect the list using cur.next = null.
class Solution {
    public ListNode rotateRight(ListNode head, int k) {
        if (head == null) {
            return head;
        }
 
        ListNode cur = head;
        int n = 1;
        while (cur.next != null) {
            n++;
            cur = cur.next;
        }
 
        cur.next = head;
        k %= n;
        for (int i = 0; i < n - k; i++) {
            cur = cur.next;
        }
 
        head = cur.next;
        cur.next = null;
        return head;
    }
}
 
  • Time Complexity: — Exactly two passes: one pass to calculate length and form the ring, and a second pass of at most steps to cut the ring.
  • Space Complexity: — Re-links existing node pointers in place without allocating extra memory.