I have a function that builds substrings given a string recursively. Could anyone please tell me what’s the complexity of this? I’m guessing it’s O(2*n), because given an input of n, there can be 2*n substrings, but i’m not 100% sure.
Here’s the code:
def build_substrings(string):
""" Returns all subsets that can be formed with letters in string. """
result = []
if len(string) == 1:
result.append(string)
else:
for substring in build_substrings(string[:-1]):
result.append(substring)
substring = substring + string[-1]
result.append(substring)
result.append(string[-1])
return result
I actually have on more question that i think doesn’t deserve a new topic. I was wondering what’s the complexity of searching a key in a dictionary in Python(if item in dictionary)?
Thank you alot for your help!
If N is the length of string.Number of substring of length >=1<=N is (N * N+1)/2.
So time Complexity would be O(N**2)
The python dict is a hashmap, its worst case is therefore O(n) if the hash function is bad and results in a lot of collisions. However that is a very rare case where every item added has the same hash and so is added to the same chain which for a major Python implementation would be extremely unlikely. The average time complexity is of course O(1).