Delete a word from a trie without losing "car" or "cards"
Question
A search box suggests words from a trie. It holds car, card, cards, care and cat. Each node has a dict of children, one per letter, and an is_word flag.
Write delete(root, word). It returns True if the word was stored and is now gone, and False if it was not a word. The other words must stay. Nodes that no word uses any more should be removed.
root = build(["car", "card", "cards", "care", "cat"]) delete(root, "card") # True: car and cards stay delete(root, "cards") # True delete(root, "ca") # False: a path, but not a word
class Node: def __init__(self): self.children = {} # letter -> Node self.is_word = False # does a word end here? def insert(root, word): node = root for ch in word: node = node.children.setdefault(ch, Node()) node.is_word = True def build(word_list): root = Node() for word in word_list: insert(root, word) return root def words(node, prefix=""): found = [prefix] if node.is_word else [] for ch in sorted(node.children): found += words(node.children[ch], prefix + ch) return found def delete(root, word): ... # True if the word was removed
Show hints (3)
- "FIND IT FIRST"
Walk down the letters of the word. If a letter is missing, or the last node is not a word end, return
Falseand change nothing. - "TWO REASONS"
Clearing
is_wordremoves the word. A node must still stay if another word ends there, likecar, or if it has children, like the path tocards. - "WALK BACK UP"
Save each (parent, letter) pair on the way down. After clearing the flag, walk back up. Cut a child only if it is not a word end and has no children. Stop at the first node you keep.
Show checked explanation
First find the word: every letter must exist, and the last node must have is_word set. Clear the flag. Then walk back up and remove nodes that are not a word end and have no children. Stop at the first node you must keep. Delete, insert and search are O(L) for a word of length L.
def delete(root, word): path, node = [], root for ch in word: if ch not in node.children: return False path.append((node, ch)) node = node.children[ch] if not node.is_word: return False node.is_word = False for parent, ch in reversed(path): if parent.children[ch].is_word or parent.children[ch].children: break # another word still needs this node del parent.children[ch] return True root = build(["car", "card", "cards", "care", "cat"]) for word in ["card", "cards", "ca"]: print(word, delete(root, word), words(root))
card True ['car', 'cards', 'care', 'cat'] cards True ['car', 'care', 'cat'] ca False ['car', 'care', 'cat']
Code run on CPython 3.12 against the examples above. Checked by an editor other than the author.
Walkthrough
The solution uses Node, build and words from the task. The five words share one tree of 8 nodes, counting the root:
(root)
└── c
└── a
├── r*
│ ├── d*
│ │ └── s*
│ └── e*
└── t*A star marks a node where a word ends. Watch the node count:
| delete | returns | what changes | nodes |
|---|---|---|---|
| card | True | d loses its star but keeps its child s | 8 |
| cards | True | s goes, then d; r stays, it ends car | 6 |
| ca | False | a has no star, so nothing changes | 6 |
Deleting card removes no node, because d is on the way to cards. Deleting cards clears the flag on s. Now s has no star and no children, so it goes. Then d is in the same state, so it goes too. At r the walk stops, because car ends there.
Once you keep a node, you keep every node above it, since they lead to it. That is why the loop can stop at the first node it keeps.
A word can end in the middle of the tree, not only at a leaf. car ends at r, which still has children. That is why each node needs its own is_word flag.
The walk down and the walk up are both at most L steps. With dict children, each step costs O(1) on average.
Common mistakes
- Deleting every node on the word's path. All five words start with
c, so deletingcardthis way would also removecar,cards,careandcat. - Cutting nodes only because they have no children. After
cardandcardsare gone, deletingcarewould also cutr, andcarwould vanish. - Checking only that the path exists.
cais a path but not a word. ReturningTruefor it, or clearing a flag there, reports a word that was never stored. - Clearing the flag but never removing nodes. Lookups stay correct, but dead nodes pile up: after deleting
cards, the unuseddandswould stay in memory.
Follow-up questions
- "Now write
starts_with(prefix)for the suggestions." Walk the prefix letter by letter. If every letter exists, returnTrue; you don't look atis_word. After the deletes above,starts_with("ca")isTrueandstarts_with("card")isFalse. To list the suggestions, collect the words below that node. - "How many nodes can a trie have?" At most one node per letter of all the words, plus the root. Shared prefixes save space. Our five words have 19 letters but need only 8 nodes. An array of 26 child slots per node adds slots, not nodes.
- "The same word can be added twice. Delete should remove one copy. What changes?" Replace the
is_wordflag with a count. Insert adds 1 at the last node, and delete subtracts 1. A node stays while its count is above 0 or it has children.deletereturnsFalsewhen the count is already 0.
What a strong answer covers
Checks that the word exists before changing anything. Names both reasons to keep a node: a word ends there, or it has children. Prunes from the bottom up and stops early. Knows a word can end at an inner node, and that each operation is O(L).
Open in interactive practice deck →