Glowing Letter Tiles

MediumtrieAlso known as Implement Trie (Prefix Tree)

In a phone word game, you drag your finger across letter tiles to spell words. While you drag, the trail glows: green if the letters so far already spell a word, amber if they do not yet but could still grow into one, and grey if no word starts that way, so you should let go.

The trail colour updates on every tile you touch, and the dictionary holds tens of thousands of words. The game also adds new words during a season, so the dictionary has to accept additions too.

Your task

Write a class TileDictionary:

  • constructor(): start with an empty dictionary.
  • add(word): add a word. Adding the same word twice is allowed and changes nothing.
  • isWord(letters): return true if exactly this word was added.
  • isPrefix(letters): return 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: amber. "start" was added: green. No word begins with "stx": 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 word counts as a prefix of itself, so both answers are true. "te" is only the beginning of "tea", so it is 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 every word in a list. For isWord, scan for an equal word; for isPrefix, scan for a word that starts with the letters.

Each query looks at every word, so it costs O(n · L) for n words of length up to L. A hash set fixes isWord, but not isPrefix: a set can only answer "is this exact string here?". You could also put every prefix of every word into a second set, but that stores each word up to 20 times.

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