LeetCode 25: Reverse Nodes in k-Group — Python Solution

LeetCode 25: Reverse Nodes in k-Group is a Hard linked list problem. This Python walkthrough develops a group boundary reversal 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.

DifficultyHard
TopicLinked List
Reusable patterngroup boundary reversal
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, find the kth node from the previous group tail. If it exists, reverse exactly that closed group and reconnect both ends. The invariant worth writing beside the code is: Every completed group is reversed and connected, while nodes after the next boundary remain untouched.

Step-by-step algorithm

  1. Identify the input state consumed by reverseKGroup(head, k) and initialize the data required by the group boundary reversal pattern.
  2. Find the kth node from the previous group tail. If it exists, reverse exactly that closed group and reconnect both ends.
  3. After each update, verify the page’s central invariant: Every completed group is reversed and connected, while nodes after the next boundary remain untouched.
  4. Finish only after the boundary behavior is covered: A final group shorter than k remains in original order.

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 reverseKGroup(self, head, k):
        dummy = ListNode(0, head)
        group_prev = dummy
        while True:
            kth = group_prev
            for _ in range(k):
                kth = kth.next
                if not kth:
                    return dummy.next
            group_next = kth.next
            prev, current = group_next, group_prev.next
            while current is not group_next:
                following = current.next
                current.next = prev
                prev, current = current, following
            old_start = group_prev.next
            group_prev.next = kth
            group_prev = old_start

Reading the implementation

The main entry point is reverseKGroup(head, k). The named working state includes dummy, group_prev, kth, group_next, prev; those variables make the group boundary reversal state visible instead of hiding it in incidental control flow.

The implementation uses 3 loops with separate responsibilities, so preprocessing and the main traversal can each stay linear in their own input. In concrete terms, find the kth node from the previous group tail. If it exists, reverse exactly that closed group and reconnect both ends.

Correctness argument

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

Preservation. Find the kth node from the previous group tail. If it exists, reverse exactly that closed group and reconnect both ends. Each update records the current item without invalidating earlier decisions; consequently, every completed group is reversed and connected, while nodes after the next boundary remain untouched.

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().reverseKGroup(linked([1,2,3,4,5]),2)) == [2,1,4,3,5]

Common mistakes and edge cases

  • Problem-specific boundary: A final group shorter than k remains in original order.
  • 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 every completed group is reversed and connected, while nodes after the next boundary remain untouched.

Interview review checklist

  • Explain why group boundary reversal matches the structure of this input.
  • State the invariant in one sentence before tracing code: Every completed group is reversed and connected, while nodes after the next boundary remain untouched.
  • Derive O(n) time and O(1) extra space from how many times each element or state is visited.
  • Test the boundary explicitly: A final group shorter than k remains in original order.

Browse the searchable 100 LeetCode Python Solutions hub. Previous: 92. Reverse Linked List II · Next: 19. Remove Nth Node From End of List