Algorithm
Rotate List
Solution
class Solution:
def rotateRight(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:
if not head or not head.next or k == 0: return head
length, tail = 1, head
while tail.next:
tail = tail.next
length += 1
k = k % length
if k == 0: return head
tail.next = head
steps_to_new_tail = length - k
new_tail = head
for _ in range(steps_to_new_tail - 1):
new_tail = new_tail.next
new_head = new_tail.next
new_tail.next = None
return new_headVideo GuideLeetcode Daily
Time Complexity
O(N)
Space Complexity
O(1)
