Skip to the solution
MediumLow-Level DesignAsked in 20246 min read

Trie autocomplete suffix search

2.4k views

The problem

Problem, as an interviewer would state it: "Implement a Trie (prefix tree) with insert(word) and autocomplete(prefix), returning every real inserted word that starts with the given prefix."

Examples:

Code
trie.insert("cat"); trie.insert("car"); trie.insert("card");
trie.autocomplete("ca"); // ["car", "card", "cat"]

Clarifying questions expected:

  • Should autocomplete results be returned in a specific order (like alphabetical), or is any order acceptable?
  • Should the prefix itself, if it is also a complete inserted word, be included in its own results?
  • What is the real time complexity of autocomplete relative to the total number of inserted words, versus just the matching ones?

Code / implementation expected: Yes — real, direct proof of correct, sorted autocomplete results across multiple real prefixes, including a genuinely unmatched prefix returning an empty array.

  • js-coding
  • utility
  • algorithm

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

6 min read · 9 sections

Run the code

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

JavaScriptReal, direct proof: autocomplete() returns the correct, sorted matches across multiple real prefixes, including a prefix that is itself a complete word

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 65 of 154 in JavaScript coding

Keep your momentum going.

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

Up nextMedium

Custom Object.create polyfill

Continue