Report Spam Message Problem
#3295
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 3295.
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 <= 10^51 <= message[i].length, bannedWords[i].length <= 15message[i]andbannedWords[i]consist only of lowercase English letters.
Solution
Approach: Hash Set
Put all banned words into a hash set. Scan message and count the words found in the set; as soon as the count reaches 2 the message is spam, so return true. If the scan ends with fewer than two matches, return false.
Complexity:
- Time complexity:
O(n + m), up to the word length - Space complexity:
O(m)
class Solution:
def reportSpam(self, message: List[str], bannedWords: List[str]) -> bool:
s = set(bannedWords)
return sum(w in s for w in message) >= 2