Query Engine for Content Moderation Event Logs
Data Structure DesignAuto-graded · 17 test casesLast updated
Build an efficient query system over sorted violation records supporting policy lookups, post lookups, and time-based aggregations using indexing and binary search.
You need to build a query engine for a content moderation system. The engine receives a chronologically ordered log of moderation events, where each event is a triple [post_id, policy, timestamp]. The log is sorted in non-decreasing order by timestamp.
Your task is to process this log and answer various queries efficiently. Implement a function that takes the log and a series of query operations, then returns the results of all queries in order.
The system must support five types of queries:
-
count_unique_posts_by_policywith argument[policy]: Return how many different posts have ever violated the given policy. -
get_policies_for_postwith argument[post_id]: Return a sorted list of all distinct policies that this post has violated. If the post has no violations, return an empty list. -
count_unique_posts_at_timewith argument[timestamp]: Return how many different posts have at least one violation record at exactly this timestamp. -
count_unique_posts_in_rangewith arguments[start_time, end_time]: Return how many different posts have at least one violation within the inclusive time range[start_time, end_time]. -
count_violations_by_policy_in_rangewith arguments[policy, start_time, end_time]: Return the total number of violation records for the specified policy within the inclusive time range. Count each record separately, even if the same post violates the policy multiple times.
Constraints
1 <= len(logs) <= 10^5post_idandpolicyare non-empty alphanumeric strings (including underscores) with length<= 640 <= timestamp <= 10^14- The
logsarray is sorted bytimestampin non-decreasing order start_time <= end_timefor all range queries- Up to
2 * 10^4total query operations will be executed - Queries may reference policies or posts that do not exist in the log
Examples
Example 1
Input: content_moderation_query_engine([['post_1', 'spam', 100], ['post_2', 'copyright', 100], ['post_1', 'hate_speech', 150], ['post_3', 'spam', 200], ['post_1', 'spam', 250]], ['count_unique_posts_by_policy', 'get_policies_for_post', 'count_unique_posts_at_time', 'count_unique_posts_in_range', 'count_violations_by_policy_in_range'], [['spam'], ['post_1'], [100], [100, 150], ['spam', 100, 250]])
Output: [2, ['hate_speech', 'spam'], 2, 2, 3]
Hints
Hint 1
Build indexes during initialization to make each query fast—aggregate the data once rather than scanning repeatedly.
Hint 2
The log is already sorted by time, so you can use binary search for range queries without additional sorting.
Hint 3
For counting distinct posts in a time range, a post might appear at multiple timestamps within that range, so you need to track uniqueness across all matching records.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The core insight is to preprocess the log once during initialization and build indexes that make each query type fast. Rather than scanning the entire log for every query, we aggregate the data into specialized data structures.
We construct five indexes in a single pass:
-
posts_by_policy: A dictionary mapping each policy to the set of posts that violated it. Enables instant lookups for counting unique posts per policy. -
policies_by_post: A dictionary mapping each post to the set of policies it violated. Enables instant lookups for retrieving all policies a post violated. -
timestampsandposts_at_timestamp: Two parallel arrays.timestampsholds distinct timestamps in sorted order, andposts_at_timestamp[i]holds the set of posts with violations attimestamps[i]. Since the input is already sorted, we can build these by checking if the current timestamp differs from the last one. -
policy_timestamps: A dictionary mapping each policy to a sorted list of timestamps where it was violated. Crucially, this list contains one entry per log record (not deduplicated), so it can answer "how many times" queries.
With these indexes, each query type is handled as follows:
- Count unique posts by policy: Look up the policy in
posts_by_policyand return the set size. - Get policies for post: Look up the post in
policies_by_post, sort the result, and return it. - Count unique posts at exact time: Binary search for the timestamp in the
timestampsarray. If found, return the size of the corresponding post set. - Count unique posts in range: Use
bisect_left(start_time)andbisect_right(end_time)to find which timestamp buckets fall within the range, then union all post sets in those buckets and return the union size. - Count violations by policy in range: Look up the policy's timestamp list, then use binary search to find how many entries fall within
[start_time, end_time].
Why It Works
Using sets in posts_by_policy and policies_by_post automatically deduplicates, so a post that violates the same policy multiple times is counted once. The timestamp bucketing groups all events at the same moment, enabling efficient exact-time lookups. For range queries over distinct posts, we union the relevant buckets because a single post might appear in multiple timestamps within the range. For counting violation records by policy, we keep duplicates in policy_timestamps so repeated violations are counted separately.
Binary search works because the input is sorted and we preserve that order in our indexes. bisect_left(start) finds the first timestamp >= start, and bisect_right(end) finds the first timestamp > end, so the slice between them covers exactly [start, end].
Complexity
Let N be the number of log records, T the number of distinct timestamps, and P the number of policies for a single post.
- Initialization: O(N) time and O(N) space. Each record is processed once and added to constant-time data structures.
count_unique_posts_by_policy: O(1) per query.get_policies_for_post: O(P log P) per query for sorting.count_unique_posts_at_time: O(log T) per query for binary search.count_unique_posts_in_range: O(log T + R) per query, where R is the number of records in the range. Worst case O(N) if the range covers the entire log.count_violations_by_policy_in_range: O(log N) per query for binary search.
Solution
from bisect import bisect_left, bisect_right
from collections import defaultdict
from typing import List
def content_moderation_query_engine(logs: List[List], operations: List[str], arguments: List[List]) -> List:
policies_by_post = defaultdict(set)
posts_by_policy = defaultdict(set)
timestamps = []
posts_at_timestamp = []
policy_timestamps = defaultdict(list)
for post_id, policy, timestamp in logs:
policies_by_post[post_id].add(policy)
posts_by_policy[policy].add(post_id)
if not timestamps or timestamps[-1] != timestamp:
timestamps.append(timestamp)
posts_at_timestamp.append(set())
posts_at_timestamp[-1].add(post_id)
policy_timestamps[policy].append(timestamp)
results = []
for operation, args in zip(operations, arguments):
if operation == "count_unique_posts_by_policy":
policy = args[0]
results.append(len(posts_by_policy.get(policy, set())))
elif operation == "get_policies_for_post":
post_id = args[0]
results.append(sorted(policies_by_post.get(post_id, set())))
elif operation == "count_unique_posts_at_time":
timestamp = args[0]
idx = bisect_left(timestamps, timestamp)
if idx < len(timestamps) and timestamps[idx] == timestamp:
results.append(len(posts_at_timestamp[idx]))
else:
results.append(0)
elif operation == "count_unique_posts_in_range":
start_time, end_time = args
left = bisect_left(timestamps, start_time)
right = bisect_right(timestamps, end_time)
unique_posts = set()
for i in range(left, right):
unique_posts.update(posts_at_timestamp[i])
results.append(len(unique_posts))
elif operation == "count_violations_by_policy_in_range":
policy, start_time, end_time = args
values = policy_timestamps.get(policy, [])
left = bisect_left(values, start_time)
right = bisect_right(values, end_time)
results.append(right - left)
return results