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
        
        # 1. Find length and original tail
        last = head
        length = 1
        while last.next:
            last = last.next
            length += 1
            
        # 2. Adjust k
        k = k % length
        if k == 0:
            return head
            
        # 3. Make circular and find new split
        last.next = head
        steps_to_new_tail = length - k
        new_tail = head
        for _ in range(steps_to_new_tail - 1):
            new_tail = new_tail.next
            
        # 4. Break the circle
        new_head = new_tail.next
        new_tail.next = None
        
        return new_head

Time Complexity

O(N)

Space Complexity

O(1)