Given the head of a linked list, rotate the list to the right by k places.
Given the list: 1->2->3->4->5, and k = 2, the list becomes 4->5->1->2->3.
k is zero?
k is greater than the length of the list?
k is greater than the length of the list, then k should effectively be k % n where n is the length of the list.rotate meaning that we move the last k elements to the front?
k elements should be moved to the front.To rotate the list:
k:
k such that 0 <= k < length (i.e., k = k % length).k = 0 after normalization, no rotation is needed.class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def rotateRight(head: ListNode, k: int) -> ListNode:
if not head or not head.next or k == 0:
return head
# Determine the length of the list
length = 1
current = head
while current.next:
current = current.next
length += 1
# Connect the tail to the head to make it circular
current.next = head
# Compute the effective rotations needed
k = k % length
steps_to_new_head = length - k
# Find the new head and the new tail
new_tail = head
for _ in range(steps_to_new_head - 1):
new_tail = new_tail.next
new_head = new_tail.next
new_tail.next = None
return new_head
Thus, the time complexity is O(n).
k % length to handle cases where k is larger than the list length.Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?