Reverse Nodes in k-Group
Given the head of a linked list and a positive integer k, reverse the nodes of the list k at a time and return the new head.
If the number of nodes isn't a multiple of k, leave the last group of fewer than k nodes in its original order. Change the links between nodes, not the values inside them.
Example 1
Input: head = [1, 2, 3, 4, 5], k = 2 Output: [2, 1, 4, 3, 5]
1, 2 and 3, 4 are reversed. 5 is a group of one, which is fewer than k, so it stays.
Example 2
Input: head = [1, 2, 3, 4, 5], k = 3 Output: [3, 2, 1, 4, 5]
Constraints
- The list has
nnodes, where1 <= k <= n <= 5000. 0 <= Node.val <= 1000
Approach
Copying the values into an array, reversing chunks and writing them back would be easy, but it uses O(n) extra space and changes values instead of links. Instead, reverse each group in place with the same three-pointer loop used to reverse a whole list, and stitch each group back into the list.
A dummy node in front of the head means there's always a node before the current group. For each group, first walk k steps to find the group's last node. If the list runs out first, the remaining nodes stay as they are. Otherwise, reverse the group with its first node pointing to the node after the group, connect the node before the group to the old last node, and move on with the old first node as the new "node before."
Steps
- Create a dummy node pointing to
head, and setgroup_prevto the dummy. - Walk
knodes fromgroup_prevto find the group's last node,kth. If you reach the end first, returndummy.next. - Reverse the nodes from
group_prev.nexttokth, starting withprevset to the node afterkth. - Point
group_prev.nextatkth, movegroup_prevto the group's old first node, and repeat.
from typing import Optional
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def reverse_k_group(head: Optional[ListNode], k: int) -> Optional[ListNode]:
dummy = ListNode(0, head)
group_prev = dummy # the node just before the next group
while True:
kth = group_prev
for _ in range(k): # make sure a full group of k nodes remains
kth = kth.next
if kth is None:
return dummy.next
group_next = kth.next
# reverse the group in place, pointing its first node at group_next
prev, curr = group_next, group_prev.next
while curr is not group_next:
curr.next, prev, curr = prev, curr, curr.next
first = group_prev.next # becomes the last node of the reversed group
group_prev.next = kth
group_prev = firstComplexity
- Time:
O(n). Each node is checked once while counting and moved once while reversing. - Space:
O(1). Only a few pointers are used.
Common mistakes
- Reversing the last group even when it has fewer than
knodes. - Starting the reversal with
prevset to null. The group's first node then points to null and cuts off the rest of the list. - Forgetting to update
group_prev. The next group then gets connected to the wrong node.