Skip to content

Commit d8f911f

Browse files
Merge pull request neetcode-gh#298 from niketanmoon/main
Solved TLE issue. Added removeWord function to update the Trie after …
2 parents b2736dd + 093e405 commit d8f911f

File tree

1 file changed

+37
-36
lines changed

1 file changed

+37
-36
lines changed

212-Word-Search-II.py

Lines changed: 37 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -2,64 +2,65 @@ class TrieNode:
22
def __init__(self):
33
self.children = {}
44
self.isWord = False
5-
self.refs = 0
5+
6+
class Trie:
7+
def __init__(self):
8+
self.root = TrieNode()
69

710
def addWord(self, word):
8-
cur = self
9-
cur.refs += 1
11+
current = self.root
1012
for c in word:
11-
if c not in cur.children:
12-
cur.children[c] = TrieNode()
13-
cur = cur.children[c]
14-
cur.refs += 1
15-
cur.isWord = True
13+
if c not in current.children:
14+
current.children[c] = TrieNode()
15+
current = current.children[c]
16+
current.isWord = True
1617

1718
def removeWord(self, word):
18-
cur = self
19-
cur.refs -= 1
20-
for c in word:
21-
if c in cur.children:
22-
cur = cur.children[c]
23-
cur.refs -= 1
19+
node = self.root
20+
path = [(None, node)]
21+
for char in word:
22+
node = node.children[char]
23+
path.append((char, node))
24+
node.isWord = False
2425

26+
for i in range(len(path) - 1, 0, -1):
27+
char, currNode = path[i][0], path[i][1]
28+
parentNode = path[i - 1][1]
29+
if currNode.isWord or currNode.children:
30+
break
31+
del parentNode.children[char]
2532

2633
class Solution:
2734
def findWords(self, board: List[List[str]], words: List[str]) -> List[str]:
28-
root = TrieNode()
29-
for w in words:
30-
root.addWord(w)
35+
trie = Trie()
3136

32-
ROWS, COLS = len(board), len(board[0])
33-
res, visit = set(), set()
37+
# Converting words list to a trie
38+
for word in words:
39+
trie.addWord(word)
40+
41+
rows, columns = len(board), len(board[0])
42+
result, visit = set(), set()
3443

3544
def dfs(r, c, node, word):
36-
if (
37-
r < 0
38-
or c < 0
39-
or r == ROWS
40-
or c == COLS
41-
or board[r][c] not in node.children
42-
or node.children[board[r][c]].refs < 1
43-
or (r, c) in visit
44-
):
45+
if (r < 0 or c < 0 or
46+
r == rows or c == columns or
47+
board[r][c] not in node.children or (r, c) in visit):
4548
return
4649

4750
visit.add((r, c))
4851
node = node.children[board[r][c]]
4952
word += board[r][c]
5053
if node.isWord:
51-
node.isWord = False
52-
res.add(word)
53-
root.removeWord(word)
54+
result.add(word)
55+
trie.removeWord(word)
5456

5557
dfs(r + 1, c, node, word)
5658
dfs(r - 1, c, node, word)
5759
dfs(r, c + 1, node, word)
5860
dfs(r, c - 1, node, word)
5961
visit.remove((r, c))
6062

61-
for r in range(ROWS):
62-
for c in range(COLS):
63-
dfs(r, c, root, "")
64-
65-
return list(res)
63+
for r in range(rows):
64+
for c in range(columns):
65+
dfs(r, c, trie.root, "")
66+
return list(result)

0 commit comments

Comments
 (0)