• + 0 comments

    Python Hybrid Algo Approach

    Time Complexity: O(N^2)
    Space Complexity: O(N)
    
    from collections import OrderedDict
    
    def decrement(V, val):
        ''' Decrement the value and remove if the count drops to zero.'''
        V[val] -= 1
        if V[val] == 0:
            del V[val]
    
    def del_rec(cur_i, max_i, cnt, cur_sum, S, K, V, A):
        ''' Recursive function to help adjust the sequence. '''
        if cnt == K:
            decrement(V, cur_sum)
        else:
            del_rec(cur_i, max_i, cnt+1, cur_sum + A[cur_i], S, K, V, A)
            if cur_i < max_i:
                del_rec(cur_i+1, max_i, cnt, cur_sum, S, K, V, A)
    
    T = int(input().strip())
    for _ in range(T):
        N, K = map(int, input().strip().split())
        S = sorted(map(int, input().strip().split()))
        
        # Initialize ordered dictionary to track occurrences
        V = OrderedDict()
        for x in S:
            if x not in V:
                V[x] = 1
            else:
                V[x] += 1
        
        #array A using first element division logic
        A = [S[0] // K] + [0] * (N - 1)
        decrement(V, S[0])  # Decrease the count of the first element
        
        #  subsequent elements of A
        for n in range(1, N):
            A[n] = list(V.keys())[0] - (K - 1) * A[0]
            if n < N - 1:
                del_rec(0, n, 1, A[n], S, K, V, A)
        
        print(' '.join(map(str, A)))