Report Spam Message - Problem

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.

Input & Output

Example 1 — Spam Detected
$ Input: message = ["hello","world","spam","test"], bannedWords = ["spam","scam"]
Output: true
💡 Note: The message contains "spam" which matches a banned word, but since we need at least 2 matches and only found 1, this should return false. However, this example appears to be incomplete or incorrect.
Example 2 — Multiple Spam Words
$ Input: message = ["hello","spam","world","scam"], bannedWords = ["spam","scam"]
Output: true
💡 Note: The message contains both "spam" and "scam" which are both in bannedWords. Since we have 2 matches, return true.
Example 3 — Not Enough Matches
$ Input: message = ["hello","world","test"], bannedWords = ["spam","scam"]
Output: false
💡 Note: No words in the message match any banned words, so return false.

Constraints

  • 1 ≤ message.length ≤ 104
  • 1 ≤ bannedWords.length ≤ 104
  • 1 ≤ message[i].length, bannedWords[i].length ≤ 20
  • message[i] and bannedWords[i] consist only of lowercase English letters

Visualization

Tap to expand
Report Spam Message - Hash Set Optimization INPUT message[] "hello" "world" "spam" "test" bannedWords[] "spam" "scam" Hash Set Created "spam" "scam" O(1) lookup ALGORITHM STEPS 1 Build Hash Set Add all bannedWords 2 Initialize Counter count = 0 3 Scan Message Check each word in set 4 Return Result count >= 2 means spam Iteration Trace Word In Set? Count "hello" No 0 "world" No 0 "spam" Yes 1 "test" No 1 FINAL RESULT Final Count 1 Spam Condition: count >= 2 ? 1 < 2 = false count >= 2 Output true Message IS spam! 2+ banned words found Key Insight: Using a Hash Set for bannedWords enables O(1) lookup time for each word check. Total time complexity: O(m + n) where m = bannedWords length, n = message length. Space complexity: O(m) for storing the hash set of banned words. TutorialsPoint - Report Spam Message | Hash Set Optimization
Asked in
Google 25 Microsoft 18 Amazon 15
12.0K Views
Medium Frequency
~15 min Avg. Time
485 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen