Scrivio Interview library
Linked listsLinked listsReported 15 times · 16 min read · updated 15 November 2026

Rotate a linked list to the right by k positions.

1What it means to rotate a line of nodes

Picture a group of children standing in a line in the playground, each one pointing at the child who comes after them. The teacher can speak only to the first child, and to reach anyone else she must follow the pointing fingers one child at a time. The last child points at nobody. Now the teacher says that the last two children should walk round to the front. Nobody else moves; only a few fingers change where they point.

That line of children is a singly linked list. Each child is a node, a small object that holds a value, and the pointing finger is a reference called next, which says which node comes after it. The first node is the head, the only one we are handed, and the last node's next is null, Java's word for nothing. Rotating the list to the right by k means taking the last k nodes and moving them to the front, keeping their order.

We will keep one example. The list is 1 -> 2 -> 3 -> 4 -> 5 and k is 2. The last two nodes, 4 and 5, move to the front, and the answer is 4 -> 5 -> 1 -> 2 -> 3. Check it one step at a time: rotating by one gives 5 -> 1 -> 2 -> 3 -> 4, and once more gives 4 -> 5 -> 1 -> 2 -> 3.

PictureThe example list before and after rotating by 2

Top row: the list we are given. Bottom row: the answer, made of the same five nodes. The marked nodes are the last two, which move to the front.

  1. 1234545123

    1The top row is 1 -> 2 -> 3 -> 4 -> 5. Rotating right by 2 moves nodes 4 and 5 to the front, so the bottom row reads 4 -> 5 -> 1 -> 2 -> 3.

What to assume

Can the list be empty or have a single node?
Yes, and both come back unchanged, because there is nothing to move.
Can k be zero?
Yes, and then nothing changes.
Can k be larger than the length?
Yes, and this one matters. Rotating a five-node list five times brings every node back where it started, so rotating by 7 is the same as rotating by 2. In general rotating by k equals rotating by k mod length, the remainder after dividing k by the length. We also assume we rearrange the existing nodes and return the new head.

The good news is that the problem is smaller than it looks. Look at the bottom row of the picture and count the arrows that changed. Node 3 used to point at 4 and now points at nothing, because it is the new last node. Node 5 used to point at nothing and now points at 1. Every other arrow is exactly as it was. However large the list is, a rotation changes only a couple of arrows. The whole problem is finding which ones.

A careful candidate asks a few questions first. Can the list be empty or have a single node? Yes, and both come back unchanged, because there is nothing to move. Can k be zero? Yes, and then nothing changes. Can k be larger than the length? Yes, and this one matters. Rotating a five-node list five times brings every node back where it started, so rotating by 7 is the same as rotating by 2. In general rotating by k equals rotating by k mod length, the remainder after dividing k by the length. We also assume we rearrange the existing nodes and return the new head.

2How to recognise a linked list cutting problem

A beginner reading this question often thinks first of arrays, because rotating an array is a familiar exercise. With an array you can jump straight to any position, copy the last k values aside and shift the rest. A linked list cannot jump. To reach node 4 we must start at node 1 and follow three arrows, and no node knows the one before it. So the array tricks, which rely on jumping, lose their advantage here.

So let us read the question slowly, one clue at a time. The first clue is the phrase by k positions, counted from the right. Positions near the end of a list we can only walk forward are the hard part, because the list does not tell us how long it is. Whenever a question measures something from the tail of a singly linked list, we either count the length first or keep two references a fixed distance apart.

The second clue is the word rotate itself. A rotation keeps the order of the nodes and only changes where the list starts, the way a line of children walking round in a circle keeps its order. That suggests joining the end of the list to its start, so the nodes form a ring, and then choosing where to open it again.

Together the clues point to the linked lists pattern, and to a technique of changing a few links in place. In place means we reuse the nodes we already have and build no copy. The rule to carry to new problems is this. In a linked list, moving a whole block of nodes costs nothing once you know where to cut, because only the links at the cut and at the ends change, so the real work is finding the cut with one walk.

Some patterns look similar but do not fit. The array trick of reversing the whole thing and then reversing both parts does work on a list, but it rewrites every link for no gain. Fast and slow pointers find the middle of a list, which is not the position we need. Two pointers k apart could find the k-th node from the end, but they need k to be smaller than the length, and that is not promised.

3The honest first attempt, one step at a time

The honest first attempt follows the definition literally, and that is a perfectly good place to start. To rotate by one, walk to the node just before the last, detach the last node, and put it in front of the head. Then do that k times. It is easy to believe, because each step is something we did by hand a moment ago.

Step throughRotating one step at a time, seven times

Each frame is the list after one more single-step rotation. The marked node is the one that has just moved to the front.

  1. 12345
    steps done
    0
    arrows walked
    0

    1We start with 1 -> 2 -> 3 -> 4 -> 5 and k = 7, so the brute force will walk the whole list seven times.

  2. 51234
    steps done
    1
    arrows walked
    3

    2Step 1 walks three arrows to node 4, detaches node 5 and puts it in front: 5 -> 1 -> 2 -> 3 -> 4.

  3. 45123
    steps done
    2
    arrows walked
    6

    3Step 2 walks the list again from the new head and moves node 4 to the front: 4 -> 5 -> 1 -> 2 -> 3, the real answer.

  4. 34512
    steps done
    3
    arrows walked
    9

    4Step 3 moves node 3 to the front: 3 -> 4 -> 5 -> 1 -> 2. We are now past the answer.

  5. 23451
    steps done
    4
    arrows walked
    12

    5Step 4 moves node 2 to the front: 2 -> 3 -> 4 -> 5 -> 1.

  6. 12345
    steps done
    5
    arrows walked
    15

    6Step 5 moves node 1 to the front, and the list is exactly what we started with. Five steps of work have cancelled out.

  7. 45123
    steps done
    7
    arrows walked
    21

    7Steps 6 and 7 repeat steps 1 and 2 and end at 4 -> 5 -> 1 -> 2 -> 3, after 21 arrows walked for a two-node move.

Java
// Brute force: k times, move the last node to the front.
static Node rotateRight(Node head, int k) {
if (head == null || head.next == null) return head;
for (int step = 0; step < k; step++) {
Node beforeLast = head;
while (beforeLast.next.next != null) beforeLast = beforeLast.next; // walk to the end
Node last = beforeLast.next;
beforeLast.next = null; // node before the last becomes the tail
last.next = head; // the last node goes in front
head = last;
}
return head;
}

Let us run it by hand with k = 7, a value the question allows. Each step starts at the head and walks three arrows to reach the node before the last, then changes three references. The picture shows the list after each step. Watch what happens at step 5.

Now let us count. Each step walks about n arrows for an n-node list, and there are k steps, so the time is O(n x k), read as order n times k. The space is O(1), only a few references. That looks harmless for k = 2, but nothing stops k from being two billion on a list of five nodes, and then the program walks billions of arrows for an answer we could have written down at once.

So where is the waste? It comes in two kinds, and the picture shows both. First, whole rounds of work cancel out: every five steps restore the original list, so steps 1 to 5 bought nothing. Second, each step walks the whole list again just to find its end, yet all seven steps together amount to one change, opening the list at a different place.

4From the waste to closing the ring and cutting it

Let us remove the first waste with arithmetic. To know which rounds cancel, we need the length of the list, so we walk it once and count. While we are at the end, we keep a reference to the last node, called the tail, because we will need it. For our list the length is 5 and the tail is node 5. Then we replace k with k mod length. For k = 7 that is 2, and for our real k = 2 it stays 2. If it comes out as 0, the list is unchanged and we return the head at once.

Now the second waste. Instead of moving nodes one at a time, let us ask what the finished list looks like and change only the arrows that differ. We saw it in the opening picture. The new head is node 4. The new last node is node 3, the one just before it, so its next must become null. And the old tail, node 5, must point at the old head, node 1. Two arrows, nothing else.

Which node becomes the new last node in general? The last k nodes move to the front, so the new last node is the one with k nodes after it. Counting positions from 0 at the head, it sits at position length - k - 1. For our list that is 5 - 2 - 1 = 2, and position 2 holds node 3, which agrees with the picture. From the head we reach it by following length - k - 1 arrows, two of them here.

A beginner usually asks a fair question at this point. Why not cut first, setting node 3's next to null, and join the ends afterwards? Let us try it and see. The moment node 3 points at null, nodes 4 and 5 can no longer be reached from the head. We could save node 4 in a variable first, and that works, but there is a tidier order that needs no extra care. Join first, then cut.

Here is that order, and it is the children again. First the last child points at the first child, so the line becomes a circle, in code tail.next = head. Nothing is lost, because every node is still reachable from every other. Then we walk from the head length - k - 1 steps to the new last node, take the node after it as the new head, and break the circle with newTail.next = null. The new head is then the start of a straight line again.

Why is this always correct? In the ring the nodes keep their original order, going round. Opening the ring just before position length - k means the line starts with positions length - k up to length - 1, which are exactly the last k nodes, followed by positions 0 up to length - k - 1, which are the rest in their old order. That is the definition of a right rotation by k.

5Watching the ring close and open on the example

The picture plays the method on 1 -> 2 -> 3 -> 4 -> 5 with k = 2. The nodes never move on the page; only the arrows change. Under the nodes, nt stands for newTail and nh for newHead. Watch for the moment the arrow from node 5 bends back to node 1, and the moment node 3's arrow is cut.

Step throughClose the ring, then cut it, on 1 -> 2 -> 3 -> 4 -> 5 with k = 2

The nodes stay in place; only arrows change. nt is newTail and nh is newHead. A back arrow is the ring, and a slash means next is null.

  1. 12345headtail
    length
    1
    k
    2

    1We start with tail on the head, node 1, and length = 1, because we have seen one node so far.

  2. 12345headtail
    length
    3
    k
    2

    2The counting loop moves tail forward twice, onto node 3, adding one to length each time.

  3. 12345headtail
    length
    5
    k
    2

    3Two more moves put tail on node 5, whose next is null, so the loop stops. The list has length 5.

  4. 12345headtail
    length
    5
    k
    2 % 5 = 2

    4Now k %= length gives 2 % 5 = 2. It is not 0, so the list really must change and we carry on.

  5. 12345headtail
    length
    5
    k
    2
    steps to take
    5 - 2 - 1 = 2

    5tail.next = head joins node 5 back to node 1. The list is now a ring, and every node can still be reached.

  6. 12345nttail
    k
    2
    i
    1
    loop while
    i < 3

    6newTail starts on the head, node 1, which is position 0. It must reach position 2.

  7. 12345nttail
    k
    2
    i
    1

    7With i = 1 the loop moves newTail one arrow forward, onto node 2.

  8. 12345nttail
    k
    2
    i
    3, loop ends

    8With i = 2 it moves onto node 3. Then i becomes 3, the test i < 3 fails, and newTail stays on node 3.

  9. 12345ntnh
    new head
    node 4
    new tail
    node 3

    9newHead = newTail.next is node 4, and newTail.next = null cuts the ring after node 3.

  10. 45123nh
    result
    4 -> 5 -> 1 -> 2 -> 3

    10Following the arrows from newHead now gives 4 -> 5 -> 1 -> 2 -> 3 and then null, which we return.

Let us read the important frames back. The first three frames are the counting walk, which gives us two things at once, the length 5 and a reference to node 5. Without that reference we could not close the ring without walking again.

In the fifth frame the arrow from node 5 bends back to node 1. For a moment the list has no end at all, which sounds alarming, but it is safe because we know exactly where we will cut it. Frames six to eight walk newTail two arrows, from position 0 to position 2. In the ninth frame node 3's arrow is cut, and the last frame redraws the same nodes in the order the arrows now give. Only two arrows changed in the whole run, node 5's and node 3's.

6The complete Java program

Here is the complete program. It has a small Node class, the rotateRight method, and two helpers: of builds a list from values and show prints one. main runs our example, the k = 4 case on a three-node list, a rotation by exactly the length, a single node with a large k, and an empty list.

Java
public class RotateList {
static class Node {
int val; Node next;
Node(int val, Node next) { this.val = val; this.next = next; }
}
// Rotate the list to the right by k places and return the new head.
static Node rotateRight(Node head, int k) {
if (head == null || head.next == null) return head;
int length = 1;
Node tail = head;
while (tail.next != null) { tail = tail.next; length++; } // find the length and the tail
k %= length; // rotating by the length changes nothing
if (k == 0) return head;
tail.next = head; // close the list into a ring
Node newTail = head;
for (int i = 1; i < length - k; i++) newTail = newTail.next; // node length - k from the start
Node newHead = newTail.next;
newTail.next = null; // cut the ring after the new tail
return newHead;
}
static Node of(int... values) {
Node head = null;
for (int i = values.length - 1; i >= 0; i--) head = new Node(values[i], head);
return head;
}
static String show(Node head) {
StringBuilder sb = new StringBuilder("[");
for (Node n = head; n != null; n = n.next) sb.append(n.val).append(n.next != null ? ", " : "");
return sb.append("]").toString();
}
public static void main(String[] args) {
System.out.println(show(rotateRight(of(1, 2, 3, 4, 5), 2))); // [4, 5, 1, 2, 3]
System.out.println(show(rotateRight(of(0, 1, 2), 4))); // [2, 0, 1]
System.out.println(show(rotateRight(of(1, 2, 3), 3))); // [1, 2, 3]
System.out.println(show(rotateRight(of(7), 100))); // [7]
System.out.println(show(rotateRight(of(), 1))); // []
}
}

Let us read rotateRight in the order it runs. The first line returns an empty list or a single node unchanged, and not only for tidiness. With an empty list, the counting loop would read head.next on null and throw an exception, and with one node every rotation gives the same list.

Next we count. length starts at 1, because head is already one node, and tail starts on head. The while loop moves tail forward while there is a next node, adding one each time, so it stops on the last node with length correct. Then k %= length throws away the full rounds that would cancel out. If k is now 0 we return head straight away, before touching any arrow.

Then tail.next = head closes the ring. newTail starts on head, and the for loop runs with i from 1 while i < length - k, which is length - k - 1 moves, exactly the number we worked out. For the example that is i = 1 and i = 2, two moves, ending on node 3. We save newTail.next as newHead before cutting, because after newTail.next = null that arrow is gone. Finally we return newHead.

The beginner's mistake to watch for here is forgetting the cut. The code would return node 4 as the head of a list that never ends, and the first program that prints it would loop forever. The second classic mistake is forgetting k %= length, which makes the walk to the new tail run off the end of the list when k is larger than the length.

For 0 -> 1 -> 2 with k = 4, the length is 3 and 4 % 3 = 1, so the new tail is node 1 at position 1 and the program prints [2, 0, 1].

7How much it costs, and the cases at the edges

Let us count on the example. The counting loop followed 4 arrows, and the walk to the new tail followed 2 more, so 6 moves in all, plus a handful of assignments. In general the count is n - 1 moves, and the second walk is fewer than n, so the time is O(n), however large k is. Compare that with 21 moves for the brute force with k = 7.

The space is O(1): four variables, length, tail, newTail and newHead, whatever the size of the list.

Comparing the approaches
ApproachTimeExtra spaceMoves on 5 nodes, k = 7
Rotate by one, k timesO(n x k)O(1)21
Rotate by one, (k mod n) timesO(n^2) worst caseO(1)6
Count, reduce k, ring and cutO(n)O(1)6

The table shows why reducing k alone is not quite enough. It rescues the brute force from huge k, but k mod n can still be close to n, and then n single-step rotations of n moves each cost about n squared. The ring and cut does one walk and one partial walk, whatever k is.

Now the edge cases. An empty list and a single node return at the first line, so rotating 7 by 100 gives [7]. When k is 0 or any multiple of the length, the modulo makes it 0 and we return the head without forming a ring. When k is length - 1, the new tail is the head itself, the for loop runs zero times, and the cut happens right after the first node. The ring is always cut before we return, so we never hand back a list that loops.

8Follow-up questions

How would you rotate to the left by k instead?

A left rotation by k moves the first k nodes to the end, and that is the same as a right rotation by length - k. So we count the list, reduce k with k mod length, and then the new tail is the node at position k - 1 instead of length - k - 1. We close the ring, walk k - 1 arrows from the head, take the next node as the new head, and cut. Everything else, including the cost, stays the same.

Can you find the cut with two pointers instead of counting the length?

Only partly. Two references set k nodes apart and moved together find the k-th node from the end in one walk, but only when k is smaller than the length, and we cannot reduce k without knowing the length. So we still count first. Once k is reduced, either way of finding the cut works, and both are O(n). Counting is simpler to explain, which helps in an interview.

What would change for a doubly linked list?

In a doubly linked list each node also has a prev reference to the node before it. The idea is the same, close the ring and cut it, but now four references change instead of two: the old tail and old head point at each other both ways, and at the cut the new tail's next and the new head's prev both become null. Forgetting the prev side is the usual mistake.

9Conclusion

We rotated the list by counting it once, reducing k with k mod length so that cancelling rounds disappear, joining the tail to the head, and cutting the ring after position length - k - 1. Only two arrows change, so it costs O(n) time and O(1) space for any k. The clue to remember is a position counted from the end of a singly linked list: count first, then find the one place to cut.

What to say in the interviewAbout 70 seconds aloud

Open with

Let me confirm the details: I rotate to the right, I rearrange the existing nodes, and k can be zero or larger than the length. Rotating one node at a time, k times, works but costs O(n times k), and every length rotations cancel out.

Then, if they want more

So first I walk the list once to get its length and keep a reference to the tail. Then I reduce k to k mod length, and if that is zero I return the head unchanged. Otherwise the last k nodes move to the front, so the new tail is the node at position length minus k minus one.

I join the tail to the head to make a ring, walk from the head that many steps to the new tail, take its next node as the new head, and set the new tail's next to null to cut the ring. Only two links change. That is O(n) time and O(1) extra space.

An empty list or a single node is returned at once, and the ring is always cut before I return, so the result never loops.

About this answer

Last updated
15 November 2026
Written for
Java 21, using only java.util
Checked
The Java solution was compiled and run, and each printed result matches the comment beside it. The pictures are checked against the format when the site is built. The explanation around the code is a study note: confirm anything critical against the documentation below. What the checks cover
Where the question comes from
Public interview write-ups, reworded by Scrivio; counted 15 times in that collection. How it is counted
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Rotate a linked list to the right by k positions.": https://scrivio-interview-library.netlify.app/data-structures/solutions/rotate-a-linked-list-to-the-right-by-k-positions-80a3a7/