MediumPro challengePythonJavaScriptTypeScript
Linked List — Rotate List
Data StructuresLinked List
solve(values, k) builds a singly linked list and rotates it to the right by k
places: the last k nodes move to the front. k can be larger than the list. Return the
resulting values.
Do not rotate one step at a time k times. Find the length n (and the tail) in one pass,
reduce k to k % n, link the tail to the head to make a ring, walk n - k nodes
from the head to find the new tail, and cut the ring right after it.
Examples
solve([1,2,3,4,5], 2) → [4,5,1,2,3]
solve([0,1,2], 4) → [2,0,1] // 4 % 3 = 1
solve([1,2], 0) → [1,2]Sample tests
Test #1Rotate by 2
Input: [[1,2,3,4,5],2]
Output: [4,5,1,2,3]
Test #2k larger than the length
Input: [[0,1,2],4]
Output: [2,0,1]
Test #3k = 0
Input: [[1,2],0]
Output: [1,2]