oneby7

Linked Lists Reversing and rewiring

301. Rotate List

Medium

You are given head, the first node of a singly linked list, and an integer k. Rotate the list to the right by k places, and return the head of the rotated list.

Rotating to the right by one place moves the last node to the front, so 1 → 2 → 3 becomes 3 → 1 → 2. Rotating by k places does that k times.

The examples write a list as its values from the head on, so head = [4,1,6] is the list 4 → 1 → 6. The output shows the list you return the same way. An empty list is null, which shows as [].

Example 1

head
38164
output
64381

Input: head = [3, 8, 1, 6, 4], k = 2

Output: [6,4,3,8,1]

Explanation: Rotating by one place moves 4 to the front, which gives 4 → 3 → 8 → 1 → 6. The second place moves 6 to the front.

Example 2

5-27
head
75-2
output

Input: head = [5, -2, 7], k = 4

Output: [7,5,-2]

Explanation: One place gives [7,5,-2], two give [-2,7,5], three give [5,-2,7], and four give [7,5,-2].

Example 3

Input: head = [], k = 6

Output: []

Explanation: An empty list has no nodes to move, so the answer is the empty list.

Check your understanding

Work out the answer for this input before you write any code.

head = [2, 9, 4, 7, 5, 1], k = 4

Constraints

  • 0 ≤ number of nodes ≤ 105
  • -109 ≤ Node.val ≤ 109
  • 0 ≤ k ≤ 2 × 109

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.