C++ 0208.cpp
class Trie {
set<string> all;
// not a trie, just basic tree ...
public:
void insert(string word) {
all.insert(word);
}
bool search(string word) {
return all.count(word) > 0;
}
bool startsWith(string prefix) {
auto pos = all.lower_bound(prefix);
if (pos == all.end())
return false;
return pos->find(prefix) == 0;
}
};
Difficulty
and has an acceptance rate of about 70% (2+ million submissions).
Typical patterns to solve this problem:
- Design
- Hash Table
- String
- Trie
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The presented implementation defines a Trie class that provides three public operations: insertion of a word, exact-match search, and prefix search. Internally the class stores all inserted strings in a std::set<std::string> named all. Although the name suggests a trie data structure, the actual storage is a balanced binary search tree provided by the C++ Standard Library. This choice influences how each operation is performed and determines the characteristics of the code.
Key Steps
The core functionality is expressed through three member functions. Each function directly manipulates or queries the all container.
Insertion
void insert(string word) {
all.insert(word);
}
The insert method forwards the supplied word to the std::set::insert operation. Because std::set maintains elements in sorted order and guarantees uniqueness, duplicate insertions are silently ignored, and the container remains ordered without additional effort.
Exact-match Search
bool search(string word) {
return all.count(word) > 0;
}
The search method uses std::set::count, which returns either 0 or 1 for a set. The comparison with zero yields a boolean indicating whether the word exists in the collection.
Prefix Search
bool startsWith(string prefix) {
auto pos = all.lower_bound(prefix);
if (pos == all.end())
return false;
return pos->find(prefix) == 0;
}
The startsWith routine first obtains an iterator to the first element that is not less than the given prefix via lower_bound. If the iterator reaches the end of the set, no candidate exists and the function returns false. Otherwise the code checks whether the candidate string begins with the prefix by invoking std::string::find and confirming that the returned position is zero.
Edge Cases Handled
The implementation gracefully manages several boundary conditions without explicit checks.
When the set is empty, lower_bound returns all.end(). The subsequent guard if (pos == all.end()) ensures that the function returns false rather than dereferencing an invalid iterator.
If the prefix supplied is an empty string, lower_bound yields an iterator to the smallest element in the set. The subsequent find call on that element will always succeed at position zero, causing startsWith to return true. This behavior aligns with the conventional definition that every string starts with the empty prefix.
When the prefix is longer than any stored word, lower_bound will point to the first element that is lexicographically greater. The find check will fail because the longer prefix cannot be a prefix of a shorter word, resulting in false. No out-of-range accesses occur because the code never attempts to read beyond the bounds of the candidate string.
Duplicate insertions are automatically ignored by the set container. The insert method does not need to perform a pre-existence check; the underlying container enforces uniqueness, and the set remains correctly ordered.
Performance Optimizations
The choice of std::set provides several implicit performance benefits. The container is typically implemented as a self-balancing binary search tree (often a red-black tree). This guarantees logarithmic time for insertion, lookup, and lower_bound operations, which the code relies on directly. By delegating ordering and uniqueness to the standard library, the implementation avoids manual tree management and benefits from highly tuned library code.
The startsWith method leverages lower_bound to jump directly to the first possible match rather than scanning the entire set. This reduces the amount of string comparison work, especially when the set contains many entries that are lexicographically far from the requested prefix.
Using std::string::find with a starting position of zero is an efficient way to test for a prefix because the standard library can often short-circuit the search as soon as a mismatch is detected. The combination of a targeted iterator from lower_bound and the early-exit nature of find minimizes the number of character comparisons required for a prefix query.
Overall, the code relies on the standard library’s optimized data structures and algorithms, resulting in concise logic while still delivering strong performance characteristics for the supported operations.
ELI5 - Simplified Explanation
Imagine a big magical chest where you keep all of your favorite storybooks. This piece of code is just like a helper who manages those books for you.
The part called insert is like taking a new book and carefully placing it inside the chest so you do not lose it. The part called search is like asking the helper if a specific book is already tucked away inside. The helper runs to the chest, looks through all the books, and tells you if the one you named is resting in there.
The last part, which is called startsWith, is like a guessing game. You tell the helper just the very beginning of a title, like playing, and the helper looks through the chest to see if any of the books start with those same letters. If the helper finds a book that begins with your clue, it lets you know you found a match. This helper keeps everything tidy and makes it easy to find exactly what you need whenever you want to read.
Code Quality
Complexity Analysis
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | ||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|
| author | solutions | |||||||||||
| www | AlgoMonster | C++ | Python | Java | TS | |||||||
| WalkCCC | C++ | Python | Java | |||||||||
| leetcode.ca | C++ | Python | Java | C# | Rust | JS | Go | TS | ||||
| LeetcodeHelp | C++ | Python | Java | |||||||||
| MemoryLimitExceeded | C++ | Python | ||||||||||
| Progiez | C++ | Python | Java | |||||||||
| github | aylei | Rust | ||||||||||
| begeekmyfriend | C | |||||||||||
| BigEggStudy | C# | |||||||||||
| black-shadows | C++ | |||||||||||
| bujosa | Python | |||||||||||
| charles-wangkai | Java | |||||||||||
| everthis | JS | |||||||||||
| fartem | Ruby | |||||||||||
| fengvyi | C++ | |||||||||||
| fpdjsns | C++ | |||||||||||
| fsq | Python | |||||||||||
| gaosq0604 | Python | |||||||||||
| Garvit244 | Python | |||||||||||
| halfrost | Go | |||||||||||
| haoel | C++ | |||||||||||
| JoshCrozier | JS | |||||||||||
| keineahnung2345 | C++ | |||||||||||
| Krazune | C++ | |||||||||||
| lennylxx | C | |||||||||||
| linouk23 | C++ | |||||||||||
| lkwq007 | Python | |||||||||||
| luangong | C++ | |||||||||||
| qiyuangong | Python | |||||||||||
| ruoru | Rust | |||||||||||
| shreymehul | C# | |||||||||||
| sonugiri1043 | C++ | |||||||||||
| suxrobGM | C# | |||||||||||
| trung-hn | Python | |||||||||||
| varunu28 | Java | |||||||||||
| vli02 | C | |||||||||||
| vthwang | Java | |||||||||||
| wisdompeak | C++ | |||||||||||
| yuanliu666 | Kotlin | |||||||||||
| YuriSpiridonov | Python | |||||||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||||||
| WalkCCC | C++, Python, Java | |||||||||||
| leetcode.ca | C++, C#, Go, Java, JavaScript, Python, Rust, TypeScript | |||||||||||
| LeetcodeHelp | C++, Java, Python | |||||||||||
| MemoryLimitExceeded | Python, C++ | |||||||||||
| Progiez | C++, Java, Python | |||||||||||
| aylei | Rust | |||||||||||
| begeekmyfriend | C | |||||||||||
| BigEggStudy | C# | |||||||||||
| black-shadows | C++, C++ | |||||||||||
| bujosa | Python | |||||||||||
| charles-wangkai | Java | |||||||||||
| everthis | JavaScript | |||||||||||
| fartem | Ruby | |||||||||||
| fengvyi | C++ | |||||||||||
| fpdjsns | C++ | |||||||||||
| fsq | Python | |||||||||||
| gaosq0604 | Python | |||||||||||
| Garvit244 | Python | |||||||||||
| halfrost | Go | |||||||||||
| haoel | C++ | |||||||||||
| JoshCrozier | JavaScript | |||||||||||
| keineahnung2345 | C++ | |||||||||||
| Krazune | C++ | |||||||||||
| lennylxx | C | |||||||||||
| linouk23 | C++ | |||||||||||
| lkwq007 | Python | |||||||||||
| luangong | C++ | |||||||||||
| qiyuangong | Python | |||||||||||
| ruoru | Rust | |||||||||||
| shreymehul | C# | |||||||||||
| sonugiri1043 | C++ | |||||||||||
| suxrobGM | C# | |||||||||||
| trung-hn | Python | |||||||||||
| varunu28 | Java | |||||||||||
| vli02 | C | |||||||||||
| vthwang | Java | |||||||||||
| wisdompeak | C++ | |||||||||||
| yuanliu666 | Kotlin | |||||||||||
| YuriSpiridonov | Python |
Videos
Similar Problems
- problem 211: Design Add and Search Words Data Structure
- problem 642: Design Search Autocomplete System
- problem 648: Replace Words
- problem 676: Implement Magic Dictionary
- problem 1804: Implement Trie II (Prefix Tree)
- problem 2227: Encrypt and Decrypt Strings
- problem 3042: Count Prefix and Suffix Pairs I
- problem 3045: Count Prefix and Suffix Pairs II
Solved On The Same Day
- problem 19: Remove Nth Node From End of List
- problem 61: Rotate List
- problem 739: Daily Temperatures
- problem 23: Merge k Sorted Lists
- problem 214: Shortest Palindrome
- problem 1316: Distinct Echo Substrings
- problem 1392: Longest Happy Prefix
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality