Glowing Letter Tiles
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)returnstrueif exactly this word was added.isPrefix(letters)returnstrueif at least one added word starts withletters. 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
new TileDictionary()
.add("star")
.add("start")
.isWord("sta")
.isPrefix("sta")
.isWord("start")
.isPrefix("stx")[null, null, null, false, true, true, false]
"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.
new TileDictionary()
.add("tea")
.isWord("tea")
.isPrefix("tea")
.isWord("te")[null, null, true, true, false]
"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- Hint 1
Write down "car", "cart" and "cat". All three share "ca", and two of them share "car". How could you store them so shared beginnings are written once?
- Hint 2
Draw a tree where each edge is one letter. Every word is a path from the root, and words with the same beginning share the start of the path. Checking a prefix means following edges letter by letter.
- Hint 3
After adding "cart", following c → a → r succeeds, but "car" was never added. What extra fact must a node remember for
isWord? - Hint 4
Make each node a map from letter to child, plus a flag
endthat says a word stops at this node.addwalks the letters, creating missing children, and setsendon the last node. Both queries walk the letters and return false at a missing child. If every letter is found,isPrefixreturns true andisWordreturns the last node'send.
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.
How to solve it
A trie (prefix tree) stores words letter by letter, sharing common beginnings. Each node stands for the letters read so far, its children are the possible next letters, and a flag says whether a word ends there.
Trace the first example:
- add "star" creates the path root → s → t → a → r and marks r as an end.
- add "start" walks the existing s, t, a and r nodes, adds a child t under r and marks it as an end.
- isWord "sta" walks s → t → a. The node exists but is not an end, so the result is false.
- isPrefix "sta" makes the same walk, which succeeds, so the result is true.
- isWord "start" walks to the second t, which is an end, so the result is true.
- isPrefix "stx" fails because there is no child x after s → t, so the result is false.
A common mistake is to leave out the end flag. Without it, "sta" counts as a word just because "star" passes through it.
class TileDictionary {
constructor() {
this.root = { kids: new Map(), end: false };
}
add(word) {
let node = this.root;
for (const ch of word) {
if (!node.kids.has(ch)) node.kids.set(ch, { kids: new Map(), end: false });
node = node.kids.get(ch);
}
node.end = true; // a word stops here
}
walk(letters) { // node reached by following letters, or null
let node = this.root;
for (const ch of letters) {
node = node.kids.get(ch);
if (!node) return null;
}
return node;
}
isWord(letters) {
const node = this.walk(letters);
return node !== null && node.end;
}
isPrefix(letters) {
return this.walk(letters) !== null;
}
}class TileDictionary:
def __init__(self):
self.root = {"kids": {}, "end": False}
def add(self, word):
node = self.root
for ch in word:
node = node["kids"].setdefault(ch, {"kids": {}, "end": False})
node["end"] = True # a word stops here
def _walk(self, letters): # node reached by following letters, or None
node = self.root
for ch in letters:
node = node["kids"].get(ch)
if node is None:
return None
return node
def is_word(self, letters):
node = self._walk(letters)
return node is not None and node["end"]
def is_prefix(self, letters):
return self._walk(letters) is not NoneRun your code to see results here. Run checks the examples. Submit checks every test, including hidden edge cases.