Library/Coding patterns that get asked/Graphs, trees and tables

Tries: prefixes and autocomplete

85 min7 partsCoreFundamentalsChecked Dec 2026
Start the lessonShort steps, each with something to do
What you'll learn
  • Build a trie as dicts inside dicts with an end marker, look up a word or a prefix in time set by its length, and say what it costs in memory next to a set of the same words
  • Keep a count on each node, to count the words under a prefix in one walk and to find the shortest prefix that picks out each word
  • Collect the words under a prefix with a depth-first walk, return the best k, and choose between ranking per query and keeping the best k on every node
  • Walk a trie alongside another search, to split text into dictionary words and to find many words on one grid
  • Put every suffix of every name in one trie, count each name once per node, and find each name's shortest fragment that no other name contains
  • Delete with counts, compress a trie, match the longest IP prefix with a trie over bits, and say when a sorted list or a set of prefixes beats a trie

A fragment that finds one item, the way the coding round asks

Shortest Uncommon Substring in an Array is on Airbnb's LeetCode tag lists in two compilations (3 sources), and an Airbnb candidate reported getting it with the input in a different form (1 report). This lesson's practice problem is that shape, a toy shop's search box, in three levels:

  1. shortest_prefixes(names): each name's shortest prefix that no other name starts with.
  2. shortest_fragments(names): each name's shortest fragment, from anywhere in it, that no other name contains.
  3. FragmentIndex(names) with add, remove and fragment, which must not start over on each question.
On kite, kitten, kayak, yoyo, robot, rock and rocketReturns
kitten's shortest prefix"kitt"
rock's shortest prefixNone: rocket starts with all of it
kite's shortest fragment"ite"
rocket's shortest fragment"ke", which starts before "et"

The lesson builds it from a dict of dicts: counts on the nodes, autocomplete, walking a trie alongside another search, and every suffix in one trie. 11 steps end with a small task in the editor.

Part 1 of 7about 21 min
Dict of dicts

A trie is a dict of dicts

A search box that suggests as you type asks one question on every keystroke: which names start with what's been typed so far? A set can't answer that well. It finds tent with one hash, but for te it has to check every name.

# a key that's never a letter: a whole word ends here
END = "$"


def insert(trie, word):
    node = trie
    for ch in word:
        # the child for ch, made empty if it isn't there yet
        node = node.setdefault(ch, {})
    node[END] = True


CATALOG = ["tent", "tents", "tarp", "tea", "lamp", "lantern"]
trie = {}
for word in CATALOG:
    insert(trie, word)
print(trie["t"]["e"])
{'n': {'t': {'$': True, 's': {'$': True}}}, 'a': {'$': True}}

That's the node for te. A node is a dict from each next letter to the child node, and '$' says a whole word ends at that node. setdefault(ch, {}) follows a letter that's there and makes an empty child for one that isn't.

Here are the six items from an outdoor shop, going in one at a time.

Predict

The six words have 27 letters in all. How many nodes do they need below the top?

Pick an answer above to see the rest

The end marker is a key inside the node, so one node can be a word and a prefix

With words in the trie, every question is a lookup.

# the node that s leads to, or None
def find_node(trie, s):
    node = trie
    for ch in s:
        node = node.get(ch)
        if node is None:
            return None
    return node


def has_word(trie, word):
    node = find_node(trie, word)
    return node is not None and END in node


def has_prefix(trie, prefix):
    return find_node(trie, prefix) is not None


print(find_node(trie, "ten"))
print(has_prefix(trie, "ten"), has_word(trie, "ten"))
print(has_word(trie, "tent"), has_prefix(trie, "tex"))
{'t': {'$': True, 's': {'$': True}}}
True False
True False

Every lookup is the same walk down from the top. What decides the answer is where the walk ends:

Every lookup walks down from the top
tent
t
→
e
→
n
→
t$
an end marker there: a word
ten
t
→
e
→
nno $
the node exists, with no end marker: a prefix
tex
t
→
e
→
xno child
the walk falls off: neither

The node for ten exists, because tent passes through it, but nobody inserted ten, so it has no end marker.

tent is a word even though tents goes on below it. A node can be both, which is why the marker is a key inside the node and not a kind of node. Use a key that can't be a letter of any word: "$" works for lowercase words.

In the editor, write longest_word_prefix(trie, text). It finds the longest word at the start of three texts.

Insert and lookup take one step per letter, however many words the trie holds

Next to a plain set of words, the trie's costs look like this.

A set of n wordsA trie of n words
Is tent a word?hash all 4 letters4 steps down
Does a word start with te?look at all n words2 steps down

Insert and lookup each take one dict step per letter: O(L) for a word of L letters. That's the length of the word, not the size of the dictionary.

A set lookup is O(L) as well, because hashing a new string reads all of it. So the trie doesn't win on whole words. It wins on prefix questions, which a set can only answer with a scan.

In the editor, write lookup(trie, s): a word, a prefix, or neither, in one walk. It looks up tent, ten and tex.

In Python, a trie of 100,000 words took about 8 times a set's memory

Every node is a whole dict, and the trie pays for that in memory. Here's the measurement:

import random
import sys
import tracemalloc

with open("/usr/share/dict/words") as f:
    every = sorted({w for w in f.read().split() if w.isascii() and w.isalpha() and w.islower()})
# 968,341 letters in all
words = random.Random(7).sample(every, 100_000)

tracemalloc.start()
trie = {}
for word in words:
    insert(trie, word)
trie_bytes = tracemalloc.get_traced_memory()[0]
tracemalloc.stop()

tracemalloc.start()
word_set = set(words)
set_bytes = tracemalloc.get_traced_memory()[0] + sum(sys.getsizeof(w) for w in words)
tracemalloc.stop()

The word list for every large measurement in this lesson is these 100,000 words, drawn at random from the lowercase words in /usr/share/dict/words, the list that ships with macOS.

Predict

sys.getsizeof({"a": {}}) returns a size in bytes. Does that number include the inner dict?

Pick an answer above to see the rest

The same insert nests any path of keys, such as dotted parameter names

A prep site lists turning flat parameter names into a nested dict grouped by layer as a Netflix machine learning engineer question (1 source). It's trie insertion, with the parts between the dots as the letters:

from pprint import pprint


def nest(flat):
    nested = {}
    for key, value in flat.items():
        *path, last = key.split(".")
        node = nested
        for part in path:
            node = node.setdefault(part, {})
        node[last] = value
    return nested


flat = {"layers.0.weight": 0.12, "layers.0.bias": 0.5,
        "layers.1.weight": -0.3, "head.weight": 1.7}
pprint(nest(flat), width=60, sort_dicts=False)
Predict

nest() runs on layers.0.weight, then on layers.0.bias. What happens at the second key?

Pick one to see what it prints.
Pick an answer above to see the rest
Part 1 done
Part 2 of 7about 6 min
Counts

Counts on the nodes

Each node can also count the words that pass through it.

# how many words pass through or end at this node
COUNT = "#"


def insert_counted(trie, word):
    node = trie
    # the top: every word starts with the empty string
    node[COUNT] = node.get(COUNT, 0) + 1
    for ch in word:
        node = node.setdefault(ch, {})
        node[COUNT] = node.get(COUNT, 0) + 1
    node[END] = True


def count_prefix(trie, prefix):
    node = find_node(trie, prefix)
    return 0 if node is None else node.get(COUNT, 0)


counted = {}
for word in CATALOG:
    insert_counted(counted, word)
print([count_prefix(counted, p) for p in ["", "t", "te", "ten", "tents", "l", "lan", "x"]])
Predict

What is count_prefix(counted, ""), the count on the top?

Pick one to see what it prints.
Pick an answer above to see the rest

A word's shortest unique prefix ends where the count first drops to 1, and a word that starts another has none

The counts answer level 1 of the practice problem directly.

Predict

Walk lamp down its path. Where does the count first drop to 1?

Pick an answer above to see the rest
Part 2 done
Part 3 of 7about 12 min
Autocomplete

Autocomplete: the best k under a prefix

Autocomplete asks for the best few words under what's been typed.

Typing te should show a few suggestions, the best first. That's two steps: find the node for the prefix, then collect every word below it. The collecting is the depth-first-search lesson's walk with your own stack, carrying the string spelled so far. Let the end marker hold each word's score, so the walk can rank:

import heapq


def insert_scored(trie, word, score):
    node = trie
    for ch in word:
        node = node.setdefault(ch, {})
    # the marker now carries the word's score
    node[END] = score


# highest score first, ties in alphabetical order
def best_k(trie, prefix, k):
    pairs = words_under(trie, prefix)
    return [word for _, word in heapq.nsmallest(k, pairs, key=lambda p: (-p[0], p[1]))]


SCORES = {"tent": 120, "tents": 45, "tarp": 120, "tea": 300, "lamp": 95, "lantern": 60}
scored = {}
for word, score in SCORES.items():
    insert_scored(scored, word, score)
print(words_under(scored, "te"))
print(best_k(scored, "t", 3))
print(best_k(scored, "tent", 3))
print(best_k(scored, "x", 3))
Predict

best_k(scored, "t", 3), with tea 300, tarp 120, tent 120 and tents 45. What comes back?

Pick one to see what it prints.
Pick an answer above to see the rest
Predict

words_under pushes ten, then tea, and pops from the end of its stack. Which word does it find first?

Pick an answer above to see the rest

Ranking at query time costs the most on a short prefix, whose subtree is huge

The cost has three parts:

  • Find the node for a prefix of p letters: O(p).
  • Walk the s nodes under it: O(s).
  • Rank its m words: O(m log k).

A short prefix has a huge subtree.

On the 100,000 words, each scored in sample order by rng = random.Random(3) with rng.randint(1, 1_000_000), with k = 5 and the best of 7 runs:

best_k on the 100,000 words, log scale
s: 10,679 words under it
7,154 µs
co: 3,008
1,943 µs
pre: 1,480
981 µs
trans: 238
163 µs
zyx: 0
0.4 µs

Seven milliseconds on the first keystroke, and the first keystroke is the one every user types.

Keeping the best k on every node makes a suggestion one walk, but a lower score is costly

The other end of the trade: store on each node the best k words of its subtree, already in order. Then a suggestion is the walk to the node and nothing more. On the six items with k = 3:

NodeIts best 3, highest score first
ttea 300, tarp 120, tent 120
tetea 300, tent 120, tents 45
tentent 120, tents 45
tatarp 120
llamp 95, lantern 60

An insert now updates the list on every node along the word's path: O(L · k log k) for L letters. Inserting tea put it on the lists at t, te and tea.

Same 100,000 words, k = 5, builds timed with tracemalloc off as before:

k = 5Rank at query timeBest 5 kept on every node
Build132 ms566 ms
Memory69.8 MiB151.5 MiB
Suggest for s7,154 µs0.3 µs
Suggest for trans163 µs0.3 µs

Memory more than doubles, and building takes 4.3 times as long.

The bigger catch is change. When a word's score goes up, walk its path and re-sort each list. When it goes down, a node may need the next best word from below, and only a walk of the subtree finds it.

A middle way keeps lists only on the top two or three levels, where the subtrees are big and the query time goes.

In the editor, finish insert_ranked(trie, word, score, k). It suggests the best 3 under t and under la.

Part 3 done
Part 4 of 7about 7 min
Walking alongside

The trie's real edge over a set: you can walk it one letter at a time and stop the moment no word goes on. Any search that reads text letter by letter can carry a trie node along.

Word Break, on Netflix's LeetCode company tag list (1 source), is the cleanest case: can text be cut into a sequence of dictionary words?

# words is a set
def can_split_slices(text, words):
    # ok[i]: text[:i] splits into words
    ok = [True] + [False] * len(text)
    for end in range(1, len(text) + 1):
        for start in range(end):
            if ok[start] and text[start:end] in words:
                ok[end] = True
                break
    return ok[-1]


GEAR = ["tent", "tents", "pole", "poles", "stake", "take", "takes"]
print(can_split_slices("tentspole", set(GEAR)), can_split_slices("tentpol", set(GEAR)))
True False

The usual answer is a table. ok[i] is True when text[:i] splits into words. ok[0] is True for the empty split. ok[end] becomes True when some start has ok[start] and text[start:end] is in the word set.

Predict

can_split_slices on a text of 1,000 letters, at worst: about how many slices does it try?

Pick an answer above to see the rest

Walk the trie from each start the table reached, and stop when no word goes on

A trie lets the same table skip the slices altogether. Call the new version can_split(text, trie). It keeps the ok table, but its outer loop runs over starts instead of ends.

A start that ok hasn't reached is skipped: no split gets there, so no word can start there. From a start it has reached, walk the trie along the text one letter at a time, the way lookup does. Step to the child for text[end], and stop the moment there's no child, because no word goes on. Wherever the node you reach holds the end marker, a word ends after text[end], so set ok[end + 1] to True.

On the gear words it gives True for tentspole and False for tentpol, the same answers as the slices.

To count the splits instead, keep a number in each cell. ways[i] is how many ways text[:i] splits, with ways[0] = 1 for the empty split. Where the yes-or-no version sets True, add ways[start] to the cell past the word's end.

Predict

On tentspole, the walk from start 0 goes t, e, n, t, s, and then meets p. Which ok entries does it mark?

Pick an answer above to see the rest

On these texts, the trie walk was about six times faster than the bounded slices

Then measure all three versions on the same texts.

Predict

Double the text, from 1,001 letters to 2,009. About how much longer does can_split_slices take?

Pick an answer above to see the rest
Part 4 done
Part 5 of 7about 12 min
Every suffix

Every suffix in one trie

Level 2 of the practice problem asks about fragments from anywhere in a name, and a trie only answers prefixes. One observation fixes that, so that one trie holds them all:

The suffixes of lantern, each with a fragment that starts it
lantern
lantern
antern
antern
ntern
ntern
tern
tern
ern
ern
rn
rn
n
n

Green: lan, an, nte, ter, er, rn and n, each the start of a suffix.

Every fragment of a name is a prefix of one of its suffixes. ter in lantern is how the suffix tern starts. So insert every suffix, and every fragment becomes a path from the top.

Sedgewick and Wayne's Algorithms book gives the same trick for substring search. Their trie is laid out as a TST, a ternary search trie, which is another way to arrange a trie's nodes.

Put a count on each node: the number of names that contain its fragment. A name's shortest fragment that no other name contains is then the shortest walk, from any starting letter of the name, down to a node whose count is 1.

Walk from every start until a count is 1, and keep a later fragment only if it's shorter

Here is an insert, with a bug that gets fixed below, and the query:

# counts every visit: wrong when a fragment repeats
def add_suffixes(trie, name):
    for start in range(len(name)):
        node = trie
        for ch in name[start:]:
            node = node.setdefault(ch, {})
            node[COUNT] = node.get(COUNT, 0) + 1


def shortest_fragment(trie, name):
    best = None
    for start in range(len(name)):
        node = trie
        for end in range(start, len(name)):
            if best is not None and end - start + 1 >= len(best):
                # can't beat best from here, and a tie keeps the earlier one
                break
            node = node[name[end]]
            if node[COUNT] == 1:
                best = name[start : end + 1]
                break
    return best


fragments = {}
for name in CATALOG:
    add_suffixes(fragments, name)
for name in CATALOG:
    print(name, shortest_fragment(fragments, name))
Predict

Among the six items, what is lamp's shortest fragment that no other name contains?

Pick one to see what it prints.
Pick an answer above to see the rest

Count names, not visits, because one name can reach a node twice

add_suffixes adds 1 every time a name's walk passes a node, and one name can pass the same node twice. Three toys show it, ["yoyo", "kayak", "pole"]. Here is yoyo going in:

The suffixes of yoyo, as paths from the top
yoyo
yoyo
oyo
oyo
yo: the y and yo nodes again
yo
o: the o node again
o
a node this name already reached

So yo gets 2 from yoyo alone. Here are the counts both ways:

Fragment: the names with itCount by visitsCount by names
y: yoyo, kayak32
yo: yoyo21
o: yoyo, pole32
k: kayak21
a: kayak21

Counting visits gives yoyo the answer oy and kayak the answer ka. Both are wrong.

yo is in no other name, but it appears twice in yoyo, so its count is 2 and the query walks past it. kayak has two ks and nobody else has one, yet k counts 2.

The count has to mean names. So a name adds 1 to a node once, however often it gets there. The right answers are yo and k.

To remember which nodes one name has counted, keep a set for the length of one insert. A node is a dict, and a dict can't go in a set: it's mutable, so it's unhashable, as in the hash-maps lesson.

Its id can go in a set. id(node) is an integer that's unique to that object and stays the same while the object exists. Every node stays alive in the trie, so no id gets reused during the insert.

In the editor, finish add_name(trie, name). It adds three names and prints two counts: yo, twice in one name, and kit, in two names.

Adding or removing a name of L letters takes about L²/2 dict steps

Each name takes one walk from every start, so its cost grows with its length.

Predict

A name of 20 letters goes in, with one walk from each start. About how many dict steps is that?

Pick an answer above to see the rest

A Counter of fragments was smaller for short names, and the trie for a name of 1,000 letters

The same counts also fit in a Counter keyed by the fragment itself, where a set does the once-per-name rule for free:

from collections import Counter

counts = Counter()
for name in ["ana", "anna"]:
    counts.update({name[i:j] for i in range(len(name)) for j in range(i + 1, len(name) + 1)})
print(counts["a"], counts["an"], counts["nn"])
2 2 1

a shows up twice in each name, and still counts once for each: 2 names, so 2.

Predict

One name of 1,000 letters goes into a Counter of fragments. About how many letters do its fragment strings hold in all?

Pick an answer above to see the rest
Part 5 done
Part 6 of 7about 6 min
The worked example

A worked example: many words on one grid

The prompt: given a grid of letters and a list of words, return every word that can be spelled along a path of cells that share a side, using no cell twice in one word. This is LeetCode's Word Search II, the many-words version of the word search question on Netflix's list (1 source).

1. Clarify. Can two words share cells? Yes, each word is its own path. Report a word once even if the grid spells it twice, and return them sorted. How big? Say a 6 by 6 grid and up to 100,000 words. Those sizes pick the design.

2. The obvious answer. Run the depth-first-search lesson's one-word grid search once per word. It's correct and already written.

Its cost grows with the number of words. And every word that starts with ca re-walks the same ca paths as every other one.

Put every word in one trie, and carry its node along one search from each cell

3. The insight. Put all the words in one trie, and run one depth-first search from each cell, carrying the trie node for the path so far. A step into a neighbor happens only if the trie has a child for that cell's letter. A path that no word continues dies at once, and a path that a thousand words share is walked once.

SIDES = ((-1, 0), (1, 0), (0, -1), (0, 1))


def words_on_grid(grid, words):
    trie = {}
    for word in words:
        node = trie
        for ch in word:
            node = node.setdefault(ch, {})
        # the marker holds the word, so a find builds no string
        node[END] = word
    rows, cols = len(grid), len(grid[0])
    found, used = [], set()

    def visit(r, c, parent):
        node = parent.get(grid[r][c])
        if node is None:
            # no word goes on with this letter
            return
        if END in node:
            # report it once, then forget it
            found.append(node.pop(END))
        used.add((r, c))
        for dr, dc in SIDES:
            nr, nc = r + dr, c + dc
            if 0 <= nr < rows and 0 <= nc < cols and (nr, nc) not in used:
                visit(nr, nc, node)
        # the undo step
        used.remove((r, c))
        if not node:
            # nothing left to find below: cut the branch
            del parent[grid[r][c]]

    for r in range(rows):
        for c in range(cols):
            visit(r, c, trie)
    return sorted(found)


GRID = ["tarp", "ento", "aesl"]
WORDS = ["tent", "tents", "tea", "tarp", "stop", "pots", "top", "sea", "lamp", "seal"]
print(words_on_grid(GRID, WORDS))
Predict

The grid's rows are tarp, ento and aesl. Which of these words does it not spell: tea, stop or seal?

Pick one to see what it prints.
Pick an answer above to see the rest

Trace it on a small grid: a path dies as soon as no word goes on

4. Trace it. The grid is passed one row per string, ["tarp", "ento", "aesl"]. Here it is, with the cells of four of the words found:

The grid, and the path of each word
grid
tarpentoaesl
tarp
tarpentoaesl
tea
tarpentoaesl
tents
tarpentoaesl
stop
tarpentoaesl

tent is the first four cells of tents. pots and top run the same cells as stop, and sea runs along the bottom row.

lamp never starts. The one l sits in the bottom-right corner, next to o and s, and the trie wants an a after l.

Test the edges, then measure: at 100,000 words, building the trie took most of the time

5. Edge cases.

  • A word of one letter is found at the first cell with that letter.
  • The same word listed twice makes one path and one marker, so it's reported once.
  • A word longer than the number of cells can never be found, and the search finds that out without trying it specially.
  • The recursion goes as deep as the longest word, 24 letters in the big list below, so the recursion limit isn't a concern here.

6. Cost, measured. The grid, one row per string: ["hlxhhr", "uaarhc", "czathi", "tedgme", "ushmbc", "macede"]. The words are the first 1,000, 10,000 and 100,000 of the sample, one run each:

WordsOne search per wordOne trie
1,0009.7 ms0.9 ms
10,00086.8 ms8.6 ms
100,000861.1 ms172.5 ms

They found 0, 4 and 47 words.

The trie version's time is mostly building the trie: building it alone for the 100,000 words took 140.4 ms. Say that trade out loud.

If the same word list is searched on many grids, remember that pop and del change the trie. Rebuild it per grid, since a copy.deepcopy of it took about three times as long as a fresh build. Or drop both the pop and the del, and collect the found words in a set.

Watch · 16 min

The same plan as this worked example, one trie for all the words and a depth-first search from each cell. Drawn from 5:06 and coded from 12:32.

Word Search II - Backtracking Trie - Leetcode 212 - Python · NeetCode · Jun 2021YouTube
Part 6 done
Part 7 of 7about 21 min
Follow-ups

Delete a word by lowering the counts, and drop a branch when its count reaches 0

With counts, deleting is the insert run backwards, plus one decision: drop a branch as soon as no word uses it.

Sedgewick and Wayne name the two styles. A lazy delete only removes the marker. An eager delete also cleans up the links to parts of the trie that no word uses any more.

shop = {}
for word in CATALOG:
    insert_counted(shop, word)
print(remove(shop, "tents"), has_word(shop, "tent"), count_prefix(shop, "te"))
print(remove(shop, "lantern"), has_word(shop, "lamp"), count_prefix(shop, "la"))
print(remove(shop, "ten"))
Predict

remove(shop, "tents") runs on the six items. What is count_prefix(shop, "te") after it?

Pick one to see what it prints.
Pick an answer above to see the rest

A compressed trie merges chains of single children: 29.0 MiB against 69.8 on the 100,000 words

Of the 395,243 nodes in the 100,000-word trie, top included, 262,658 have exactly one child and 87,811 have none. A compressed trie, also called a radix tree, merges every chain of single children into one edge labeled with a string.

Predict

Merge every chain of single children on the six items. They had 18 nodes below the top. How many are left?

Pick an answer above to see the rest

A router forwards by the longest matching prefix, and a trie over 32 bits finds it in one walk

A router sends a packet by the most specific route that covers its address. RFC 4632 puts it in one line: "Forwarding in the Internet is done on a longest-match basis." Sedgewick and Wayne's example is an address, 128.112.136.12, that goes to the route for 128.112 because that's the longest matching prefix the table knows.

A route like 128.112.0.0/16 covers every address whose first 16 bits match. So a trie over bits, two children per node, answers it in one walk. Insert each route's first bits. Then walk an address's 32 bits, and remember the last route you passed:

import ipaddress


def add_route(trie, cidr, hop):
    net = ipaddress.ip_network(cidr)
    bits = format(int(net.network_address), "032b")[: net.prefixlen]
    node = trie
    for bit in bits:
        node = node.setdefault(bit, {})
    node[END] = hop


routes = {}
add_route(routes, "0.0.0.0/0", "default")
add_route(routes, "128.112.0.0/16", "campus")
add_route(routes, "128.112.136.0/24", "lab")
print([next_hop(routes, a) for a in ["128.112.136.12", "128.112.9.9", "8.8.8.8"]])
Predict

Routes: 0.0.0.0/0 goes to default, 128.112.0.0/16 to campus and 128.112.136.0/24 to lab. Where does 128.112.9.9 go?

Pick one to see what it prints.
Pick an answer above to see the rest

For a fixed word list and prefix questions only, a sorted list or a set of prefixes can beat a trie

Two simpler structures answer prefix questions:

from bisect import bisect_left

ordered = sorted(CATALOG)
prefixes = {word[:i] for word in CATALOG for i in range(1, len(word) + 1)}


def has_prefix_bisect(p):
    # where p would go: every word from here on is >= p
    i = bisect_left(ordered, p)
    return i < len(ordered) and ordered[i].startswith(p)


def count_prefix_bisect(p):
    return bisect_left(ordered, p + "{") - bisect_left(ordered, p)


print(ordered)
print(has_prefix_bisect("te"), count_prefix_bisect("te"), count_prefix_bisect("x"))
print(len(prefixes), "te" in prefixes)
Predict

ordered is ['lamp', 'lantern', 'tarp', 'tea', 'tent', 'tents']. What is bisect_left(ordered, "te")?

Pick one to see what it prints.
Pick an answer above to see the rest
Predict

Which answers "is this a prefix?" fastest: the trie, the sorted list or the set of every prefix?

Pick an answer above to see the rest
Predict

Sorted, the items read lamp, lantern, tarp, tea, tent, tents. What is lantern's shortest unique prefix?

Pick a trie when the search walks it letter by letter, its nodes carry changing data, or the keys are bits

So which would you use?

  • For a fixed word list and prefix questions only, the sorted list: it's the smallest, and it counts and lists.
  • For yes or no on prefixes, many times, the set of prefixes.
  • The trie wins when the search walks letter by letter alongside something else, as in word break and the grid. It also wins when nodes carry data that changes, like counts with deletions, and when the keys are bits.

Say the honest version out loud. Knowing what a trie costs, and when not to build one, is what shows you've used one.

For a million items, build each prefix's best k offline and serve it from a key-value store

A prep site's guide for Netflix machine learning engineers lists type-ahead suggestions for titles as a design question (1 source).

At that scale, ranking per keystroke from a trie in one process isn't the design. Build each prefix's best k offline, keep them in a key-value store keyed by the prefix, and make each keystroke one lookup.

For the practice problem's fragments, a million names would need about L²/2 nodes each. So index fragments of one fixed length, such as every fragment of 3 letters, and check only the candidates they point to.

Palindrome Pairs can use a trie of the words reversed

Palindrome Pairs, on Airbnb's LeetCode company tag list with the trie tag (1 source), is the hard one in this family: find every pair of words whose concatenation reads the same backwards.

The trie holds the words reversed, and each word walks down it, checking whether what's left over is a palindrome. Write the slow version first, a check of every pair, then reach for the trie.

The tests you'd write cover a word inside another, empty and missing prefixes, and repeats

Test the cases a trie gets wrong first.

  • A word that's a prefix of another, in both orders of insertion.
  • The empty prefix.
  • A prefix nobody has.
  • A word inserted twice, if the caller can do that.
  • Deleting a word that isn't there, and deleting the only word under a branch.
  • For fragments: a fragment repeated inside one name, a name inside another, a tie between two fragments of the same length, and removing then adding back the same name.

The practice problem, start to finish

That's every piece the practice problem needs. It asks for the three levels from the start of the lesson, from a blank file, and the interviewer follows up after each one.

Check yourself
6 questions
  1. 1.A trie holds tent and tents, and nobody inserted ten. What tells you ten isn't a word?

  2. 2.What does checking whether some word starts with a prefix of p letters cost in a trie of n words?

  3. 3.You count, on every node, the words that pass through it. Which word has no prefix that only it starts with, among tent, tents and tarp?

  4. 4.Autocomplete keeps the best k words on every node. What gets expensive?

  5. 5.Every suffix of yoyo, kayak and pole goes in one trie, and each node counts every visit. What does yoyo get as its shortest unique fragment, and why?

  6. 6.You have a fixed list of 100,000 words and must count the words under a prefix, with memory tight. What would you use?

Practice

Sources (10)
  1. Built-in Types: dict.setdefault · Python 3.12 documentation · Oct 26, 2026
    “If key is in the dictionary, return its value. If not, insert key with a value of default and return default.”
  2. sys.getsizeof · Python 3.12 documentation · Oct 26, 2026
    “Only the memory consumption directly attributed to the object is accounted for, not the memory consumption of objects it refers to.”
  3. tracemalloc: Trace memory allocations · Python 3.12 documentation · Oct 26, 2026
    “The tracemalloc module is a debug tool to trace memory blocks allocated by Python.”
  4. heapq: nsmallest · Python 3.12 documentation · Oct 26, 2026
    “Return a list with the n smallest elements from the dataset defined by iterable.”
  5. Built-in Functions: id · Python 3.12 documentation · Oct 26, 2026
    “This is an integer which is guaranteed to be unique and constant for this object during its lifetime.”
  6. bisect: bisect_left · Python 3.12 documentation · Oct 26, 2026
    “The returned insertion point ip partitions the array a into two slices such that all(elem < x for elem in a[lo : ip]) is true for the left slice and all(elem >= x for elem in a[ip : hi]) is true for the right slice.”
  7. 5.2 Tries: Substring matches · Algorithms, 4th Edition (Sedgewick and Wayne), booksite · Jun 12, 2020
    “To support substring matches, insert the suffixes of each word (e.g., string, tring, ring, ing, ng, g) into the TST.”
  8. 5.2 Tries: deletion · Algorithms, 4th Edition (Sedgewick and Wayne), booksite · Jun 12, 2020
    “Eager delete = clean up any dead parent links.”
  9. 5.2 Tries: longest matching prefix · Algorithms, 4th Edition (Sedgewick and Wayne), booksite · Jun 12, 2020
    “IP routing table wants to forward to 128.112.136.12, instead forwards to 128.112 which is longest matching prefix that it knows about.”
  10. RFC 4632: Classless Inter-domain Routing (CIDR), section 5.1 · IETF, RFC Editor · Aug 1, 2006
    “Forwarding in the Internet is done on a longest-match basis.”