Reverse Nodes in k-Group

hard

Reverse the nodes of a linked list k at a time and return the modified list

Reverse Nodes in K-Group

Key Insight

Count k nodes ahead, reverse that segment, connect to the result of the next group

Step 1Setup
k = 3Group 1: [1,2,3]Remaining: [4,5]
1
2
3
4
5
null

List [1,2,3,4,5] with k=3. Reverse groups of 3.

1 / 6
Practice the Code

Step-by-Step Walkthrough: Reverse Nodes in K-Group

Count k nodes ahead, reverse that segment, connect to the result of the next group

  1. Setup

    List [1,2,3,4,5] with k=3. Reverse groups of 3.

  2. Count K=3 Nodes

    Count ahead: 1, 2, 3. We have k nodes, so reverse this group.

  3. Reverse Group 1

    Reverse [1,2,3] to [3,2,1]. Node 1 will later connect to the next group.

  4. Connect Groups

    Link the tail of reversed group (node 1) to the next group (node 4).

  5. Check Remaining

    Count ahead from node 4: only 2 nodes (4, 5). Less than k=3, so leave as-is.

  6. Result

    First group reversed, remaining nodes unchanged.