Reverse Nodes in k-Group

Reverse a linked list k nodes at a time by moving each group's nodes to its front, and leave a short tail as it is.

Given the head of a singly linked list, where each node links only to the node after it, and a positive whole number k, reverse the nodes k at a time: the first k nodes, then the next k, and so on. If fewer than k nodes remain at the end, leave them in their order. Only the links between nodes may change, not the values stored in them. Return the head of the changed list.

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]
Solution

The Idea

Picture five cards in a row, numbered 1 to 5. Example 1 takes them two at a time and flips each pair: 1, 2 becomes 2, 1, and 3, 4 becomes 4, 3. Card 5 has no partner, so it stays at the end, and the row reads 2, 1, 4, 3, 5. Example 2 flips three at a time: 1, 2, 3 becomes 3, 2, 1, and the two cards left over, 4 and 5, are too few for a group.

A linked list is built like a chain of those cards. In a linked list, every node stores one value plus next, the link to the node that follows. The first node is the head, and getting to any node means starting at the head and following the links. So we cannot lift a group out and flip it; we change links, one node at a time.

Reversing the nodes inside a group is only half the job. After the first group of Example 1 becomes 2, 1, the list must start at 2, and node 1 must link to 3, the start of the next group. When that next group becomes 4, 3, node 1's link has to change again, to 4. How do we keep track of where each group hangs on to the rest of the list?

Keep a marker on the node just before the current group, and call it before. The first group has no node in front of it, so we add a placeholder node in front of the head, whose next is the head. Such a placeholder is called a dummy node. Look at the picture below.

The list 1, 2, 3, 4, 5 with k = 2, behind a dummy node. At the start, before is the dummy node and group 1 holds 1 and 2. After group 1 the list reads 2, 1, 3, 4, 5 and before is node 1. After group 2 it reads 2, 1, 4, 3, 5 and before is node 3. Node 5 is left on its own and stays as it is.

In the row labelled start, before is on the dummy node, and group 1 holds 1 and 2. In the row labelled after group 1, the group reads 2, 1, and before has moved to node 1. Node 1 was the group's first node and is now its last, so group 2, nodes 3 and 4, hangs right after it.

In the row labelled after group 2, the list reads 2, 1, 4, 3, 5, and before is on node 3, again the old first node of the group just reversed. Only node 5 is left, one node where k = 2 needs two, so it stays as it is.

So the whole job is one round per group, each starting from before: make sure k nodes follow it, reverse them, and move before to the group's old first node. The dummy node means the first group is handled like every other one.

Solution Approach

Turning that idea into code means settling three things: how to tell whether a full group is left, how to reverse one group in place, and where before goes after each group.

Checking for a full group

How do we know that k nodes follow before? Walk a second marker, check, forward from before, up to k steps. The last node's next is null, Java's value for "no node". If check reaches null before taking all k steps, fewer than k nodes are left, they stay as they are, and the work is done.

The check comes before any relinking. If we started reversing and ran out of nodes halfway, as with 4 and 5 in Example 2, we would have to undo those moves to leave the short tail in order.

Reversing one group in place

How do we reverse k nodes without losing hold of any of them? Call the group's first node first. Take the node right after it, call it moved, unhook it, and hook it in right after before, at the front of the group.

Three links change, in this order. first.next = moved.next closes the gap that moved leaves. moved.next = before.next links moved to the current front of the group. Then before.next = moved makes it the new front. Each change reads a link that a later one overwrites, so the order matters.

In group 1 of Example 1, one move takes node 2 to the front, and the group reads 2, 1. With k = 3, a second move takes node 3 to the front as well, giving 3, 2, 1. Every node except first is moved once, so a group needs k - 1 moves. Reverse Linked List II uses the same move for one stretch of a list.

Notice that first never moves itself. The other nodes are pulled in front of it, so it slides to the back of the group and stays linked to whatever follows the group. Both ends of the group are joined correctly after every move.

A simpler way would copy the values into an array, reverse each block of k, and write them back. The problem rules that out, because only links may change, and it would also need an array as long as the list.

Moving on to the next group

Where does before go once a group is reversed? To the node just before the next group, which is the group's new last node. That is first, the node that slid to the back, so the round ends with before = first, just as node 1 and then node 3 carry the label before in the picture.

Java Solution

The method reverseKGroup works in these steps:

  1. First, create dummy, a node whose next is head, and start before on it.
  2. A while (true) loop handles one group per round. Inside it, a first for loop moves check from before up to k steps forward. If check becomes null, fewer than k nodes are left, and the method returns dummy.next, the head of the changed list.
  3. Set first to before.next, the first node of the group.
  4. A second for loop runs k - 1 times. Each time it takes moved, the node after first, closes the gap with first.next = moved.next, and puts moved at the front of the group with moved.next = before.next and before.next = moved.
  5. Set before to first, now the group's last node, and start the next round.

Around the method, a small ListNode class holds one node, build makes a list from numbers, and show prints a list in brackets. The main method runs both examples, then six nodes in groups of three, k equal to the length, k = 1, and k larger than the list.

Java
public class ReverseNodesInKGroup {

    static class ListNode {
        int val;
        ListNode next;
        ListNode(int val, ListNode next) { this.val = val; this.next = next; }
    }

    public static ListNode reverseKGroup(ListNode head, int k) {
        ListNode dummy = new ListNode(0, head);
        ListNode before = dummy;                    // the node just before the current group
        while (true) {
            ListNode check = before;
            for (int i = 0; i < k; i++) {           // are there k nodes left?
                check = check.next;
                if (check == null) {
                    return dummy.next;              // fewer than k: leave them as they are
                }
            }
            ListNode first = before.next;           // stays in place, ends up last in the group
            for (int i = 0; i < k - 1; i++) {
                ListNode moved = first.next;        // take the node after first
                first.next = moved.next;            // close the gap it leaves
                moved.next = before.next;           // and insert it right after before
                before.next = moved;
            }
            before = first;                         // the node just before the next group
        }
    }

    static ListNode build(int... values) {
        ListNode head = null;
        for (int i = values.length - 1; i >= 0; i--) {
            head = new ListNode(values[i], head);
        }
        return head;
    }

    static String show(ListNode node) {
        StringBuilder sb = new StringBuilder("[");
        for (; node != null; node = node.next) {
            sb.append(node.val).append(node.next != null ? ", " : "");
        }
        return sb.append("]").toString();
    }

    public static void main(String[] args) {
        System.out.println(show(reverseKGroup(build(1, 2, 3, 4, 5), 2)));
        System.out.println(show(reverseKGroup(build(1, 2, 3, 4, 5), 3)));
        System.out.println(show(reverseKGroup(build(1, 2, 3, 4, 5, 6), 3)));
        System.out.println(show(reverseKGroup(build(1, 2, 3, 4, 5), 5)));
        System.out.println(show(reverseKGroup(build(1, 2, 3, 4, 5), 1)));
        System.out.println(show(reverseKGroup(build(1, 2, 3), 4)));
    }
}

Running it prints:

Output
[2, 1, 4, 3, 5]
[3, 2, 1, 4, 5]
[3, 2, 1, 6, 5, 4]
[5, 4, 3, 2, 1]
[1, 2, 3, 4, 5]
[1, 2, 3]

Example 1 gives [2, 1, 4, 3, 5], the list in the row labelled after group 2, and Example 2 gives [3, 2, 1, 4, 5], with 4 and 5 still in order. On the third line, [3, 2, 1, 6, 5, 4], six nodes split into two full groups and nothing is left over. In the third round check finds no node after 4, and the method returns.

With k = 5 the whole list is one group and comes back as [5, 4, 3, 2, 1]. With k = 1 each group is a single node, the second loop makes no moves, and the list is unchanged. The last line, [1, 2, 3], comes from k = 4 on three nodes: check reaches null in the first round, so nothing is reversed.

The line before = first is the easy one to get wrong. Writing before = before.next instead moves before one node forward, onto the new front of the group, so the next round treats node 1 and node 3 of Example 1 as a group. Node 1 keeps sliding back, and the two examples print [2, 3, 4, 5, 1] and [3, 4, 5, 2, 1].

Complexity

Each round walks check over the next group and then relinks that group, so every node is handled a fixed number of times.

  • Time: O(n) for a list of n nodes: check passes each node once, in the round of its group or in the last round over the short tail, and the second loop moves each node at most once, with three link changes.
  • Space: O(1). The groups are relinked in place. The only new node is dummy, plus a few variables, and there is no recursion whose calls would pile up with the length of the list.

With k = 2 every pair of neighbours is swapped, which is Swap Nodes in Pairs.