StartsWith
Lesson 7 of 14 in Coddy's Tries - Data Structures Series #8 course.
The whole reason tries exist is to answer prefix questions fast. startsWith checks whether any stored word begins with a given prefix - it does not care whether that prefix itself is a complete inserted word.
The walk is almost identical to search: from the root, follow children one character at a time. If a character is missing along the way, no stored word starts with that prefix, so return false. If you walk through every character without stopping, the answer is true - the subtree below that node contains at least one stored word.
The only difference from search: there is no isEndOfWord check at the end. Reaching the end of the prefix is enough.
Challenge
EasyAdd a method startsWith to the Trie class.
It gets a string prefix and returns:
trueif some inserted word starts withprefix(the prefix can match a full word, or be the leading part of a longer one).falseotherwise.
Try it yourself
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "trie.h"
int main() {
Trie t;
Trie_init(&t);
char line[1024];
while (fgets(line, sizeof(line), stdin)) {
line[strcspn(line, "\r\n")] = '\0';
char* cmd = strtok(line, " \t");
if (!cmd) continue;
if (strcmp(cmd, "rootIsEmpty") == 0) { printf("%s\n", TrieNode_childrenCount(t.root) == 0 ? "true" : "false"); }
if (strcmp(cmd, "hasChild") == 0) { char* arg = strtok(NULL, " \t"); if (arg) printf("%s\n", t.root->children[(unsigned char)arg[0]] != NULL ? "true" : "false"); }
if (strcmp(cmd, "insert") == 0) { char* arg = strtok(NULL, " \t"); if (arg) Trie_insert(&t, arg); }
if (strcmp(cmd, "search") == 0) { char* arg = strtok(NULL, " \t"); if (arg) printf("%s\n", Trie_search(&t, arg) ? "true" : "false"); }
if (strcmp(cmd, "startsWith") == 0) { char* arg = strtok(NULL, " \t"); if (arg) printf("%s\n", Trie_startsWith(&t, arg) ? "true" : "false"); }
}
return 0;
}