Hint: Count words where strncmp returns 0 for prefix length [OK]
Common Mistakes:
Counting words that contain prefix anywhere
Off-by-one errors in loop
Incorrect prefix length in strncmp
4. Find the bug in this C code that counts words starting with prefix prefix:
int countWords(char *words[], int n, char *prefix) {
int count = 0;
for (int i = 0; i <= n; i++) {
if (strncmp(words[i], prefix, strlen(prefix)) == 0) {
count++;
}
}
return count;
}
medium
A. Initialize count to 1 instead of 0
B. Use strcmp instead of strncmp
C. Loop condition should be i < n, not i <= n
D. strlen(prefix) should be replaced with strlen(words[i])
Solution
Step 1: Analyze loop boundary
Loop runs from i = 0 to i <= n, which accesses words[n] (out of bounds).
Step 2: Correct loop condition
Change to i < n to avoid accessing beyond array size.
Final Answer:
Loop condition should be i < n, not i <= n -> Option C
Quick Check:
Array index must be less than size [OK]
Hint: Use i < n for array loops to avoid overflow [OK]
Common Mistakes:
Using <= instead of < in loops
Confusing strcmp and strncmp usage
Wrong length argument in strncmp
5. You have a list of words and want to count how many start with prefix pre. Which approach is best to optimize counting if you must do many prefix queries efficiently?
hard
A. Build a trie (prefix tree) from words and count nodes matching prefix
B. Use strncmp on each word for every query
C. Sort words and use binary search for prefix range
D. Store words in a hash set and check prefix membership
Solution
Step 1: Understand multiple prefix queries
Checking each word with strncmp repeatedly is slow for many queries.
Step 2: Choose data structure for fast prefix counting
Trie stores words by prefixes, allowing quick count of words with given prefix.
Step 3: Compare alternatives
Binary search helps but trie is more direct for prefix counts; hash set doesn't support prefix queries well.
Final Answer:
Build a trie (prefix tree) from words and count nodes matching prefix -> Option A
Quick Check:
Trie = fast prefix count [OK]
Hint: Use trie for fast multiple prefix queries [OK]
Common Mistakes:
Using linear search for many queries
Ignoring trie benefits for prefix problems
Using hash set which doesn't support prefix search
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.