Python o(n) time o(1) space recursive solution


  • 0
    C
    class Solution:
        def reverseKGroup(self, head, k):
            length = 0
            current = head
            while current:
                length += 1
                current = current.next
            if k>length: return head
            current = head
            prev = None
            count = 1
            while count <= k:
                nextCurrent = current.next
                if prev: current.next = prev
                prev = current
                current = nextCurrent
                count += 1
            head.next = self.reverseKGroup(current, k)
            return prev

  • 0
    M

    This is not O(n) because every time you call this method, you scan the list to get the length once.


  • 0
    Z

    It is not O(1) space because it is recursion


Log in to reply
 

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