Python coding

Flip a list in blocks of k

Write reverse_in_groups(head, k): split a singly linked list into consecutive blocks of k nodes, reverse the order of the nodes inside each full block, and return the new first node. The blocks keep their original order, and a final block with fewer than k nodes is left exactly as it is.

k ≥ 1 and the list may be empty. Re-link the nodes instead of rewriting values: O(1) extra memory.

The tests call the provided run_reverse_in_groups(values, k), which builds the list from values and returns the values of the list you return.

  • run_reverse_in_groups([1,2,3,4,5], 2) → [2,1,4,3,5]
  • run_reverse_in_groups([1,2,3,4,5,6], 3) → [3,2,1,6,5,4]
  • run_reverse_in_groups([1,2,3,4,5,6,7,8], 3) → [3,2,1,6,5,4,7,8]
Ctrl/⌘ + Enter runs · Tab indents
Hint 1

It is the plain list reversal applied block by block. A dummy node before the head gives every block, even the first, a node that comes before it.

Hint 2

Before touching a block, walk k steps to confirm it is complete and to find the node after it. If the list ends first, stop: the leftover stays as it is.

Hint 3

After reversing a block, fix both seams: the node before it must point at the block's new first node, and the block's old first node (now its last) at whatever follows.

Solution and why it works
pythonO(n) · O(1)
# --- your code ---
def reverse_in_groups(head: "ListNode | None", k: int) -> "ListNode | None":
    dummy = ListNode(0, head)
    before = dummy                       # last node of the part already done
    while True:
        last = before
        for _ in range(k):               # find the k-th node of the next block
            last = last.next
            if last is None:
                return dummy.next        # fewer than k left: keep them as they are
        after = last.next
        prev, cur = after, before.next   # reversing onto `after` re-attaches the block's end
        while cur is not after:
            nxt = cur.next
            cur.next = prev
            prev, cur = cur, nxt
        first = before.next              # old first node is now the block's last
        before.next = last
        before = first


# --- provided: do not edit ---
class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next


def build_list(values: list[int]) -> ListNode | None:
    head = None
    for v in reversed(values):
        head = ListNode(v, head)
    return head


def to_values(head: ListNode | None, limit: int) -> list[int]:
    out = []
    while head is not None:
        if len(out) == limit:
            raise ValueError("the result has more nodes than the input: is there a cycle?")
        out.append(head.val)
        head = head.next
    return out


def run_reverse_in_groups(values: list[int], k: int) -> list[int]:
    return to_values(reverse_in_groups(build_list(values), k), len(values))

Each round handles one block: before is the node just before it, last its k-th node and after whatever follows. Reversing with prev starting at after re-attaches the block's new tail for free; then before.next = last fixes the front seam, and the block's old first node becomes the next before. The dummy node removes the special case for the first block. The trap is reversing as you count: check that k nodes exist first, or the leftover gets flipped too.