download

Delete a word from a trie without losing "car" or "cards"

Algorithms~20 minReviewed 1 Nov 2026Free · No sign-in

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.

"PYTHON"
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
"CODE · PYTHON"
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)
  1. "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 False and change nothing.

  2. "TWO REASONS"

    Clearing is_word removes the word. A node must still stay if another word ends there, like car, or if it has children, like the path to cards.

  3. "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.

"SOLUTION · PYTHON"
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))
"OUTPUT"
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:

"TEXT"
(root)
└── c
    └── a
        ├── r*
        │   ├── d*
        │   │   └── s*
        │   └── e*
        └── t*

A star marks a node where a word ends. Watch the node count:

deletereturnswhat changesnodes
cardTrued loses its star but keeps its child s8
cardsTrues goes, then d; r stays, it ends car6
caFalsea has no star, so nothing changes6

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 deleting card this way would also remove car, cards, care and cat.
  • Cutting nodes only because they have no children. After card and cards are gone, deleting care would also cut r, and car would vanish.
  • Checking only that the path exists. ca is a path but not a word. Returning True for 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 unused d and s would stay in memory.

Follow-up questions

  • "Now write starts_with(prefix) for the suggestions." Walk the prefix letter by letter. If every letter exists, return True; you don't look at is_word. After the deletes above, starts_with("ca") is True and starts_with("card") is False. 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_word flag 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. delete returns False when 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 →

Original OfferVibe question. Topic idea from Crushing the Technical Interview (Keith Henning, 2025); text, examples and code are our own.
© 2026 OfferVibe · Text CC BY-NC-SA 4.0 · code MITFree to share and adapt with credit, not for commercial use. Code samples are free for any use.