Problem statement

https://binarysearch.com/problems/Rotate-Linked-List-by-K/

Solution

Equal to leetcode 0061. Rotate List

Complexity

O(n) for time and O(1) for space.

Code

class Solution:
    def solve(self, head, k):
        if not head or not head.next: return head
        
        last, n = head, 1
        while last.next:
            last = last.next
            n += 1
            
        if k % n == 0: return head
        
        middle = head
        for i in range(n - k%n-1):
            middle = middle.next
            
        new_head = middle.next
        last.next = head
        middle.next = None
        return new_head