Problem 252609 · medium · Phase 02 Linear Data Structures

Rotate a List to the Right

linked list · rotation · modulo

Given the head of a singly linked list and a non-negative integer k, rotate the list to the right by k places: the last node moves to the front, k times. Return the head. Note that k may be much larger than the length of the list.

Examples

Input:  head = 1 -> 2 -> 3 -> 4 -> 5, k = 2
Output: 4 -> 5 -> 1 -> 2 -> 3

Input:  head = 0 -> 1 -> 2, k = 4
Output: 2 -> 0 -> 1

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…