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
Understanding the Visualization
1
Input
Linked list [1,2,3,4,5] with k=2
2
Process
Reverse complete groups of k nodes
3
Output
Result: [2,1,4,3,5]
Key Takeaway
🎯 Key Insight: Only reverse complete groups of k nodes, leaving incomplete groups at the end unchanged
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code