Problem 252609 · medium · Level 02 Linear Data Structures

Turning the Carousel

linked list · rotation · modulo

The horses of a carousel are kept as a singly linked list, starting with the horse at the gate. Each click of the motor turns the ride by one place, so the last horse in the list arrives at the gate and becomes the new first one. Given the head and a non-negative number of clicks k, return the head after all k clicks. k can be far larger than the number of horses.

Examples

Input:  head = 8 -> 6 -> 7 -> 5 -> 3 -> 0, k = 2
Output: 3 -> 0 -> 8 -> 6 -> 7 -> 5

Input:  head = 4 -> 9 -> 2, k = 5
Output: 9 -> 2 -> 4
Explanation: rotating 3 nodes by 3 changes nothing, so k = 5 acts like k = 2.

Constraints

  • 0 <= number of nodes <= 10**4
  • 0 <= k <= 10**9
  • Target: O(n) time, O(1) extra space; do not rotate one step at a time

Goals

  • Reduce a large shift with the modulo operator
  • Close the list into a ring and reopen it at the right spot
Starting Python…