Level 1 Distinct counts by post, policy and day
A moderation model flags posts that break content rules, and every flag is written to a log. Build ViolationLogAnalyzer, which is created once from the whole log and then answers many questions about it.
class ViolationLogAnalyzer:
def __init__(self, logs: list[tuple[str, str, str]]): ...
Each log entry is (post_id, policy, date): the post that was flagged, the rule it broke ("spam", "nudity", ...) and the day, as "YYYY-MM-DD". The list is sorted by date (entries on the same day are in any order). The model sometimes flags the same post for the same rule on the same day more than once; such repeats count once everywhere.
Implement:
policies_for_post(post_id) -> int: how many different policies this post has ever broken.posts_for_policy(policy) -> int: how many different posts have ever broken this policy.violations_on(date) -> int: how many different(post_id, policy)pairs were flagged on this day.
Unknown posts, policies or days give 0. The log may be empty.
Do the counting once in __init__; each query must then be O(1). The tests build a log of 200,000 entries and ask 200,000 questions.
a = ViolationLogAnalyzer([
("p1", "spam", "2024-03-01"),
("p1", "spam", "2024-03-01"), # repeat, ignored
("p2", "spam", "2024-03-01"),
("p1", "hate", "2024-03-02"),
("p1", "spam", "2024-03-05"),
])
a.policies_for_post("p1") # 2 (spam, hate)
a.posts_for_policy("spam") # 2 (p1, p2)
a.violations_on("2024-03-01") # 2 (p1/spam, p2/spam)
a.violations_on("2024-03-03") # 0
Show hint
Build dicts of sets (post -> {policies} etc.) while scanning, then keep only their sizes.