← DSA
HARD

Reverse Nodes in k-Group

PracticeNeetCode ↗LeetCode ↗

Given the head of a linked list, reverse the nodes k at a time and return the modified list. If the number of remaining nodes is less than k, leave that final group as-is.

Example

Input head = [1,2,3,4,5], k = 2
Output [2,1,4,3,5]

Key Pointers

Step-by-Step Analysis

  1. Starting from head, walk k nodes ahead to check a full group exists; if not, return head unchanged (base case).
  2. Reverse the k nodes in the current group with standard prev/curr pointer reversal, stopping exactly at the k-th node.
  3. Recursively process the remainder of the list (starting right after this group), and connect the result to the tail of the just-reversed group (the original head of this group).
  4. Return the new head of this group — the node that was originally last in it — up the recursion chain.

Complexity

Time: O(n) — Space: O(n/k) for the recursion stack

Code

class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next

def reverseKGroup(head: ListNode | None, k: int) -> ListNode | None:
    node = head
    count = 0
    while node and count < k:
        node = node.next
        count += 1

    if count < k:
        return head

    prev = None
    curr = head
    for _ in range(k):
        nxt = curr.next
        curr.next = prev
        prev = curr
        curr = nxt

    head.next = reverseKGroup(curr, k)
    return prev

Code Explanation

How the solution above works, piece by piece.

  1. First count ahead: if fewer than k nodes remain, return head unchanged. That's how the leftover 5 stays in place.
  2. Reverse exactly k nodes with the prev/curr loop. Afterwards prev is the new group head and curr is the first node of the next group.
  3. head was the first node of the group and is now its last, so head.next = reverseKGroup(curr, k) connects it to the processed remainder.
  4. Return prev, the new head of this group.
  5. Every node is visited a constant number of times: O(n) time; the recursion uses O(n / k) stack frames.

Visual Walkthrough

Running it on head = [1, 2, 3, 4, 5], k = 2:

1 to 5 reversed in groups of twogroups of k = 212345Noneeach full group is reversed; the last group has only 1 node → kept21435None
The function checks that k nodes remain, reverses just those k, and recursively handles the rest. The old group head (now the group tail) is linked to whatever the recursive call returns.
group 1group 2

Video Explanation

NeetCode — Reverse Nodes in k-Group, LeetCode 25