pythonalgorithmtime-complexitycode-complexity

Leetcode 78 - Generate power set time complexity


Leetcode 78 question potential solution:

class Solution(object):
    def __init__(self):
        self.map = {}
    
    def helper(self, count, nums, vals, result):       
        
        if count == 0:
            result += [vals]        
            
        for i in range(len(nums)):
            self.helper(count - 1, nums[i+1:], vals + [nums[i]], result)
        
    
    def subsets(self, nums):
        result = []
        result.append([])
        
        for count in range(1,len(nums)+1):
            self.helper(count, nums, [], result)   
            
        return result

For the above solution, will the time complexity be O(2^n) or will it be O(n * 2^n) ?


Solution

  • One can find out the complexity by looking for different N how many times is the helper function called, code-wise would look like the following:

    class Solution(object):
    
        def __init__(self):
            self.map = {}
            self.counter = 0
    
        def helper(self, count, nums, vals, result):
            self.counter += 1
            if count == 0:
                result += [vals]
    
            for i in range(len(nums)):
                self.helper(count - 1, nums[i + 1:], vals + [nums[i]], result)
    
        def subsets(self, nums):
            result = [[]]
    
            for count in range(1, len(nums) + 1):
                self.helper(count, nums, [], result)
    
            return self.counter
    

    So for:

    N Time the helper function gets called
    1 2
    2 8
    3 24
    4 64
    5 160
    6 384
    7 896
    8 2048
    9 4608
    10 10240
    ... ....
    N O(n * 2^n)

    The helper function has a complexity of O(2^n) and since you called for each element of the list nums:

    for count in range(1,len(nums)+1):
        self.helper(count, nums, [], result)  
    

    the overall time complexity is O(n * 2^n)