AlgoTales · Roadmap

Word dictionary

Intermediate · 10 min · code in PHP, JavaScript, Java and Go

Where you will meet this in real life

A word dictionary with wildcards lets a search include a "joker" such as a dot that matches any letter. When the search meets a joker, it tries every possible branch at that point and succeeds if any branch spells a real word.

Practical use cases

  • Web app: Crossword and Wordle helper page. A puzzle helper site lets the player type "c_t" or "pl__e" with blanks for unknown letters. At every blank the code tries all letters that exist in the trie at that spot, so it lists "cat", "cot", "cut" without testing all dictionary words. Results appear while the player is still typing.
  • Web app: Wildcard search in an admin panel. Support staff search order codes like "ORD-2024-?-77" where one character was unreadable on a printed receipt. Trying all characters only at the unknown spot finds the matching codes quickly, instead of scanning the whole order table. Staff stop scrolling through hundreds of orders and get the handful of real candidates at once.
  • System: Pattern rules and filters. Rule engines for file names or domain filters sometimes allow a single-character wildcard. A trie that branches at the wildcard checks only the paths that can actually match. Only the branches that actually exist are tried, so a few wildcards cost far less than testing every word.

The story: Aarav's Crossword Joker

Aarav loved the Sunday crossword in the newspaper. This week he was stuck on a six-letter word: "C _ I C K E _" with some squares already filled. He knew the letters he had, but not the gaps.

Mira built him a dictionary using her lane-of-letters board. But there was a twist. A normal lookup walks one definite lane per letter. How do you look up a word with a blank? "Easy," she said. "At a blank, don't pick a lane. Send a runner down every lane and see whether any of them reaches a green flag with the remaining letters."

For "c.b" the runner at c split in two, one for the A lane and one for the U lane. The A-runner came back empty-handed (no b below). The U-runner found b and a green flag. "Cub!" shouted Aarav.

This is the classic word dictionary problem: addWord plus a search where "." matches any letter. It is a normal trie search, with one change: on a dot, try all children, recursively.

How to spot this problem, and where you need it

Users type a pattern with unknown characters and you must find every stored word that fits, but comparing the pattern with all stored words is too slow.

Signs you need it

  • Search input allows placeholders such as ?, _ or . that stand for any single character.
  • The problem statement says "wildcard", "dot matches any letter" or "pattern with blanks".
  • You are using regular expressions on every stored string and it gets slow with large lists.
  • Users complain that finding a code with one unreadable character is painful.

Where to use it in a project

  • Crossword, Wordle and anagram helper pages with blank letters.
  • Support tools that look up partially known codes, plates or references.

The solution

Store words in a trie. To search a pattern, walk it letter by letter. For a normal letter, follow that one child. For a wildcard, try every child at this spot, one after another, continuing the rest of the pattern from each. If any route ends on an end-of-word flag, the pattern matches. Branches that do not exist are never explored.

Payoff: Before: matching the pattern against all 100,000 words. After: exploring only the few branches that stay possible.

Explain it like I am 8

A joker card in a game fits any card. In our word road, when you meet a joker you are allowed to try every turn at that spot. If any turn leads you to the end of the word with a green flag, you win.

How it works, step by step

  1. addWord is the normal trie insert.
  2. search walks the pattern with an index, recursively: go(node, i).
  3. If the pattern letter is a normal letter, follow that single child (stop with false if missing).
  4. If it is a dot, loop over every child and recurse; return true if any call returns true.
  5. When the pattern is used up, the answer is the node's end flag.

The code in four languages

PHP

<?php
class TrieNode {
    public array $kids = [];
    public bool $end = false;
}

class WordDictionary {
    private TrieNode $root;
    public function __construct() { $this->root = new TrieNode(); }

    public function addWord(string $w): void {
        $n = $this->root;
        foreach (str_split($w) as $ch) { $n->kids[$ch] ??= new TrieNode(); $n = $n->kids[$ch]; }
        $n->end = true;
    }

    public function search(string $pattern): bool {
        return $this->go($this->root, $pattern, 0);
    }

    private function go(TrieNode $n, string $p, int $i): bool {
        if ($i === strlen($p)) { return $n->end; }          // pattern used up
        $ch = $p[$i];
        if ($ch === '.') {                                  // joker: try every child
            foreach ($n->kids as $kid) {
                if ($this->go($kid, $p, $i + 1)) { return true; }
            }
            return false;
        }
        if (!isset($n->kids[$ch])) { return false; }        // normal letter: one lane
        return $this->go($n->kids[$ch], $p, $i + 1);
    }
}

$d = new WordDictionary();
foreach (['cat', 'car', 'cub', 'dog'] as $w) { $d->addWord($w); }
foreach (['c.b', 'd.g', 'c..', 'ca', 'd.', '...', 'bat'] as $q) {
    echo $q . ': ' . ($d->search($q) ? 'yes' : 'no') . PHP_EOL;
}

JavaScript

class TrieNode {
  constructor() { this.kids = {}; this.end = false; }
}

class WordDictionary {
  constructor() { this.root = new TrieNode(); }

  addWord(w) {
    let n = this.root;
    for (const ch of w) { if (!n.kids[ch]) n.kids[ch] = new TrieNode(); n = n.kids[ch]; }
    n.end = true;
  }

  search(pattern) { return this.go(this.root, pattern, 0); }

  go(n, p, i) {
    if (i === p.length) return n.end;                  // pattern used up
    const ch = p[i];
    if (ch === '.') {                                  // joker: try every child
      for (const k in n.kids) {
        if (this.go(n.kids[k], p, i + 1)) return true;
      }
      return false;
    }
    if (!n.kids[ch]) return false;                     // normal letter: one lane
    return this.go(n.kids[ch], p, i + 1);
  }
}

const d = new WordDictionary();
for (const w of ['cat', 'car', 'cub', 'dog']) d.addWord(w);
for (const q of ['c.b', 'd.g', 'c..', 'ca', 'd.', '...', 'bat']) {
  console.log(q + ': ' + (d.search(q) ? 'yes' : 'no'));
}

Java

import java.util.*;

public class Main {
    static class TrieNode {
        Map<Character, TrieNode> kids = new HashMap<>();
        boolean end = false;
    }

    static class WordDictionary {
        private final TrieNode root = new TrieNode();

        void addWord(String w) {
            TrieNode n = root;
            for (char ch : w.toCharArray()) {
                n.kids.putIfAbsent(ch, new TrieNode());
                n = n.kids.get(ch);
            }
            n.end = true;
        }

        boolean search(String pattern) { return go(root, pattern, 0); }

        private boolean go(TrieNode n, String p, int i) {
            if (i == p.length()) return n.end;                 // pattern used up
            char ch = p.charAt(i);
            if (ch == '.') {                                   // joker: try every child
                for (TrieNode kid : n.kids.values()) {
                    if (go(kid, p, i + 1)) return true;
                }
                return false;
            }
            if (!n.kids.containsKey(ch)) return false;         // normal letter: one lane
            return go(n.kids.get(ch), p, i + 1);
        }
    }

    public static void main(String[] args) {
        WordDictionary d = new WordDictionary();
        for (String w : new String[]{"cat", "car", "cub", "dog"}) d.addWord(w);
        for (String q : new String[]{"c.b", "d.g", "c..", "ca", "d.", "...", "bat"}) {
            System.out.println(q + ": " + (d.search(q) ? "yes" : "no"));
        }
    }
}

Go

package main

import "fmt"

type TrieNode struct {
	kids map[byte]*TrieNode
	end  bool
}

func newTrieNode() *TrieNode { return &TrieNode{kids: map[byte]*TrieNode{}} }

type WordDictionary struct {
	root *TrieNode
}

func NewWordDictionary() *WordDictionary { return &WordDictionary{root: newTrieNode()} }

func (d *WordDictionary) AddWord(w string) {
	n := d.root
	for i := 0; i < len(w); i++ {
		if n.kids[w[i]] == nil {
			n.kids[w[i]] = newTrieNode()
		}
		n = n.kids[w[i]]
	}
	n.end = true
}

func (d *WordDictionary) Search(pattern string) bool {
	return d.root.match(pattern, 0)
}

func (n *TrieNode) match(p string, i int) bool {
	if i == len(p) {
		return n.end // pattern used up
	}
	ch := p[i]
	if ch == '.' { // joker: try every child
		for _, kid := range n.kids {
			if kid.match(p, i+1) {
				return true
			}
		}
		return false
	}
	kid := n.kids[ch]
	if kid == nil {
		return false // normal letter: one lane
	}
	return kid.match(p, i+1)
}

func main() {
	d := NewWordDictionary()
	for _, w := range []string{"cat", "car", "cub", "dog"} {
		d.AddWord(w)
	}
	for _, q := range []string{"c.b", "d.g", "c..", "ca", "d.", "...", "bat"} {
		answer := "no"
		if d.Search(q) {
			answer = "yes"
		}
		fmt.Printf("%s: %s\n", q, answer)
	}
}

Time: O(L) normally, up to O(all letters) with many dots · Extra space: O(L). Without dots it is a plain walk; every dot can multiply the branches, so the worst case may visit the whole trie.

Watch out for

  • Stopping at the first child when you see a dot instead of trying all of them.
  • Treating "." as a literal letter when inserting words (patterns are for searching, not storing).
  • Forgetting the end flag at the very end: "ca" must not match because cat is stored.

Quick check

  1. On a "." in the pattern, what should the search do?
    • Skip the letter and move on without moving down
    • Try every child of the current node
    • Return false
  2. Stored words: cat, car. Does "c.." match?
    • No, three dots are too many
    • Yes, via cat or car
    • Only via car
  3. Which pattern is the cheapest to search?
    • "..."
    • a pattern with no dots
    • ".a."