# 26.5 Exercises

## Factual

1. Suppose we use the following trie to represent a map. What would `get("sea")` return? What about `get("sell")`?

<figure><img src="https://2316889115-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FCLYj7ccqvV6l4Pt9R0w5%2Fuploads%2FYe9CtpUAFdSnKj5obfW5%2Fimage.png?alt=media&#x26;token=a27e3323-9e5e-4e56-b3b5-b76fe065288c" alt=""><figcaption></figcaption></figure>

2. Consider the Trie-based set below. What does `keysWithPrefix("sp")` return? What nodes does it visit during this call?

![](https://2316889115-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FCLYj7ccqvV6l4Pt9R0w5%2Fuploads%2FBZ0YdUF2O2Q3AOLEJSes%2Fimage.png?alt=media\&token=686669e3-3e85-4b02-a6fe-3a8ccd3a53b2)

3. What is the worst-case runtime when searching for a single word in a trie? Let $$R$$ be the size of the alphabet, and $$N$$ be the number of items in the trie, and $$L$$ be the length of the word being operated on.

<details>

<summary>Problem 1</summary>

`sea` terminates at the node with value 6. `sell` does not exist in the trie (since it does not terminate at the node with `l`, so the `get` operation returns null.

</details>

<details>

<summary>Problem 2</summary>

`keysWithPrefix` follows the prefix to the final letter of the prefix, then performs DFS from that node to get all children.&#x20;

During this procedure, it traverses the nodes `s, p, i, t, e, y`. The final return value is `spit, spite, spy`.

</details>

<details>

<summary>Problem 3</summary>

$$\Theta(L)$$. In the worst case, the word is a prefix of some other word in the trie, but is not present in the trie itself. In this case, we go through all the letters of the word.

</details>

## Metacognitive

1. Compare the worst-case number of character comparisons required to insert a word into an LLRB, hash table, and R-way trie. Let $$R$$ be the size of the alphabet, and $$N$$ be the number of items in the trie, and $$L$$ be the maximum length of any word.

<details>

<summary>Problem 1</summary>

**LLRB**: We always insert at the bottom of the LLRB, so there are $$\Theta(\log N)$$comparisons to figure out where the new node goes. Each word comparison takes up to $$L$$ character comparisons. Thus, there are $$\Theta(L \log N)$$ comparisons.

**Hash table**: In the worst case, all items hash to the same bucket. On an insertion, we must compare a word to all other words in the bucket for equality. Assuming this bucket has $$N$$ items, this takes $$\Theta(LN)$$ comparisons.

**R-way trie**: In the worst case, we follow or create $$L$$ nodes to the end of the word. Thus, there are at most $$\Theta(L)$$ comparisons.

</details>
