Reverse Nodes in k-Group Problem
Description
LeetCode Problem 25.
Given a linked list, reverse the nodes of a linked list k at a time and return its 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 it is.
You may not alter the values in the list's nodes, only nodes themselves may be changed.
Example 1:
Input: head = [1,2,3,4,5], k = 2
Output: [2,1,4,3,5]
Example 2:
Input: head = [1,2,3,4,5], k = 3
Output: [3,2,1,4,5]
Example 3:
Input: head = [1,2,3,4,5], k = 1
Output: [1,2,3,4,5]
Example 4:
Input: head = [1], k = 1
Output: [1]
Constraints:
- The number of nodes in the list is in the range sz.
- 1 <= sz <= 5000
- 0 <= Node.val <= 1000
- 1 <= k <= sz
Solution
Approach: Reverse One Group at a Time
We handle the list as a series of blocks of k nodes. For each block we first check that it is complete, reverse it in place, and then link it back between the part before it and the part after it.
Keep groupPrev, the node just before the current group (a dummy node in front of head for the first group). Then repeat:
- Find the group. Walk
ksteps fromgroupPrevto reachkth, the group's last node. If the list ends earlier, fewer thanknodes remain: stop, leaving them as they are. - Reverse it. Remember
groupNext = kth.next. Reverse the nodes fromfirst = groupPrev.nextup tokthwith the usualprev/currloop, but start withprev = groupNextinstead of null. That way the group's old first node, which becomes its last, already points at the rest of the list. - Reconnect.
kthis now the group's first node, so setgroupPrev.next = kth. The oldfirstis now the group's last node and the node before the next group:groupPrev = first.
k = 2: dummy -> 1 -> 2 -> 3 -> 4 -> 5
group 1 reversed: dummy -> 2 -> 1 -> 3 -> 4 -> 5 groupPrev = 1
group 2 reversed: dummy -> 2 -> 1 -> 4 -> 3 -> 5 groupPrev = 3
only 5 is left (fewer than k): stop
Checking that k nodes exist before reversing is the step people miss: reversing first and undoing it later for a short last group is error-prone.
Complexity: O(n) time, where n is the number of nodes (each node is visited once while counting and once while reversing), and O(1) extra space.
class Solution:
def reverseKGroup(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:
dummy = ListNode(0, head)
group_prev = dummy # node just before the group to reverse
while True:
# Find the last node of the group; fewer than k nodes left means we are done.
kth = group_prev
for _ in range(k):
kth = kth.next
if kth is None:
return dummy.next
group_next = kth.next # first node after the group
# Reverse the group in place. Its first node must end up pointing at group_next,
# so the reversal starts with prev = group_next instead of None.
first = group_prev.next
prev, curr = group_next, first
while curr is not group_next:
next_node = curr.next
curr.next = prev
prev = curr
curr = next_node
group_prev.next = kth # kth is now the group's first node
group_prev = first # and the old first node is its last
Now write it from memory
Close the write-up and solve it yourself against the tests.