Embercode
✕
Tries (C++)Quick quiz

Trie bug hunt

8 questions. Covers Debugging lab: trie bugs.

Questions 1 to 5 of 8

  1. 1. A student writes this insert for lowercase words. What goes wrong? ``cpp void insert(const std::string& word) { TrieNode* node = root_.get(); for (char c : word) { int idx = c - 'A'; auto& next = node->children.at(idx); if (!next) next = std::make_unique<TrieNode>(); node = next.get(); } node->is_end = true; } ``
  2. 2. This version of insert is meant to mark the end of each word. What goes wrong? ``cpp void insert(const std::string& word) { TrieNode* node = root_.get(); for (char c : word) { auto& next = node->children[c - 'a']; if (!next) { next = std::make_unique<TrieNode>(); if (c == word.back()) next->is_end = true; } node = next.get(); } } ``
  3. 3. This search crashes on some words that are not in the trie. What is the bug? ``cpp bool search(const std::string& word) const { const TrieNode* node = root_.get(); for (char c : word) { node = node->children.at(c - 'a').get(); } return node->is_end; } ``
  4. 4. This search gives true for words that were never inserted. What is the bug? ``cpp bool search(const std::string& word) const { const TrieNode* node = root_.get(); for (char c : word) { const TrieNode* next = node->children[c - 'a'].get(); if (next == nullptr) return false; node = next; } return node != nullptr; } ``
  5. 5. What does this program print? ``cpp #include <iostream> #include <string> using namespace std; int main() { string word = "tea"; for (char c : word) { cout << (c - 'a') << (c == word.back() ? '\n' : ','); } } ``

5 question(s) left on this page.