Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Full lesson preview

Rotate a list right by k

Rotate a singly linked list to the right by k places. Input is given as a Python list representing node values.

Python practice15 minLinked ListsIntermediateLast updated March 27, 2026

Problem statement

Given the head of a singly linked list (represented as a Python list of values) and an integer k, rotate the list to the right by k places and return the resulting list as a Python list. Rotation means moving the last k nodes to the front in the same order. You should handle cases where k is larger than the list length, k is zero, the list is empty, or the list contains one element.

Task

Implement rotation of a linked list by k positions and return the resulting list values.

Examples

Rotate [1,2,3,4,5] by 2

Input

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

Output

[4, 5, 1, 2, 3]

The last two elements [4,5] move to the front.

Input format

A Python list of integers representing the linked list values, and an integer k.

Output format

A Python list of integers representing the rotated linked list values.

Constraints

- 0 <= len(list) <= 10^4 (practical test sizes small) - k >= 0 - Values can be any integers Implement in O(n) time and O(1) extra space when operating on the linked structure.

Samples

Sample 1

Input

[0, 1, 2], 4

Output

[2, 0, 1]

k mod n = 1, so last element moves to front.