Bird
Raised Fist0
DSA Pythonprogramming~20 mins

Count Words with Given Prefix in DSA Python - Practice Problems & Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Prefix Count Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of prefix count after insertions
What is the output of the code after inserting words and counting the prefix 'app'?
DSA Python
class TrieNode:
    def __init__(self):
        self.children = {}
        self.count = 0

class Trie:
    def __init__(self):
        self.root = TrieNode()

    def insert(self, word):
        node = self.root
        for ch in word:
            if ch not in node.children:
                node.children[ch] = TrieNode()
            node = node.children[ch]
            node.count += 1

    def count_prefix(self, prefix):
        node = self.root
        for ch in prefix:
            if ch not in node.children:
                return 0
            node = node.children[ch]
        return node.count

trie = Trie()
words = ['apple', 'app', 'application', 'apt', 'banana']
for w in words:
    trie.insert(w)

print(trie.count_prefix('app'))
A4
B3
C2
D1
Attempts:
2 left
💡 Hint
Count how many words start with 'app' in the list.
❓ Predict Output
intermediate
2:00remaining
Count prefix with no matching words
What is the output of counting prefix 'bat' after inserting given words?
DSA Python
class TrieNode:
    def __init__(self):
        self.children = {}
        self.count = 0

class Trie:
    def __init__(self):
        self.root = TrieNode()

    def insert(self, word):
        node = self.root
        for ch in word:
            if ch not in node.children:
                node.children[ch] = TrieNode()
            node = node.children[ch]
            node.count += 1

    def count_prefix(self, prefix):
        node = self.root
        for ch in prefix:
            if ch not in node.children:
                return 0
            node = node.children[ch]
        return node.count

trie = Trie()
words = ['cat', 'car', 'cart', 'dog']
for w in words:
    trie.insert(w)

print(trie.count_prefix('bat'))
A0
B1
C2
D3
Attempts:
2 left
💡 Hint
Check if any word starts with 'bat'.
❓ Predict Output
advanced
2:00remaining
Count prefix after multiple insertions with overlapping prefixes
What is the output after inserting words and counting prefix 'a'?
DSA Python
class TrieNode:
    def __init__(self):
        self.children = {}
        self.count = 0

class Trie:
    def __init__(self):
        self.root = TrieNode()

    def insert(self, word):
        node = self.root
        for ch in word:
            if ch not in node.children:
                node.children[ch] = TrieNode()
            node = node.children[ch]
            node.count += 1

    def count_prefix(self, prefix):
        node = self.root
        for ch in prefix:
            if ch not in node.children:
                return 0
            node = node.children[ch]
        return node.count

trie = Trie()
words = ['a', 'ab', 'abc', 'abcd', 'abcde']
for w in words:
    trie.insert(w)

print(trie.count_prefix('a'))
A4
B0
C5
D1
Attempts:
2 left
💡 Hint
Count all words starting with 'a'.
❓ Predict Output
advanced
2:00remaining
Count prefix after inserting words with shared and unique prefixes
What is the output of counting prefix 'ban' after inserting the words?
DSA Python
class TrieNode:
    def __init__(self):
        self.children = {}
        self.count = 0

class Trie:
    def __init__(self):
        self.root = TrieNode()

    def insert(self, word):
        node = self.root
        for ch in word:
            if ch not in node.children:
                node.children[ch] = TrieNode()
            node = node.children[ch]
            node.count += 1

    def count_prefix(self, prefix):
        node = self.root
        for ch in prefix:
            if ch not in node.children:
                return 0
            node = node.children[ch]
        return node.count

trie = Trie()
words = ['banana', 'band', 'bandana', 'ban', 'banner', 'bat']
for w in words:
    trie.insert(w)

print(trie.count_prefix('ban'))
A5
B6
C3
D4
Attempts:
2 left
💡 Hint
Count words starting with 'ban' only.
🧠 Conceptual
expert
2:00remaining
Understanding Trie node count increments
In a Trie implementation for counting words with a given prefix, why is the count incremented at each node during insertion?
ATo store the length of the word inserted.
BTo count the total number of children nodes under that node.
CTo mark the end of a word at that node.
DTo keep track of how many words pass through that node, enabling quick prefix counts.
Attempts:
2 left
💡 Hint
Think about how prefix counts are retrieved efficiently.

Practice

(1/5)
1. What does the function countWordsStartingWith(words, prefix) do when given a list of words and a prefix?
easy
A. Counts how many words contain the prefix anywhere inside
B. Returns the first word that starts with the prefix
C. Counts how many words in the list start with the given prefix
D. Removes all words that start with the prefix from the list

Solution

  1. Step 1: Understand the function purpose

    The function is designed to count words that begin with a specific prefix, not just contain it anywhere.
  2. Step 2: Compare options with function behavior

    Only Counts how many words in the list start with the given prefix correctly describes counting words starting with the prefix. Others describe different behaviors.
  3. Final Answer:

    Counts how many words in the list start with the given prefix -> Option C
  4. Quick Check:

    Counting words starting with prefix = Counts how many words in the list start with the given prefix [OK]
Hint: Focus on 'start with' meaning prefix at word beginning [OK]
Common Mistakes:
  • Confusing 'start with' and 'contain' prefix
  • Thinking function returns words instead of count
  • Assuming it removes words instead of counting
2. Which of the following Python code snippets correctly counts words starting with a prefix p in a list words?
easy
A. sum(word.startswith(p) for word in words)
B. sum(word.startswith(p) == 'True' for word in words)
C. sum(word.startswith(p) is 'True' for word in words)
D. sum(word.startswith(p) = True for word in words)

Solution

  1. Step 1: Check syntax correctness

    sum(word.startswith(p) = True for word in words) uses '=' inside sum which is invalid syntax for comparison.
  2. Step 2: Understand boolean summation

    Options B and C incorrectly compare boolean to string 'True' (always False). Only sum(word.startswith(p) for word in words) correctly sums booleans directly (True counts as 1).
  3. Final Answer:

    sum(word.startswith(p) for word in words) -> Option A
  4. Quick Check:

    Use sum with boolean directly for counting [OK]
Hint: Use sum with boolean expressions directly, no need for == or is [OK]
Common Mistakes:
  • Using '=' instead of '==' for comparison
  • Comparing boolean to string 'True'
  • Confusing syntax causing errors
3. What is the output of the following code?
words = ['apple', 'app', 'application', 'banana', 'apply']
prefix = 'app'
count = sum(word.startswith(prefix) for word in words)
print(count)
medium
A. 2
B. 3
C. 5
D. 4

Solution

  1. Step 1: Identify words starting with 'app'

    Words starting with 'app' are 'apple', 'app', 'application', and 'apply' -- total 4 words.
  2. Step 2: Calculate sum of True values

    Each word starting with prefix counts as 1, so sum is 4.
  3. Final Answer:

    4 -> Option D
  4. Quick Check:

    Count words starting with 'app' = 4 [OK]
Hint: Count words starting exactly with prefix, not just containing it [OK]
Common Mistakes:
  • Counting words that contain prefix anywhere
  • Missing one word that starts with prefix
  • Confusing prefix length with word length
4. Find the error in this code that tries to count words starting with prefix 'pre':
def count_prefix(words, prefix):
    count = 0
    for word in words:
        if word.startswith == prefix:
            count += 1
    return count

words = ['prefix', 'preach', 'prevent', 'post']
prefix = 'pre'
print(count_prefix(words, prefix))
medium
A. Using 'word.startswith == prefix' instead of 'word.startswith(prefix)'
B. Missing return statement in function
C. Incorrect variable name 'count' used
D. Loop should be 'for prefix in words' instead of 'for word in words'

Solution

  1. Step 1: Identify incorrect method usage

    The code uses 'word.startswith == prefix' which compares method to string, incorrect syntax.
  2. Step 2: Correct method call

    It should be 'word.startswith(prefix)' to check if word starts with prefix.
  3. Final Answer:

    Using 'word.startswith == prefix' instead of 'word.startswith(prefix)' -> Option A
  4. Quick Check:

    Method call needs parentheses with argument [OK]
Hint: Remember to call methods with parentheses and arguments [OK]
Common Mistakes:
  • Comparing method itself instead of calling it
  • Forgetting parentheses after method name
  • Mixing variable names in loop
5. Given a list of words, how would you count words starting with any prefix from a list of prefixes prefixes? Choose the correct code snippet.
words = ['cat', 'car', 'dog', 'cart', 'cow']
prefixes = ['ca', 'do', 'co']
hard
A. sum(word.startswith(prefixes[0]) or word.startswith(prefixes[1]) for word in words)
B. sum(any(word.startswith(p) for p in prefixes) for word in words)
C. sum(word.startswith(prefixes) for word in words)
D. sum(word.startswith(p) and p in prefixes for word in words)

Solution

  1. Step 1: Understand requirement for multiple prefixes

    We need to check if each word starts with any prefix in the prefixes list.
  2. Step 2: Analyze options for correct logic

    sum(any(word.startswith(p) for p in prefixes) for word in words) uses any() to correctly check if word starts with any prefix. sum(word.startswith(prefixes[0]) or word.startswith(prefixes[1]) for word in words) only checks first two prefixes (misses 'cow' with 'co'). sum(word.startswith(prefixes) for word in words) passes list to startswith (TypeError). sum(word.startswith(p) and p in prefixes for word in words) uses unbound p and incorrect and logic.
  3. Final Answer:

    sum(any(word.startswith(p) for p in prefixes) for word in words) -> Option B
  4. Quick Check:

    Use any() to check multiple prefixes per word [OK]
Hint: Use any() inside sum() to check multiple prefixes per word [OK]
Common Mistakes:
  • Passing list directly to startswith instead of iterating
  • Using 'and' instead of 'or' logic
  • Hardcoding prefix checks instead of looping
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