Last active
December 7, 2019 15:27
-
-
Save rishi93/47bebedd0455b47dd83019d3ff7a4e8d to your computer and use it in GitHub Desktop.
Daily Coding Problem - 11
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| """ | |
| This problem was asked by Twitter. | |
| Implement an autocomplete system. That is, given a query string s and a set of all possible query strings, return all strings in the set that have s as a prefix. | |
| For example, given the query string de and the set of strings [dog, deer, deal], return [deer, deal]. | |
| Hint: Try preprocessing the dictionary into a more efficient data structure to speed up queries. | |
| """ | |
| class Node: | |
| def __init__(self): | |
| self.children = [None]*26 | |
| self.isEnd = False | |
| class Trie: | |
| def __init__(self): | |
| self.root = Node() | |
| def addWord(self, word): | |
| curr = self.root | |
| for letter in word: | |
| index = ord(letter) - ord('a') | |
| if curr.children[index] is None: | |
| curr.children[index] = Node() | |
| curr = curr.children[index] | |
| curr.isEndOfWord = True | |
| def search(self, word): | |
| curr = self.root | |
| for letter in word: | |
| index = ord(letter) - ord('a') | |
| if curr.children[index] is None: | |
| return False | |
| curr = curr.children[index] | |
| if curr.isEndOfWord: | |
| return True | |
| else: | |
| return False | |
| words = ["deer", "dear", "deal", "deep", "dead", "dean"] | |
| trie = Trie() | |
| for word in words: | |
| trie.addWord(word) | |
| print(trie.search("deal")) | |
| print(trie.search("deat")) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment