Grokking 75: Top Coding Interview Questions

0% completed

Solution: Design Add and Search Words Data Structure

Problem Statement

Design a data structure that supports the addition of new words and the ability to check if a string matches any previously added word.

Implement the Solution class:

  • Solution() Initializes the object.
  • void addWord(word) Inserts word into the data structure, making it available for future searches.
  • bool search(word) Checks if there is any word in the data structure that matches word. The method returns true if such a match exists, otherwise returns false.

Note: In the search query word, the character `'.'

.....

.....

.....

Like the course? Get enrolled and start learning!
J

Jimmy

· 2 years ago

For example #1 in the Justification section, "banana" does not match the "....." pattern.

For example #3 in the Expected Output section, the expected output for ["h...o"] should be 1, not 0.

Show 1 reply
Tuấn Trần

Tuấn Trần

· 2 years ago

In python, I think my code works well, but the test cases seem not well organized.

In word match case, the function returns true, but the test code prints "0", instead of "1" in the expected result:

Your Input ["Solution","addWord","addWord","addWord","search","search","search","search"] [[],["apple"],["banana"],["cherry"],["apple"],["ban..a"],["cherr."],["b.n.n."]] Output [-1,-1,-1,-1,0,0,0,0] Expected [-1,-1,-1,-1,1,1,1,1]
Show 2 replies
E H

E H

· a year ago

I found it a bit more easier and understandable to do this in a BFS way. Time and space complexity remains the same.

// class TrieNode { // TrieNode[] children = new TrieNode[26]; // Representing each character of the alphabet. // boolean isEnd = false; // To determine if the current TrieNode marks the end of a word. // } public class Solution { private TrieNode root; public Solution() { // ToDo: Write Your Code Here. this.root = new TrieNode(); } // Function to add a word into the trie structure. public void addWord(String word) { // ToDo: Write Your Code Here. TrieNode start = root; for (char c : word.toCharArray()) { if (start.children[c - 'a'] == null) { start.children[
V

vkvikaskmr

· 3 months ago

How is time complexity O(m*(26^n))? I think it should be O(26^n) because we won't be searching the entire trie but only till the length of the search word.

Show 1 reply
Faraz Ahmed

Faraz Ahmed

· 16 days ago

this constraint is wrong, i see the word is containing more than 2 dots in some example

There will be at most 2 dots in word for search queries