Ruby O(1) Space and O(n) Time recursive solution


  • 0
    S
    def reverse_k_group(head, k)
        return head unless head
        tail = head
        k.times do |i|
            if tail.next || i == k - 1
                tail = tail.next
            else
                return head
            end
        end
        pre = reverse_k_group(tail, k)
        current = head
        k.times do
            tmp = current.next
            current.next = pre
            pre = current
            current = tmp
        end
        pre
    end
    

  • -1

    Recursive is never O(1) space. It should be called" O(1) space without considering recursive method stack"


Log in to reply
 

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