sagelearnai

Rotate List

Difficulty: Medium · Pattern: Linked List · LeetCode #61

Rotate the list to the right by k places and return the new head.

Examples

text
1 → 2 → 3 → 4 → 5, k = 2  →  4 → 5 → 1 → 2 → 3
0 → 1 → 2, k = 4          →  2 → 0 → 1

Hints

  1. k can be larger than the length; use k mod n.
  2. Connect the tail to the head, walk to the new tail, and break the ring.

Approach

Compute the length n and the tail. If the list is empty or k % n == 0, return the head. Otherwise link tail.next = head (a ring), walk n − k % n − 1 steps from the head to the new tail, set the new head to newTail.next, and cut newTail.next = null. O(n).

Complexity

Time: O(n). Space: O(1).

Python solution
def rotateRight(head, k):
    if not head:
        return head
    n, tail = 1, head
    while tail.next:
        tail = tail.next; n += 1
    k %= n
    if k == 0:
        return head
    tail.next = head
    new_tail = head
    for _ in range(n - k - 1):
        new_tail = new_tail.next
    new_head = new_tail.next
    new_tail.next = None
    return new_head
JavaScript solution
function rotateRight(head, k) {
  if (!head) return head;
  let n = 1, tail = head;
  while (tail.next) { tail = tail.next; n++; }
  k %= n; if (k === 0) return head;
  tail.next = head;
  let nt = head; for (let i = 0; i < n - k - 1; i++) nt = nt.next;
  const nh = nt.next; nt.next = null; return nh;
}