Editor

Wildcard Word Counter

#482 · Data structures · Expert · 250 XP · about 55 min

A crossword helper stores a dictionary and answers questions like "how many words fit c.t?". Build a WordCounter class:

  • WordCounter() starts with no words.
  • add(word) stores a word of lowercase letters. Adding a word that is already stored changes nothing.
  • count(pattern) returns how many stored words match pattern. A pattern is made of lowercase letters and dots: a dot matches any one letter, a letter matches only itself, and a word matches only if it has exactly as many letters as the pattern has characters.

Words can be added after count has been called, and later counts include them.

Examples

wc = WordCounter()
for w in ['cat', 'cot', 'cut', 'cart', 'dog', 'cat']:
    wc.add(w)
wc.count('c.t')     # returns 3    (cat, cot, cut)
wc.count('...')     # returns 4    (cat, cot, cut, dog)
wc.count('c..t')    # returns 1    (cart)
wc.count('d.')      # returns 0

Constraints

  • Words and patterns have 1 to 10 characters
  • Up to 20,000 calls of add and 20,000 calls of count, in any order
  • A pattern can have dots anywhere, any number of them. With 20,000 stored words, comparing a pattern with every word is too slow.

Fastest solvers

Leaderboard

First solves only, ranked by stars and then time.