Rotate List

Move the last k nodes of a linked list to its front, by counting the nodes and rewiring two links.

Given the head of a linked list and a number k, rotate the list to the right by k places and return the new head. One rotation to the right takes the last node off the end and puts it at the front. The number k is zero or more, and it may be larger than the length of the list.

Example 1
Input: head = [1, 2, 3, 4, 5], k = 2
Output: [4, 5, 1, 2, 3]
Example 2
Input: head = [0, 1, 2], k = 4
Output: [2, 0, 1]
Explanation: 4 rotations of 3 nodes equal 1 rotation.
Solution

The Idea

Think of five people, numbered 1 to 5, standing in a line, and the last one walks to the front. Do that twice and the line reads 5, 1, 2, 3, 4, then 4, 5, 1, 2, 3, the answer to Example 1. In a linked list, each item is a node: a box holding a number and a link to the next node. The list only knows its first node, the head.

Example 2 rotates a list of three nodes four times. Three rotations bring 0, 1, 2 all the way round to where it started, so only the fourth one changes anything. A list of n nodes repeats every n rotations, which means only the remainder of k divided by n matters.

Even so, moving one node at a time means a trip to the end of the list for every rotation. Is there a quicker way? Look at the two lists in Example 1 side by side: the last two nodes, 4 and 5, moved to the front as one block, and the rest, 1, 2, 3, followed them unchanged. So a rotation by k is just one cut and one join. Look at the picture below.

Rotating 1, 2, 3, 4, 5 right by 2. The link between 3, the new tail, and 4, the new head, is cut. A new link goes from 5, the old tail, to 1, the old head. The row labelled after reads 4, 5, 1, 2, 3.

In the row labelled before, node 1 is the old head and node 5 is the old tail, the last node. The link from 3 to 4 is cut, so 4 becomes the new head and 3 the new tail. The curved arrow labelled new link joins the old tail, 5, to the old head, 1. Read the row labelled after from the left and you get 4, 5, 1, 2, 3.

So the whole rotation changes only two links, wherever the cut falls. The work is in finding the right places: the old tail, and the node where the cut goes.

Solution Approach

Turning that idea into code means settling two things: how to make a huge k small, and how to find the new tail. First, though, why is the simple way of moving one node at a time too slow?

Moving one node at a time

Why not simply repeat the rotation k times? Each rotation walks to the end of the list to find the last node, so it costs about n steps. With k = 2,000,000,000 and five nodes, that is ten billion steps to reach an answer the cut-and-join finds in under ten.

Reducing k

How do we get rid of the extra full turns? Count the nodes first, and call the count n. Since n rotations give back the same list, k % n (the remainder after dividing by n) rotations give the same result as k. In Example 2, 4 % 3 is 1. If the remainder is 0, the list stays as it is.

The walk that counts the nodes ends on the last node, so the same walk also finds the old tail. Nothing has to be walked twice for it.

Finding the new tail

Where does the cut go? The last k nodes move to the front, so the first n - k nodes stay at the back. The new tail is therefore node number n - k, counting from 1 at the head. In Example 1, that is node 5 - 2 = 3. Reaching it from the head takes n - k - 1 steps, and the node after it is the new head.

Java Solution

The method rotateRight works in these steps:

  1. First, an empty list (head is null) has nothing to rotate, so return null.
  2. Walk a pointer named tail from the head to the last node, counting the nodes in n on the way. When the loop stops, tail is on the old tail.
  3. Reduce k with k %= n. If it is now 0, return head unchanged.
  4. Start a second pointer, newTail, at the head, and a loop moves it forward until it stands on node number n - k.
  5. Keep the node after it in newHead. Then cut the list by setting newTail.next to null, and join the old tail to the old head with tail.next = head.
  6. Return newHead.

The class also has a small ListNode class for the boxes, build to make a list from numbers and show to print it. The main method runs both examples, a k equal to the length, a k over two billion, a single node and an empty list.

Java
public class RotateList {

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

    public static ListNode rotateRight(ListNode head, int k) {
        if (head == null) {
            return null;
        }
        int n = 1;
        ListNode tail = head;
        while (tail.next != null) {      // count the nodes and stop on the last one
            tail = tail.next;
            n++;
        }
        k %= n;                          // every n rotations give the same list back
        if (k == 0) {
            return head;
        }
        ListNode newTail = head;
        for (int i = 1; i < n - k; i++) {  // walk to node number n - k
            newTail = newTail.next;
        }
        ListNode newHead = newTail.next;
        newTail.next = null;             // cut the list after the new tail
        tail.next = head;                // the old tail now leads to the old head
        return newHead;
    }

    static ListNode build(int... values) {
        ListNode dummy = new ListNode(0);
        ListNode last = dummy;
        for (int v : values) {
            last.next = new ListNode(v);
            last = last.next;
        }
        return dummy.next;
    }

    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(rotateRight(build(1, 2, 3, 4, 5), 2)));
        System.out.println(show(rotateRight(build(0, 1, 2), 4)));
        System.out.println(show(rotateRight(build(1, 2, 3, 4, 5), 5)));
        System.out.println(show(rotateRight(build(1, 2, 3, 4, 5), 2000000002)));
        System.out.println(show(rotateRight(build(7), 3)));
        System.out.println(show(rotateRight(build(), 1)));
    }
}

Running it prints:

Output
[4, 5, 1, 2, 3]
[2, 0, 1]
[1, 2, 3, 4, 5]
[4, 5, 1, 2, 3]
[7]
[]

Example 1 comes out as [4, 5, 1, 2, 3] and Example 2 as [2, 0, 1], as expected. On the third line, rotating five nodes by 5 gives back [1, 2, 3, 4, 5], because 5 % 5 is 0 and the method returns early.

The fourth line rotates the same five nodes by 2,000,000,002. The remainder 2,000,000,002 % 5 is 2, so the result is [4, 5, 1, 2, 3] again, as fast as with k = 2. A single node, [7], cannot change, and the empty list prints [].

The line k %= n is easy to leave out, and the code still compiles. Without it, Example 2 prints [1, 2, 0] and rotating five nodes by 5 prints [2, 3, 4, 5, 1]. Once k reaches n, n - k is 0 or less, so the loop never runs and the cut always lands after the first node.

Complexity

The work is two walks from the head: one to the old tail, and one to the new tail.

  • Time: O(n), for a list of n nodes: the first walk visits every node once to count them, and the second stops at node n - k, before the end. Because of k %= n, a huge k adds no steps.
  • Space: O(1). No node is copied. The method keeps three pointers and a count, and changes only two links, newTail.next and tail.next.

The same rotation on an array, where elements cannot be relinked, is Rotate Array.