Algo-Sim › Tries

Design Add and Search Words

Medium · Tries · step through it in Java, Python and C++ on your own input

A dictionary where search may contain '.', which matches any one letter. Wildcards branch into every child and backtrack.

Problem

Design a word dictionary with addWord(word) and search(word). In search, the character . matches any single letter, so search(".ad") finds bad. Return whether any added word matches.

Constraints

Edge cases to test

Follow-up questions

What is the worst case for search?
With many dots it branches into every child: O(26^d · L) for d dots, though real tries are much sparser.
How can you speed up dot-heavy queries?
Group words by length first, so a pattern only searches words of its own length.

Solution

Java

class WordDictionary {
    private static class Node {
        Node[] next = new Node[26];
        boolean end;
    }
    private final Node root = new Node();

    public void addWord(String word) {
        Node node = root;
        for (char c : word.toCharArray()) {
            int i = c - 'a';
            if (node.next[i] == null) node.next[i] = new Node();
            node = node.next[i];
        }
        node.end = true;
    }

    public boolean search(String word) {
        return match(word, 0, root);
    }

    private boolean match(String word, int i, Node node) {
        if (node == null) return false;
        if (i == word.length()) return node.end;
        char c = word.charAt(i);
        if (c != '.') return match(word, i + 1, node.next[c - 'a']);
        for (Node child : node.next) {
            if (match(word, i + 1, child)) return true;
        }
        return false;
    }
}

Python

class Node:
    def __init__(self):
        self.next = [None] * 26
        self.end = False


class WordDictionary:
    def __init__(self):
        self.root = Node()

    def addWord(self, word):
        node = self.root
        for c in word:
            i = ord(c) - ord("a")
            if node.next[i] is None:
                node.next[i] = Node()
            node = node.next[i]
        node.end = True

    def search(self, word):
        return self._match(word, 0, self.root)

    def _match(self, word, i, node):
        if node is None:
            return False
        if i == len(word):
            return node.end
        c = word[i]
        if c != ".":
            return self._match(word, i + 1, node.next[ord(c) - ord("a")])
        for child in node.next:
            if self._match(word, i + 1, child):
                return True
        return False

C++

#include <bits/stdc++.h>
using namespace std;

class WordDictionary {
  public:
    class Node {
      public:
        vector<Node *> next = vector<Node *>(26, nullptr);
        bool end = false;
    };
    Node *root = new Node();

    void addWord(string &word) {
        Node *node = root;
        for (char c : word) {
            int i = c - 'a';
            if (node->next[i] == nullptr)
                node->next[i] = new Node();
            node = node->next[i];
        }
        node->end = true;
    }

    bool search(string &word) {
        return match(word, 0, root);
    }

    bool match(string &word, int i, Node *node) {
        if (node == nullptr)
            return false;
        if (i == int(word.size()))
            return node->end;
        char c = word[i];
        if (c != '.')
            return match(word, i + 1, node->next[c - 'a']);
        for (Node *child : node->next) {
            if (match(word, i + 1, child))
                return true;
        }
        return false;
    }
};

More Tries problems