Bitpath

Boss lesson · Unit 04

Autocomplete

Collect every word under a prefix with a depth-first search

11 exercisesabout 3 min

What you practise

  • Collect every word under a prefix with DFS

Try a question from this lesson

Pick one

You type "ca" into a search box backed by a trie of car, cart, cat and dog. Where in the trie are all the suggestions?

The idea

Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.

Concept

The boss: autocomplete

The task: return every stored word that starts with a prefix.

Step one: walk the prefix down to its node. Step two, shown here: a depth-first search from that node. It carries the letters so far in path, and records the path whenever it stands on a flagged node.

def collect(node, path, out):
    if node.end:
        out.append(path)
    for ch, kid in node.kids.items():
        collect(kid, path + ch, out)
function collect(node, path, out) {
  if (node.end) out.push(path);
  for (const [ch, kid] of node.kids) {
    collect(kid, path + ch, out);
  }
}
function collect(
  node: TrieNode,
  path: string,
  out: string[],
): void {
  if (node.end) out.push(path);
  for (const [ch, kid] of node.kids) {
    collect(kid, path + ch, out);
  }
}

Python note.items() yields each letter with its child. path + ch builds a new string, so sibling branches cannot disturb each other.

JavaScript noteLooping over a Map yields [key, value] pairs, unpacked here as [ch, kid]: the letter and its child node.

TypeScript noteout: string[] is filled in place, so the function returns void. path: string is never changed: each call gets its own longer copy.

9 more exercises in the app

  • 3× type the answer
  • 1× fill the blanks
  • 3× multiple choice
  • 1× true or false
  • 1× match the pairs

Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.

One email when Bitpath is ready to try. Nothing else. Privacy