Time-Indexed Moderation Log Queries
Medium · Coding & Algorithms · Software Engineer · Technical Screen
Problem Statement
Build an in-memory analytics index over a chronological log of Trust & Safety enforcement events. You are given a fixed snapshot logs, where each entry [post_id, policy, timestamp] records that post_id triggered policy at integer time timestamp. Entries in logs are pre-ordered so timestamp never decreases from one entry to the next; several entries may share the same timestamp, and a single post_id may trigger different policies or repeat the same policy multiple times.
Implement a PolicyViolationTracker class supporting these methods:
__init__(self, logs: List[List]): Indexeslogsso subsequent queries execute quickly.count_unique_posts_by_policy(self, policy: str) -> int: Returns how many distinctpost_idvalues appear in at least one entry forpolicy.get_policies_for_post(self, post_id: str) -> List[str]: Returns every distinctpolicytriggered bypost_id, ordered alphabetically in standard ASCII/lexicographical order (or[]ifpost_idnever appears).count_unique_posts_at_time(self, timestamp: int) -> int: Returns how many distinctpost_idvalues have at least one entry at exacttimestamp.count_unique_posts_in_range(self, start_time: int, end_time: int) -> int: Returns how many distinctpost_idvalues have at least one entry withstart_time <= timestamp <= end_time.count_violations_by_policy_in_range(self, policy: str, start_time: int, end_time: int) -> int: Returns the total number of log entries (counting repeated entries from the same post) matchingpolicywithstart_time <= timestamp <= end_time.
Also implement the batch entry point evaluated by the test harness:
def policy_violation_tracker(
logs: List[List],
operations: List[str],
arguments: List[List],
) -> List:
policy_violation_tracker constructs one PolicyViolationTracker(logs) instance, invokes operations[i] with positional arguments arguments[i] for each i, and returns the collected return values in order.
Examples
Example 1
logs = [
["pin_10", "malware", 20],
["pin_20", "nudity", 20],
["pin_10", "harassment", 50],
["pin_30", "malware", 80],
["pin_10", "malware", 110],
["pin_20", "malware", 110],
]
operations = [
"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",
]
arguments = [
["malware"],
["pin_10"],
[20],
[20, 80],
["malware", 20, 110],
]
Output: [3, ["harassment", "malware"], 2, 3, 4]
Walk-through:
- "malware" appears on "pin_10", "pin_20", and "pin_30", giving 3 distinct posts.
- "pin_10" triggered "malware" (twice) and "harassment" (once), yielding ["harassment", "malware"] once deduplicated and sorted.
- At timestamp == 20, "pin_10" and "pin_20" appear (2 distinct posts).
- Over [20, 80], entries at 20, 20, 50, 80 touch "pin_10", "pin_20", and "pin_30" (3 distinct posts).
- Over [20, 110], "malware" has 4 total log entries (20, 80, 110, and 110), counting "pin_10" twice.
Example 2
logs = [
["pin_7", "phishing", 300],
["pin_7", "phishing", 300],
["pin_8", "impersonation", 450],
]
operations = [
"count_unique_posts_at_time",
"count_violations_by_policy_in_range",
"get_policies_for_post",
"count_unique_posts_in_range",
]
arguments = [
[300],
["phishing", 300, 300],
["pin_99"],
[301, 449],
]
Output: [1, 2, [], 0]
Walk-through: At 300, "pin_7" has two identical entries — counting as 1 unique post for count_unique_posts_at_time(300) but 2 violation records for count_violations_by_policy_in_range("phishing", 300, 300). "pin_99" has no entries ([]), and no timestamps fall inside [301, 449] (0).
Constraints
1 <= len(logs) <= 10^5post_idandpolicyare non-empty strings (len <= 64) containing only ASCII letters, digits, and underscores.0 <= timestamp <= 10^14logsis ordered in non-decreasingtimestamporder.start_time <= end_timefor every range call, and both boundaries are inclusive.1 <= len(operations) == len(arguments) <= 2 * 10^4
Step-by-step walkthrough
Understand the five queries and what must be deduplicated
We receive a static log
logsof[post_id, policy, timestamp]entries, already ordered sotimestampnever decreases, and must answer up to2 * 10^4calls across five methods:Method What it counts / returns ---------------------------------------------- ------------------------------------------------ count_unique_posts_by_policy(policy) distinct post_ids that ever triggered 'policy' get_policies_for_post(post_id) sorted distinct policies triggered by 'post_id' count_unique_posts_at_time(timestamp) distinct post_ids at exact 'timestamp' count_unique_posts_in_range(start, end) distinct post_ids in inclusive [start, end] count_violations_by_policy_in_range(pol, s, e) ALL entries (repeats included!) of 'pol' in [s, e]Keep the difference sharp between distinct posts (if
pin_10appears three times inside[start, end], it contributes1tocount_unique_posts_in_range) and raw log entries (every matching entry adds1tocount_violations_by_policy_in_range).Why scanning per query (or per window) is too slow
Looping through
logson each query takesO(n)work. Withn = 10^5entries andq = 2 * 10^4calls,n * q = 2 * 10^9steps will time out.Even if we jump straight to the matching slice
[lo, hi)with binary search, computinglen(set(posts[lo:hi]))on everycount_unique_posts_in_rangecall still walks allhi - loentries! When2 * 10^4calls ask about wide windows spanning almost all10^5entries,set(posts[lo:hi])still performs~2 * 10^9iterations. Becauselogsis fixed once__init__runs, we can build indexes once up front so every query runs inO(1)or polylogarithmic time.Answer the three point queries with pre-aggregated hash sets
Three methods look up one exact key (
policy,post_id, ortimestamp). In a single pass overlogsinside__init__, we populate three dictionaries of Pythonsets:posts_by_policy[policy]-> set of distinctpost_idstringspolicies_by_post[post_id]-> set of distinctpolicystringsposts_by_time[timestamp]-> set of distinctpost_idstrings
Sets ignore duplicates automatically, so counts take
O(1)time vialen(...), andget_policies_for_postreturnssorted(...)(a fresh list in lexicographical ASCII order so caller code cannot mutate our internal set):def count_unique_posts_by_policy(self, policy: str) -> int: return len(self.posts_by_policy.get(policy, ())) def get_policies_for_post(self, post_id: str) -> List[str]: # sorted() returns a fresh list in lexicographical order so callers cannot mutate internal sets. return sorted(self.policies_by_post.get(post_id, ())) def count_unique_posts_at_time(self, timestamp: int) -> int: return len(self.posts_by_time.get(timestamp, ()))Count policy violations in a range with binary search
count_violations_by_policy_in_range(policy, start_time, end_time)counts all matching entries, duplicates included. Appending each entry's timestamp totimes_by_policy[policy]during our single pass keepstimes_by_policy[policy]automatically sorted becauselogsarrives in non-decreasing timestamp order.In a sorted list, all timestamps inside
[start_time, end_time]occupy one contiguous slice[left_idx, right_idx)that binary search (bisect) locates inO(log n)time:policy_times ("malware"): [ 20, 80, 110, 110 ] index: 0 1 2 3 ^ ^ bisect_left(20) = 0 bisect_right(110) = 4 -> count = 4 - 0 = 4bisect_left(policy_times, start_time)finds the first index withtime >= start_time(keeping ties atstart_time).bisect_right(policy_times, end_time)lands one past the last index withtime <= end_time(keeping ties atend_time).
def count_violations_by_policy_in_range(self, policy: str, start_time: int, end_time: int) -> int: policy_times = self.times_by_policy.get(policy) if policy_times is None: return 0 left_idx = bisect_left(policy_times, start_time) right_idx = bisect_right(policy_times, end_time) if right_idx <= left_idx: return 0 return right_idx - left_idxKey trick for unique posts in a range: count first occurrences via `prev_index`
Applying
bisect_leftandbisect_righttoself.times(all entry timestamps) converts[start_time, end_time]into the half-open index slice[lo, hi). How can we count unique posts insidelogs[lo:hi]without scanning fromlotohi?Count each post only at its earliest index inside
[lo, hi)! During__init__, recordprev_index[i]= the most recent index< iwherelogs[i]'spost_idappeared (or-1ifiis that post's very first entry inlogs):index i: 0 1 2 3 4 5 post_id: pin_10 pin_20 pin_10 pin_30 pin_10 pin_20 timestamp: 20 20 50 80 110 110 prev_index: -1 -1 0 -1 2 1 |<-------- query [50, 110] -------->| lo = 2 hi = 6 i=2: prev= 0 < 2 (COUNT pin_10!) i=3: prev=-1 < 2 (COUNT pin_30!) i=4: prev= 2 >= 2 (skip repeat pin_10!) i=5: prev= 1 < 2 (COUNT pin_20!)Notice why this holds for every post present in
[lo, hi): - Its earliest entry inside[lo, hi)has no prior entry inside[lo, hi), so itsprev_index[i]must be strictly less thanlo(prev_index[i] < lo). - Every later entry of that same post inside[lo, hi)points back to an index>= lo, soprev_index[i] >= lo.Thus, the count of distinct posts in
[lo, hi)equals the exact number of indicesiin[lo, hi)satisfyingprev_index[i] < lo!Answer `prev_index[i] < lo` in `O(log^2 n)` with a merge sort tree
Now we only need to answer: "Within slice
prev_index[lo:hi], how many entries are strictly< lo?"A merge sort tree is a binary segment tree over index intervals
[node_lo, node_hi)in which every node stores a sorted list ofprev_index[node_lo:node_hi]:[0..6): [-1, -1, -1, 0, 1, 2] / \ [0..3): [-1, -1, 0] [3..6): [-1, 1, 2] / \ / \ [0..1):[-1] [1..3):[-1, 0] [3..4):[-1] [4..6):[1, 2]- Build (
O(n log n)): Every leaf[i, i + 1)holds[prev_index[i]], and each internal node merges its two sorted children (sorted(left_values + right_values)runs in linear time under Python's Timsort). Across~log2(n)tree levels, total memory isO(n log n). - Query (
O(log^2 n)): Any query slice[lo, hi)splits intoO(log n)tree nodes completely contained inside[lo, hi). On each covered node,bisect_left(self.tree[node], lo)counts values< loinO(log n)time.
def _build(self, node: int, node_lo: int, node_hi: int, prev_index: List[int]) -> None: """Populate tree[node] with sorted prev_index values for slice [node_lo, node_hi).""" if node_hi - node_lo == 1: self.tree[node] = [prev_index[node_lo]] return mid = (node_lo + node_hi) // 2 left_child = 2 * node right_child = 2 * node + 1 self._build(left_child, node_lo, mid, prev_index) self._build(right_child, mid, node_hi, prev_index) # Python's Timsort detects the two already-sorted child lists and merges them in O(len) time. left_values = self.tree[left_child] right_values = self.tree[right_child] self.tree[node] = sorted(left_values + right_values) def _count_prev_below(self, node: int, node_lo: int, node_hi: int, lo: int, hi: int) -> int: """Count indices i in [lo, hi) intersect [node_lo, node_hi) where prev_index[i] < lo.""" # Disjoint interval: contributes zero records. if hi <= node_lo or node_hi <= lo: return 0 # Fully covered interval: binary-search how many sorted prev_index values are strictly < lo. if lo <= node_lo and node_hi <= hi: return bisect_left(self.tree[node], lo) mid = (node_lo + node_hi) // 2 left_count = self._count_prev_below(2 * node, node_lo, mid, lo, hi) right_count = self._count_prev_below(2 * node + 1, mid, node_hi, lo, hi) return left_count + right_count- Build (
Wire up `__init__`, `count_unique_posts_in_range`, and the harness wrapper
In
__init__, one pass populates the three set dictionaries, the timestamp arrays, andprev_index, then buildsself.tree(allocating4 * max(1, self.size)slots, the standard safe size for a 1-indexed segment tree). Finally,policy_violation_trackercreatesPolicyViolationTracker(logs)once and dispatches each(method_name, args)call.Tracing Example 1: -
count_unique_posts_by_policy("malware")->len({"pin_10", "pin_20", "pin_30"}) = 3-get_policies_for_post("pin_10")->sorted({"malware", "harassment"}) = ["harassment", "malware"]-count_unique_posts_at_time(20)->len({"pin_10", "pin_20"}) = 2-count_unique_posts_in_range(20, 80)->[lo, hi) = [0, 4),prev_index[0:4] = [-1, -1, 0, -1], values< 0are-1, -1, -1->3-count_violations_by_policy_in_range("malware", 20, 110)->"malware"times[20, 80, 110, 110],4 - 0 = 4Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple from bisect import bisect_left, bisect_right class PolicyViolationTracker: def __init__(self, logs: List[List]): # posts_by_policy: {"malware": {"pin_10", "pin_20", "pin_30"}, ...} self.posts_by_policy: Dict[str, Set[str]] = {} # policies_by_post: {"pin_10": {"malware", "harassment"}, ...} self.policies_by_post: Dict[str, Set[str]] = {} # posts_by_time: {20: {"pin_10", "pin_20"}, ...} self.posts_by_time: Dict[int, Set[str]] = {} # times_by_policy: {"malware": [20, 80, 110, 110], ...} (sorted timestamps per policy) self.times_by_policy: Dict[str, List[int]] = {} # times: [20, 20, 50, 80, 110, 110] (all record timestamps in sorted log order) self.times: List[int] = [] # prev_index[i]: earlier log index (< i) of the same post_id, or -1 if first seen at i prev_index: List[int] = [] last_seen_index: Dict[str, int] = {} # Phase 1: scan the chronologically sorted log once to populate all lookup tables. for idx, record in enumerate(logs): post_id, policy, timestamp = record[0], record[1], record[2] self.posts_by_policy.setdefault(policy, set()).add(post_id) self.policies_by_post.setdefault(post_id, set()).add(policy) self.posts_by_time.setdefault(timestamp, set()).add(post_id) # Because 'logs' is already sorted by timestamp, appending preserves sorted order. self.times_by_policy.setdefault(policy, []).append(timestamp) self.times.append(timestamp) prev_index.append(last_seen_index.get(post_id, -1)) last_seen_index[post_id] = idx # Phase 2: build a 1-indexed merge sort tree over prev_index[0..size). # tree[node] stores the sorted prev_index values for that node's index slice. self.size = len(logs) self.tree: List[Optional[List[int]]] = [None] * (4 * max(1, self.size)) if self.size > 0: self._build(1, 0, self.size, prev_index) def _build(self, node: int, node_lo: int, node_hi: int, prev_index: List[int]) -> None: """Populate tree[node] with sorted prev_index values for slice [node_lo, node_hi).""" if node_hi - node_lo == 1: self.tree[node] = [prev_index[node_lo]] return mid = (node_lo + node_hi) // 2 left_child = 2 * node right_child = 2 * node + 1 self._build(left_child, node_lo, mid, prev_index) self._build(right_child, mid, node_hi, prev_index) # Python's Timsort detects the two already-sorted child lists and merges them in O(len) time. left_values = self.tree[left_child] right_values = self.tree[right_child] self.tree[node] = sorted(left_values + right_values) def _count_prev_below(self, node: int, node_lo: int, node_hi: int, lo: int, hi: int) -> int: """Count indices i in [lo, hi) intersect [node_lo, node_hi) where prev_index[i] < lo.""" # Disjoint interval: contributes zero records. if hi <= node_lo or node_hi <= lo: return 0 # Fully covered interval: binary-search how many sorted prev_index values are strictly < lo. if lo <= node_lo and node_hi <= hi: return bisect_left(self.tree[node], lo) mid = (node_lo + node_hi) // 2 left_count = self._count_prev_below(2 * node, node_lo, mid, lo, hi) right_count = self._count_prev_below(2 * node + 1, mid, node_hi, lo, hi) return left_count + right_count def count_unique_posts_by_policy(self, policy: str) -> int: return len(self.posts_by_policy.get(policy, ())) def get_policies_for_post(self, post_id: str) -> List[str]: # sorted() returns a fresh list in lexicographical order so callers cannot mutate internal sets. return sorted(self.policies_by_post.get(post_id, ())) def count_unique_posts_at_time(self, timestamp: int) -> int: return len(self.posts_by_time.get(timestamp, ())) def count_unique_posts_in_range(self, start_time: int, end_time: int) -> int: # Convert inclusive time window [start_time, end_time] into half-open log slice [lo, hi). # bisect_left includes ties at start_time; bisect_right includes ties at end_time. lo = bisect_left(self.times, start_time) hi = bisect_right(self.times, end_time) if lo >= hi: return 0 # Each unique post in [lo, hi) has prev_index[i] < lo ONLY at its earliest record in [lo, hi). return self._count_prev_below(1, 0, self.size, lo, hi) def count_violations_by_policy_in_range(self, policy: str, start_time: int, end_time: int) -> int: policy_times = self.times_by_policy.get(policy) if policy_times is None: return 0 left_idx = bisect_left(policy_times, start_time) right_idx = bisect_right(policy_times, end_time) if right_idx <= left_idx: return 0 return right_idx - left_idx def policy_violation_tracker(logs: List[List], operations: List[str], arguments: List[List]) -> List: # Instantiate the tracker once, then dispatch each requested method call in order. tracker = PolicyViolationTracker(logs) results: List[Any] = [] for method_name, args in zip(operations, arguments): method = getattr(tracker, method_name) results.append(method(*args)) return results✅ Submit now — all tests should pass.
Intuition & how it works
Picture logs as a bound chronological ledger that never changes after startup. Rather than flipping through every page on each question, we spend one initialization pass building back-of-the-book indexes: hash maps of hash sets (dictionaries mapping a lookup key to a duplicate-free set in O(1) average time) for exact-key queries, plus sorted timestamp lists for binary search (repeatedly halving a sorted array to jump straight to start_time and end_time). For the trickiest query — counting distinct posts inside an arbitrary window [lo, hi) without walking every row inside the window — we tag each entry i with prev_index[i] (the most recent earlier row index < i of that same post_id, or -1 if none), because a post's first occurrence inside [lo, hi) is the unique row of that post where prev_index[i] < lo.
Scanning the whole log per call costs O(n) time, and even binary-searching [lo, hi) before building len(set(posts[lo:hi])) still walks O(hi - lo) entries per call. Across 20,000 wide range queries over 100,000 entries, rescanning slices touches roughly 2 * 10^9 rows and times out. Storing prev_index inside a merge sort tree (a binary segment tree over index slices where every node holds its slice's prev_index numbers in sorted order) lets us count how many entries in [lo, hi) satisfy prev_index[i] < lo by binary-searching O(log n) pre-sorted tree nodes in O(log^2 n) total steps.
Walk through Example 1's 6-entry log ([pin_10@20, pin_20@20, pin_10@50, pin_30@80, pin_10@110, pin_20@110]):
1. Compute prev_index: row 0 (pin_10) -> -1; row 1 (pin_20) -> -1; row 2 (pin_10 repeat) -> 0; row 3 (pin_30) -> -1; row 4 (pin_10 repeat) -> 2; row 5 (pin_20 repeat) -> 1, yielding prev_index = [-1, -1, 0, -1, 2, 1].
2. Query count_unique_posts_in_range(20, 80): binary search maps [20, 80] to slice [0, 4), where prev_index[0:4] = [-1, -1, 0, -1]; three entries (-1, -1, -1) are < 0, returning 3 (pin_10, pin_20, pin_30).
3. Query count_unique_posts_in_range(50, 110): binary search maps [50, 110] to slice [2, 6), where prev_index[2:6] = [0, -1, 2, 1]; three entries (0, -1, 1) are < 2 while row 4 has prev_index = 2 >= 2 (ignored as a second pin_10 inside the window), returning 3.
Complexity
- Initialization (
__init__):O(n log n)time fornentries. A singleO(n)pass fills the dictionaries, timestamp lists, andprev_index, and building the merge sort tree touchesO(log n)levels ofntotal integers where Python's Timsort merges the two pre-sorted child lists in linearO(node_size)time per node. count_unique_posts_by_policyandcount_unique_posts_at_time:O(1)average time, requiring one dictionary lookup andlen(...)on the stored set.get_policies_for_post:O(k log k)time, wherekis the count of distinct policies triggered bypost_id, to sort thosekstrings in lexicographical order (standard ASCII character-by-character order).count_violations_by_policy_in_range:O(log n)time, running two binary searches (bisect_leftandbisect_right) on that policy's sorted timestamp list.count_unique_posts_in_range:O(log^2 n)time, running two binary searches onself.timesand then visitingO(log n)merge-sort-tree nodes with oneO(log n)bisect_leftcall at each covered node.- Space:
O(n log n)memory. The dictionaries and flat timestamp arrays useO(n)space, while the merge sort tree stores each of thenprev_indexintegers once per tree level across~log2(n)levels (~1.8 * 10^6ints atn = 10^5).
Edge cases
- Unseen
policy,post_id, ortimestamp:.get(..., ())returns an empty tuple and yields0or[]cleanly without raisingKeyError. - Intervals outside all entries or strictly between timestamps (such as
[301, 449]in Example 2):bisect_leftandbisect_rightproducelo == hi, hittingif lo >= hi: return 0. - Multiple entries tied at
start_timeorend_time:bisect_leftat the left boundary andbisect_rightat the right boundary include every tied entry on both inclusive endpoints. - Duplicate identical entries (
["pin_7", "phishing", 300]twice): Set-based andprev_indexunique-post queries count"pin_7"once, whereascount_violations_by_policy_in_rangecounts every matching row. - Point interval (
start_time == end_time): Narrows[lo, hi)to entries at that exact timestamp, agreeing withcount_unique_posts_at_time. - ASCII string ordering on numbered policy labels: Lexicographical sort places
"beta_10"before"beta_2"because'1' < '2'.
Common mistakes
- Mixing up distinct-post counts and raw-entry counts: Deduplicating
times_by_policyundercountscount_violations_by_policy_in_range, while counting raw entries overcountscount_unique_posts_*. - Flipping
bisect_leftandbisect_right: Usingbisect_rightonstart_timeorbisect_leftonend_timedrops entries sitting on the boundary (causingcount_unique_posts_in_range(50, 50)to return0instead of1). - Building
set(posts[lo:hi])on each range call: Works on tiny inputs, yet degrades toO(n)per wide query (O(n * q)overall) and times out under heavy range workloads. - Computing
prev_indexper(post_id, policy)pair instead of perpost_id: Ifpin_10triggers"malware"and"harassment"inside the same interval,count_unique_posts_in_rangemust still countpin_10once. - Returning a cached internal list from
get_policies_for_post: Caller mutations would corrupt future lookups;sorted(...)allocates a fresh list every call.
Follow-up questions
- How can
count_unique_posts_in_rangeavoid scanning every record inside wide time intervals when thousands of range queries arrive? Ourprev_index+ merge sort tree structure already answers arbitrary online intervals inO(log^2 n)time regardless of how many rows sit inside[start_time, end_time](and adding fractional cascading — pre-storing child binary-search pointers inside parent nodes — drops query time toO(log n)). When all queries arrive up front as an offline batch, sort queries byhi, sweep left to right keeping a Fenwick tree (a compact array supportingO(log n)point updates and prefix sums) with+1only at each post's most recent index, and answer allqqueries inO((n + q) log n)time andO(n)memory. When~1%relative error is acceptable, store mergeable HyperLogLog sketches (compact fixed-size probabilistic distinct counters) at segment tree nodes. - What changes to your indexing structures and concurrency control are needed if violation events stream in continuously rather than loading once at startup? Chronological appends update the hash sets, per-policy timestamp lists, and
prev_index[new_i]inO(1)amortized time because appending at the tail never altersprev_indexof earlier entries. Replace the single static merge sort tree with a logarithmic collection of power-of-two static merge sort trees (merging equal-sized blocks upon append like binary carry propagation), achievingO(log^2 n)amortized append andO(log^3 n)range queries (O(log^2 n)with fractional cascading); late out-of-order arrivals can wait in a short bounded watermark buffer before commit. For thread safety, protect multi-index mutations with a readers-writer lock (permitting concurrent query readers or one exclusive writer) or immutable copy-on-write block swaps — Python's GIL (Global Interpreter Lock, which only serializes individual bytecode instructions) does not make multi-dictionary updates atomic. - How would you partition and query the log across a cluster of machines when the dataset outgrows a single server's RAM? Shard (split records across
Mservers via a deterministic hash function) byhash(post_id) mod M. Because all entries for a givenpost_idland on one shard,get_policies_for_posthits a single machine, andcount_unique_posts_*results across theMshards are mutually disjoint so an aggregator node simply sums theMinteger counts!count_violations_by_policy_in_rangelikewise sums exact counts across allMshards. If you instead partition by time ranges so narrow windows hit one shard, exact multi-shardcount_unique_posts_in_rangerequires shuffling post IDs or merging per-shard HyperLogLog sketches when approximate counts are acceptable.
Follow-up questions
- How can `count_unique_posts_in_range` avoid scanning every record inside wide time intervals when thousands of range queries arrive?
- What changes to your indexing structures and concurrency control are needed if violation events stream in continuously rather than loading once at startup?
- How would you partition and query the log across a cluster of machines when the dataset outgrows a single server's RAM?
Similar questions
- Masonry Column Height Allocation
- Percentile Bootstrap Interval for Mean Order Amount
- Unique Pin Traversal Over Linked Boards
- Mean Distinct Saved Pins Across Users
- Count Reachable Tiles Within Step Limit
- Distinct Active Pin Counts Across Time Segments
More Pinterest interview questions
- Prune and Reindex a Parent-Array Forest Medium
- Minimum Boardings on Circular Bus Routes Medium
- Confusion Matrix Metrics and ML Foundations Hard Pro
- Multi-Topic Behavioral Onsite: Metrics, Leadership, Team Dynamics, and Conflict Hard Pro
- Seven-Day Highly Active User Share by Country Medium Pro
- Bootstrap Aggregating Classifier Over Decision Trees Hard Pro
- Closest Qualifying Elevator Medium Pro
- Balance Group IOUs with Fewer Transfers Medium Pro
- Clearing Shared Expenses in Minimal Transfers Medium Pro
- Minimum-Transfer Ledger Settlement Medium Pro