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.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.
C++
Java
Python
C#
JavaScript
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.
C++
Python
JavaScript
Java
C#
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. |
Longest Common Prefix - Leetcode 14 - Python • NeetCode • 217,791 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