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
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code