Skip to content

Commit d1f33da

Browse files
Merge pull request #238 from Vijayaa21/main
Create Design Add and Search Words Data Structure.py
2 parents 1ef7fc2 + 00f739a commit d1f33da

File tree

1 file changed

+102
-0
lines changed

1 file changed

+102
-0
lines changed
Lines changed: 102 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,102 @@
1+
"""
2+
Data Structure: Word Dictionary (Trie with Wildcard Search)
3+
4+
Description:
5+
This data structure allows adding words and searching for them efficiently,
6+
including support for the wildcard character '.' which matches any letter.
7+
8+
Use Case:
9+
Useful in applications like autocomplete, spell-checkers, and word games
10+
where prefix and pattern-based searches are required.
11+
12+
Time Complexity:
13+
- addWord(word): O(L), where L = length of the word
14+
- search(word): O(L * 26) in the worst case (when '.' is used frequently)
15+
Average case is close to O(L).
16+
17+
Space Complexity:
18+
O(N * L), where N = number of words and L = average word length.
19+
"""
20+
21+
class TrieNode:
22+
"""Represents a single node in the Trie."""
23+
def __init__(self):
24+
self.children = {}
25+
self.is_word = False
26+
27+
28+
class WordDictionary:
29+
"""
30+
Implements a Trie-based word dictionary with wildcard search support.
31+
32+
Methods:
33+
addWord(word): Insert a word into the dictionary.
34+
search(word): Search for a word, supporting '.' as a wildcard.
35+
"""
36+
def __init__(self):
37+
self.root = TrieNode()
38+
39+
def addWord(self, word: str) -> None:
40+
"""
41+
Insert a word into the trie.
42+
43+
Args:
44+
word (str): Word to be added.
45+
"""
46+
node = self.root
47+
for ch in word:
48+
if ch not in node.children:
49+
node.children[ch] = TrieNode()
50+
node = node.children[ch]
51+
node.is_word = True
52+
53+
def search(self, word: str) -> bool:
54+
"""
55+
Search for a word in the trie (supports '.' as a wildcard).
56+
57+
Args:
58+
word (str): Word or pattern to search.
59+
60+
Returns:
61+
bool: True if the word exists in the trie, otherwise False.
62+
"""
63+
return self._dfs(self.root, word, 0)
64+
65+
def _dfs(self, node: TrieNode, word: str, index: int) -> bool:
66+
"""Helper DFS method to handle wildcard searches."""
67+
if index == len(word):
68+
return node.is_word
69+
70+
ch = word[index]
71+
72+
# Wildcard case
73+
if ch == ".":
74+
for child in node.children.values():
75+
if self._dfs(child, word, index + 1):
76+
return True
77+
return False
78+
79+
# Exact match case
80+
if ch in node.children:
81+
return self._dfs(node.children[ch], word, index + 1)
82+
83+
return False
84+
85+
86+
def main():
87+
"""Test the WordDictionary implementation with examples."""
88+
wd = WordDictionary()
89+
90+
# Test case 1: Adding and searching words
91+
wd.addWord("bad")
92+
wd.addWord("dad")
93+
wd.addWord("mad")
94+
95+
print(wd.search("pad")) # False (not in dictionary)
96+
print(wd.search("bad")) # True
97+
print(wd.search(".ad")) # True (wildcard match)
98+
print(wd.search("b..")) # True (wildcard match for "bad")
99+
100+
101+
if __name__ == "__main__":
102+
main()

0 commit comments

Comments
 (0)