Hey @Dian_Us_Suqlain,
Yay! Here’s an approach for Word Break I:
class TrieNode:
def __init__(self):
self.children = {}
self.end_of_word = False
def insert_to_trie(word, root):
current = root
for letter in word:
current = current.children.setdefault(letter, TrieNode())
current.end_of_word = True
def build_trie(words):
root = TrieNode()
for word in words:
insert_to_trie(word, root)
return root
def search_in_trie(node, s, index, dp):
current = node
for i in range(index, len(s)):
if s[i] not in current.children:
return False
current = current.children[s[i]]
if current.end_of_word:
dp[i+1] = True
def word_break(s, word_dict):
root = build_trie(word_dict)
dp = [False] * (len(s) + 1)
dp[0] = True
for i in range(len(s)):
if dp[i]:
search_in_trie(root, s, i, dp):
return dp[-1]
Time: O(nk), where k is the length of the longest word in the dictionary
Space: O(n+w), where w is the total number of characters in the dictionary