Rotate List

Medium#61n apart

You get the head of a linked list and a number k. Turn the list to the right k times: each turn moves the last node to the front. Return the new head. Our example: 3 → 8 → 1 → 6 → 4, k = 7 — the answer is 6 → 4 → 3 → 8 → 1.

input
head: the head of a linked list, maybe empty; k: by how many places to rotate it right.
returns
The head of the list rotated right by k: at each place, its last node moves to the front.
constraints
  • 0 ≤ nodes ≤ 500
  • −100 ≤ Node.val ≤ 100
  • 0 ≤ k ≤ 2 · 10⁹
our 13 tests keep to them
examples
Open a test in the tests panel: it shows the input and the expected answer.
/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */
/**
 * @param {ListNode} head
 * @param {number} k
 * @return {ListNode}
 */
function rotateRight(head, k) {

}
Ctrl ↵
format
reset

saved in this browser

13 tests · limit 3 s

Stuck?

See the solution run step by step on our example, then why it works and its complexity.

Watch the walkthrough →

Next: more fast and slow pointers problems

Pattern “Fast and slow pointers” →

The problem and its statement belong to LeetCode. Here are our own retelling, example and solution. Patterns Hero is not affiliated with LeetCode.