Bitpath

Lesson 1 · Unit 04

Shared prefixes

Letters on edges, child maps and the end-of-word flag

12 exercisesabout 3 min

What you practise

  • Structure, child maps, the end-of-word flag

Try a question from this lesson

Pick one

A hash set holds the words car, cart, cat and dog. You want every word that starts with "ca". How many of the stored words does the set have to examine?

The ideas

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

Concept

A tree of letters

A trie stores words one letter per step, along paths from the root. Words that begin the same way share their first nodes: here car, cart and cat all go through the same c and the same a.

Each child is indented under its parent, and a star marks a node where a word ends. The r is starred because "car" is a word, and it is also on the way to "cart".

# (root)
#   c
#     a
#       r *
#         t *
#       t *
#   d
#     o
#       g *
// (root)
//   c
//     a
//       r *
//         t *
//       t *
//   d
//     o
//       g *
// (root)
//   c
//     a
//       r *
//         t *
//       t *
//   d
//     o
//       g *

Concept

A node is a map and a flag

Each node holds two things: a map from a letter to the child node for that letter, and a flag that is true when a word ends at this node.

The letters themselves live in the map keys, not in the nodes. Here the word "to" is built by hand.

class TrieNode:
    def __init__(self):
        self.kids = {}
        self.end = False

root = TrieNode()
t = TrieNode()
o = TrieNode()
root.kids["t"] = t
t.kids["o"] = o
o.end = True
print(len(root.kids), t.end, o.end)
class TrieNode {
  kids = new Map();
  end = false;
}
const root = new TrieNode();
const t = new TrieNode();
const o = new TrieNode();
root.kids.set("t", t);
t.kids.set("o", o);
o.end = true;
console.log(root.kids.size, t.end, o.end);
class TrieNode {
  kids = new Map<string, TrieNode>();
  end = false;
}
const root = new TrieNode();
const t = new TrieNode();
const o = new TrieNode();
root.kids.set("t", t);
t.kids.set("o", o);
o.end = true;
console.log(root.kids.size, t.end, o.end);

Python notekids is a dict from a letter to a child node. Every node starts with end as False: a fresh node ends no word.

JavaScript noteClass fields like kids = new Map() run once per object, so every node gets its own separate map.

TypeScript noteMap<string, TrieNode> says the keys are letters and the values are child nodes. Without it the map would accept anything, and get would return any.

9 more exercises in the app

  • 3× type the answer
  • 3× multiple choice
  • 1× true or false
  • 1× fill the blanks
  • 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