← Whiteboard questions

Reverse Nodes In K Group

Reverse a list in blocks of a fixed size

DSA, Hard, Linked List

Which structure or algorithm, and what does it cost.

You get a linked list and a whole number k. Cut the list into blocks of k nodes from the front. Reverse every full block. If the last block has fewer than k nodes, leave it as it is. Relink the existing nodes; do not copy the values into new nodes. A node has val and next. Your code gets the first node and k, and returns the first node of the result. The examples list the values in order so that they stay short.

Examples

Input values = [1, 2, 3, 4, 5, 6, 7], k = 3
Output [3, 2, 1, 6, 5, 4, 7]
Why two full blocks are reversed, and the leftover 7 stays.
Input values = [4, 5, 6], k = 5
Output [4, 5, 6]
Why there are fewer than 5 nodes, so there is no full block.
Input values = [6, 1, 8, 3], k = 4
Output [3, 8, 1, 6]
Why the whole list is one full block, so all of it is reversed.

Constraints

Your answer must contain

Target Aim for O(n) time and O(1) extra memory.

Hints

Try the problem first. Open one hint at a time.

Hint 1 a nudge

You already know how to reverse a whole list. Think of each block of k nodes as a small list of its own.

Hint 2 the approach

Before you reverse a block, check that k nodes remain. Then reverse it and connect it to the block before it and the block after it.

Hint 3 the key step

Keep a pointer to the node before the block. Reverse the block so its first node points past the block. Link the earlier node to the new first node.

Walkthrough

Full walkthrough brute force to best

Brute force

Copy all values into an array, reverse every full block of k with a slice, and build a new list from the array. This takes O(n) time but O(n) memory, and it creates new nodes instead of relinking the old ones.

Best method

Put a dummy node before the list and keep group_prev, the node just before the current block. Walk k nodes from group_prev to find the block's last node. If the list ends first, stop, because the rest is a short block and stays as it is. Otherwise note the node after the block. Reverse the block with the usual three-pointer loop, but start prev on the node after the block, so the old first node ends up pointing at the rest of the list. The old first node is now the last node of the block. Point group_prev at the new first node, then move group_prev to that old first node and repeat. Each node is visited a constant number of times, and no extra storage grows with n.

Hand trace

Run on [1, 2, 3, 4, 5, 6, 7] with k = 3. Block one: group_prev is the dummy, the last node is 3, and the node after is 4. Reverse 1, 2, 3 so 1 points to 4 and the block reads 3, 2, 1. The dummy points to 3. Now group_prev is 1. Block two: the last node is 6, and the node after is 7. Reverse 4, 5, 6 so 4 points to 7. Node 1 points to 6. Now group_prev is 4. Walking 3 nodes from 4 passes 7 and reaches the end, so stop. The result is [3, 2, 1, 6, 5, 4, 7].

Code

class Node:
    def __init__(self, val, nxt=None):
        self.val = val
        self.next = nxt
def reverse_k_group(head, k):       # head is the first node
    dummy = Node(0, head)
    group_prev = dummy              # the node just before the current group
    while True:
        end = group_prev
        for _ in range(k):          # find the last node of the group
            end = end.next if end else None
        if not end:
            break                   # fewer than k nodes left: keep them as they are
        group_next = end.next
        prev, cur = group_next, group_prev.next
        while cur is not group_next:
            nxt = cur.next
            cur.next = prev
            prev, cur = cur, nxt
        first = group_prev.next     # now the last node of the reversed group
        group_prev.next = end
        group_prev = first
    return dummy.next               # the first node of the result

# Test helper, not part of the answer: builds a list of nodes from values and reads it back.
def build(values):
    head = None
    for v in reversed(values):
        head = Node(v, head)
    return head
def to_values(head):
    out = []
    while head:
        out.append(head.val)
        head = head.next
    return out

Time and memory

O(n) time: finding each block end and reversing it touches each node a constant number of times. O(1) extra memory: a few pointers and a dummy node.

Common mistakes

  • Reversing a short last block. Count k nodes first, and leave the block alone when the list ends early.
  • Starting the reversal with prev as null. That cuts the rest of the list off. Start prev on the node after the block.
  • Forgetting to link the block before it to the new first node of the reversed block.
  • Moving group_prev to the wrong node. After a reversal the old first node is the last one, and that is where the next block starts.

Related problems

More Linked List problems
Reverse Nodes In K Group: walkthrough and Python solution