Linked List Group Reverser - Problem

Given the head of a singly linked list and an integer k, reverse every group of k consecutive nodes in the linked list.

If the number of remaining nodes is less than k, leave them in their original order.

Example:

Input: head = [1,2,3,4,5,6,7,8], k = 3
Output: [3,2,1,6,5,4,7,8]

The first group [1,2,3] becomes [3,2,1], the second group [4,5,6] becomes [6,5,4], and the remaining nodes [7,8] stay as-is since there are fewer than 3 nodes.

Input & Output

Example 1 — Basic Case
$ Input: head = [1,2,3,4,5,6,7,8], k = 3
Output: [3,2,1,6,5,4,7,8]
💡 Note: First group [1,2,3] becomes [3,2,1], second group [4,5,6] becomes [6,5,4]. The remaining nodes [7,8] have fewer than k=3 nodes so they stay unchanged.
Example 2 — Perfect Groups
$ Input: head = [1,2,3,4,5,6], k = 2
Output: [2,1,4,3,6,5]
💡 Note: All nodes form complete groups of k=2: [1,2] becomes [2,1], [3,4] becomes [4,3], [5,6] becomes [6,5].
Example 3 — No Complete Groups
$ Input: head = [1,2,3], k = 4
Output: [1,2,3]
💡 Note: Since there are only 3 nodes but k=4, no complete group exists. The list remains unchanged.

Constraints

  • 1 ≤ number of nodes ≤ 5000
  • 0 ≤ Node.val ≤ 1000
  • 1 ≤ k ≤ number of nodes

Visualization

Tap to expand
INPUTALGORITHMRESULTLinked List: [1,2,3,4,5,6,7,8]k = 312345678Group 1Group 2Remaining1Count k=3 nodes2Reverse group links3Connect with next4Repeat for next groupGroups marked by dashed boxesIn-Place ReversalNo extra space neededOutput: [3,2,1,6,5,4,7,8]32165478Groups ReversedIncomplete groups unchangedKey Insight:Reverse each complete group of k nodes immediately when encountered, leaving incomplete groups unchanged.TutorialsPoint - Linked List Group Reverser | In-Place Reversal
Asked in
Google 45 Amazon 38 Microsoft 32 Facebook 28
68.0K Views
High Frequency
~25 min Avg. Time
2.2K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen