Glowing Letter Tiles

MediumtrieAlso known as Implement Trie (Prefix Tree)

In a phone word game you drag across letter tiles, and the trail glows on every tile you touch: green if the letters so far spell a word, amber if they could still grow into one, grey if no word starts that way. The dictionary holds tens of thousands of words, and the game adds new ones during a season.

Your task

Write a class TileDictionary:

  • constructor() creates an empty dictionary.
  • add(word) adds a word. Adding the same word twice is allowed and changes nothing.
  • isWord(letters) returns true if exactly this word was added.
  • isPrefix(letters) returns true if at least one added word starts with letters. A word counts as starting with itself.

Each method should take time proportional to the length of its argument, not to the size of the dictionary.

class TileDictionary

Examples

Example 1
Input
new TileDictionary()
.add("star")
.add("start")
.isWord("sta")
.isPrefix("sta")
.isWord("start")
.isPrefix("stx")
Output
[null, null, null, false, true, true, false]
Why

"sta" is not a word, but both "star" and "start" begin with it, so the tile is amber. "start" was added, so its tile is green. No word begins with "stx", so that tile is grey.

Example 2
Input
new TileDictionary()
.add("tea")
.isWord("tea")
.isPrefix("tea")
.isWord("te")
Output
[null, null, true, true, false]
Why

"tea" is a word and a prefix of itself, so both calls return true. "te" is only the beginning of "tea", so it is a prefix but not a word.

Constraints

  • 1 ≤ length of every word and letters argument ≤ 20
  • Only lowercase letters a to z.
  • At most 10,000 calls in total.
Start with brute force

Keep the words in a list and scan it for each query: O(n · L) for n words of length up to L. A hash set fixes isWord but not isPrefix, because a set only answers whether an exact string is present. A second set holding every prefix works, but it stores up to 20 prefixes for each word.

Hints

0 of 4 shown

Walkthrough and solution

Unlocks when you pass every test. Stuck for a while? Looking is fine too, as long as you then close it and write the code yourself.

Ctrl+Enter runs

Run your code to see results here. Run checks the examples. Submit checks every test, including hidden edge cases.

Write code