KatInterview

61. Rotate List

MediumSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem asks us to rotate a linked list to the right by k positions. Rotating to the right means taking the last node and moving it to the front, repeated k times. For a list of length n, rotating k times is equivalent to moving the last k % n nodes to the front.

Solution

Rotate List in Python

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
from typing import Optional

class Solution:
    def rotateRight(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:
        # Edge cases: empty list, single node list, or no rotation.
        if not head or not head.next or k == 0:
            return head

        # 1. Find the length of the list and the tail node.
        n = 1
        tail = head
        while tail.next:
            tail = tail.next
            n += 1
        
        # 2. Calculate effective rotations.
        k = k % n
        if k == 0:
            return head # No effective rotation needed.
            
        # 3. Form a cycle by connecting the tail to the head.
        tail.next = head
        
        # 4. Find the new tail, which is at position (n - k - 1) from the start.
        new_tail = head
        for _ in range(n - k - 1):
            new_tail = new_tail.next
            
        # 5. The new head is the node after the new tail.
        new_head = new_tail.next
        
        # 6. Break the cycle.
        new_tail.next = None
        
        return new_head

Rotate List in Java

/**
 * 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) {
        // Edge cases: empty list, single node list, or no rotation.
        if (head == null || head.next == null || k == 0) {
            return head;
        }

        // 1. Find the length of the list and the tail node.
        int n = 1;
        ListNode tail = head;
        while (tail.next != null) {
            tail = tail.next;
            n++;
        }

        // 2. Calculate effective rotations.
        k = k % n;
        if (k == 0) {
            return head; // No effective rotation needed.
        }

        // 3. Form a cycle by connecting the tail to the head.
        tail.next = head;

        // 4. Find the new tail, which is at position (n - k - 1) from the start.
        ListNode newTail = head;
        for (int i = 0; i < n - k - 1; i++) {
            newTail = newTail.next;
        }

        // 5. The new head is the node after the new tail.
        ListNode newHead = newTail.next;

        // 6. Break the cycle.
        newTail.next = null;

        return newHead;
    }
}

Rotate List in C++

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* rotateRight(ListNode* head, int k) {
        // Edge cases: empty list, single node list, or no rotation.
        if (!head || !head->next || k == 0) {
            return head;
        }

        // 1. Find the length of the list and the tail node.
        int n = 1;
        ListNode* tail = head;
        while (tail->next) {
            tail = tail->next;
            n++;
        }

        // 2. Calculate effective rotations.
        k = k % n;
        if (k == 0) {
            return head; // No effective rotation needed.
        }

        // 3. Form a cycle by connecting the tail to the head.
        tail->next = head;

        // 4. Find the new tail, which is at position (n - k - 1) from the start.
        // We need to traverse n - k steps to find the new head. The node before it is the new tail.
        ListNode* new_tail = head;
        for (int i = 0; i < n - k - 1; i++) {
            new_tail = new_tail->next;
        }

        // 5. The new head is the node after the new tail.
        ListNode* new_head = new_tail->next;

        // 6. Break the cycle.
        new_tail->next = nullptr;

        return new_head;
    }
};

Rotate List in TypeScript

/**
 * Definition for singly-linked list.
 * class ListNode {
 *     val: number
 *     next: ListNode | null
 *     constructor(val?: number, next?: ListNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.next = (next===undefined ? null : next)
 *     }
 * }
 */

function rotateRight(head: ListNode | null, k: number): ListNode | null {
    // Edge cases: empty list, single node list, or no rotation.
    if (!head || !head.next || k === 0) {
        return head;
    }

    // 1. Find the length of the list and the tail node.
    let n = 1;
    let tail: ListNode = head;
    while (tail.next) {
        tail = tail.next;
        n++;
    }

    // 2. Calculate effective rotations.
    k = k % n;
    if (k === 0) {
        return head; // No effective rotation needed.
    }

    // 3. Form a cycle by connecting the tail to the head.
    tail.next = head;

    // 4. Find the new tail, which is at position (n - k - 1) from the start.
    let newTail: ListNode = head;
    for (let i = 0; i < n - k - 1; i++) {
        newTail = newTail.next!;
    }

    // 5. The new head is the node after the new tail.
    const newHead: ListNode | null = newTail.next;

    // 6. Break the cycle.
    newTail.next = null;

    return newHead;
};

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.