Reverse Nodes in k-Group
Reverse a linked list in blocks of k nodes, leaving a short last block alone, with O(1) extra memory.
The problem
You get the head of a linked list and a positive integer k. Reverse the nodes in consecutive groups of k: the first k nodes, then the next k, and so on. If fewer than k nodes are left at the end, leave them in their original order. Change the links rather than the values, and return the new head.
Input head = [10, 20, 30, 40, 50, 60, 70, 80], k = 3
Output [30, 20, 10, 60, 50, 40, 70, 80]
Two full groups of 3 are reversed; the last two nodes (70 and 80) don't make a full group, so they stay as they are.
Input head = [5, 6, 7, 8], k = 4
Output [8, 7, 6, 5]
k equals the length, so the whole list is one group.
Key constraint: The follow-up asks for O(1) extra memory, so no copying nodes into an array and no recursion used as a stack.
How to spot the pattern
- Reversal is applied to fixed-size blocks of a list, not to the whole list.
- Each reversed block has to be reattached to the part before it and the part after it.
The idea
Handle one group at a time. Keep a pointer groupPrev to the node just before the current group, and first check that k more nodes exist; if they don't, you are done. Reverse those k nodes with the usual three-pointer loop, then stitch the group back in: the node before the group must point to the group's new first node, and the group's old first node, now its last, must point to whatever follows the group. That old first node is groupPrev for the next round.
Brute force: Copy the nodes into an array, reverse each full block of k in the array and relink everything, which uses O(n) extra space.
Step by step
- 1Create a dummy node in front of
headand setgroupPrevto the dummy. - 2Walk
knodes fromgroupPrevto find the group's last nodekth; if the list ends first, returndummy.next. - 3Save
groupNext = kth.next, then reverse theknodes, starting withprev = groupNextso the group's first node ends up pointing togroupNext. - 4Set
groupPrev.nexttokth, the group's new first node, and movegroupPrevto the group's old first node. - 5Repeat from the second step until a group comes up short.
See the pattern move
The linked lists pattern on a small example. Step through it, or press play.
Code
class Solution:
def reverseKGroup(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:
dummy = ListNode(0, head)
group_prev = dummy
while True:
# Find the k-th node after group_prev; stop if the group is not full.
kth = group_prev
for _ in range(k):
kth = kth.next
if kth is None:
return dummy.next
group_next = kth.next
# Reverse the group. Starting prev at group_next makes the group's
# first node point to group_next once it becomes the last node.
prev, curr = group_next, group_prev.next
while curr is not group_next:
nxt = curr.next
curr.next = prev
prev = curr
curr = nxt
# Stitch the reversed group in; its old first node is now its last.
old_first = group_prev.next
group_prev.next = kth
group_prev = old_firstComplexity
Time
O(n)
Space
O(1)
Each node is visited a constant number of times: once while checking that its group is full and once while reversing it.
Watch out for
- Reversing the last group even when it has fewer than
knodes; always countknodes before you reverse. - Losing the rest of the list: the reversed group's last node (its old first node) must point to
groupNext. - Forgetting to move
groupPrevto the old first node, so the next round starts in the wrong place.
Follow-up questions
What if the last group should also be reversed when it is shorter than k?
Skip the length check and reverse whatever is left; the stitching stays the same.
Can you solve it recursively?
Yes: reverse the first k nodes, then set the old first node's next to the result of the recursive call on the rest of the list. It is easier to write, but it uses O(n / k) stack space.
In Hinglish
Pehle check karo ki k nodes hain ya nahi, phir us group ko ulta karo aur aage-peeche dono taraf sahi se jod do. Jo group poora nahi hai use waise hi chhod do.