What if you could find all words starting with your favorite letters instantly, no matter how big the list?
Why Count Words with Given Prefix in DSA C++?
Imagine you have a huge list of words, like a dictionary, and you want to find out how many words start with a certain set of letters, like "pre".
Doing this by checking each word one by one is like looking for all your friends in a crowd by calling their full names loudly and waiting for a response.
Checking each word manually is very slow and tiring, especially if the list is very long.
You might miss some words or make mistakes counting them.
It's like trying to find all your friends in a stadium by shouting their names one by one--it takes too long and is easy to mess up.
Using a smart structure like a prefix tree (Trie) helps you quickly find how many words start with the letters you want.
It organizes words by their letters, so you can jump straight to the part where words with your prefix live and count them fast.
int countWordsWithPrefix(vector<string> words, string prefix) {
int count = 0;
for (string word : words) {
if (word.substr(0, prefix.size()) == prefix) {
count++;
}
}
return count;
}struct TrieNode {
TrieNode* children[26] = {nullptr};
int prefixCount = 0;
};
class Trie {
TrieNode* root = new TrieNode();
public:
void insert(string word) {
TrieNode* current = root;
for (char ch : word) {
int index = ch - 'a';
if (!current->children[index]) {
current->children[index] = new TrieNode();
}
current = current->children[index];
current->prefixCount++;
}
}
int countWordsWithPrefix(string prefix) {
TrieNode* current = root;
for (char ch : prefix) {
int index = ch - 'a';
if (!current->children[index]) return 0;
current = current->children[index];
}
return current->prefixCount;
}
};This lets you instantly know how many words start with any prefix, even in huge word lists, making searches lightning fast.
Search engines use this to suggest words as you type, showing you popular words starting with the letters you entered.
Manual checking is slow and error-prone for large word lists.
Using a Trie organizes words by letters for fast prefix counting.
This method speeds up searches and suggestions in real applications.
Practice
Solution
Step 1: Understand the problem statement
The problem asks to find how many words start with a given prefix from a list of words.Step 2: Identify the key operation
We need to check each word and count those that begin with the prefix.Final Answer:
Count how many words in a list start with a specific prefix -> Option AQuick Check:
Counting words with prefix = Count how many words in a list start with a specific prefix [OK]
- Counting all words instead of only those with prefix
- Looking for longest word instead of counting
- Replacing prefix instead of counting
word starts with prefix pref?Solution
Step 1: Understand string::find usage
Usingword.find(pref) == 0checks ifprefis found at the start (index 0) ofword.Step 2: Check other options
if (word == pref) { /* starts with prefix */ } checks equality, not prefix. if (word.substr(1, pref.size()) == pref) { /* starts with prefix */ } checks substring starting at index 1, which is wrong. if (word.compare(pref) == 1) { /* starts with prefix */ } compares strings but result 1 means greater, not prefix.Final Answer:
if (word.find(pref) == 0) { /* starts with prefix */ } -> Option DQuick Check:
find(pref) == 0 means prefix match [OK]
- Using equality instead of prefix check
- Checking substring from wrong index
- Misunderstanding compare() return values
std::vector words = {"apple", "app", "application", "banana"};
std::string prefix = "app";
int count = 0;
for (const auto& w : words) {
if (w.find(prefix) == 0) {
count++;
}
}
std::cout << count << std::endl;Solution
Step 1: Check each word for prefix "app"
"apple" starts with "app" (count=1), "app" starts with "app" (count=2), "application" starts with "app" (count=3), "banana" does not.Step 2: Count total matches
Total words starting with "app" are 3.Final Answer:
3 -> Option AQuick Check:
Words starting with "app" = 3 [OK]
- Counting words that contain prefix anywhere
- Off-by-one errors in counting
- Ignoring words that exactly equal prefix
pref:int count = 0;
for (auto w : words) {
if (w.find(pref)) {
count++;
}
}Solution
Step 1: Understand find() return value
find() returns position or npos. Using if(w.find(pref)) treats 0 as false, so words starting at index 0 are skipped.Step 2: Correct condition for prefix check
We must check if w.find(pref) == 0 to confirm prefix at start.Final Answer:
The condition should check if w.find(pref) == 0, not just w.find(pref) -> Option CQuick Check:
Check find() == 0 for prefix [OK]
- Using if(w.find(pref)) which fails for prefix at start
- Not using reference in loop (less critical here)
- Initializing count incorrectly
Choose the best approach.
Solution
Step 1: Understand repeated prefix queries
Checking each word every time is slow for large lists and many queries.Step 2: Use Trie data structure
A Trie stores words by prefixes, allowing fast counting of words with given prefix in O(length of prefix) time.Step 3: Evaluate other options
Binary search after sorting helps but is less efficient for many queries. Hash set doesn't support prefix queries efficiently.Final Answer:
Use a Trie (prefix tree) to store words and count prefix matches quickly -> Option BQuick Check:
Trie = fast prefix counting [OK]
- Checking all words each query (slow)
- Using hash set which doesn't support prefix queries
- Ignoring Trie advantages for prefix problems
Ready to prove it?
Pass the test and this pattern moves unknown
