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.