SDE & MLE Prep

25. Reverse Nodes in k-Group

Problem

Reverse the nodes of a linked list k at a time; a final group with fewer than k nodes stays as it is. Only relink nodes, don't change values.

Example: 1→2→3→4→5, k = 2 → 2→1→4→3→5; k = 3 → 3→2→1→4→5

Constraints: follow-up: O(1) extra memory.

For each group: check k nodes exist, reverse them in place, then connect the previous group's tail to the new head and move on. A dummy head keeps the first group uniform.

k=2:  d -> 1 -> 2 -> 3 -> 4 -> 5
      d -> 2 -> 1 -> 4 -> 3 -> 5   (last group < k stays)

Complexity: O(n) time, O(1) space.

class Solution:
    def reverseKGroup(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:
        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      # reverse [group_prev.next .. kth]
            while cur is not group_next:
                cur.next, prev, cur = prev, cur, cur.next
            first = group_prev.next
            group_prev.next = kth
            group_prev = first