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.
Example 1:
Input: words = ["pay","attention","practice","attend"], pref = "at"
Output: 2
Explanation: The 2 strings that contain "at" as a prefix are: "attention" and "attend".
Example 2:
Input: words = ["leetcode","win","loops","success"], pref = "code"
Output: 0
Explanation: There are no strings that contain "code" as a prefix.
Constraints:
1 <= words.length <= 1001 <= words[i].length, pref.length <= 100words[i] and pref consist of lowercase English letters.Problem Overview: You are given an array of strings words and a string pref. The task is to count how many words in the array start with the prefix pref. A word is considered valid if its first characters exactly match the prefix.
Approach 1: Iterative Prefix Check (O(n * m) time, O(1) space)
The most direct solution scans every word in the array and checks whether it starts with pref. For each string, compare the first m characters (where m is the length of the prefix). Many languages provide a built‑in operation such as startsWith() or substring comparison, which performs this check efficiently. Since each of the n words may require up to m character comparisons, the time complexity is O(n * m). The algorithm uses constant extra memory O(1). This approach is simple, readable, and usually preferred for small or moderate input sizes involving arrays of strings.
Approach 2: Trie-based Prefix Matching (O(n * m) build, O(m) query, O(n * m) space)
A Trie (prefix tree) stores characters of all words so shared prefixes occupy the same path. Insert every word character by character into the Trie while maintaining a count of words passing through each node. Once built, traverse the nodes corresponding to pref. The stored counter at the final node directly gives the number of words starting with that prefix. Building the structure takes O(n * m) time and space because each character is inserted once. The prefix lookup itself takes O(m). Trie solutions are common in string matching problems when many prefix queries are expected.
Recommended for interviews: The iterative prefix check is what interviewers typically expect for this problem. It demonstrates clean iteration and efficient use of built‑in string operations. The Trie approach shows deeper knowledge of prefix data structures and becomes valuable if the system must answer many prefix queries repeatedly.
This approach involves iterating over each word in the list and checking if it starts with the given prefix. This can be achieved using the available string methods in each respective programming language, which allow us to check for a prefix directly. The approach is straightforward and efficient for the given constraints.
This C code defines a function countWordsWithPrefix which counts the number of words in the given array that start with the specified prefix. It uses the strncmp function to compare the start of each word with the prefix.
Time Complexity: O(n * m), where n is the number of words and m is the length of the prefix.
Space Complexity: O(1), no extra space needed except for variables.
A trie (prefix tree) is a data structure that is very efficient for prefix-based operations. In this approach, we'll first insert all the words into a trie. Then, we'll traverse the trie with the characters of the prefix and count all words that continue from there. Though a bit more complex to implement, this approach is optimal for scenarios where you perform multiple prefix searches.
This C code uses a trie to efficiently store and search the words. Each node in the trie represents a letter and can branch out to the next potential letter in any stored words. After constructing the trie with all the words, we traverse it with the prefix and count all completions that continue from there.
Time Complexity: O(L + k), where L is the total number of characters in all words and k is the number of characters in the prefix.
Space Complexity: O(ALPHABET_SIZE * L), where ALPHABET_SIZE is 26 for lowercase letters and L is the total number of characters in all words.
| Approach | Complexity |
|---|---|
| Iterative Approach | Time Complexity: O(n * m), where n is the number of words and m is the length of the prefix. |
| Trie-based Approach | Time Complexity: O(L + k), where L is the total number of characters in all words and k is the number of characters in the prefix. |
| Default Approach | — |
| Approach | Time | Space | When to Use |
|---|---|---|---|
| Iterative Prefix Check | O(n * m) | O(1) | Best for a single query over the array. Simple and optimal for most interview scenarios. |
| Trie-based Prefix Matching | O(n * m) build, O(m) query | O(n * m) | Useful when many prefix queries must be answered repeatedly on the same dataset. |
Counting Words With a Given Prefix - Leetcode 2185 - Python • NeetCodeIO • 7,745 views views
Watch 9 more video solutions →Practice Counting Words With a Given Prefix with our built-in code editor and test cases.
Practice on FleetCode