Banned-Word Review Screener with Per-User Strike Counts
Data Structure DesignAuto-graded · 14 test casesLast updated
Simulate a stateful screening service driven by an operation log: whole-token, case-insensitive banned-word checks, replaceable word lists, and per-user flagged-review tallies.
Banned-Word Review Screener
A shopping site wants to screen user-submitted product reviews. A review is flagged when it contains at least one banned word. The service also keeps a tally of how many of each user's reviews have been flagged. The list of banned words can be swapped out while the service is running.
Instead of calling a class directly, your function receives a log of operations and must replay it, returning one result per operation.
Operations
Each operation is a name in operations, paired with an argument list at the same index in arguments.
| Operation | Arguments | Effect | Result |
|---|---|---|---|
"init" | [words] | Start a fresh service whose banned list is words. All previous state, including every user's tally, is discarded. | None |
"process_review" | [user_id, review_text] | Decide whether the review is flagged. If it is, add 1 to that user's tally. | True if flagged, else False |
"get_violation_count" | [user_id] | Look up how many of this user's reviews have been flagged so far. | the tally (an int, 0 if the user has none) |
"update_prohibited_words" | [new_words] | Replace the current banned list with new_words (do not merge). Tallies are kept as they are. | None |
Matching rules
- Split
review_textinto tokens on whitespace. Punctuation is not removed: it stays part of the token. For example, in"This is spam."the token is"spam.", which does not match the banned word"spam". - Matching is case-insensitive:
"Spam","SPAM"and"spam"are the same word (use Unicode case folding). - A token matches only if it equals a banned word in full. Substrings never match, so banning
"spam"does not flag"spammy", unless"spammy"is itself banned. - A review is flagged if at least one token matches. A review with several banned tokens still adds only 1 to the tally.
- An empty or whitespace-only review has no tokens and is never flagged.
- Every
process_reviewuses the banned list that is current at that moment. - If an operation other than the four above appears, raise
ValueError. - Before any
"init", the banned list is empty and no tallies exist.
Task
Implement screen_reviews(operations, arguments) that replays the log and returns the list of results, in order, one per operation.
Constraints
len(operations) == len(arguments).user_idvalues and review texts are strings; banned words are strings.- The banned list may be empty.
- Processing a review should take time linear in its length, independent of the number of banned words.
Examples
Example 1
Input: screen_reviews(['init', 'process_review', 'process_review', 'get_violation_count'], [[['spam', 'bot']], ['user1', 'This is a great product'], ['user1', 'This is spam'], ['user1']])
Output: [None, False, True, 1]
Hints
Hint 1
Keep two pieces of state: a collection of banned words that supports fast membership tests, and a mapping from user to the number of flagged reviews.
Hint 2
Normalize case once when a banned list is stored, and normalize each token when checking it. Use plain whitespace splitting and do not strip punctuation.
Hint 3
Stop at the first matching token, since each review adds at most 1. Remember that `init` clears tallies, while `update_prohibited_words` replaces only the word list and keeps tallies.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Maintain two pieces of state while replaying the log:
banned: a set of case-folded banned words, giving O(1) average membership checks.strikes: a dictionary fromuser_idto the number of that user's flagged reviews.
For each operation:
init: rebuildbannedfrom the given words (case-folded) and clearstrikes.process_review: split the text on whitespace, case-fold each token, and check whether any token is inbanned. If so, increment the user's tally by exactly 1. Append the boolean result.get_violation_count: returnstrikes.get(user_id, 0).update_prohibited_words: rebuildbannedfrom the new words, replacing the old set.strikesis untouched.- Anything else raises
ValueError.
Why it is correct
- Case-insensitivity: both stored words and review tokens are case-folded, so differently cased forms compare equal.
- Whole-token matching: set membership compares full tokens, so
"spammy"never matches"spam", and overlapping banned words are simply separate entries. - Punctuation:
str.split()leaves punctuation attached, so"spam."is a different token from"spam", exactly as the rules require. - One increment per review:
anyyields a single boolean, and the tally is increased once at most, so the tally counts reviews rather than offending words. - Updates: replacing the set means every later review sees the current list, while the untouched dictionary preserves history.
- Edge cases: empty text gives no tokens, so
anyisFalse; unknown users return 0 because they are never stored.
Complexity
Let L be the length of a review text and K the total characters in a banned list.
init/update_prohibited_words: O(K) time, O(K) space.process_review: O(L) average time, independent of the number of banned words; O(L) temporary space for tokens.get_violation_count: O(1) average.- Persistent state: O(number of banned words + number of flagged users).
Reference solution
from typing import List
def screen_reviews(operations: List[str], arguments: List[List]) -> List:
banned = set()
strikes = {}
results = []
for op, args in zip(operations, arguments):
if op == "init":
banned = {w.casefold() for w in args[0]}
strikes = {}
results.append(None)
elif op == "process_review":
user_id, text = args
flagged = any(tok.casefold() in banned for tok in text.split())
if flagged:
strikes[user_id] = strikes.get(user_id, 0) + 1
results.append(flagged)
elif op == "get_violation_count":
results.append(strikes.get(args[0], 0))
elif op == "update_prohibited_words":
banned = {w.casefold() for w in args[0]}
results.append(None)
else:
raise ValueError(f"Unknown operation: {op}")
return results