DSA interview question
You're building the core data structure behind a search engine's autocomplete and typo-suggestion service. The basic Trie (insert/search/startsWith) isn't enough — your team needs a production-grade Trie that also supports deletion (e.g., removing a deprecated search term) and counting how many indexed words exactly match a given string, or how many indexed words have a given string as a prefix — both needed for ranking suggestions by popularity. Design and implement this Trie class.
class Trie {
public:
Trie();
void insert(string word);
int countWordsEqualTo(string word); // exact match count
int countWordsStartingWith(string prefix); // prefix match count
void erase(string word); // remove one occurrence of word
};
| Operations (in order) | Output / State |
|---|---|
insert("apple"), insert("apple"), insert("app") | Trie now has "apple" x2, "app" x1 |
countWordsEqualTo("apple") | 2 |
countWordsStartingWith("app") | 3 (counts "apple" x2 + "app" x1, since all start with "app") |
erase("apple") | One "apple" removed, one remains |
countWordsEqualTo("apple") | 1 |
countWordsStartingWith("app") | 2 (1 remaining "apple" + 1 "app") |
erase("apple"), erase("app") | All words removed |
countWordsEqualTo("app") | 0 |
countWordsStartingWith("a") | 0 |
erase("nonexistent") | No-op, should not crash or corrupt state |
(This mirrors a well-known GFG/competitive-programming Trie variant where each node tracks both endCount and prefixCount, supporting duplicates and proper deletion.)
countWordsEqualTo, countWordsStartingWith, and erase."countWordsEqualTo meaningful beyond just 0/1.)erase, should I assume the word being erased is guaranteed to exist, or do I need to handle erasing a non-existent word gracefully (no-op, no crash)? (Always handle defensively — confirm expected behavior.)On Practick another engineer interviews you live for 60 minutes on a question from this bank. They have the full interviewer guide beside the call: the expected answer to every follow-up, hints to give if you stall, and a scoring rubric. You get the model solution once the session settles. It is free: interview someone for an hour and you have earned your own.
Book a free mock interviewAll 474 dsa interview questions
DSA mock interviews · System design interview questions · Free mock interview practice · Browse interviewers · Sign in