I am preparing for some coding interviews and came up with a solution to the following problem:
"Find longest word that can be made of other words in a list of words".
I have a hard time figuring out the time complexity of my algorithm. It would be great, if you can help me to figure out the time complexity of the following code.
It is more than n²
(n⋅log n
for sorting, number_of_words ⋅ word_length + recursion
), but not sure how to calculate the exact complexity due to recursion part.
def valid_pair(a,b, words):
return a in words and b in words
def valid_word(word, words):
for i in range(len(word)):
left, right = word[:i], word[i:]
valid = valid_pair(left, right, words)
if valid:
return valid
elif left in words:
return valid_word(right, words)
return False
words = ["cde","abcde","bcd","c","d","e","a"]
words = sorted(words, key = len, reverse = True)
for w in words:
if valid_word(w, words):
print w
break