Problem
Given thehead of a linked list, rotate the list to the right by k places.
Examples
Constraints
- The number of nodes in the list is in the range [0, 500].
- -100 <= Node.val <= 100
- 0 <= k <= 2 * 10^9
Documentation Index
Fetch the complete documentation index at: /llms.txt
Use this file to discover all available pages before exploring further.
Tested Python solution for LeetCode 61 with 17 pytest cases. Generate a practice environment with lcpy.
lcpy gen -n 61 # by problem number
lcpy gen -s rotate_list # by problem name
head of a linked list, rotate the list to the right by k places.
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]
from leetcode_py import ListNode
class Solution:
# Time: O(n) — single pass to close ring then cut
# Space: O(1)
def rotate_right(self, head: ListNode[int] | None, k: int) -> ListNode[int] | None:
if not head or not head.next or k == 0:
return head
# Count length and close the list into a ring
tail = head
length = 1
while tail.next:
tail = tail.next
length += 1
tail.next = head
# Effective rotations; new tail is at (length - k % length) steps from head
k %= length
steps_to_new_tail = length - k
new_tail = head
for _ in range(steps_to_new_tail - 1):
assert new_tail.next is not None
new_tail = new_tail.next
assert new_tail.next is not None
new_head = new_tail.next
new_tail.next = None
return new_head
| Time | Space |
|---|---|
| O(n) — single pass to close ring then cut | O(1) |