Reverse Nodes in k-Group

Hard

Topics
Linked ListRecursion

Given the head of a linked list, reverse the nodes k at a time and return the modified list. Nodes left over (fewer than k) stay in their original order.

Example 1

before12345null
after21435null
Each full block of 2 is reversed; a trailing block shorter than 2 is left as it is, which is why each group has to be measured before being touched. The separators mark the blocks.
Linked list values from head to tail.
Input:  head = [1,2,3,4,5], k = 2
Output: [2,1,4,3,5]

Example 2

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

Constraints

  • 1 <= number of nodes <= 5000
  • 0 <= Node.val <= 1000
  • 1 <= k <= number of nodes
Editorial — intuition, approach, complexity and pitfalls

Intuition

Process the list in fixed-size blocks: for each full group of k nodes, reverse it, then connect the reversed block to the rest. A leftover partial group at the end is left untouched.

Approach

  1. Check that k more nodes exist ahead; if not, stop.
  2. Reverse the next k pointers, tracking the group boundary.
  3. Reconnect the previous group’s tail to the new head, and continue from the group’s (now) tail.

Dry Run

list = 1 -> 2 -> 3 -> 4 -> 5, k = 2
`gp` is the node just before the group being reversed. dummy sits before the head.

before group 1:   1 2 3 4 5    gp = dummy (val 0)
  reverse the first two, then stitch: gp.next = 2, tail(1).next = 3
after  group 1:   2 1 3 4 5    gp = 1
before group 2:   2 1 3 4 5    gp = 1
  reverse 3 and 4, then stitch: gp.next = 4, tail(3).next = 5
after  group 2:   2 1 4 3 5    gp = 3
has_k(5) is false with only one node left, so 5 is left alone.

answer 2 1 4 3 5

`gp` moves to `tail`, not to `prev`. After reversing, the node that was first in
the group is now last in it, so it is the correct predecessor for the next
group -- advancing to `prev` instead would skip the whole group. And `has_k` is
checked BEFORE reversing, which is what leaves a short final group untouched
rather than reversing it halfway.

Complexity

  • Time — O(n): each node is reversed once.
  • Space — O(1): iterative pointer manipulation.

Common Pitfalls

  • Only reverse a group once you have confirmed k nodes remain, otherwise you would reverse a partial tail.

Full Solution — all languages

class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next
class Solution:
    def reverseKGroup(self, head, k):
        def has_k(node):
            for _ in range(k):
                if not node: return False
                node=node.next
            return True
        dummy=ListNode(0,head); gp=dummy
        while has_k(gp.next):
            prev=None; curr=gp.next
            for _ in range(k):
                nxt=curr.next; curr.next=prev; prev=curr; curr=nxt
            tail=gp.next; gp.next=prev; tail.next=curr; gp=tail
        return dummy.next
Asked at Qualcomm Salesforce
SensAI
Beta
Tap the mic to stop voice mode