Implement Magic Dictionary

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

Problem

Design a dictionary that checks whether a word is exactly one letter change away from a stored word.

Implement MagicDictionary:

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: ops = ["MagicDictionary","buildDict","search","search","search","search"], args = [[],[["game","code"]],["gate"],["game"],["cone"],["codes"]]
Output: [null,null,true,false,true,false]

"gate" and "cone" differ from a stored word in one position; "game" differs in none, and "codes" has the wrong length.

Input: ops = ["MagicDictionary","buildDict","search","search"], args = [[],[["ab","bb"]],["ab"],["cb"]]
Output: [null,null,true,true]

"ab" is stored itself, but changing its a to b gives "bb", which is also stored.

Constraints

Approaches

Follow-up

A trie works too: walk the search word down the trie, allowing exactly one step onto a different letter, and accept when you finish at the end of a word having used that one change. It shares prefixes between stored words, which saves memory when many words start the same way.

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…