Reverse Nodes in k-Group
Difficulty: Hard · Pattern: Linked List · LeetCode #25
Reverse the nodes of the list k at a time and return the head. If the number of remaining nodes is less than k, leave them as they are. Change links, not values, with O(1) extra memory.
Examples
text
1 → 2 → 3 → 4 → 5, k = 2 → 2 → 1 → 4 → 3 → 5
1 → 2 → 3 → 4 → 5, k = 3 → 3 → 2 → 1 → 4 → 5Hints
- Before reversing, verify that k nodes remain from the current position.
- Reverse exactly k nodes, then connect the previous group's tail to the new group head.
Approach
groupPrev starts at a dummy. Loop: find the k-th node after groupPrev; if it doesn't exist, stop. Let groupNext = kth.next. Reverse the nodes between groupPrev.next and kth (standard reversal, with prev initialized to groupNext so the reversed tail links forward). Then set groupPrev.next = kth and move groupPrev to the old group head (now the tail). O(n), O(1).
Complexity
Time: O(n). Space: O(1).
Python solution
def reverseKGroup(head, k):
dummy = ListNode(0, head)
group_prev = dummy
while True:
kth = group_prev
for _ in range(k):
kth = kth.next
if not kth:
return dummy.next
group_next = kth.next
prev, cur = group_next, group_prev.next
while cur is not group_next:
cur.next, prev, cur = prev, cur, cur.next
first = group_prev.next
group_prev.next = kth
group_prev = firstJavaScript solution
function reverseKGroup(head, k) {
const dummy = new ListNode(0, head); let groupPrev = dummy;
for (;;) {
let kth = groupPrev;
for (let i = 0; i < k; i++) { kth = kth.next; if (!kth) return dummy.next; }
const groupNext = kth.next;
let prev = groupNext, cur = groupPrev.next;
while (cur !== groupNext) { const nxt = cur.next; cur.next = prev; prev = cur; cur = nxt; }
const first = groupPrev.next;
groupPrev.next = kth; groupPrev = first;
}
}