typedef struct TrieNode {
struct TrieNode* children[26];
int isEndOfWord;
} TrieNode;
TrieNode* getNode() {
TrieNode* node = (TrieNode*)malloc(sizeof(TrieNode));
node->isEndOfWord = 0;
for (int i = 0; i < 26; i++) node->children[i] = NULL;
return node;
}
void insert(TrieNode* root, const char* key) {
TrieNode* pCrawl = root;
for (int i = 0; key[i] != '\0'; i++) {
int index = key[i] - 'a';
if (!pCrawl->children[index])
pCrawl->children[index] = getNode();
pCrawl = pCrawl->children[index];
}
pCrawl->isEndOfWord = 1;
}
int startsWith(TrieNode* root, const char* prefix) {
TrieNode* pCrawl = root;
for (int i = 0; prefix[i] != '\0'; i++) {
int index = prefix[i] - 'a';
if (!pCrawl->children[index])
return 0;
pCrawl = pCrawl->children[index];
}
return 1;
}
int main() {
TrieNode* root = getNode();
insert(root, "apple");
insert(root, "app");
insert(root, "application");
printf("%d\n", startsWith(root, "app"));
return 0;
}The prefix "app" is present because words "app", "apple", and "application" were inserted. The function returns 1 if prefix exists.
#include <stdio.h> #include <string.h> #include <stdlib.h> #define MAX_WORDS 5 int startsWith(char* words[], int n, const char* prefix) { int len = strlen(prefix); for (int i = 0; i < n; i++) { if (strncmp(words[i], prefix, len) == 0) { return 1; } } return 0; } int main() { char* words[MAX_WORDS] = {"banana", "band", "bandana", "apple", "application"}; printf("%d\n", startsWith(words, MAX_WORDS, "ban")); return 0; }
Words "banana", "band", and "bandana" start with "ban", so the function returns 1.
Trie allows direct traversal by characters of the prefix, making search time proportional to prefix length. Hash Map requires checking all keys or additional indexing.
int startsWith(TrieNode* root, const char* prefix) { TrieNode* pCrawl = root; for (int i = 0; prefix[i] != '\0'; i++) { int index = prefix[i] - 'a'; if (!pCrawl->children[index]) return 0; pCrawl = pCrawl->children[index]; } return 1; } int main() { TrieNode* root = NULL; printf("%d\n", startsWith(root, "cat")); return 0; }
The code does not check if root is NULL before accessing children, causing a segmentation fault when dereferencing NULL pointer.
Trie is ideal for autocomplete because it allows fast prefix search by traversing nodes per character, sharing common prefixes to save memory. Hash Map cannot do prefix search efficiently. Sorted arrays require O(log n) binary search but less efficient for prefix enumeration. Linked lists are slow for search.
