Skip to content

Commit 42c3949

Browse files
committed
add solution: word-break
1 parent 1f96e6f commit 42c3949

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed

word-break/dusunax.py

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
'''
2+
# 139. Word Break
3+
4+
use dynamic programming to check if the string is segmentable.
5+
6+
> **use dp to avoid redundant computations:**
7+
> backtracking approach will check all possible combinations of words recursively, which has time complexity of O(2^n))
8+
9+
## Time and Space Complexity
10+
11+
```
12+
TC: O(n^2)
13+
SC: O(n)
14+
```
15+
16+
#### TC is O(n^2):
17+
- nested loops for checking if the string is segmentable. = O(n^2)
18+
- outer loop: iterate each char index from the start to the end. = O(n)
19+
- inner loop: for each index in the outer loop, checks substrings within the range of valid words in wordDict. = worst case, O(n)
20+
21+
#### SC is O(n):
22+
- using a dp array to store whether index i is segmentable. = O(n)
23+
'''
24+
class Solution:
25+
def wordBreak(self, s: str, wordDict: List[str]) -> bool:
26+
word_set = set(wordDict)
27+
n = len(s)
28+
29+
segment_dp = [False] * (n + 1) # SC: O(n)
30+
segment_dp[0] = True # Base case: an empty string is segmentable
31+
32+
for end in range(1, n + 1): # TC: O(n^2)
33+
for start in range(end):
34+
if segment_dp[start] and s[start:end] in word_set:
35+
segment_dp[end] = True
36+
break
37+
38+
return segment_dp[n]

0 commit comments

Comments
 (0)