Skip to the solution
MediumDSA13 min read

Implement Trie for autocomplete — how do you handle wildcards (.)?

899 views

The problem

Question presented to candidate: "Design a word dictionary in Python with addWord(word) and search(pattern), where a . in the pattern matches any single letter. Then extend it to autocomplete: as the user types, return up to three suggestions in alphabetical order. What does a search cost when the pattern has many dots?"

What a strong answer should cover:

  • A trie with an end-of-word flag; addWord is an O(L) insert.
  • A recursive search with an index: one child for a letter, every child for a ., the end flag at the end, and an early return on the first match.
  • Autocomplete as "walk the prefix, then a preorder DFS in letter order that stops after k words", which yields alphabetical results without sorting.
  • Honest complexity: O(L) without dots, up to Σ^d paths with d dots (bounded by the trie size); a brute-force list scan is O(N·L) per query.
  • Python details: dict children, any() over a generator (not a list) for the early exit, sorted() because dicts keep insertion order, and passing an index rather than slicing the pattern.

Clarifying questions expected:

  • Does . match exactly one letter? Is there also a *?
  • Should suggestions be alphabetical or ranked by popularity, and how many?
  • Is the alphabet only lower-case a–z?

Code / implementation expected: Yes — a WordDictionary/trie class with addWord, search (with .) and a suggest(prefix, k) method, in Python.

  • trie
  • string
  • Google

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

13 min read · 12 sections

Python code

Edit the code and run it here. Each printed line with an expected value becomes a test.

PythonaddWord and search with '.' wildcards
PythonAutocomplete per keystroke, wildcard prefixes, cost of dots

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 56 of 154 in DSA

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All DSA questions
Up nextMedium

How do you search in a rotated sorted array?

Continue