Rotate List
Medium
Topics
Given the head of a linked list, rotate the list to the right by k places and return the new head.
Example 1
before
after
Rotating right by 2 moves the shaded tail to the front. Since
k can far exceed the length, the real shift is k % 5 = 2 — taking k literally is the usual timeout.Linked list values from head to tail.
Input: head = [1,2,3,4,5], k = 2 Output: [4,5,1,2,3]
Example 2
before
after
Input: head = [0,1,2], k = 4 Output: [2,0,1]
Constraints
- 0 <= number of nodes <= 500
- -100 <= Node.val <= 100
- 0 <= k <= 2*10^9
Editorial — intuition, approach, complexity and pitfalls
Intuition
Rotating right by k moves the last k nodes to the front, so the new head is at index n - k and the new tail is just before it. No node needs to move; two pointer writes do the whole job.
Two details carry the problem. k reaches 2×10⁹ while the list holds at most 500 nodes, so k must be reduced modulo n before anything else — otherwise you walk two billion steps. And closing the list into a ring first means the cut is a single operation instead of a splice.
Approach
- Walk to the tail, counting the nodes to get
n. - Reduce
kmodulon; if it is zero the list is unchanged. - Join the tail to the head, forming a ring.
- Walk
n - k - 1steps from the head to reach the new tail. - Take its successor as the new head and cut the ring there.
Dry Run
input 1 -> 2 -> 3 -> 4 -> 5 k = 2
n = 5, k % n = 2, new head is at index n - k = 3
close the ring 1 -> 2 -> 3 -> 4 -> 5 -+
^----------------------+
walk to index 2 new tail = node 3
cut after it new head = node 4
answer 4 -> 5 -> 1 -> 2 -> 3
[0,1,2] k = 4 -> 2 -> 0 -> 1 k % 3 = 1
[1,2] k = 2000000000 -> 1 -> 2 k % 2 = 0, untouched
[] k = 5 -> empty
[1] k = 99 -> 1Complexity
- Time — O(n): one pass to measure and one partial pass to the cut point.
- Space — O(1).
Common Pitfalls
- Rotating one position at a time,
ktimes. Withkup to 2×10⁹ that never finishes; the modulus is not an optimisation, it is the difference between terminating and not. - Taking the modulus before counting the nodes, which needs
nand so cannot work. - Dividing by
nwithout handling the empty list. The early return for a null or single-node head is what keeps the modulus safe. - Cutting at
n - ksteps instead ofn - k - 1. The walk has to stop on the new tail, not on the new head. - Leaving the ring closed. Forgetting the final
new_tail.next = Nonereturns a circular list, and anything that traverses it runs forever. - Rotating left instead of right. Rotating right by
kis rotating left byn - k; mixing them up passes the symmetric cases and fails the rest.
Full Solution — all languages
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def rotateRight(self, head, k):
if not head or not head.next:
return head
n = 1
tail = head
while tail.next:
tail = tail.next
n += 1
k %= n
if k == 0:
return head
tail.next = head
steps = n - k
new_tail = head
for _ in range(steps - 1):
new_tail = new_tail.next
new_head = new_tail.next
new_tail.next = None
return new_headimport java.util.*;
class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
}
}
class Solution {
public ListNode rotateRight(ListNode head, int k) {
if (head == null || head.next == null) return head;
int n = 1;
ListNode tail = head;
while (tail.next != null) {
tail = tail.next;
n++;
}
k %= n;
if (k == 0) return head;
tail.next = head;
int steps = n - k;
ListNode newTail = head;
for (int i = 0; i < steps - 1; i++) newTail = newTail.next;
ListNode newHead = newTail.next;
newTail.next = null;
return newHead;
}
}#include <bits/stdc++.h>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode(int x): val(x), next(nullptr) {
}
};
class Solution {
public: ListNode* rotateRight(ListNode* head, int k) {
if (!head || !head->next) return head;
int n = 1;
ListNode* tail = head;
while (tail->next) {
tail = tail->next;
n++;
}
k %= n;
if (k == 0) return head;
tail->next = head;
int steps = n - k;
ListNode* newTail = head;
for (int i = 0; i < steps - 1; i++) newTail = newTail->next;
ListNode* newHead = newTail->next;
newTail->next = nullptr;
return newHead;
}
};/** Node shape: { val, next }. Build/return plain objects or use this ctor. */ function ListNode(val, next) {
this.val = (val === undefined ? 0 : val);
this.next = (next === undefined ? null : next);
}
/**
* @param {ListNode} head
* @param {number} k
* @return {ListNode}
*/ var rotateRight = function(head, k) {
if (!head || !head.next) return head;
let n = 1, tail = head;
while (tail.next) {
tail = tail.next;
n++;
}
k %= n;
if (k === 0) return head;
tail.next = head;
const steps = n - k;
let newTail = head;
for (let i = 0; i < steps - 1; i++) newTail = newTail.next;
const newHead = newTail.next;
newTail.next = null;
return newHead;
};
Asked at
Nvidia