Leetcode 2185: Counting Words With a Given Prefix

grid47
grid47
Exploring patterns and algorithms
Apr 2, 2024 5 min read

You are given an array of strings and a target prefix. Your task is to count how many strings in the array start with this target prefix.
Problem
Approach
Steps
Complexity
Input: The input consists of an array of strings and a string prefix.
Example: Input: words = ['train', 'truck', 'trip', 'track'], pref = 'tr'
Constraints:
• 1 <= words.length <= 100
• 1 <= words[i].length, pref.length <= 100
• words[i] and pref consist of lowercase English letters.
Output: Return the number of strings in the array that start with the given prefix.
Example: Output: 3
Constraints:
• The prefix must match the beginning of the string exactly.
Goal: Count the strings in the array that begin with the specified prefix.
Steps:
• Loop through each word in the array.
• For each word, check if it starts with the given prefix.
• Increment the count for each word that matches the condition.
Goal: Conditions that the solution must satisfy.
Steps:
• 1 <= words.length <= 100
• 1 <= words[i].length, pref.length <= 100
• The input strings and the prefix consist only of lowercase English letters.
Assumptions:
• The input list is not empty.
• The input strings are valid lowercase words.
Input: Input: words = ['apple', 'april', 'banana', 'appreciate'], pref = 'ap'
Explanation: The words that start with 'ap' are 'apple', 'april', and 'appreciate'. Hence, the result is 3.

Input: Input: words = ['dog', 'cat', 'doe', 'dong'], pref = 'do'
Explanation: The words that start with 'do' are 'dog', 'doe', and 'dong'. Hence, the result is 3.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus