Currently fastest Python code

  • 1

    This spins through the list once to get the length, then a second time to find the cut point. That saves lots of iterations through the list for rotation values larger than the length of the list.

    class Solution(object):
        def rotateRight(self, head, k):
            :type head: ListNode
            :type k: int
            :rtype: ListNode
            if k == 0 or not head:
                return head
            len = 0
            n = lastNode = head
            while n:
                len += 1
                lastNode = n
                n =
            if k % len == 0:
                return head
            newHead = newTail = head
            for i in range((len - k) % len):
                newTail = newHead
                newHead =
   = head
   = None
            return newHead

  • 0

    Can you tell me what's your runtime? I copy your code and submit, the result is 62ms, beat 38%.

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.