Reverse Nodes in k-Group - Problem

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

k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k then left-out nodes, in the end, should remain as it is.

You may not alter the values in the list's nodes, only nodes themselves may be changed.

Input & Output

Example 1 — Basic Case
$ Input: head = [1,2,3,4,5], k = 2
Output: [2,1,4,3,5]
💡 Note: Reverse first 2 nodes: [1,2] becomes [2,1]. Reverse next 2 nodes: [3,4] becomes [4,3]. Node 5 remains as is since it's incomplete group.
Example 2 — Perfect Groups
$ Input: head = [1,2,3,4,5,6], k = 3
Output: [3,2,1,6,5,4]
💡 Note: Reverse first 3 nodes: [1,2,3] becomes [3,2,1]. Reverse next 3 nodes: [4,5,6] becomes [6,5,4]. All nodes form complete groups.
Example 3 — Single Node
$ Input: head = [1], k = 1
Output: [1]
💡 Note: When k=1, no reversal needed. Return original list unchanged.

Constraints

  • The number of nodes in the list is n.
  • 1 ≤ k ≤ n ≤ 5000
  • 0 ≤ Node.val ≤ 1000

Visualization

Tap to expand
Reverse Nodes in k-Group INPUT Linked List: 1 2 3 4 5 NULL Groups of k=2: [1,2] [3,4] [5] Input Values: head = [1,2,3,4,5] k = 2 Reverse every 2 nodes ALGORITHM STEPS 1 Count k nodes Check if k nodes exist 2 Reverse k nodes In-place pointer reversal First group [1,2]: 1 --> 2 becomes 2 --> 1 3 Connect groups Link reversed to next group 4 Repeat or keep rest Leftover nodes unchanged Complexity: Time: O(n) Space: O(1) FINAL RESULT Reversed List: 2 1 4 3 5 NULL Group reversals: [2,1] OK [4,3] OK [5] kept Output: [2,1,4,3,5] Successfully reversed in k-groups Key Insight: In-place reversal uses three pointers (prev, curr, next) to reverse links without extra space. Track the tail of each reversed group to connect it with the head of the next reversed group. If remaining nodes are less than k, leave them unchanged - no reversal needed. TutorialsPoint - Reverse Nodes in k-Group | In-Place Reversal Approach
Asked in
Google 45 Amazon 38 Microsoft 32 Facebook 28
78.0K Views
Medium-High Frequency
~25 min Avg. Time
892 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