Skip to main content

Command Palette

Search for a command to run...

Solving Leetcode Interviews in Seconds with AI: Report Spam Message

Updated
2 min read

Introduction

In this blog post, we will explore how to solve the LeetCode problem "3295" 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 message and an array of strings bannedWords. An array of words is considered spam if there are at least two words in it that exactly match any word in bannedWords. Return true if the array message is spam, and false otherwise. Example 1: Input: message = ["hello","world","leetcode"], bannedWords = ["world","hello"] Output: true Explanation: The words "hello" and "world" from the message array both appear in the bannedWords array. Example 2: Input: message = ["hello","programming","fun"], bannedWords = ["world","programming","leetcode"] Output: false Explanation: Only one word from the message array ("programming") appears in the bannedWords array. Constraints: 1 <= message.length, bannedWords.length <= 105 1 <= message[i].length, bannedWords[i].length <= 15 message[i] and bannedWords[i] consist only of lowercase English letters.

Explanation

Here's the breakdown of the solution:

  • Hashing for Efficiency: Use a hash set (Python's set) to store the bannedWords. This allows for O(1) average-case time complexity for checking if a word is banned.
  • Counting Banned Words: Iterate through the message array and increment a counter each time a word is found in the bannedWords set.
  • Early Exit: If the counter reaches 2, return True immediately because the message is already considered spam.

  • Runtime Complexity: O(m + n), where n is the length of bannedWords and m is the length of message.

  • Storage Complexity: O(n), where n is the length of bannedWords.

Code

    def is_spam(message: list[str], bannedWords: list[str]) -> bool:
    """
    Determines if a message is spam based on the number of banned words it contains.

    Args:
        message: A list of strings representing the message.
        bannedWords: A list of strings representing the banned words.

    Returns:
        True if the message is spam, False otherwise.
    """

    banned_set = set(bannedWords)
    banned_count = 0

    for word in message:
        if word in banned_set:
            banned_count += 1
            if banned_count >= 2:
                return True

    return False

More from this blog

C

Chatmagic blog

2894 posts