Short recursive python solution

  • 0
        def reverseKGroup(self, head, k):
            :type head: ListNode
            :type k: int
            :rtype: ListNode
            def reverseInGroup(curr, k, length):
                #if remaining list is lesser than K, return as is without reversing this remaining group
                if length < k:
                    return curr
                tail = curr
                count = 0
                prev = None
                while count < k and curr:
                    count += 1
                    temp =
           = prev
                    prev = curr
                    curr = temp
                groupHead = prev
                if curr: = reverseInGroup(curr, k, length-k)
                return groupHead
            if not head:
            length, curr = 0, head
            while curr:
                length += 1
                curr =
            return reverseInGroup(head, k, length)```

Log in to reply

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