Trie Flashcards

1
Q
  1. Implement Trie (Prefix Tree)
    Solved
    Medium
    Topics
    Companies

A trie (pronounced as “try”) or prefix tree is a tree data structure used to efficiently store and retrieve keys in a dataset of strings. There are various applications of this data structure, such as autocomplete and spellchecker.

Implement the Trie class:

Trie() Initializes the trie object.
void insert(String word) Inserts the string word into the trie.
boolean search(String word) Returns true if the string word is in the trie (i.e., was inserted before), and false otherwise.
boolean startsWith(String prefix) Returns true if there is a previously inserted string word that has the prefix prefix, and false otherwise.

Example 1:

Input
[“Trie”, “insert”, “search”, “search”, “startsWith”, “insert”, “search”]
[[], [“apple”], [“apple”], [“app”], [“app”], [“app”], [“app”]]
Output
[null, null, true, false, true, null, true]

Explanation
Trie trie = new Trie();
trie.insert(“apple”);
trie.search(“apple”); // return True
trie.search(“app”); // return False
trie.startsWith(“app”); // return True
trie.insert(“app”);
trie.search(“app”); // return True

Constraints:

1 <= word.length, prefix.length <= 2000
word and prefix consist only of lowercase English letters.
At most 3 * 104 calls in total will be made to insert, search, and startsWith.

https://leetcode.com/problems/implement-trie-prefix-tree/

A

from collections import defaultdict
class Trie(object):

def \_\_init\_\_(self):
    Trie = lambda: defaultdict(Trie)
    self.trie = Trie()

def insert(self, word):
    """
    :type word: str
    :rtype: None
    """
    cur = self.trie
    for c in word:
        cur = cur[c]
    cur["$"] = True
    

def search(self, word):
    """
    :type word: str
    :rtype: bool
    """
    cur = self.trie
    for c in word:
        if c not in cur:
            return False
        cur = cur[c]
    return "$" in cur
    

def startsWith(self, prefix):
    """
    :type prefix: str
    :rtype: bool
    """
    cur = self.trie
    for c in prefix:
        if c not in cur:
            return False
        cur = cur[c]
    return True
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q
  1. Design Add and Search Words Data Structure
    Solved
    Medium
    Topics
    Companies
    Hint

Design a data structure that supports adding new words and finding if a string matches any previously added string.

Implement the WordDictionary class:

WordDictionary() Initializes the object.
void addWord(word) Adds word to the data structure, it can be matched later.
bool search(word) Returns true if there is any string in the data structure that matches word or false otherwise. word may contain dots '.' where dots can be matched with any letter.

Example:

Input
[“WordDictionary”,”addWord”,”addWord”,”addWord”,”search”,”search”,”search”,”search”]
[[],[“bad”],[“dad”],[“mad”],[“pad”],[“bad”],[“.ad”],[“b..”]]
Output
[null,null,null,null,false,true,true,true]

Explanation
WordDictionary wordDictionary = new WordDictionary();
wordDictionary.addWord(“bad”);
wordDictionary.addWord(“dad”);
wordDictionary.addWord(“mad”);
wordDictionary.search(“pad”); // return False
wordDictionary.search(“bad”); // return True
wordDictionary.search(“.ad”); // return True
wordDictionary.search(“b..”); // return True

Constraints:

1 <= word.length <= 25
word in addWord consists of lowercase English letters.
word in search consist of '.' or lowercase English letters.
There will be at most 2 dots in word for search queries.
At most 104 calls will be made to addWord and search.
A

from collections import defaultdict

class WordDictionary:

def \_\_init\_\_(self):
    Trie = lambda: defaultdict(Trie)
    self.trie = Trie()

def addWord(self, word: str) -> None:
    cur = self.trie
    for c in word:
        cur = cur[c]
    cur["$"] = True

def searchRec(self, word, trie) -> bool:
    cur = trie
    for i, c in enumerate(word):
        if c == '.':
            for key in cur.keys():
                if key == "$":
                    continue
                if self.searchRec(word[i+1:], cur[key]):
                    return True
            return False
        elif c not in cur:
            return False
        else:
            cur = cur[c]
    return ("$" in cur)

def search(self, word: str) -> bool:
    return self.searchRec(word, self.trie)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q
  1. Word Search II
    Solved
    Hard
    Topics
    Companies
    Hint

Given an m x n board of characters and a list of strings words, return all words on the board.

Each word must be constructed from letters of sequentially adjacent cells, where adjacent cells are horizontally or vertically neighboring. The same letter cell may not be used more than once in a word.

Example 1:

Input: board = [[“o”,”a”,”a”,”n”],[“e”,”t”,”a”,”e”],[“i”,”h”,”k”,”r”],[“i”,”f”,”l”,”v”]], words = [“oath”,”pea”,”eat”,”rain”]
Output: [“eat”,”oath”]

Example 2:

Input: board = [[“a”,”b”],[“c”,”d”]], words = [“abcb”]
Output: []

Constraints:

m == board.length
n == board[i].length
1 <= m, n <= 12
board[i][j] is a lowercase English letter.
1 <= words.length <= 3 * 104
1 <= words[i].length <= 10
words[i] consists of lowercase English letters.
All the strings of words are unique.

https://leetcode.com/problems/word-search-ii/description/

A

from collections import defaultdict

class Solution(object):
def findWords(self, board, words):
“””
:type board: List[List[str]]
:type words: List[str]
:rtype: List[str]
“””
ROWS, COLS = len(board), len(board[0])
Trie = lambda: defaultdict(Trie)
root = Trie()
for word in words:
cur = root
for char in word:
cur = cur[char]
cur[’$’] = word
output = []
seen = set()
directions = [[0,1], [1,0], [0,-1], [-1, 0]]

    def rec(r, c, t):
        curchar = board[r][c]
        cur = t[curchar]
        found = cur.pop('$', False)
        if found:
            output.append(found)
        seen.add((r, c))
        for rm, cm in directions:
            row = r + rm
            col = c + cm
            if row in range(ROWS) and col in range(COLS) and (row, col) not in seen and board[row][col] in cur:
                rec(row, col, cur)
        if not cur:
            t.pop(curchar)
        seen.remove((r,c))
    
    for r in range(ROWS):
        for c in range(COLS):
            if board[r][c] in root:
                rec(r, c, root)
    return output
How well did you know this?
1
Not at all
2
3
4
5
Perfectly