Skip to main content

Command Palette

Search for a command to run...

Solving Leetcode Interviews in Seconds with AI: Counting Words With a Given Prefix

Updated
2 min read

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 pref is a prefix of that word using string slicing.
    • Count Matches: Increment a counter if the prefix matches.
  • 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

More from this blog

C

Chatmagic blog

2894 posts