Short Python O(n) time and O(1) space

  • 0

    First find n which represent total number of nodes, then do n//k times reverse processes. Remember to re-initialize pre and p before the next reverse process.

    class Solution(object):
        def reverseKGroup(self, head, k):
            :type head: ListNode
            :type k: int
            :rtype: ListNode
            dummy = p = ListNode(0)
   = head
            n = 0
            while                   # find how many nodes we have in total
                p =
                n += 1
            pre, p = dummy,
            for j in range(n//k):           # we need n//k times reverse processes
                for i in range(k-1):
          ,, =,,
                pre, p = p,          # set new "pre" and "p" node

Log in to reply

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