Taro Logo

Counting Words With a Given Prefix

Easy
Meta logo
Meta
3 views
Topics:
ArraysStrings

You are given an array of strings words and a string pref.

Return the number of strings in words that contain pref as a prefix.

A prefix of a string s is any leading contiguous substring of s.

For example:

  1. If words = ["pay","attention","practice","attend"] and pref = "at", the output should be 2 because "attention" and "attend" contain "at" as a prefix.
  2. If words = ["leetcode","win","loops","success"] and pref = "code", the output should be 0 because none of the words contain "code" as a prefix.

Write a function that takes an array of strings words and a string pref as input and returns the number of strings in words that have pref as a prefix. What is the time and space complexity of your solution? Consider edge cases such as an empty words array or an empty pref string.

Solution


Naive Solution

The most straightforward approach is to iterate through the words array and, for each word, check if the pref is a prefix of that word. We can use string slicing or built-in prefix checking methods to achieve this.

Code (Python)

def prefix_count_naive(words, pref):
    count = 0
    for word in words:
        if word.startswith(pref):
            count += 1
    return count

Time Complexity

O(N * M), where N is the number of words in the words array, and M is the maximum length of a word in words or the length of pref.

Space Complexity

O(1), as we use only a constant amount of extra space.

Optimal Solution

The optimal solution has the same time and space complexity as the naive solution because we still need to iterate through all the words to check for the prefix. However, the code can be slightly optimized for readability and conciseness.

Code (Python)

def prefix_count_optimal(words, pref):
    return sum(1 for word in words if word.startswith(pref))

Time Complexity

O(N * M), where N is the number of words in the words array, and M is the maximum length of a word in words or the length of pref.

Space Complexity

O(1), as we use only a constant amount of extra space.

Edge Cases

  • Empty words array: Should return 0.
  • Empty pref: Every word has an empty string as a prefix, so return the number of words.
  • pref longer than a word in words: The word cannot have pref as a prefix, so it should not be counted.

Summary

Both solutions have the same time and space complexity. The optimal solution is just a more concise way to express the same logic. We iterate through the words array and check if each word starts with the given prefix pref. The count of such words is then returned.