Bird
Raised Fist0
DSA Cprogramming~20 mins

Trie vs Hash Map for Prefix Matching in DSA C - Compare & Choose

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Prefix Matching Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of prefix search using Trie
Given the following Trie insertion and prefix search code, what is the output of searching for prefix "app"?
DSA C
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;
}
ACompilation error
B0
C3
D1
Attempts:
2 left
💡 Hint
Check if the prefix "app" exists in the Trie after insertions.
❓ Predict Output
intermediate
2:00remaining
Output of prefix search using Hash Map
Given the following code using a hash map to store words and check prefix existence, what is the output of searching for prefix "ban"?
DSA C
#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;
}
A1
BCompilation error
C0
DRuntime error
Attempts:
2 left
💡 Hint
Check if any word starts with "ban" in the array.
🧠 Conceptual
advanced
2:00remaining
Why is Trie more efficient than Hash Map for prefix matching?
Which of the following best explains why a Trie is more efficient than a Hash Map for prefix matching in large datasets?
ATrie stores characters in a tree structure allowing prefix search in O(k) time where k is prefix length, while Hash Map requires checking all keys.
BTrie sorts all words alphabetically, which Hash Map cannot do.
CHash Map cannot store strings as keys, so Trie is the only option.
DTrie uses less memory than Hash Map because it stores only unique words.
Attempts:
2 left
💡 Hint
Think about how prefix search works in both data structures.
🔧 Debug
advanced
2:00remaining
Identify the bug in Trie prefix search
What error will the following Trie prefix search code produce when searching for prefix "cat" if the Trie is empty?
DSA C
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;
}
AReturns 1 incorrectly
BReturns 0 without error
CSegmentation fault (accessing NULL pointer)
DCompilation error due to missing TrieNode definition
Attempts:
2 left
💡 Hint
Check what happens if root is NULL before accessing children.
🚀 Application
expert
3:00remaining
Choosing data structure for autocomplete system
You are designing an autocomplete system for a search engine with millions of queries. Which data structure is best suited for fast prefix matching and why?
AHash Map, because it stores all queries as keys and allows O(1) lookup for any prefix.
BTrie, because it provides fast prefix search in O(k) time and efficient memory usage with shared prefixes.
CArray of strings sorted alphabetically, because binary search can find prefixes quickly.
DLinked list of queries, because it is simple to implement and traverse.
Attempts:
2 left
💡 Hint
Consider time complexity and memory efficiency for prefix search in large datasets.

Practice

(1/5)
1. Which data structure is generally more efficient for prefix matching in a large set of strings?
easy
A. Trie, because it stores characters in a tree structure allowing fast prefix search
B. Hash Map, because it stores keys with direct access for any substring
C. Array, because it stores elements sequentially for quick prefix lookup
D. Stack, because it allows last-in-first-out access which helps prefix matching

Solution

  1. Step 1: Understand prefix matching requirement

    Prefix matching means finding all strings starting with a given prefix quickly.
  2. Step 2: Compare Trie and Hash Map for prefix search

    Trie stores characters in nodes along paths, enabling fast prefix traversal. Hash Map is good for exact key lookup but not efficient for prefix search.
  3. Final Answer:

    Trie, because it stores characters in a tree structure allowing fast prefix search -> Option A
  4. Quick Check:

    Prefix search = Trie [OK]
Hint: Trie is best for prefix search, Hash Map for exact keys [OK]
Common Mistakes:
  • Thinking Hash Map supports prefix search efficiently
  • Confusing array or stack with prefix matching
  • Assuming Hash Map stores substrings as keys
2. Which of the following is the correct way to insert a word into a Trie node in C?
easy
A. node->children[word[i] - 'a'] = createNode();
B. node[word[i]] = createNode();
C. node->children[word[i]] = createNode();
D. node.children[word[i] - 'a'] = createNode();

Solution

  1. Step 1: Understand Trie node children indexing

    Children array is indexed by character offset from 'a', so use word[i] - 'a'.
  2. Step 2: Use correct pointer syntax in C

    Since node is a pointer, use '->' to access children array.
  3. Final Answer:

    node->children[word[i] - 'a'] = createNode(); -> Option A
  4. Quick Check:

    Pointer access + char offset = node->children[word[i] - 'a'] = createNode(); [OK]
Hint: Use '->' for pointer and subtract 'a' for index [OK]
Common Mistakes:
  • Using dot instead of arrow for pointer
  • Not subtracting 'a' from character
  • Using character directly as index
3. Given the following C code snippet for prefix search using a Trie, what will be the output?
TrieNode* root = createNode();
insert(root, "apple");
insert(root, "app");
insert(root, "bat");

printf("%d", startsWith(root, "app"));
printf("%d", startsWith(root, "bat"));
printf("%d", startsWith(root, "cat"));
Assume startsWith returns 1 if prefix exists, else 0.
medium
A. 111
B. 110
C. 101
D. 100

Solution

  1. Step 1: Analyze inserted words and prefixes

    Words inserted: "apple", "app", "bat". Prefixes checked: "app", "bat", "cat".
  2. Step 2: Check prefix existence

    "app" is prefix of "apple" and "app" -> returns 1. "bat" is inserted word -> returns 1. "cat" not inserted -> returns 0.
  3. Final Answer:

    110 -> Option B
  4. Quick Check:

    Prefix found = 1,1,0 [OK]
Hint: Check if prefix matches any inserted word start [OK]
Common Mistakes:
  • Assuming startsWith returns count instead of boolean
  • Confusing prefix with exact match
  • Ignoring that 'cat' was not inserted
4. The following C code attempts to check if a prefix exists in a Trie but always returns 0. What is the bug?
int startsWith(TrieNode* root, char* prefix) {
    TrieNode* node = root;
    for (int i = 0; prefix[i]; i++) {
        if (node->children[prefix[i]] == NULL) {
            return 0;
        }
        node = node->children[prefix[i]];
    }
    return 1;
}
medium
A. Returning 1 instead of 0 when prefix is empty
B. Not checking if root is NULL before loop
C. Indexing children array without subtracting 'a' from prefix[i]
D. Using prefix[i] instead of prefix[i] - 'a' in loop condition

Solution

  1. Step 1: Identify children array indexing

    Children array is indexed by character offset from 'a', so must use prefix[i] - 'a'.
  2. Step 2: Explain impact of wrong indexing

    Using prefix[i] directly accesses out-of-bound indices, causing NULL always and returning 0.
  3. Final Answer:

    Indexing children array without subtracting 'a' from prefix[i] -> Option C
  4. Quick Check:

    Correct indexing = prefix[i] - 'a' [OK]
Hint: Always subtract 'a' when indexing children array [OK]
Common Mistakes:
  • Forgetting to subtract 'a' from character
  • Not checking for NULL root
  • Confusing loop condition with indexing
5. You want to implement a prefix search system for millions of English words. Which approach is better and why?
  1. Use a Trie to store all words and traverse nodes for prefix queries.
  2. Use a Hash Map storing all prefixes as keys with lists of words as values.
Choose the best option.
hard
A. Hash Map, because it uses less memory than Trie
B. Hash Map, because it stores all prefixes explicitly for instant lookup
C. Trie, because it requires storing all prefixes as keys explicitly
D. Trie, because it uses less memory and supports fast prefix traversal

Solution

  1. Step 1: Compare memory usage of Trie vs Hash Map for prefixes

    Trie stores characters in shared nodes, avoiding duplicate prefix storage. Hash Map stores every prefix explicitly, causing large memory use.
  2. Step 2: Compare prefix query speed and scalability

    Trie allows fast traversal by characters without storing all prefixes. Hash Map lookup is fast but building and storing all prefixes is expensive and slow.
  3. Final Answer:

    Trie, because it uses less memory and supports fast prefix traversal -> Option D
  4. Quick Check:

    Memory efficient prefix search = Trie [OK]
Hint: Trie shares prefix nodes, Hash Map stores all prefixes explicitly [OK]
Common Mistakes:
  • Assuming Hash Map uses less memory for prefixes
  • Thinking Trie stores all prefixes as separate keys
  • Ignoring scalability for millions of words
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard