Skip to main content

Command Palette

Search for a command to run...

Solving Leetcode Interviews in Seconds with AI: Find Words Containing Character

Updated
2 min read

Introduction

In this blog post, we will explore how to solve the LeetCode problem "2942" 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 0-indexed array of strings words and a character x. Return an array of indices representing the words that contain the character x. Note that the returned array may be in any order. Example 1: Input: words = ["leet","code"], x = "e" Output: [0,1] Explanation: "e" occurs in both words: "leet", and "code". Hence, we return indices 0 and 1. Example 2: Input: words = ["abc","bcd","aaaa","cbc"], x = "a" Output: [0,2] Explanation: "a" occurs in "abc", and "aaaa". Hence, we return indices 0 and 2. Example 3: Input: words = ["abc","bcd","aaaa","cbc"], x = "z" Output: [] Explanation: "z" does not occur in any of the words. Hence, we return an empty array. Constraints: 1 <= words.length <= 50 1 <= words[i].length <= 50 x is a lowercase English letter. words[i] consists only of lowercase English letters.

Explanation

  • Iterate through the words array using a for loop and keep track of the index.
    • For each word, check if the character x is present in the word using the in operator.
    • If the character is present, add the index to the result array.
  • Runtime Complexity: O(NM), where N is the number of words, and M is the maximum length of a word. *Storage Complexity: O(K), where K is the number of words that contain the character x.

Code

    def findWordsContaining(words, x):
    """
    Given a 0-indexed array of strings words and a character x, return an array of indices representing the words that contain the character x.

    Args:
        words (list[str]): A list of strings.
        x (str): A character.

    Returns:
        list[int]: A list of indices.
    """
    result = []
    for i in range(len(words)):
        if x in words[i]:
            result.append(i)
    return result

More from this blog

C

Chatmagic blog

2894 posts

Solving Leetcode Interviews in Seconds with AI: Find Words Containing Character