Skip to the code
cf.
+25 XP

#229 Rotate a Slide Deck

medium

A presentation app stores its slides in a linked list. The "rotate right" button takes the last slide and puts it at the front. Pressing it k times in a row should be instant, even when k is huge.

Write rotateDeck(head, k) that returns the head of the list after rotating it right k times. An empty list stays empty.

Example 1

Input: head = [1,2,3,4,5], k = 2
Output: [4,5,1,2,3]

After one rotation: 5, 1, 2, 3, 4. After two: 4, 5, 1, 2, 3.

Example 2

Input: head = [0,1,2], k = 4
Output: [2,0,1]

Rotating a 3-slide deck 3 times changes nothing, so 4 rotations equal 1.

Constraints

  • The list has 0 to 500 nodes.
  • -100 <= node.val <= 100
  • 0 <= k <= 2 * 10^9

Lists are written as arrays here, like [1, 2, 3]. Your function works with ListNode objects, each with val and next.

Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).