hard Reverse Nodes in k-Group
Problem Statement
Given the head of a linked list, reverse each k node of the list at a time and return the modified list.
Here, 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, the remaining nodes at the end should stay as they are.
Note: You can only change the nodes themselves, not the values inside them.
Examples
-
Example 1:
- Input: head = [1, 2, 3, 4, 5, 6], k = 3
- Expected Output: [3, 2, 1, 6, 5, 4]
- Justification: The list is reversed in groups of three. First group [1, 2, 3] becomes [3, 2, 1] and the second group [4, 5, 6] becomes [6, 5, 4].
-
Example 2:
- Input: head = [1, 2, 3, 4, 5], k = 2
- Expected Output: [2, 1, 4, 3, 5]
- Justification: The list is reversed in groups of two. First group [1, 2] becomes [2, 1] and the second group [3, 4] becomes [4, 3]. The last node [5] remains unchanged.
-
Example 3:
- Input: head = [1, 2, 3, 4, 5, 6, 7], k = 4
- Expected Output: [4, 3, 2, 1, 5, 6, 7]
- Justification: The list is reversed in groups of four. First group [1, 2, 3, 4] becomes [4, 3, 2, 1]. The remaining nodes [5, 6, 7] are left as they are because their count is less than k.
Constraints:
- The number of nodes in the list is
n. 1 <= k <= n <= 50000 <= Node.val <= 1000
Try it yourself
Try solving this question here:
✅ Solution Reverse Nodes in k-Group
Problem Statement
Given the head of a linked list, reverse each k node of the list at a time and return the modified list.
Here, 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, the remaining nodes at the end should stay as they are.
Note: You can only change the nodes themselves, not the values inside them.
Examples
-
Example 1:
- Input: head = [1, 2, 3, 4, 5, 6], k = 3
- Expected Output: [3, 2, 1, 6, 5, 4]
- Justification: The list is reversed in groups of three. First group [1, 2, 3] becomes [3, 2, 1] and the second group [4, 5, 6] becomes [6, 5, 4].
-
Example 2:
- Input: head = [1, 2, 3, 4, 5], k = 2
- Expected Output: [2, 1, 4, 3, 5]
- Justification: The list is reversed in groups of two. First group [1, 2] becomes [2, 1] and the second group [3, 4] becomes [4, 3]. The last node [5] remains unchanged.
-
Example 3:
- Input: head = [1, 2, 3, 4, 5, 6, 7], k = 4
- Expected Output: [4, 3, 2, 1, 5, 6, 7]
- Justification: The list is reversed in groups of four. First group [1, 2, 3, 4] becomes [4, 3, 2, 1]. The remaining nodes [5, 6, 7] are left as they are because their count is less than k.
Constraints:
- The number of nodes in the list is
n. 1 <= k <= n <= 50000 <= Node.val <= 1000
Solution
To solve this problem, we will traverse the linked list and reverse every k nodes. We need to handle the reversal in-place, ensuring we only modify the pointers of the nodes. We must also manage the situation where the number of nodes remaining at the end of the list is less than k, in which case those nodes should not be reversed. This approach is effective because it ensures that the nodes are only traversed once, giving an
We will use a loop to process each group of k nodes. For each group, we will reverse the nodes by adjusting the pointers. After reversing each group, we will reconnect it to the previous part of the list. This method ensures that the nodes are reversed in place and the list remains properly connected.
Step-by-step Algorithm
-
Initialize a dummy node: Create a dummy node and set its next pointer to the head of the linked list. This dummy node will help manage the list manipulation easily.
-
Initialize pointers: Set two pointers,
groupPrevandgroupNext, to the dummy node. These pointers will help in identifying the beginning and the end of the group to be reversed. -
Iterate through the linked list: Use a loop to iterate through the linked list.
- Move the
groupNextpointer k nodes ahead: Increment a counter to count nodes and move thegroupNextpointer until it reaches k nodes ahead. If there are less than k nodes remaining, break out of the loop.
- Move the
-
Reverse the k nodes:
- Set the initial pointers for reversal: Set a
prevpointer to the node next togroupPrevand acurrpointer to the node next toprev. - Perform the reversal: Use a loop to reverse the k nodes. For each node in the group, adjust the pointers to reverse the links. Move the
currpointer to the next node after each reversal.
- Set the initial pointers for reversal: Set a
-
Move the
groupPrevpointer: After reversing the k nodes, move thegroupPrevpointer k nodes ahead to the end of the reversed group. -
Return the new head: After the loop completes, return the next node of the dummy node as the new head of the modified list.
Algorithm Walkthrough
Let's walkthrough the algorithm for head = [1, 2, 3, 4, 5, 6], k = 3
-
Initialization:
- Create a dummy node:
dummy = ListNode(0),dummy.next = head - Initialize pointers:
groupPrev = dummy,groupNext = dummy
- Create a dummy node:
-
First Iteration:
- Move groupNext pointer k nodes ahead:
- Move to
groupNext = groupNext.next(1) - Move to
groupNext = groupNext.next(2) - Move to
groupNext = groupNext.next(3)
- Move to
- Check if there are k nodes:
groupNextis not null, so continue.
- Move groupNext pointer k nodes ahead:
-
Reverse the first k nodes:
- Set initial pointers:
prev = groupPrev.next(1),curr = prev.next(2) - Reversal process:
- Step 1:
prev.next = curr.next(1 -> 3)curr.next = groupPrev.next(2 -> 1)groupPrev.next = curr(dummy -> 2)curr = prev.next(3)- List state: dummy -> 2 -> 1 -> 3 -> 4 -> 5 -> 6
- Step 2:
prev.next = curr.next(1 -> 4)curr.next = groupPrev.next(3 -> 2)groupPrev.next = curr(dummy -> 3)curr = prev.next(4)- List state: dummy -> 3 -> 2 -> 1 -> 4 -> 5 -> 6
- Step 1:
- Move
groupPrevpointer k nodes ahead:groupPrev = prev(1)
- Set initial pointers:
-
Second Iteration:
- Move groupNext pointer k nodes ahead:
- Move to
groupNext = groupNext.next(4) - Move to
groupNext = groupNext.next(5) - Move to
groupNext = groupNext.next(6)
- Move to
- Check if there are k nodes:
groupNextis not null, so continue.
- Move groupNext pointer k nodes ahead:
-
Reverse the second k nodes:
- Set initial pointers:
prev = groupPrev.next(4),curr = prev.next(5) - Reversal process:
- Step 1:
prev.next = curr.next(4 -> 6)curr.next = groupPrev.next(5 -> 4)groupPrev.next = curr(1 -> 5)curr = prev.next(6)- List state: dummy -> 3 -> 2 -> 1 -> 5 -> 4 -> 6
- Step 2:
prev.next = curr.next(4 -> null)curr.next = groupPrev.next(6 -> 5)groupPrev.next = curr(1 -> 6)curr = prev.next(null)- List state: dummy -> 3 -> 2 -> 1 -> 6 -> 5 -> 4
- Step 1:
- Move
groupPrevpointer k nodes ahead:groupPrev = prev(4)
- Set initial pointers:
-
End of list:
- The loop ends as there are no more nodes to process.
-
Return the new head:
- Return
dummy.nextwhich points to the new head of the reversed list: 3 -> 2 -> 1 -> 6 -> 5 -> 4
- Return
Code
// class ListNode {
// int val;
// ListNode next;
// ListNode(int x) { val = x; }
// }
public class Solution {
public ListNode reverseKGroup(ListNode head, int k) {
// Dummy node initialization
ListNode dummy = new ListNode(0);
dummy.next = head;
// Initialize pointers
ListNode groupPrev = dummy;
ListNode groupNext = dummy;
// Loop through the list
while (true) {
int count = 0;
// Move groupNext pointer k nodes ahead
while (count < k && groupNext != null) {
groupNext = groupNext.next;
count++;
}
// If there are less than k nodes remaining, break
if (groupNext == null) break;
// Initialize pointers for reversing
ListNode prev = groupPrev.next;
ListNode curr = prev.next;
// Reverse k nodes
for (int i = 1; i < k; i++) {
prev.next = curr.next;
curr.next = groupPrev.next;
groupPrev.next = curr;
curr = prev.next;
}
// Move the groupPrev pointer k nodes ahead
groupPrev = prev;
groupNext = prev;
}
return dummy.next;
}
public static void main(String[] args) {
Solution sol = new Solution();
// Example 1
ListNode head1 = new ListNode(1);
head1.next = new ListNode(2);
head1.next.next = new ListNode(3);
head1.next.next.next = new ListNode(4);
head1.next.next.next.next = new ListNode(5);
head1.next.next.next.next.next = new ListNode(6);
ListNode result1 = sol.reverseKGroup(head1, 3);
printList(result1);
// Example 2
ListNode head2 = new ListNode(1);
head2.next = new ListNode(2);
head2.next.next = new ListNode(3);
head2.next.next.next = new ListNode(4);
head2.next.next.next.next = new ListNode(5);
ListNode result2 = sol.reverseKGroup(head2, 2);
printList(result2);
}
public static void printList(ListNode head) {
while (head != null) {
System.out.print(head.val + " ");
head = head.next;
}
System.out.println();
}
}
Complexity Analysis
- Time Complexity: The algorithm traverses each node in the list a constant number of times. Therefore, the time complexity is
, where (n) is the number of nodes in the list. - Space Complexity: The algorithm uses a constant amount of extra space regardless of the input size. Therefore, the space complexity is
.
🤖 Don't fully get this? Learn it with Claude
Stuck on Reverse Nodes in k-Group? Open Claude, copy a block below, and it'll teach you this exact concept — visually and interactively.
Progressively stronger hints — you still solve it.
I'm working on the problem **Reverse Nodes in k-Group** (DSA). Give me a HINT LADDER: start with the tiniest nudge, then wait. Only reveal the next, stronger hint when I ask. Do NOT show the full solution unless I type 'show solution'. Keep me doing the thinking. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
See the technique, not just code.
Explain the optimal approach to **Reverse Nodes in k-Group** with a VISUAL walkthrough: trace it on a small concrete example using ASCII art / a step-by-step diagram, narrate what changes each step, then give time & space complexity with a one-line derivation. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
Catch bugs, edge cases, sub-optimality.
I'll paste my solution to **Reverse Nodes in k-Group**. Review it for correctness, missed edge cases, and time/space complexity, then coach me toward the optimal — don't just rewrite it. Ask me to paste my code now. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
Lock in recognition with look-alikes.
Give me 2 problems that use the SAME underlying pattern as **Reverse Nodes in k-Group**. For each, let me attempt first, then review my answer and name the trigger signal that reveals the pattern. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.