#pragma once #include #include #include #include #include #include namespace Void::Trie { // ── Trie ────────────────────────────────────────────────────────────────────── // Prefix tree over std::string keys with optional associated values of type V. // Stores words character-by-character; each node has up to 256 children. template class Trie { struct Node { std::unordered_map> children; std::optional value; // set only at end-of-word nodes }; public: Trie() : root_{std::make_unique()} {} void insert(std::string_view key, V value = V{}) { Node* cur = root_.get(); for (char c : key) { auto& child = cur->children[c]; if (!child) child = std::make_unique(); cur = child.get(); } if (!cur->value.has_value()) ++size_; cur->value = std::move(value); } [[nodiscard]] bool contains(std::string_view key) const { const Node* node = find_node(key); return node && node->value.has_value(); } [[nodiscard]] std::optional get(std::string_view key) const { const Node* node = find_node(key); if (!node) return std::nullopt; return node->value; } bool erase(std::string_view key) { return erase_impl(root_.get(), key, 0); } [[nodiscard]] bool starts_with(std::string_view prefix) const { return find_node(prefix) != nullptr; } [[nodiscard]] std::vector keys_with_prefix(std::string_view prefix) const { std::vector result; const Node* node = find_node(prefix); if (!node) return result; std::string buf{prefix}; collect(node, buf, result); return result; } [[nodiscard]] std::size_t size() const noexcept { return size_; } [[nodiscard]] bool empty() const noexcept { return size_ == 0; } private: const Node* find_node(std::string_view key) const { const Node* cur = root_.get(); for (char c : key) { auto it = cur->children.find(c); if (it == cur->children.end()) return nullptr; cur = it->second.get(); } return cur; } void collect(const Node* node, std::string& buf, std::vector& out) const { if (node->value.has_value()) out.push_back(buf); for (const auto& [c, child] : node->children) { buf += c; collect(child.get(), buf, out); buf.pop_back(); } } bool erase_impl(Node* node, std::string_view key, std::size_t depth) { if (depth == key.size()) { if (!node->value.has_value()) return false; node->value.reset(); --size_; return true; } auto it = node->children.find(key[depth]); if (it == node->children.end()) return false; const bool erased = erase_impl(it->second.get(), key, depth + 1); // Prune leaf nodes that hold no value and have no children if (erased && it->second->children.empty() && !it->second->value.has_value()) { node->children.erase(it); } return erased; } std::unique_ptr root_; std::size_t size_{0}; }; } // namespace Void::Trie