Chapter 11: Tries

Chapter 11: Tries · Study Questions
The trie conceptInsertionSearch and prefix queriesAutocompleteDeletionTime and memoryCompressed and suffix tries
Sercan KÜLCÜ · Giresun University · Computer Engineering

Output Question · The Trie Concept

Question 1: Number of Nodes and nulls

The words ev, evli, eski, es, ekmek are inserted into a trie that uses a 26-element array. Draw the trie. How many nodes are there including the root, and how many child references are null in total?

Show answer evliskikmek
  • Nodes: e · ev, evl, evli · es, esk, eski · ek, ekm, ekme, ekmek → 11 + root = 12 (17 characters).
  • References: 12 × 26 = 312; the used ones equal the number of edges (11) → 301 nulls (≈ 96%).
  • "ev" and "es" are both words and prefixes of other words; only the isEnd mark shows this (double circle).

Step-by-Step Trace · Insertion

Question 2: insert("kara") Trace

With "kar" and "kale" already in the trie, how many new nodes does insert("kara") create?

karle

The trie holds "kar" and "kale". node starts at the root.

karle

'k' → i = 10; children[10] is set → no new node needed, move to node "k" (shared prefix).

karle

'a' → i = 0; children[0] is set → no new node needed, move to node "ka" (shared prefix).

karle

'r' → i = 17; children[17] is set → no new node needed, move to node "kar" (shared prefix).

karlea

'a' → i = 0; children[0] == null → a new TrieNode is created and linked (blue).

karlea

node is now the "kara" node.

karlea

Loop finished: isEnd = true (double circle). Only 1 new node was created; the prefix "kar" was shared. O(L).

public void insert(String word) {
  TrieNode node = root;
  for (char ch : word.toCharArray()) {
    int i = ch - 'a';
    if (node.children[i] == null)
      node.children[i] = new TrieNode();
    node = node.children[i];
  }
  node.isEnd = true;
}

Multiple Choice · Insertion

Question 3: Inserting a Word That Is a Prefix

With only kalem in the trie, what happens when insert("ka") is called?

D: the k and a branches already exist; the loop only moves forward and the final node gets marked. C is wrong: the path existed but "ka" was not a word; after the insert, search("ka") returns true. "kalem" is unaffected.

Output Question · Search

Question 4: search and startsWith

What does the following code print for a trie containing kale, kalem, kar, kara?

// trie: kale, kalem, kar, kara
System.out.println(search("kal"));
System.out.println(startsWith("kal"));
System.out.println(search("kara"));
System.out.println(search("karar"));
System.out.println(startsWith("kx"));
Show answer
false
true
true
false
false
  • "kal": the path exists, but isEnd is false → search false, startsWith true.
  • "kara": marked node → true. "karar": no r branch after "kara" → early false.
  • "kx": no x branch after k → false.
kalemra

Multiple Choice · Search

Question 5: Path Exists but Word Does Not

The trie holds and, ant, dad, do. Which of the following calls returns false even though the whole path being searched exists in the trie?

andtdado

D: the path a → n exists, but the "an" node has isEnd = false; "an" is only a prefix of and and ant. For dog and ab a branch is missing (no g after do, no b after a) and the loop returns false early; dad returns true.

Multiple Choice · Search

Question 6: Forgetting isEnd

If the last line of search is written as return true; instead of return node.isEnd;, what does the method turn into?

A: The loop still returns false when it hits a missing branch, but if the path exists it returns true without checking the mark: this is exactly startsWith. If the trie contains a "da" node, search("da") now wrongly returns true. C is wrong: the return false line still runs.

Step-by-Step Trace · Autocomplete

Question 7: complete("ka") Trace

With kar, kale, kalem, kas, at in the trie, which list does complete("ka") return?

karlemsat

Trie: kar, kale, kalem, kas, at. findNode("ka") goes down k → a from the root to find the prefix node.

karlemsat

collect("ka"): "ka" is not a word (isEnd = false); the children will be visited in index order: 'l', 'r', 's'.

karlemsat

collect("kal"): "kal" is not a word (isEnd = false); the children will be visited in index order: 'e'.

karlemsat

"kale" is marked → added to result: result = [kale].

karlemsat

"kalem" is marked → added to result: result = [kale, kalem].

karlemsat

"kar" is marked → added to result: result = [kale, kalem, kar].

karlemsat

"kas" is marked → added to result: result = [kale, kalem, kar, kas].

karlemsat

All calls have returned: complete("ka") → [kale, kalem, kar, kas]. "at" is never visited; only the subtree of the prefix node is traversed.

List<String> complete(String prefix) {
  List<String> result = new ArrayList<>();
  TrieNode d = findNode(prefix);
  if (d != null)
    collect(d, new StringBuilder(prefix), result);
  return result;
}
void collect(TrieNode d, StringBuilder path,
             List<String> result) {
  if (d.isEnd) result.add(path.toString());
  for (int i = 0; i < 26; i++)
    if (d.children[i] != null) {
      path.append((char) ('a' + i));
      collect(d.children[i], path, result);
      path.setLength(path.length() - 1);
    }
}

Output Question · Autocomplete

Question 8: Output of complete

What does the code print for a trie in which the words bal, ba, bas, bat, baba were inserted in this order?

// trie: bal, ba, bas, bat, baba
System.out.println(complete("ba"));
System.out.println(complete("bx"));
System.out.println(complete("bas"));
Show answer
[ba, baba, bal, bas, bat]
[]
[bas]
  • collect first adds the node itself ("ba" is marked), then visits the children in index order: b (1) < l (11) < s (18) < t (19).
  • The insertion order does not affect the result; the output is always alphabetical.
  • No "bx" node → findNode returns null → empty list.

Step-by-Step Trace · Deletion

Question 9: delete("kalem") Trace

With ka, kalem, kas in the trie, how many nodes does delete(root, "kalem", 0) delete?

kalems

Trie: ka, kalem, kas. delete descends to the end of the word; decisions are made on the way back.

kalems

k → a → l → e → m: each level calls delete(c, k, j + 1); 6 frames on the stack.

kalems

j == 5: isEnd = false; no children → true (parent may remove it).

kales

"kale" drops its child (children[12] = null); unmarked, childless → true.

kals

"kal" drops its child (children[4] = null); unmarked, childless → true.

kas

"ka" drops child l, but it is a word and has child s → false: stop.

kas

Root gets false. 3 nodes (m, e, l) deleted; ka and kas remain.

// true: the parent may remove d
boolean delete(TrieNode d, String k, int j) {
  if (j == k.length()) {        // end of word
    if (!d.isEnd) return false;
    d.isEnd = false;
    return isEmpty(d);            // childless?
  }
  int i = k.charAt(j) - 'a';
  TrieNode c = d.children[i];
  if (c == null) return false;  // no such word
  if (delete(c, k, j + 1)) {
    d.children[i] = null;          // remove the child
    return !d.isEnd && isEmpty(d);
  }
  return false;
}

Output Question · Deletion

Question 10: Numbers of Deleted Nodes

Each deletion is applied separately to the initial trie built from car, card, care, cat. How many nodes do delete("card"), delete("cat") and delete("ca") each delete? With the trie kol, kola, kolay, how many nodes does delete("kola") delete?

Show answer
  • delete("card"): the d node is left childless and unmarked → removed; it stops at "car" because "car" is marked → 1.
  • delete("cat"): t is removed; "ca" is unmarked but has the child r → 1.
  • delete("ca"): "ca" is not a word (isEnd false) → nothing changes → 0 (case 3).
  • delete("kola"): only the mark is cleared; the "kola" node has a child y ("kolay") → 0 (case 1).
cardet

Multiple Choice · Deletion

Question 11: Faulty Deletion

A student writes deletion as "set every node on the word's path to null, starting from the root". With app, apple, apt in the trie, what happens when delete("app") is called?

C: Setting the a branch of the root to null loses everything that starts with a (app, apple, apt). Correct deletion only clears isEnd and removes childless, unmarked nodes bottom-up; since "app" has a child l, no node is removed.

Multiple Choice · Analysis

Question 12: Search Time

A trie holds n = 1,000,000 words; the searched word has length L = 8. In the worst case, how many node steps does search take?

A: One child is followed per character; the number of words does not affect the time → O(L). D is the cost of a balanced BST (log n comparisons, each O(L)); C is word-by-word comparison in a plain list.

Multiple Choice · Analysis

Question 13: Trie or Hash Table?

In a dictionary application, which of the following operations cannot be done efficiently with a hash table but takes O(P) in a trie?

B: The hash values of "ki" and "kitap" are unrelated; for a prefix query a hash table has to scan the whole table. In a trie, following the path k → i is enough. Inserting, searching and deleting whole words are O(L) in both structures (hashing also reads L characters).

Output Question · Analysis

Question 14: Character Outside the Alphabet

Using the lecture's insert and search methods written with the 26-element array, what does this code print? If an error occurs, explain why.

TrieNode root = new TrieNode();
insert("kale");
System.out.println(search("kale"));
insert("çay");
System.out.println("done");
Show answer
true

Then the program terminates with an ArrayIndexOutOfBoundsException (index 134).

'ç' is Unicode 231: 231 − 97 = 134 ≥ 26 → node.children[134] exceeds the array bounds; "done" is not printed. Uppercase letters are a problem too: 'A' − 'a' = −32.

Fix: convert the input to lowercase and to the a–z alphabet, or store the children in a HashMap<Character, TrieNode> (works for any alphabet).

Multiple Choice · Analysis

Question 15: Choosing the Child Representation

For a large dictionary that includes Turkish characters (ç, ğ, ı, ö, ş, ü), which child representation keeps the memory per node small and works with any alphabet?

C: A HashMap takes space only for the children that exist and any character can be a key; access is O(1) on average. A overflows the index on Turkish letters; B allocates 65,536 references per node; D is not enough to build a tree.

Output Question · Variants

Question 16: Longest Prefix Match

In a router's binary trie the routes are: 1* → A, 10* → B, 101* → C, 0* → D. Which route do packets with addresses starting 1001…, 1011…, 0110… and 1100… take?

Show answer 1010
  • 1001…: 1 (A) → 10 (B) → no 100 node → the last route seen on the way is B.
  • 1011…: 1 → 10 → 101 (C) → C.
  • 0110…: 0 (D) → no 01 → D.
  • 1100…: 1 (A) → no 11 → A.

While descending from the root, remember the last marked (route) node: longest prefix match takes O(address length).

Multiple Choice · Variants

Question 17: Compressed Trie

For the words test, toaster, toasting, slow, slowly the standard trie has 19 nodes excluding the root. When chains of single-child, unmarked nodes are merged (compressed trie), how many nodes remain excluding the root?

B: The remaining nodes: t (two branches: e, o), test, toast (branches: e, i), toaster, toasting, slow (a word that also continues), slowly → 7. Edges now carry substrings ("oast", "ly"). 5 is just the number of words; the branching nodes are needed too.

Classic Question · Variants

Question 18: Longest Common Prefix

Design a method String longestCommonPrefix() that finds the longest common prefix of all the words in the trie. What is the result for kalem, kale, kalemlik? What is the complexity?

Show answer

Descend from the root; move on while the node has exactly one child and is not the end of a word, collecting the characters passed.

String enUzunOrtakOnek() {
  StringBuilder s = new StringBuilder();
  TrieNode d = root;
  while (!d.isEnd && onlyChild(d) >= 0) {
    int i = onlyChild(d); // -1 if none
    s.append((char) ('a' + i));
    d = d.children[i];
  }
  return s.toString();
}

kalem, kale, kalemlik → k-a-l-e is a single chain; the "kale" node is marked → stop: "kale". Without the mark check, the chain does not branch, so we would descend all the way to "kalemlik"; yet the common prefix cannot be longer than "kale", which is one of the words. Time O(P · M) (P: prefix length, M = 26: onlyChild scans M cells at every node).

The End

Chapter 11: Tries: Study Questions
Lecture slides: Chapter 11: Tries · Lecture notes
1 / 1 Sercan KÜLCÜ. All rights reserved.