Skip to main content

Command Palette

Search for a command to run...

Solving Leetcode Interviews in Seconds with AI: Count Prefixes of a Given String

Updated
3 min read

Introduction

In this blog post, we will explore how to solve the LeetCode problem "2255" 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 a string array words and a string s, where words[i] and s comprise only of lowercase English letters. Return the number of strings in words that are a prefix of s. A prefix of a string is a substring that occurs at the beginning of the string. A substring is a contiguous sequence of characters within a string. Example 1: Input: words = ["a","b","c","ab","bc","abc"], s = "abc" Output: 3 Explanation: The strings in words which are a prefix of s = "abc" are: "a", "ab", and "abc". Thus the number of strings in words which are a prefix of s is 3. Example 2: Input: words = ["a","a"], s = "aa" Output: 2 Explanation: Both of the strings are a prefix of s. Note that the same string can occur multiple times in words, and it should be counted each time. Constraints: 1 <= words.length <= 1000 1 <= words[i].length, s.length <= 10 words[i] and s consist of lowercase English letters only.

Explanation

Here's the approach:

  • Iterate through the words array.
  • For each word, check if it's a prefix of s using string slicing and comparison.
  • Increment a counter if the word is a prefix.

  • Runtime: O(n*k), where n is the number of words and k is the maximum length of a word. Storage: O(1).

Code

    def prefixCount(words: list[str], s: str) -> int:
    """
    Given a string array words and a string s, where words[i] and s comprise only of lowercase English letters.
    Return the number of strings in words that are a prefix of s.
    A prefix of a string is a substring that occurs at the beginning of the string.
    A substring is a contiguous sequence of characters within a string.

    Example 1:
    Input: words = ["a","b","c","ab","bc","abc"], s = "abc"
    Output: 3
    Explanation: The strings in words which are a prefix of s = "abc" are: "a", "ab", and "abc".
    Thus the number of strings in words which are a prefix of s is 3.

    Example 2:
    Input: words = ["a","a"], s = "aa"
    Output: 2
    Explanation: Both of the strings are a prefix of s.
    Note that the same string can occur multiple times in words, and it should be counted each time.

    Constraints:
    1 <= words.length <= 1000
    1 <= words[i].length, s.length <= 10
    words[i] and s consist of lowercase English letters only.
    """
    count = 0
    for word in words:
        if len(word) <= len(s) and s[:len(word)] == word:
            count += 1
    return count

More from this blog

C

Chatmagic blog

2894 posts