LeetCode 61: Rotate List Solution

Master LeetCode problem 61 (Rotate List), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

61. Rotate List

Problem Explanation

Explanation

To rotate a linked list to the right by k places, we can follow these steps:

  1. Find the length of the linked list and calculate the actual rotation amount by taking the remainder of k divided by the length.
  2. Connect the last node to the head node to form a circular linked list.
  3. Find the new tail node at position length - actual rotation amount - 1 and set the new head node to the next node.
  4. Break the circular list by setting the new tail node's next to null.

Time complexity: O(n) where n is the number of nodes in the linked list. Space complexity: O(1)

Solution Code

public ListNode rotateRight(ListNode head, int k) {
    if (head == null || head.next == null || k == 0) {
        return head;
    }

    int length = 1;
    ListNode current = head;
    while (current.next != null) {
        length++;
        current = current.next;
    }

    int actualRotation = k % length;
    if (actualRotation == 0) {
        return head;
    }

    current.next = head; // form a circular linked list

    ListNode newTail = head;
    for (int i = 0; i < length - actualRotation - 1; i++) {
        newTail = newTail.next;
    }

    ListNode newHead = newTail.next;
    newTail.next = null; // break the circular list

    return newHead;
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 61 (Rotate List)?

This page provides optimized solutions for LeetCode problem 61 (Rotate List) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 61 (Rotate List)?

The time complexity for LeetCode 61 (Rotate List) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 61 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 61 in Java, C++, or Python.

Back to LeetCode Solutions