Search Box Counter

Easy · Tries & String Matching · about 15 min

A shop's search box logs what happens, as a list of ops strings. Each op is one of:

  • "add <word>": a product name was added. The same name can be added more than once, and every add counts.
  • "count <prefix>": how many names added so far start with prefix? The prefix may be empty ("count "), which counts every name.

Return a list with the answer to every count op, in order. Words and prefixes are lowercase letters, and there is exactly one space after add or count.

Example:

search_box_counts(["add apple", "add app", "count ap", "count apple", "add apply", "count app"]) → [2, 1, 3]

Hints

  • Split each op at its first space to get the kind and the word.
  • Store a counter in each trie node: how many added words pass through it.
  • For a count, walk the prefix letter by letter. If a letter is missing the answer is 0, otherwise it is the counter where you stop.

Learn the pattern first: the Tries & String Matching lesson.

More Tries & String Matching problems