We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Counting Words With a Given Prefix

Number: 2292

Difficulty: Easy

Paid? No

Companies: Microsoft, Meta, DoorDash, Google


Problem Description

Given an array of strings called words and a string pref, count how many strings in words have pref as a prefix. A prefix is defined as any initial contiguous substring of a string.


Key Insights

  • The problem is straightforward and requires checking if each word starts with the given prefix.
  • Use built-in string functions (like startsWith in JavaScript or substrings in Python) to simplify the solution.
  • Since the constraints are small, a simple linear scan through the array is sufficient.

Space and Time Complexity

Time Complexity: O(n * m), where n is the number of words and m is the average length of the prefix (in worst-case, we compare each character). Space Complexity: O(1), not including the input storage.


Solution

Iterate through each word in the array and check if the word starts with the given prefix using available string operations. Count the number of words which satisfy this condition and return the count.

  • Data structures: Basic list/array iteration.
  • Algorithmic approach: Use a simple loop with a prefix check.
  • Gotchas: Ensure that the prefix is handled correctly, especially when the prefix length is greater than the current word length.

Code Solutions

# Define a function that counts words with the given prefix
def count_prefix_occurrences(words, pref):
    # Initialize the count of words having the prefix
    count = 0
    # Iterate over each word in the list
    for word in words:
        # If the current word starts with the prefix, increment the count
        if word.startswith(pref):
            count += 1
    # Return the final count of valid words
    return count

# Example usage:
words = ["pay", "attention", "practice", "attend"]
pref = "at"
print(count_prefix_occurrences(words, pref))  # Expected output: 2
← Back to All Questions