Skip to content
Programming101
Programming101

Learn everything about programming

  • Home
  • CS Subjects
    • IoT – Internet of Things
    • Digital Communication
    • Human Values
  • Programming Tutorials
    • C Programming
    • Data structures and Algorithms
  • HackerRank Solutions
    • HackerRank Algorithms Solutions
    • HackerRank C problems solutions
    • HackerRank C++ problems solutions
    • HackerRank Java problems solutions
    • HackerRank Python problems solutions
Programming101
Programming101

Learn everything about programming

Leetcode Design Add and Search Words Data Structure problem solution

YASH PAL, 31 July 2024

In this Leetcode Design Add and Search Words Data Structure problem solution we need to Design a data structure that supports adding new words and finding if a string matches any previously added string.

Implement the WordDictionary class:

  1. WordDictionary() Initializes the object.
  2. void addWord(word) Adds word to the data structure, it can be matched later.
  3. 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.
Leetcode Design Add and Search Words Data Structure problem solution

Problem solution in Python.

class WordDictionary(object):

    def __init__(self):

        self.parser = collections.defaultdict(set)

    def addWord(self, word):

        self.parser[len(word)].add(word)
            
    def search(self, word):

        if len(word) not in self.parser:
            return False
        for x in self.parser[len(word)]:
            if all(True if l == "." else l == x[i] for i,l in enumerate(word)):
                return True
        return False

Problem solution in Java.

class WordDictionary {
    class TrieNode {
        TrieNode[] children;
        boolean isWord;
        
        private final int N = 26;
        
        TrieNode() {
            children = new TrieNode[N];
        }
    }
    TrieNode root;

    public WordDictionary() {
        root = new TrieNode();
        root.isWord = true;
    }

    public void addWord(String word) {
        TrieNode cur = root;
        for (char c : word.toCharArray()) {
            if (cur.children[c - 'a'] == null) {
                cur.children[c - 'a'] = new TrieNode();
            }
            cur = cur.children[c - 'a'];
        }
        cur.isWord = true;
    }

    public boolean search(String word) {
        return dfsSearch(root, word, 0);
    }
    
    private boolean dfsSearch(TrieNode cur, String word, int i) {
        if (cur == null) return false;
        if (i == word.length()) return cur.isWord;
        char c = word.charAt(i);
        if (c == '.') {
            for (int j = 0; j < 26; j++) {
                if (dfsSearch(cur.children[j], word, i + 1)) {
                    return true;
                }
            }
            return false;
        } else {
            return dfsSearch(cur.children[c - 'a'], word, i + 1);
        }
    }
}

Problem solution in C++.

class WordDictionary {
private:
      vector<vector<string>>v;
public:   
    
    WordDictionary() : v(100002) {}

    void addWord(string word) {
        v[word.size()].push_back(word);
    }

    bool search(string word) {
        int n = word.size();
        for(int i=0;i<v[n].size();i++){
            int c=0;
            for(int j=0;j<n;j++){
                if(v[n][i][j]==word[j] || word[j]=='.')
                    c++;
                else
                    break;
            }
            if(c==n)
            {
                return 1;
            }
        }
        return 0;
    }
};

Problem solution in C.

typedef struct trie_node {
    struct trie_node *sub_chars[26];
    bool EOW;
} WordDictionary;

WordDictionary* wordDictionaryCreate() {
    WordDictionary *obj = (WordDictionary*)calloc(1,sizeof(WordDictionary));
    return obj;
}

void wordDictionaryAddWord(WordDictionary* obj, char * word) {
  while((*word)) {
      if(obj->sub_chars[(*word)-'a']==NULL) {
          obj->sub_chars[(*word)-'a'] = (WordDictionary*)calloc(1,sizeof(WordDictionary));
      }
      obj = obj->sub_chars[(*word)-'a'];
      word++;
  }
    obj->EOW = true;
}

bool wordDictionarySearch(WordDictionary* obj, char * word) {
    while(*word) {
        if( (*word) =='.') {
            for(int i =0;i<26;i++) {
                if(!obj->sub_chars[i]) continue;
                bool a = wordDictionarySearch(obj->sub_chars[i],word+1);
                if(a) return true;
            }
            return false;
        }
        else if(!obj->sub_chars[(*word)-'a']) return false;
        obj = obj->sub_chars[(*word)-'a'];
        word++;
    }
    if(obj->EOW)return true;
    else return false;
}

void wordDictionaryFree(WordDictionary* obj) {
    for(int i=0;i<26;i++) {
        if(!obj->sub_chars[i]) continue;
        wordDictionaryFree(obj->sub_chars[i]);
    }
    free(obj);
}

coding problems

Post navigation

Previous post
Next post
  • How AI Is Revolutionizing Personalized Learning in Schools
  • GTA 5 is the Game of the Year for 2024 and 2025
  • Hackerrank Day 5 loops 30 days of code solution
  • Hackerrank Day 6 Lets Review 30 days of code solution
  • Hackerrank Day 14 scope 30 days of code solution
©2025 Programming101 | WordPress Theme by SuperbThemes