Skip to the solution
MediumDSA13 min read

What is a trie and when is it useful?

1.1k views

The problem

Question presented to candidate: "What is a trie, and when would you use one instead of a hash set or a sorted list? Sketch the node structure and the basic operations in Python."

What a strong answer should cover:

  • A trie stores strings one character per edge; words with a common prefix share a path, and an end-of-word flag marks complete words.
  • insert, search and startsWith each cost O(L) in the word length, independent of how many words are stored, and search differs from startsWith only by the end-flag check.
  • When it wins: prefix queries (autocomplete, prefix counts), wildcard search, longest-prefix match; when it loses: exact-match-only lookups, where a hash set is smaller and simpler.
  • The memory trade-off: one node per distinct prefix, and per node either a fixed array (fast, wasteful) or a map (compact, slower).
  • Python details: children as a dict (any character), __slots__ to shrink nodes, dict.get for the walk, and sorted() because dicts keep insertion order, not alphabetical order.

Code / implementation expected: Optional β€” a Trie class with insert, search and startsWith in Python is a common follow-up.

  • trie
  • strings

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 Β· 11 sections

Python code

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

PythonTrie basics: insert, search, startsWith, prefix counts
PythonWords under a prefix, prefix sharing, trie vs hash set

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 41 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 find the lowest common ancestor in a binary tree?

Continue