Prefix Matching
Prefix Matching is an important application of a Trie. It helps us find words that begin with a given sequence of characters. For example, if a user types "app" into a search box, we may want to display words such as apple, application, and apply. A Trie makes this type of searching efficient because words with common starting characters share the same path.
1. What Is a Prefix?
A prefix is a sequence of characters that appears at the beginning of a word.
For example, consider the word "computer".
Some valid prefixes are:
- c
- co
- com
- comp
- compu
- comput
- compute
- computer
Notice that every prefix starts from the first character of the word. A sequence taken from the middle or end of the word is not a prefix.
Example
Word: banana
| Character Sequence | Is It a Prefix? | Reason |
|---|---|---|
| b | Yes | Starts from the first character. |
| ba | Yes | Starts from the beginning. |
| ban | Yes | Starts from the beginning. |
| banana | Yes | The complete word is also a prefix of itself. |
| ana | No | It starts from the second character. |
| nana | No | It does not start from the first character. |
2. What Is Prefix Matching?
Prefix Matching means finding words that start with a given prefix.
Suppose we have the following dictionary:
- apple
- application
- apply
- apt
- banana
- ball
- bat
Now suppose we want to find all words that start with the prefix "app".
The matching words are:
- apple
- application
- apply
The words apt, banana, ball, and bat do not match because they do not start with "app".
3. Why Do We Use a Trie for Prefix Matching?
A Trie stores words character by character. Words that share the same beginning also share the same path.
This makes it easy to reach a prefix without checking every word separately.
Consider these words:
- apple
- application
- apply
- apt
- bat
The words apple, application, and apply share the prefix "app". In the Trie, they share the path for a, p, and p.
Root
/ \
a b
| |
p a
| |
p t*
/ \
l t*
|
e*
|
...
Words beginning with "app" share:
Root → a → p → p
* = End of a complete word
The diagram is a simplified view. After reaching the shared prefix, the Trie can have different branches for the remaining characters.
4. How Does Prefix Matching Work?
Prefix matching in a Trie follows a simple process:
- Start from the root node.
- Read the characters of the given prefix one by one.
- For each character, check whether the corresponding child exists.
- If a required child is missing, the prefix does not exist.
- If all prefix characters are found, the prefix exists.
- From the final prefix node, explore its descendants to find matching words.
- First, locate the node representing the given prefix.
- Then, explore the subtree below that node to collect matching words.
5. Example: Find Words Starting with "app"
Suppose our Trie contains:
- app
- apple
- application
- apply
- apt
- bat
We want to find all words that start with "app".
Step 1: Start at the Root
Begin from the root node.
Step 2: Follow the Character 'a'
Check whether the root has a child for a. If it exists, move to it.
Step 3: Follow the Character 'p'
From the a node, follow the child p.
Step 4: Follow the Second 'p'
From the first p node, follow the second p. We have now reached the node representing "app".
Step 5: Collect Matching Words
Starting from this node, explore all its descendants. Every complete word found in this subtree begins with "app".
app
apple
application
apply
The word "app" is also included because its final node is marked as the end of a complete word.
6. Prefix Search vs Complete Word Search
These two operations may look similar, but they answer different questions.
| Feature | Complete Word Search | Prefix Search |
|---|---|---|
| Purpose | Checks whether a complete word exists. | Checks whether a prefix path exists. |
| End Marker | Must be true. | Does not need to be true. |
| Example Input | apple | app |
| Possible Result | True or false. | True or false. |
Easy Example
Suppose only the word "apple" has been inserted.
- search("app") returns false because "app" is not a complete word.
- startsWith("app") returns true because the prefix path exists.
7. C++ Function to Check Whether a Prefix Exists
We can use a function called startsWith()
to check whether a prefix exists in the Trie.
bool startsWith(string prefix) {
TrieNode* current = root;
for (char ch : prefix) {
int index = ch - 'a';
if (current->children[index] == nullptr) {
return false;
}
current = current->children[index];
}
return true;
}
Explanation
1. Start from the root:
TrieNode* current = root;
We begin at the root because every word and prefix starts there.
2. Process every prefix character:
for (char ch : prefix)
We visit each character of the given prefix one by one.
3. Convert the character into an index:
int index = ch - 'a';
This gives us the position of the character in the child array.
4. Check whether the child exists:
if (current->children[index] == nullptr) {
return false;
}
If the child does not exist, the required prefix path is missing.
5. Move to the next node:
current = current->children[index];
If the child exists, move to it and continue processing the prefix.
6. Return true:
return true;
If all prefix characters are found, the prefix exists. Notice that we do not check isEnd here.
8. Finding All Words That Match a Prefix
Checking whether a prefix exists is only one part of prefix matching. Sometimes we need to return all complete words that start with that prefix.
For this, we can use a depth-first search (DFS) to explore the Trie starting from the node where the prefix ends.
What Is DFS?
DFS stands for Depth-First Search. It is a traversal technique in which we explore one branch as deeply as possible before moving to another branch.
In a Trie, DFS helps us visit all possible character paths below a given prefix node.
Example
Suppose we have inserted these words:
- car
- card
- care
- careful
- cat
- dog
If the prefix is "car", we first reach the node representing "car". Then we explore the branches below it.
The matching words are:
- car
- card
- care
- careful
The word "car" itself must be included if its node is marked as the end of a word.
9. C++ Code to Collect All Words with a Given Prefix
We will use a helper function that explores the Trie and builds each complete word.
void collectWords(
TrieNode* current,
string& currentWord,
vector<string>& result
) {
// If this node ends a complete word
if (current->isEnd) {
result.push_back(currentWord);
}
// Explore all possible children
for (int i = 0; i < 26; i++) {
if (current->children[i] != nullptr) {
char ch = 'a' + i;
currentWord.push_back(ch);
collectWords(
current->children[i],
currentWord,
result
);
// Remove the last character
currentWord.pop_back();
}
}
}
Understanding the Helper Function
The function receives three things:
current: the Trie node currently being visited.currentWord: the characters collected so far.result: the list of complete matching words.
If the current node is the end of a word, we add the current word to the result.
Next, we check all 26 possible child positions. If a child exists, we add its character, recursively explore that child, and then remove the character when returning.
10. Complete C++ Program for Prefix Matching
The following program supports:
- Insertion of words.
- Checking whether a prefix exists.
- Finding all words that begin with a given prefix.
#include <iostream>
#include <string>
#include <vector>
using namespace std;
struct TrieNode {
TrieNode* children[26];
bool isEnd;
TrieNode() {
isEnd = false;
for (int i = 0; i < 26; i++) {
children[i] = nullptr;
}
}
};
class Trie {
private:
TrieNode* root;
void collectWords(
TrieNode* current,
string& currentWord,
vector<string>& result
) {
if (current->isEnd) {
result.push_back(currentWord);
}
for (int i = 0; i < 26; i++) {
if (current->children[i] != nullptr) {
char ch = 'a' + i;
currentWord.push_back(ch);
collectWords(
current->children[i],
currentWord,
result
);
currentWord.pop_back();
}
}
}
public:
Trie() {
root = new TrieNode();
}
void insert(string word) {
TrieNode* current = root;
for (char ch : word) {
int index = ch - 'a';
if (current->children[index] == nullptr) {
current->children[index] = new TrieNode();
}
current = current->children[index];
}
current->isEnd = true;
}
bool startsWith(string prefix) {
TrieNode* current = root;
for (char ch : prefix) {
int index = ch - 'a';
if (current->children[index] == nullptr) {
return false;
}
current = current->children[index];
}
return true;
}
vector<string> getWordsWithPrefix(string prefix) {
TrieNode* current = root;
// Find the node representing the prefix
for (char ch : prefix) {
int index = ch - 'a';
if (current->children[index] == nullptr) {
return {};
}
current = current->children[index];
}
// Collect complete words from this node
vector<string> result;
string currentWord = prefix;
collectWords(current, currentWord, result);
return result;
}
};
int main() {
Trie trie;
trie.insert("apple");
trie.insert("application");
trie.insert("apply");
trie.insert("apt");
trie.insert("banana");
trie.insert("app");
string prefix = "app";
if (trie.startsWith(prefix)) {
cout << "Prefix exists!" << endl;
vector<string> words =
trie.getWordsWithPrefix(prefix);
cout << "Matching words:" << endl;
for (string word : words) {
cout << word << endl;
}
} else {
cout << "Prefix not found!" << endl;
}
return 0;
}
11. Dry Run of the Program
First, we insert the following words:
- apple
- application
- apply
- apt
- banana
- app
Now we search for the prefix "app".
| Step | Character | Action |
|---|---|---|
| 1 | a | Find the a child of the root. |
| 2 | p | Find the p child of a. |
| 3 | p | Find the next p child. |
| 4 | Complete | The prefix node has been reached. |
Now DFS explores all children below the node representing "app". It finds the complete words:
Prefix exists!
Matching words:
app
apple
application
apply
The output order is alphabetical because the DFS checks child indexes from 0 to 25, corresponding to a through z.
12. Time Complexity of Prefix Matching
Let:
- P = length of the given prefix.
- K = total number of characters visited while collecting matching words.
- R = number of matching words returned.
Checking Whether a Prefix Exists
We process each character of the prefix once.
Time Complexity: O(P)
Collecting All Matching Words
After reaching the prefix node, DFS explores the relevant subtree. The time depends on how many Trie nodes are visited and how many characters are copied into the returned words.
A useful way to express this is O(K + total output characters), where K is the number of visited nodes.
| Operation | Time Complexity |
|---|---|
| Check prefix existence | O(P) |
| Collect matching words | Depends on the size of the matching subtree and output size |
13. Space Complexity
The Trie itself requires space for its nodes and child pointers. In addition, collecting matching words requires space for the result list and the recursion stack.
- The recursion stack can grow according to the maximum depth of the explored Trie path.
- The result list requires space for all matching words and their characters.
If M is the maximum length of a word below the prefix node, the recursive stack can use O(M) space.
14. Real-World Applications of Prefix Matching
1. Search Engine Suggestions
When a user types "data", a search engine may suggest phrases or words that begin with "data", such as database, datatype, and data structure.
2. Autocomplete in Text Editors
When a programmer types the beginning of a function or variable name, an editor can suggest matching names.
3. Contact List Searching
When a user types "rah", a contact application may display names beginning with those characters.
4. Dictionary Searching
A dictionary can use prefix matching to show all words that begin with a particular sequence.
5. Product Search
An online shopping application can suggest product names when a customer types the first few characters.
15. Common Mistakes
- Confusing prefix and substring: A prefix begins at the first character. A substring may appear anywhere inside a word.
- Checking the end marker for prefix existence: A prefix can exist even if it is not a complete stored word.
- Forgetting to collect the prefix itself: If the prefix node is also marked as the end of a word, that word must be included in the results.
- Not restoring the current word during DFS: Use pop_back() after exploring a child so that characters from one branch do not affect another branch.
- Exploring the entire Trie unnecessarily: First locate the prefix node, then explore only its subtree.
16. Interview Questions
Q1. What is a prefix?
A prefix is a sequence of characters that appears at the beginning of a word.
Q2. What is prefix matching?
Prefix matching finds words that begin with a given sequence of characters.
Q3. Why is a Trie useful for prefix matching?
Words with common starting characters share the same path. We can follow the prefix path and explore only the subtree below that prefix.
Q4. What is the difference between a prefix and a substring?
A prefix must start at the first character of a word. A substring can begin at any position inside the word.
Q5. Why do we use DFS after finding the prefix node?
DFS helps us explore all branches below the prefix node and collect every complete word that begins with that prefix.
Q6. Does prefix matching require the end-of-word marker?
Checking whether a prefix exists does not require the end marker. However, collecting complete matching words uses the marker to identify which paths represent stored words.
17. Practice Problems
- Insert "apple", "application", "apply", and "apt". Find all words starting with "app".
- Insert "cat", "car", "care", and "dog". Find all words starting with "ca".
- Write a function that checks whether a given prefix exists in a Trie.
- Write a function that returns all words matching a given prefix.
- Explain why "app" can be a valid prefix even when it is not a complete word in the Trie.
- Modify the program to search for words starting with "do".
18. Summary
Prefix Matching is used to find words that begin with a particular sequence of characters. A Trie makes this operation efficient by sharing paths for common prefixes.
- A prefix always starts from the first character of a word.
- Prefix matching finds words that begin with the given prefix.
- We first follow the prefix path from the root.
- If a required child is missing, the prefix does not exist.
- DFS can collect all complete words below the prefix node.
- The end-of-word marker identifies complete matching words.
- Checking a prefix of length P takes O(P) time.