progress

~/problems / Binary search / Binary search

Violation Log Analyzer

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or fight a boss.

medium assessment 2 levels ~40 min Pinterest

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.

⭐ Bonus: a speed test (200,000 entries, 200,000 questions) earns a star if you count once in __init__ and answer each query in O(1).

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.

Level 2 unlocks when level 1 passes.

Topic: Binary search. lo/hi invariants, lower vs upper bound, rotated arrays, bisect.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc