Counting Words With a Given Prefix - Complete Solution Guide
Counting Words With a Given Prefix is LeetCode problem 2185, a Easy level challenge. This complete guide provides step-by-step explanations, multiple solution approaches, and optimized code in python3.
Problem Statement
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"," at tention","practice"," at tend"], pref = "at" Output: 2 Explanation: The 2 strings that contain "at" as a prefix are: " at tention" and " at tend". Example 2: Input: words = ["leetcode","win","loops","success"], pref = "code" Output: 0 Explanation: There are no strin
Detailed Explanation
The problem asks you to count how many strings in a given array `words` start with a specific prefix `pref`. The input is an array of strings (`words`) and a string (`pref`). The output is a single integer representing the number of strings in `words` that begin with `pref`. The constraints specify that the lengths of the words and the prefix are relatively small, limiting the scale of the problem. For example, if `words` = ["pay","attention","practice","attend"] and `pref` = "at", the output should be 2 because "attention" and "attend" start with "at".
Solution Approach
The solution uses a straightforward iterative approach. It iterates through each string in the `words` array. For each string, it uses the built-in `startswith()` method to check if the string begins with the given `pref`. If it does, a counter is incremented. Finally, the counter (representing the total number of strings with the prefix) is returned.
Step-by-Step Algorithm
- Step 1: Initialize a counter variable `count` to 0.
- Step 2: Iterate through each string `word` in the input array `words`.
- Step 3: For each `word`, check if it starts with the prefix `pref` using `word.startswith(pref)`.
- Step 4: If `word.startswith(pref)` is true, increment the `count`.
- Step 5: After iterating through all words, return the final value of `count`.
Key Insights
- Insight 1: The `startswith()` method in Python provides a concise way to check if a string begins with a given prefix.
- Insight 2: A simple iterative approach is sufficient to solve this problem due to the small input size constraints.
- Insight 3: No significant optimizations are needed given the constraints. More complex data structures or algorithms would introduce unnecessary overhead.
Complexity Analysis
Time Complexity: O(n*m)
Space Complexity: O(1)
Topics
This problem involves: Array, String, String Matching.
Companies
Asked at: DoorDash.