Can Construct
Brute force
def can_construct_brute(
target: str,
word_bank: list[str]
) -> bool:
"""
N = len(work_bank)
M = len(target)
Time complexity: O(N^M * M)
We are removing words for the target in every iteration.
In the worst scenario, we will remove then up to M times.
And, we have N branches to explore at every iteration.
As well, in every iteration we copy and remove
some characters the target (depending on M).
Space complexity: O(M*M) = O(M²)
It will make up to M recursive calls. And for every call,
it will store the suffix
of the target.
"""
if target == "":
return True
for word in word_bank:
if word in target and target.index(word) == 0:
diff = target.removeprefix(word)
if can_construct(diff, word_bank):
return True
return FalseMemoization
Tabulation
Last updated
Was this helpful?