Reverse Nodes in K-Group
Problem
Given the
You may not alter the values in the list's nodes, only nodes themselves may be changed.
head of a linked list, reverse the nodes of the list k at a time, and return the 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.
Examples
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]
Key Insight
Break the problem into: check if k nodes exist, reverse k nodes, connect groups properly.
Process k nodes at a time: check k exist, reverse them, connect to previous tail and next head, repeat until fewer than k remain.
How to Approach This Problem
Pattern Recognition: When you see keywords like
reverse nodes in k-group linked-list,
think Linked List.
Step-by-Step Reasoning
1
Before reversing a group, we must:
Answer: Check if k nodes exist
If fewer than k nodes remain, don't reverse this group.
2
To reverse k nodes, we use:
Answer: Standard reversal, but stop after k iterations
Same reversal logic, just limited to k steps.
3
After reversing [2, 3, 4] to [4, 3, 2], we need:
Answer: Connect 4 to what came before, 2 to what comes after
The new head (4) must link to previous group's tail. The new tail (2) must link to next group's head.
4
For each group, we track:
Answer: Previous group's tail and current group's head/tail
prev_group_end points to where new head should attach. group_start becomes the new tail after reversal.
5
A dummy node before head helps:
Answer: Handle first group uniformly (no special case)
Even the first group has a "previous" (the dummy), simplifying connections.
6
We stop when:
Answer: Fewer than k nodes remain
Each iteration checks if k nodes exist. If not, stop (leave remaining as is).
Solution
def reverseKGroup(head: ListNode, k: int) -> ListNode:
dummy = ListNode(0, head)
group_prev = dummy
while True:
# Check if k nodes exist
kth = group_prev
for _ in range(k):
kth = kth.next
if not kth:
return dummy.next
group_next = kth.next
# Reverse k nodes
prev, curr = kth.next, group_prev.next
while curr != group_next:
next_temp = curr.next
curr.next = prev
prev = curr
curr = next_temp
# Connect with previous group
tmp = group_prev.next
group_prev.next = kth
group_prev = tmp
return dummy.next
Complexity Analysis
| Time | O(n) |
|---|---|
| Space | O(1) |
Master This Pattern
Build intuition with interactive MCQs. Practice Linked List problems in the LeetEye app.
Download LeetEye Free