Solving Leetcode Interviews in Seconds with AI: Counting Words With a Given Prefix
Introduction
In this blog post, we will explore how to solve the LeetCode problem "2185" using AI. LeetCode is a popular platform for preparing for coding interviews, and with the help of AI tools like Chatmagic, we can generate solutions quickly and efficiently - helping you pass the interviews and get the job offer without having to study for months.
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","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 <= 100 1 <= words[i].length, pref.length <= 100 words[i] and pref consist of lowercase English letters.
Explanation
- Iterate Through Words: Loop through each word in the input array
words.- Check Prefix: For each word, efficiently check if the input
prefis a prefix of that word using string slicing. - Count Matches: Increment a counter if the prefix matches.
- Check Prefix: For each word, efficiently check if the input
- Time Complexity: O(NM), where N is the number of words and M is the maximum length of a word or the prefix. *Space Complexity: O(1).
Code
def prefixCount(words: list[str], pref: str) -> int:
"""
Counts the number of strings in 'words' that have 'pref' as a prefix.
"""
count = 0
for word in words:
if word.startswith(pref):
count += 1
return count