Can someone please help me with the time and space complexity of this code snippet? Please refer to the leetcode question- Word break ii.Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, add spaces in s to construct a sentence where each word is a valid dictionary word. Return all such possible sentences.
def wordBreak(self, s, wordDict):
dp = {}
def word_break(s):
if s in dp:
return dp[s]
result = []
for w in wordDict:
if s[:len(w)] == w:
if len(w) == len(s):
result.append(w)
else:
tmp = word_break(s[len(w):])
for t in tmp:
result.append(w + " " + t)
dp[s] = result
return result
return word_break(s)
For time complexity analysis, almost always we'd take the worst case scenario into account.
I guess
O(N ^ 3)
runtime andO(N)
memory would be right.Here is a breakdown:
Therefore,
O(N ^ 2)
of the second block is multiplied byO(N)
of calling theword_break(s)
which would eventually make itO(N ^ 3)
.We can a bit simplify it to:
which would make it easier to see:
for i in range(len(s)):
is an order of N;for word in words:
is an order of N;if word == s[k + 1:i + 1] and (dp[k] or k == -1):
is an order of N;