← Back to Leo Academy Masterclass

Problem #61: Rotate List

Medium Linked List

Intuition & Strategy Breakdown

Calculate list length L and connect tail to head to form a cycle. Compute effective rotation k = k % L, then advance L - k steps and break the cycle to get new head.

Python Solution

class Solution:
    def rotateRight(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:
        if not head or not head.next or k == 0:
            return head
        
        # 1. Find length and last node
        last_node = head
        length = 1
        while last_node.next:
            last_node = last_node.next
            length += 1
            
        # 2. Adjust k
        k = k % length
        if k == 0: return head
        
        # 3. Make circular and find new tail
        last_node.next = head
        new_tail = head
        for _ in range(length - k - 1):
            new_tail = new_tail.next
            
        # 4. Break circle
        new_head = new_tail.next
        new_tail.next = None
        
        return new_head

Java Solution

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode rotateRight(ListNode head, int k) {
        if (head == null || head.next == null || k == 0) return head;
        ListNode lastNode = head;
        int length = 1;
        while (lastNode.next != null) {
            lastNode = lastNode.next;
            length++;
        }
        k = k % length;
        if (k == 0) return head;
        lastNode.next = head;
        ListNode newTail = head;
        for (int i = 0; i < length - k - 1; i++) {
            newTail = newTail.next;
        }
        ListNode newHead = newTail.next;
        newTail.next = null;
        return newHead;
    }
}
Watch Interactive Video on Leo Academy Main App