25. Reverse Nodes in k-Group 🔄
Last updated
Last updated
Difficulty: Hard
- Tags: Linked List
, Two Pointers
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 they are.
You may not alter the values in the list's nodes, only the nodes themselves may be changed.
🔹 Example 1:
Input:
Output:
🔹 Example 2:
Input:
Output:
The number of nodes in the list is n
.
1 <= k <= n <= 5000
0 <= Node.val <= 1000
The problem can be solved by using a two-pointer technique, iterating over the list in k
-sized groups, and reversing the nodes in each group.
Dummy Node:
We use a dummy node to simplify the reversal process. This helps in handling cases where the head of the list changes after the first reversal.
Count the Total Nodes:
First, we traverse the entire list to count the total number of nodes. This allows us to determine if there are enough nodes left to reverse in groups of k
.
Reverse in Groups of k:
We then process the list in groups of k
nodes. For each group, we reverse the nodes by adjusting their next
pointers.
After reversing a group, we move the prev
pointer to the last node in the reversed group.
Edge Cases:
If the number of remaining nodes is less than k
, they are left as-is without reversal.
O(n): The list is traversed once to count the nodes and again to reverse the groups of k
nodes.
O(1): The reversal is done in-place without using additional memory for new nodes.
Can you solve the problem in O(1) extra memory space? The above solution does not use extra space besides the dummy
node, which is constant space. The space complexity is optimal for this problem.
You can find the full solution here.