Reverse LL in group of given size K
HardReverse a block, then stitch it back
Problem
Given the head of a singly linked list containing integers, reverse the nodes of the list in groups of k and return the head of the modified list. If the number of nodes is not a multiple of k, then the remaining nodes at the end should be kept as is and not reversed. Do not change the values of the nodes, only change the links between nodes.
Reverse each block of k nodes, leaving a final short block untouched.
The idea
Check that k nodes remain, reverse exactly that block, then connect the previous block's tail to the new head and recurse or loop on the rest. The final partial group is left untouched, which is why the count check comes first.
The trick
- Count k nodes ahead before reversing — a short tail must stay as it is.
- Track the block's original head; after reversing it becomes that block's tail.
- O(n) time; iterative keeps it O(1) space.
This one walks through the worked example rather than tracing the algorithm frame by frame — a full walkthrough is still to be drawn. The code and the idea below are the real solution.
Step 1 of 2. Here's the example — head -> 1 -> 2 -> 3 -> 4 -> 5, k = 2 Values: 1, 2, 3, 4, 5, 2.
1if fewer than k nodes remain: return head2reverse the first k nodes3head.next = reverseKGroup(nextGroupHead, k) // head is now the k-th (tail of this group)4return newHeadInput
- array
- [1, 2, 3, 4, 5, 2]
Output
- answer
- —
Check yourself
3 quick questions about this walkthrough. A wrong answer costs nothing.
Examples
Example 1
- Input:
- list = 1 -> 2 -> 3 -> 4 -> 5, k = 2
- Output:
- 2 -> 1 -> 4 -> 3 -> 5
- Explanation:
- Reverse each pair; the leftover 5 stays.
Example 2
- Input:
- list = 1 -> 2 -> 3 -> 4 -> 5, k = 3
- Output:
- 3 -> 2 -> 1 -> 4 -> 5
- Explanation:
- First 3 flip; last 2 stay as-is.
Example 3
- Input:
- list = 1 -> 2 -> 3 -> 4, k = 2
- Output:
- 2 -> 1 -> 4 -> 3
- Explanation:
- Two clean reversed pairs.
Constraints
- 1 <= k <= number of nodes in the linked list <= 10^5
- -10^4 <= ListNode.val <= 10^4
Practice this problem:LeetCode(opens in a new tab)Search GeeksforGeeks(opens in a new tab)
Finished the walkthrough? Add it to your streak.