LeetCode 61: Rotate List — Python Solution

LeetCode 61: Rotate List is a Medium linked list problem. This Python walkthrough develops a cycle then cut solution, ties every code decision to a concrete invariant, and includes the regression check used before publication.

This independent guide paraphrases the task rather than reproducing LeetCode’s prompt. Use the official page for the exact statement, examples, constraints, and submission runner.

DifficultyMedium
TopicLinked List
Reusable patterncycle then cut
ComplexityO(n) time and O(1) extra space

Recognizing the pattern

Linked-list solutions depend on preserving reachability while rewiring a constant number of pointers. Dummy nodes remove many head-only special cases.

For this problem specifically, measure the length, connect tail to head to form a cycle, then cut after length minus k modulo length steps. The invariant worth writing beside the code is: The temporary cycle preserves order, and the cut selects the node whose predecessor becomes the new tail.

Step-by-step algorithm

  1. Identify the input state consumed by rotateRight(head, k) and initialize the data required by the cycle then cut pattern.
  2. Measure the length, connect tail to head to form a cycle, then cut after length minus k modulo length steps.
  3. After each update, verify the page’s central invariant: The temporary cycle preserves order, and the cut selects the node whose predecessor becomes the new tail.
  4. Finish only after the boundary behavior is covered: Normalize k; empty and one-node lists need no rotation.

Python solution

LeetCode supplies the list, tree, or graph node class referenced by this method. The downloadable test suite includes compatible local node definitions so the implementation can also run outside the judge.

class Solution:
    def rotateRight(self, head, k):
        if not head or not head.next or k == 0:
            return head
        length, tail = 1, head
        while tail.next:
            tail = tail.next
            length += 1
        k %= length
        if k == 0:
            return head
        tail.next = head
        new_tail = head
        for _ in range(length - k - 1):
            new_tail = new_tail.next
        new_head = new_tail.next
        new_tail.next = None
        return new_head

Reading the implementation

The main entry point is rotateRight(head, k). The named working state includes length, tail, new_tail, new_head; those variables make the cycle then cut state visible instead of hiding it in incidental control flow.

The implementation uses 2 loops with separate responsibilities, so preprocessing and the main traversal can each stay linear in their own input. Early returns stop as soon as the answer is forced, avoiding work that cannot change the result. In concrete terms, measure the length, connect tail to head to form a cycle, then cut after length minus k modulo length steps.

Correctness argument

Initialization. The data structure starts with exactly the information known before any input element is processed.

Preservation. Measure the length, connect tail to head to form a cycle, then cut after length minus k modulo length steps. Each update records the current item without invalidating earlier decisions; consequently, the temporary cycle preserves order, and the cut selects the node whose predecessor becomes the new tail.

Termination. The traversal consumes a finite input or finite state space. At the end, the invariant covers the complete input, which is precisely the condition required for the returned result.

Complexity and trade-offs

O(n) time and O(1) extra space. The auxiliary-space figure excludes the returned output unless the output itself is the structure being built.

Copying values into an array makes indexing easy but abandons the intended pointer-space constraint and node identity. That comparison is useful in an interview because it explains why the final implementation is preferable, not merely that it passes.

Regression check

The published implementation belongs to a 100-problem suite that is compiled and exercised behaviorally before deployment.

One reference assertion from that suite is shown below. It targets the normal path while the edge conditions in the next section cover the failure-prone boundaries.

assert listed(Solution().rotateRight(linked([1,2,3,4,5]),2)) == [4,5,1,2,3]

Common mistakes and edge cases

  • Problem-specific boundary: Normalize k; empty and one-node lists need no rotation.
  • Pattern-level pitfall: Save the next node before changing a link, terminate reused tails, and check whether the original head can be removed.
  • Invariant check: after every update, confirm that the temporary cycle preserves order, and the cut selects the node whose predecessor becomes the new tail.

Interview review checklist

  • Explain why cycle then cut matches the structure of this input.
  • State the invariant in one sentence before tracing code: The temporary cycle preserves order, and the cut selects the node whose predecessor becomes the new tail.
  • Derive O(n) time and O(1) extra space from how many times each element or state is visited.
  • Test the boundary explicitly: Normalize k; empty and one-node lists need no rotation.

Browse the searchable 100 LeetCode Python Solutions hub. Previous: 82. Remove Duplicates from Sorted List II · Next: 86. Partition List