DEV Community

tracelit
tracelit

Posted on • Originally published at tracelit.dev

LeetCode 25: Reverse Nodes In K Group — Step-by-Step Visual Trace

Hard — Linked List | Recursion | Pointers

The Problem

Given the head of a linked list, reverse the nodes of the list k at a time, returning the modified list. If the number of remaining nodes is not a multiple of k, leave the remaining nodes as they are.

Approach

The algorithm first counts the total nodes to determine if reversal is possible. It then reverses the first k nodes using iterative pointer manipulation, and recursively applies the same process to the remaining list segments.

Time: O(n) · Space: O(n/k)

Code

class Solution:
    def reverseKGroup(self, head: ListNode, k: int) -> ListNode:
        if not head or k == 1:
            return head

        # Count the number of nodes in the list
        count = 0
        current = head
        while current:
            count += 1
            current = current.next

        if count < k:
            return head

        # Reverse the first k nodes
        prev, current = None, head
        for _ in range(k):
            next_node = current.next
            current.next = prev
            prev = current
            current = next_node

        # Recursively reverse the remaining part of the list
        head.next = self.reverseKGroup(current, k)

        return prev
Enter fullscreen mode Exit fullscreen mode

Watch It Run

Watch the algorithm run step by step

Watch the algorithm run step by step

Open interactive visualization

Try it yourself: Open TraceLit and step through every line.


Built with TraceLit — the visual algorithm tracer for LeetCode practice.

Top comments (0)