File tree Expand file tree Collapse file tree 2 files changed +72
-0
lines changed
implement-trie-prefix-tree Expand file tree Collapse file tree 2 files changed +72
-0
lines changed Original file line number Diff line number Diff line change 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)
Original file line number Diff line number Diff line change 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)
You can’t perform that action at this time.
0 commit comments