Skip to content

Commit dde3d5d

Browse files
committed
[Leo] 8th Week solutions (last 2 Qs)
1 parent 90e488d commit dde3d5d

File tree

2 files changed

+72
-0
lines changed

2 files changed

+72
-0
lines changed

implement-trie-prefix-tree/Leo.py

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
class TrieNode:
2+
def __init__(self):
3+
self.children = {}
4+
self.isEnd = False
5+
6+
7+
class Trie:
8+
def __init__(self):
9+
self.root = TrieNode()
10+
11+
def insert(self, word: str) -> None:
12+
cur = self.root
13+
14+
for c in word:
15+
if c not in cur.children:
16+
cur.children[c] = TrieNode()
17+
cur = cur.children[c]
18+
cur.isEnd = True
19+
20+
## TC: O(len(word)), SC: O(len(word))
21+
22+
def search(self, word: str) -> bool:
23+
cur = self.root
24+
25+
for c in word:
26+
if c not in cur.children:
27+
return False
28+
cur = cur.children[c]
29+
return cur.isEnd
30+
31+
## TC: O(len(word)), SC: O(1)
32+
33+
def startsWith(self, prefix: str) -> bool:
34+
cur = self.root
35+
36+
for c in prefix:
37+
if c not in cur.children:
38+
return False
39+
cur = cur.children[c]
40+
return True
41+
42+
## TC: O(len(prefix)). SC: O(1)

word-search/Leo.py

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
class Solution:
2+
def exist(self, board: List[List[str]], word: str) -> bool:
3+
rows, cols = len(board), len(board[0])
4+
5+
def backtrack(r, c, index):
6+
if index == len(word):
7+
return True
8+
if r < 0 or r >= rows or c < 0 or c >= cols or board[r][c] != word[index]:
9+
return False
10+
11+
temp = board[r][c]
12+
board[r][c] = "!"
13+
14+
found = (backtrack(r + 1, c, index + 1) or
15+
backtrack(r - 1, c, index + 1) or
16+
backtrack(r, c + 1, index + 1) or
17+
backtrack(r, c - 1, index + 1))
18+
19+
board[r][c] = temp
20+
return found
21+
22+
for i in range(rows):
23+
for j in range(cols):
24+
if backtrack(i, j, 0):
25+
return True
26+
27+
return False
28+
29+
## TC: O(D of row * D of Cols * 4^L), but amortised could be O(DoR * DoC)
30+
## SC: O(L)

0 commit comments

Comments
 (0)