325. Spin the Chain

A carousel of lanterns is wired as a chain: each lantern stores a brightness number and a link to the lantern after it, and head is the first one. At the end of the night the operator spins the carousel so that the last k lanterns, one step at a time, jump from the back of the line to the front.

Return the head of the chain after it has been spun to the right by k places. Spinning by one place moves the last lantern to the front. The value of k may be far larger than the chain length, so a full turn changes nothing, and an empty chain stays empty. Aim for a single linear pass over the chain rather than k separate spins.

Example 1

Input:
head = [8,6,4,2,0], k = 2
Output:
[2,0,8,6,4]
Explanation:

The last two lanterns, 2 and 0, move to the front in their original order: 2, 0, 8, 6, 4.

Example 2

Input:
head = [31,41,59], k = 4
Output:
[59,31,41]
Explanation:

Four places on a chain of three equals one place, so 59 jumps to the front: 59, 31, 41.

Constraints

0 ≤ chain length ≤ 105
-1000 ≤ node value ≤ 1000
0 ≤ k ≤ 109

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Time per case
Python 1,600 msC++ 400 msJava 800 msJavaScript 800 msTypeScript 800 ms

Expected complexity

Time
O(n)
Space
O(1)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…