Limited-time offer: 80% off every plan

See plans

Tries Coding Interview: Spot Prefix Problems Early

A practical guide to recognising trie problems, building the structure step by step while narrating, and explaining time and space complexity honestly under interview pressure.

By Emily Miller12 min read

A trie question rarely arrives with the word "trie" in it. The interviewer describes a dictionary of words, a search-as-you-type box, or a prefix query. In a tries coding interview, the skill being tested is recognition and reasoning, not recall of a node class. This guide shows how to spot the signal, build the structure while explaining each decision, and give a complexity answer you can defend when the interviewer pushes back.

Why Tries Show Up in Coding Interviews

A candidate who has only drilled arrays and hash maps can usually write the insert loop once they see it, but they freeze earlier, at the moment of deciding what to build.

That is the real test. Many interviewers are less interested in whether you can reproduce a node class from memory than in whether you can explain why a hash map of whole words is not enough when prefixes matter. If you can say that clearly, the implementation becomes a formality.

In the first thirty seconds of a trie question, say the structure's name and your reason for choosing it before you write anything: "This looks like a prefix problem, so I want to consider a trie." That single sentence tells the interviewer where you are heading.

If you want the same reasoning-first approach applied to other topics, our Hash Maps Coding Interview: How to Explain Your Reasoning, Sorting Coding Interview: Reason Through the Algorithm Out Loud and Heaps Coding Interview Guide: Reason Out Loud About Priority and Order follow a similar pattern of naming trade-offs out loud.

How to Spot a Tries Coding Interview Problem in the Prompt

The recognition step takes thirty seconds and saves you ten minutes of wrong-direction coding. In a trie question, the prompt almost never names the structure, so train yourself to listen for specific phrases instead.

Signals in the prompt

  • "starts with" or "has this prefix"
  • "prefix" used anywhere in the problem statement
  • "dictionary of words" combined with repeated queries
  • "search as you type" or autocomplete behaviour
  • "wildcard matching" where a dot or asterisk stands in for characters

Any one of these is a strong hint. Two of them together is close to a confirmation.

Contrast with hash map problems

A hash map is a natural fit for exact-match questions. Ask it whether the word "apple" is in a set, and it handles that well. Prefix queries are a different shape, which is why the structure choice matters.

That contrast is worth saying out loud, because it shows you understand the trade-off rather than pattern-matching on the word "dictionary".

Contrast with sorting

Sorting the word list is another option worth naming. Words sharing a prefix sit next to each other in sorted order, so a range search can find them. The trade-off is that keeping the list sorted as new words arrive takes extra work, and the range reasoning is fiddlier to explain under pressure.

Say the recognition out loud

A short script you can use almost verbatim:

"This looks like a prefix problem, so I want to consider a trie before I reach for a hash map. A hash map handles exact match well, but prefix queries ask a different kind of question."

It names the structure, justifies it, and shows the interviewer you are choosing deliberately.

The Core Idea in Plain Language

A trie stores characters along edges, so words that share a beginning share the same path from the root. Each node represents a prefix, not a whole word. A flag on a node marks where a valid word ends.

Take three short words: "cat", "car", "card". The root is empty. From it, an edge labelled c leads to a node representing the prefix "c". From there, an edge labelled a leads to a node for "ca". Now the paths split: one edge labelled t reaches a node for "cat", another labelled r reaches "car". From the "car" node, one more edge labelled d reaches "card".

The nodes for "cat" and "car" are both marked as end-of-word. The node for "card" is marked too. The intermediate nodes are not, even though they represent real prefixes.

Two details matter when you write the code. First, the root is empty because every word shares the empty prefix; it is the common starting point, not a letter. Second, the end-of-word marker lives on the node rather than on the edge, because a node is what a path arrives at. When you insert "car" and later insert "card", you reuse the existing "car" node and only add the d edge plus a new marker.

If you can explain this small example cleanly, you have most of what a trie question is really asking for.

Building It Step by Step While Narrating

Narrate each decision as you make it. The interviewer is grading the reasoning, and silence hides it. You do not need to write perfect code to make this work; you need to describe the shape of each operation before you type it.

Define the node first

A node needs two things: a collection of children keyed by character, and a boolean that says whether a word ends here. Say why you chose a dictionary of children: it keeps the node small when the alphabet is sparse, and it makes the code readable. A fixed-size array is faster but wastes space unless the alphabet is small and known. Naming that trade-off is worth more than picking either option silently.

Insert

Walk character by character from the root. At each step, follow the child for that character if it exists, and create it if it does not. Creating nodes only when a child is missing is exactly where prefix sharing happens. When the loop ends, mark the final node as end-of-word. Note that the loop starts at the root, which is why the root being empty matters: the first character creates or follows the first edge.

Same walk, but fail fast the moment a child is missing. The final check is the marker, not just the path. Without it, searching for "car" would succeed in a trie that only contains "card".

StartsWith

Identical to search except for the last line: return true once the prefix walk completes, without requiring the end-of-word marker. That single difference is the whole reason the trie exists, and it is worth pointing out explicitly.

Talking About Time and Space Complexity Honestly

The complexity discussion is where a good answer separates itself from a memorised one. Insert and search are O(L) in the length of the word, independent of how many words are stored, assuming each child lookup is O(1). That independence is the interesting part: adding a million more words does not slow down a lookup of a five-letter word.

That assumption is worth unpacking out loud. A hash-map children collection gives expected O(1) lookup. A fixed-size array gives O(1) lookup too, at the cost of memory for every possible character. A list of children gives O(alphabet) per character, because you may scan the list. Naming which one you are using, and what it costs, shows you understand where the bound comes from.

Space is the honest part. The worst case is O(total characters), and shared prefixes reduce that in practice. But each node also carries its own overhead, the children collection and the end-of-word flag, so real memory use runs above the raw character count. A word list with little shared structure uses noticeably more memory than one built from common stems, because fewer nodes are shared.

The common mistake in a tries coding interview is claiming constant time. The interviewer is listening for the L. If you say "constant time" and they ask what happens with a very long word, you have to walk it back, which costs more than the extra syllable would have.

When asked to compare with a hash map, give both sides:

  • Hash maps are simpler to implement and often faster for exact match.
  • Tries win on prefix queries, wildcard matching, and ordered traversal of words.
  • A hash map answers prefix questions awkwardly, generally by looking at many or all of the keys.

That balanced answer reads as confidence, not hedging.

A typical prompt asks you to return every word in a dictionary that starts with a given prefix. Work through it in four moves.

  1. Restate the problem. "I need a structure that stores a word list, supports inserts, and returns every word beginning with a given prefix."
  2. Sketch the trie. Draw the small word list by hand and trace the prefix query. Follow the prefix down the trie, then collect everything below that node.
  3. Write the code in small pieces. Insert first, test it against the sketch. Then the prefix walk, testing that it stops correctly when a character is missing. Only then the collection step.
  4. Extend the discussion. Collecting all words under a prefix means visiting every node in that subtree. The cost is proportional to the number of nodes in the matched subtree plus the characters of the words you return. That is different from scanning every stored word, which touches the whole dictionary regardless of how few words match. Making that contrast out loud is the point.

Here is how the narration can sound for the word list "cat", "car", "card", with the prefix "car". This is an illustrative example, not a transcript of a real interview.

"I start at the root and read the prefix one character at a time. c exists, so I move to the node for 'c'. a exists, so I move to 'ca'. r exists, so I am now at the node for 'car'. The walk succeeded, so the prefix is present. Now I collect: this node is marked end-of-word, so 'car' goes into my results. It has one child, d, which is also marked, so 'card' goes in too. The 'cat' branch is not under this node, so I never touch it. The cost is the three steps of the walk plus the two nodes I visited while collecting, not a scan of the whole dictionary."

Common Follow-Ups and How to Handle Them

Interviewers often push one layer deeper when a trie comes up. Here is how to keep your footing.

  • Memory pressure. Discuss compressed tries or storing children in a fixed-size array when the alphabet is small. Say what you gain and what you give up.
  • Deletion. Explain the end-of-word marker and when a node can be pruned. A node can be removed only when it has no children and is not itself the end of another word.
  • Case sensitivity and non-letter characters. Clarify assumptions before coding. Ask whether input is lowercase letters only, or whether digits and punctuation appear.
  • Unknown optimisations. If you do not know one, say so and reason about the trade-off instead of guessing. "I'm not sure of the exact technique, but I'd expect it to trade memory for speed" is a better answer than a confident invention.

The last point matters more than it looks. In a tries coding interview, interviewers often care more about how you reason at the edge of your knowledge than about whether you have used the structure before.

Practising Tries Out Loud

Reasoning aloud is a skill separate from knowing the data structure, and it needs repetition. Reading a solution teaches you the code; saying the reasoning teaches you the interview. The loop that builds the skill is simple: attempt a problem, narrate your decisions, review the explanation, then repeat with the next one. The same habit is worth building across the Blog.

A short routine you can run this week:

  • Pick two trie problems and solve each with a timer running, narrating as you go.
  • After each one, review where your explanation got vague, not only where the code broke.
  • Record yourself and replay the complexity discussion specifically. The complexity discussion is a common place to lose clarity.
  • Keep a one-page practice log with a row per attempt: the problem, the signal you spotted, the complexity sentence you said, and one phrase to sharpen next time. Read the previous rows before you start.

Before Your Next Practice Round

A tries coding interview rewards one habit above all: naming the prefix signal early, then saying O(L) honestly instead of claiming constant time. Your next step is to write your one-line recognition script on a card and keep it where you can read it before you practise, so the first sentence of your next attempt is already decided.

Frequently asked questions

Do I need to memorise a trie implementation for coding interviews?

No. The code is short enough to derive on the spot once you understand the idea: a node holds a children collection and an end-of-word flag, and insert, search and startsWith all walk the same path. What is worth rehearsing is the reasoning, not the exact syntax.

How do I know whether to use a trie or a hash map in an interview?

Ask what kind of question the problem keeps asking. If it only checks whether a whole word exists, a hash map is the simpler choice. If it asks about beginnings of words, shared prefixes or everything that starts with a given string, a trie answers those directly, so name that reason before you start coding.

What is the time complexity of trie insert and search, and how should I explain it?

Insert and search are O(L) in the length of the word, not in the number of words stored. Add the caveat that this assumes O(1) child lookup, which a hash-map children collection gives you. If they push on a very long word, say the limit comes from the word's length, not the dictionary size.

What should I say if I have never used a trie in real code?

Be straightforward about it, then reason from first principles. Explain that words sharing a prefix share a path, and that this is what makes prefix queries cheap. Then walk through the insert and search operations as you would build them, so the interviewer can see your reasoning rather than a gap in your experience.

How can I practise explaining tries out loud before an interview?

Set a weekly loop with one slot for solving and one for listening back. In the listening slot, count how many times you named the structure and its reason before typing, and whether you said the L in your complexity sentence. Track those two habits across weeks rather than judging a single attempt.

Practise explaining tries out loud, then review your complexity answer.