ExamAdda Logo

Reverse Nodes In K Group

Easy

Given the head of a linked list, reverse the nodes of the list k at a time and return the modified list.

If the number of nodes remaining is less than k, those nodes should remain in their original order.

You must reverse the nodes themselves, not just their values.

Example 1

Input

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

Output

[2,1,4,3,5]

Explanation

The first two nodes are reversed:

[1,2] → [2,1]

 

The next two nodes are reversed:

[3,4] → [4,3]

 

The remaining node 5 has fewer than k nodes, so it stays unchanged.

Example 2

Input

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

Output

[3,2,1,4,5]

Explanation

The first three nodes are reversed. The remaining two nodes are fewer than k, so they remain unchanged.

Constraints

1 <= number of nodes <= 5000
0 <= Node.val <= 1000
1 <= k <= number of nodes

Hints:

Hint 1

Divide the linked list into groups of k nodes.

Hint 2

Before reversing a group, make sure that at least k nodes are available.

Author & Technical Reviewer

ExamAdda Technical Review Team

Technically reviewed by: ExamAdda Technical Review Team

Technical Reviewers, ExamAdda

Software engineers at ExamAdda who check every article's definitions, complexity claims and code examples before and after publishing.

Published

Aug 10, 2026

Last updated

Aug 11, 2026

Content Verification Methodology

Definitions and complexity claims were checked against authoritative computer-science references. Code examples were compiled and tested with standard, boundary and edge-case inputs.

Report a correction:editorial@examadda.org
Auto
Loading editor...
Input

Expected Output