44 - k = number of words in wordDict
55 - m = average word length in wordDict
66
7- At each index in s, we may check every word in wordDict and for each, compare up to m characters.
7+ At each index in s, we may check every word in wordDict, and for each, compare up to m characters.
88
99Space Complexity: O(n)
1010 - n = len(s), due to recursion stack and memoization table (one entry per possible starting index).
@@ -69,3 +69,76 @@ def wordBreak(self, s: str, wordDict: List[str]) -> bool:
6969 dp [index ] = dp [index - W ]
7070
7171 return bool (dp [- 1 ])
72+
73+ """
74+ Time Complexity: O(n * k * m)
75+ - n = len(s)
76+ - k = number of words in wordDict
77+ - m = average word length in wordDict
78+
79+ For every index in s, we consider each word in wordDict and, for each, match up to m characters.
80+
81+ Space Complexity: O(n)
82+ - n = len(s), required for the dp array.
83+
84+ - Uses a trie to store the words in wordDict.
85+ - Returns a list of ending indices of the words that match the prefix (i.e., all indices where a word ends if we start matching from the given index).
86+ """
87+ class Trie :
88+ def __init__ (self ):
89+ self .children = dict ()
90+ self .end = False
91+
92+ def insert (self , target : int ):
93+ node = self
94+
95+ for ch in target :
96+ if ch not in node .children :
97+ node .children [ch ] = Trie ()
98+ node = node .children [ch ]
99+
100+ node .end = True
101+
102+ def startsWith (self , target : str , start : int ) -> List [int ]:
103+ ans = []
104+ node = self
105+
106+ for i in range (start , len (target )):
107+ ch = target [i ]
108+
109+ if ch not in node .children :
110+ return ans
111+
112+ node = node .children [ch ]
113+ if node .end :
114+ ans .append (i + 1 )
115+
116+ return ans
117+
118+
119+ class Solution :
120+ def wordBreak (self , s : str , wordDict : List [str ]) -> bool :
121+ S = len (s )
122+ t = Trie ()
123+ visited = [False ] * (S + 1 )
124+
125+ for word in wordDict :
126+ t .insert (word )
127+
128+ stack = [0 ]
129+
130+ while stack :
131+ start = stack .pop ()
132+
133+ starts_with = t .startsWith (s , start )
134+
135+ for start_index in starts_with :
136+ if start_index == S :
137+ return True
138+ if visited [start_index ]:
139+ continue
140+ visited [start_index ] = True
141+ stack .append (start_index )
142+
143+ return False
144+
0 commit comments