Design Add and Search Words Data Structure

Medium · Tries · String · Depth-First Search · Design · Trie

Problem

Design a dictionary that stores words and answers lookups in which some letters may be wildcards. Implement the WordDictionary class:

Tests replay a call sequence: the first entry names the class, each later entry is a method with its arguments, and calls returning nothing report None.

Examples

Input: addWord("bad"), addWord("dad"), addWord("mad"), search("pad"), search("bad"), search(".ad"), search("b..")
Output: False, True, True, then True

"pad" was never added. ".ad" matches bad, dad and mad, and "b.." matches bad.

Input: addWord("at"), search("a"), search("a."), search(".t")
Output: False, True, then True

"a" is only the start of a stored word, so it does not match. Each dot stands for exactly one letter.

Constraints

Approaches

Follow-up

With at most two dots, a search visits at most 26² paths. What if the number of dots were unlimited? Could you speed up queries that start with dots, such as "..ad", by also storing each word reversed, or by grouping words by length?

Related problems

Start free on Cariara · Coding problems · System design studio

Starting Python
No results yet.

          
↑↓ move ↵ open esc close

Labs

Loading labs…

Run with your own input

Starting Python

Loading Python…