We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Report Spam Message

Number: 3541

Difficulty: Medium

Paid? No

Companies: IBM


Problem Description

Given an array of strings named message and an array of strings named bannedWords, determine if the message is considered spam. A message is spam if at least two words from the message exactly match any word in bannedWords. Return true if the message is spam; otherwise, return false.


Key Insights

  • Use a set to store bannedWords for efficient lookups.
  • Iterate through each word in the message and count how many appear in the bannedWords set.
  • As soon as the count reaches two, return true to avoid unnecessary iterations.
  • If the iteration completes and the count is less than two, return false.

Space and Time Complexity

Time Complexity: O(n + m), where n is the length of message and m is the length of bannedWords.
Space Complexity: O(m), for storing bannedWords in a set.


Solution

We will solve the problem by first converting the bannedWords list into a set to allow O(1) average-time lookups. Then, iterate over the message array and count each occurrence of a banned word. If the count reaches two, we immediately return true. If the loop completes and the count is less than two, we return false. This approach minimizes unnecessary processing by halting early when enough banned words are found.


Code Solutions

# Python solution

def isSpamMessage(message, bannedWords):
    # Convert bannedWords list to a set for quick lookup
    banned_set = set(bannedWords)
    # Initialize a counter for banned words found in the message
    count = 0

    # Iterate through each word in the message
    for word in message:
        # If the word is in the banned set, increment the counter
        if word in banned_set:
            count += 1
            # If at least two banned words are found, return True immediately
            if count == 2:
                return True
    # If fewer than two banned words are found during iteration, return False
    return False

# Example usage:
# message = ["hello", "world", "leetcode"]
# bannedWords = ["world", "hello"]
# print(isSpamMessage(message, bannedWords))  # Output: True
← Back to All Questions