Problem 208

Abstract / Summary

Implement a data structure that supports adding words and checking if a prefix exists efficiently.

Note

The full problem description, including helpful examples, can be found on LeetCode.

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;
    }
};
22 lines | 429 bytes | submitted August 10, 2023 | GitHub   6% comment ratio | tab size 4

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 70% (2+ million submissions).

Typical patterns to solve this problem:
  • Design
  • Hash Table
  • String
  • Trie
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
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.
LeetCode profile | GitHub repo

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.

written by openai gpt

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.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 3 | μ = 3.67 | σ = 1.59

Complexity Analysis

not analyzed yet

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
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
57 links | 40 authors | 11 languages

Videos

These are a few popular YouTube videos for this problem:
YouTube video 'Implement Trie (Prefix Tree) - Leetcode 208'
NeetCode 19 mins
Implement Trie (Prefix Tree) - Leetcode 208
YouTube video 'Implement Trie (Prefix Tree) - Leetcode 208 - Trees (Python)'
Greg Hogg 10 mins
Implement Trie (Prefix Tree) - Leetcode 208 - Trees (Python)
YouTube video 'Implement Trie (Prefix Tree) | LeetCode 208 | C++, Java, Python | May LeetCoding Day 14'
Knowledge Center 29 mins
Implement Trie (Prefix Tree) | LeetCode 208 | C++, Java, Python | May LeetCoding Day 14
YouTube video '[Java] Tries (Prefix Tree) | Solve Leetcode - Implement Trie in Code'
Eric Programming 16 mins
[Java] Tries (Prefix Tree) | Solve Leetcode - Implement Trie in Code
YouTube video 'Implement Trie (Prefix Tree) || C++/Java/Python'
Aryan Mittal 20 mins
Implement Trie (Prefix Tree) || C++/Java/Python
YouTube video 'Trie Data Structure | LeetCode 208. Implement Trie (Prefix Tree) - Interview Prep Ep 83'
Fisher Coder 18 mins
Trie Data Structure | LeetCode 208. Implement Trie (Prefix Tree) - Interview Prep Ep 83
YouTube video 'Trie Data Structure | Implementation in C++ | LeetCode Problem #208 | Implement Trie(Prefix Tree 🌳)'
The Coding Ladder 16 mins
Trie Data Structure | Implementation in C++ | LeetCode Problem #208 | Implement Trie(Prefix Tree 🌳)
YouTube video 'Implement Trie (Prefix Tree) - 208. LeetCode - Java'
Teddy Smith 13 mins
Implement Trie (Prefix Tree) - 208. LeetCode - Java
YouTube video 'Implement Trie (Prefix Tree) | Day 14 | [May LeetCoding Challenge] [Leetcode 208] [2020]'
Algorithms Made Easy 5 mins
Implement Trie (Prefix Tree) | Day 14 | [May LeetCoding Challenge] [Leetcode 208] [2020]
YouTube video 'LeetCode 208. Implement Trie (Prefix Tree) - Java'
Kacy Codes 11 mins
LeetCode 208. Implement Trie (Prefix Tree) - Java
YouTube video '208. Implement Trie (Prefix Tree) - JAVA (Detailed explanation)'
Sourin Majumdar 22 mins
208. Implement Trie (Prefix Tree) - JAVA (Detailed explanation)
YouTube video '208 || Implement Trie (Prefix Tree) || C++ || Leetcode Daily Challenge'
CodeFreaks 16 mins
208 || Implement Trie (Prefix Tree) || C++ || Leetcode Daily Challenge
YouTube video '208. Implement Trie (Prefix Tree) | JavaScript | Detailed Explanation | LeetCode Daily Challenge'
LeetCodeWithMonu 16 mins
208. Implement Trie (Prefix Tree) | JavaScript | Detailed Explanation | LeetCode Daily Challenge
YouTube video 'LeetCode 208 Implement Trie (Prefix Tree)'
Jeevan Kumar - Cracckify 14 mins
LeetCode 208 Implement Trie (Prefix Tree)
YouTube video 'Daily Leetcode #1081: Mar 17, 2023 - 208. Implement Trie (Prefix Tree)'
Programming Live with Larry 5 mins
Daily Leetcode #1081: Mar 17, 2023 - 208. Implement Trie (Prefix Tree)
YouTube video 'Implement Trie in Python | Leetcode 208 Telugu | Prefix Tree Explained | Python DSA | srkcodes'
Srk Codes 21 mins
Implement Trie in Python | Leetcode 208 Telugu | Prefix Tree Explained | Python DSA | srkcodes
YouTube video 'Daily Leetcode #556: Oct 08, 2021 - 208. Implement Trie (Prefix Tree)'
Programming Live with Larry 12 mins
Daily Leetcode #556: Oct 08, 2021 - 208. Implement Trie (Prefix Tree)
YouTube video '208. Implement Trie (Prefix Tree) | Leetcode Medium | Cpp'
Komal Pal 17 mins
208. Implement Trie (Prefix Tree) | Leetcode Medium | Cpp
YouTube video 'Implement Trie (Prefix Tree) - Leetcode 208 - Python'
Krac X 12 mins
Implement Trie (Prefix Tree) - Leetcode 208 - Python
YouTube video '76. Leetcode 208. Implement Trie (Prefix Tree) : Javascript'
Web Fusion with Bharadwaj 35 mins
76. Leetcode 208. Implement Trie (Prefix Tree) : Javascript
20 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

8 similar problems

Solved On The Same Day

3 medium 4 hard
8 solutions   August 10, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • 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