Skip to content
Search lessons, topics, tests…
Esc

    ↑ ↓ moveEnter openEsc close

    Coding problem

    A prefix tree for search suggestions

    MediumAbout 25 minFull AccessLearn it: Tries in C#: Prefix Search, Autocomplete and Wildcard Words

    The task

    A search box suggests words while the user types, so for every key press it must answer at once whether some stored word starts with the text typed so far.

    Complete the class PrefixTree. Insert(word) stores a word; stored words are not empty and hold only the lowercase letters a to z. Contains(word) returns true only when exactly that word was stored. StartsWithPrefix(prefix) returns true when some stored word begins with prefix; the empty prefix is true as soon as any word is stored. Lookups can hold any characters, and matching is case-sensitive: a text with any other character is never a stored word and never a prefix. Storing a word twice changes nothing.

    Signature

    public void Insert(string word)
    public bool Contains(string word)
    public bool StartsWithPrefix(string prefix)

    Examples

    • Insert("car"), then Contains("car"), Contains("ca"), StartsWithPrefix("ca") → true, false, true. "ca" begins a stored word but was not stored itself.
    • Insert("car"), Insert("ca"), then Contains("ca") → true. A prefix can also be a word of its own.

    Limits: Up to 100,000 words of up to 20 letters, and up to 300,000 lookups.

    The tests check: a new tree, prefixes that go past a word, a longer word that was not stored, a prefix that is also a word, the empty prefix, storing a word twice, upper-case letters, other characters, and 60,000 words that begin the same way with 240,000 lookups in time.

    Hints

      Your code

      C#Solution.csLoading the editor…

      Already included: using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net.Http; using System.Threading; using System.Threading.Tasks;

      public sealed class PrefixTree
      {
          // Stores a word of lowercase letters a to z.
          public void Insert(string word)
          {
              throw new NotImplementedException();
          }
      
          // True only when exactly this word was stored.
          public bool Contains(string word)
          {
              throw new NotImplementedException();
          }
      
          // True when some stored word begins with prefix.
          public bool StartsWithPrefix(string prefix)
          {
              throw new NotImplementedException();
          }
      }

      This problem comes with TechInterviewNotes Full Access

      Unlock all paid content on TechInterviewNotes.