Python: really short and clean solution


  • 0
    A

    base_block_length - is a shortest length of nested arrays, based on n div k. For example, for a queue of length 7 and k = 3, our minimum length will be 2, because 7 div 3 == 2

    long_block_idx - is an index + 1 of last nested array with a length base_block_length + 1 (In our example it's 3 = 2 + 1). And it is calculated as n mod k. In our previous example it is 1, because 7 mod 3 == 1. Since it is an index + 1, our last longest block index is 1 - 1 = 0. Please note: because of the implementation we operate with index + 1 instead of index

    Back to our example: first nested array has 3 elements and the rest ones have 2. k = 3 => [[X X X], [X X], [X X]]

    class Solution(object):
        def splitListToParts(self, root, k):
            result = []
    
            n = 0
            cur = root
            while cur:
                n += 1
                cur = cur.next
    
            cur = root
            base_block_length, long_block_idx = divmod(n, k)
    
            for block_idx in range(0, k):
                block = []
    
                for i in range(0, base_block_length + int(block_idx < long_block_idx)):
                    block.append(cur.val)
                    cur = cur.next
    
                result.append(block)
    
            return result
    

Log in to reply
 

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