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]): Indexes logs so subsequent queries execute quickly.
  • count_unique_posts_by_policy(self, policy: str) -> int: Returns how many distinct post_id values appear in at least one entry for policy.
  • get_policies_for_post(self, post_id: str) -> List[str]: Returns every distinct policy triggered by post_id, ordered alphabetically in standard ASCII/lexicographical order (or [] if post_id never appears).
  • count_unique_posts_at_time(self, timestamp: int) -> int: Returns how many distinct post_id values have at least one entry at exact timestamp.
  • count_unique_posts_in_range(self, start_time: int, end_time: int) -> int: Returns how many distinct post_id values have at least one entry with start_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) matching policy with start_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^5
  • post_id and policy are non-empty strings (len <= 64) containing only ASCII letters, digits, and underscores.
  • 0 <= timestamp <= 10^14
  • logs is ordered in non-decreasing timestamp order.
  • start_time <= end_time for every range call, and both boundaries are inclusive.
  • 1 <= len(operations) == len(arguments) <= 2 * 10^4

Step-by-step walkthrough

  1. Understand the five queries and what must be deduplicated

    We receive a static log logs of [post_id, policy, timestamp] entries, already ordered so timestamp never decreases, and must answer up to 2 * 10^4 calls 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_10 appears three times inside [start, end], it contributes 1 to count_unique_posts_in_range) and raw log entries (every matching entry adds 1 to count_violations_by_policy_in_range).

  2. Why scanning per query (or per window) is too slow

    Looping through logs on each query takes O(n) work. With n = 10^5 entries and q = 2 * 10^4 calls, n * q = 2 * 10^9 steps will time out.

    Even if we jump straight to the matching slice [lo, hi) with binary search, computing len(set(posts[lo:hi])) on every count_unique_posts_in_range call still walks all hi - lo entries! When 2 * 10^4 calls ask about wide windows spanning almost all 10^5 entries, set(posts[lo:hi]) still performs ~2 * 10^9 iterations. Because logs is fixed once __init__ runs, we can build indexes once up front so every query runs in O(1) or polylogarithmic time.

  3. Answer the three point queries with pre-aggregated hash sets

    Three methods look up one exact key (policy, post_id, or timestamp). In a single pass over logs inside __init__, we populate three dictionaries of Python sets:

    • posts_by_policy[policy] -> set of distinct post_id strings
    • policies_by_post[post_id] -> set of distinct policy strings
    • posts_by_time[timestamp] -> set of distinct post_id strings

    Sets ignore duplicates automatically, so counts take O(1) time via len(...), and get_policies_for_post returns sorted(...) (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, ()))
    
  4. 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 to times_by_policy[policy] during our single pass keeps times_by_policy[policy] automatically sorted because logs arrives 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 in O(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 = 4
    
    • bisect_left(policy_times, start_time) finds the first index with time >= start_time (keeping ties at start_time).
    • bisect_right(policy_times, end_time) lands one past the last index with time <= end_time (keeping ties at end_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_idx
    
  5. Key trick for unique posts in a range: count first occurrences via `prev_index`

    Applying bisect_left and bisect_right to self.times (all entry timestamps) converts [start_time, end_time] into the half-open index slice [lo, hi). How can we count unique posts inside logs[lo:hi] without scanning from lo to hi?

    Count each post only at its earliest index inside [lo, hi)! During __init__, record prev_index[i] = the most recent index < i where logs[i]'s post_id appeared (or -1 if i is that post's very first entry in logs):

    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 its prev_index[i] must be strictly less than lo (prev_index[i] < lo). - Every later entry of that same post inside [lo, hi) points back to an index >= lo, so prev_index[i] >= lo.

    Thus, the count of distinct posts in [lo, hi) equals the exact number of indices i in [lo, hi) satisfying prev_index[i] < lo!

  6. 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 of prev_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 is O(n log n).
    • Query (O(log^2 n)): Any query slice [lo, hi) splits into O(log n) tree nodes completely contained inside [lo, hi). On each covered node, bisect_left(self.tree[node], lo) counts values < lo in O(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
    
  7. Wire up `__init__`, `count_unique_posts_in_range`, and the harness wrapper

    In __init__, one pass populates the three set dictionaries, the timestamp arrays, and prev_index, then builds self.tree (allocating 4 * max(1, self.size) slots, the standard safe size for a 1-indexed segment tree). Finally, policy_violation_tracker creates PolicyViolationTracker(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 < 0 are -1, -1, -1 -> 3 - count_violations_by_policy_in_range("malware", 20, 110) -> "malware" times [20, 80, 110, 110], 4 - 0 = 4

  8. Complete 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 for n entries. A single O(n) pass fills the dictionaries, timestamp lists, and prev_index, and building the merge sort tree touches O(log n) levels of n total integers where Python's Timsort merges the two pre-sorted child lists in linear O(node_size) time per node.
  • count_unique_posts_by_policy and count_unique_posts_at_time: O(1) average time, requiring one dictionary lookup and len(...) on the stored set.
  • get_policies_for_post: O(k log k) time, where k is the count of distinct policies triggered by post_id, to sort those k strings in lexicographical order (standard ASCII character-by-character order).
  • count_violations_by_policy_in_range: O(log n) time, running two binary searches (bisect_left and bisect_right) on that policy's sorted timestamp list.
  • count_unique_posts_in_range: O(log^2 n) time, running two binary searches on self.times and then visiting O(log n) merge-sort-tree nodes with one O(log n) bisect_left call at each covered node.
  • Space: O(n log n) memory. The dictionaries and flat timestamp arrays use O(n) space, while the merge sort tree stores each of the n prev_index integers once per tree level across ~log2(n) levels (~1.8 * 10^6 ints at n = 10^5).

Edge cases

  • Unseen policy, post_id, or timestamp: .get(..., ()) returns an empty tuple and yields 0 or [] cleanly without raising KeyError.
  • Intervals outside all entries or strictly between timestamps (such as [301, 449] in Example 2): bisect_left and bisect_right produce lo == hi, hitting if lo >= hi: return 0.
  • Multiple entries tied at start_time or end_time: bisect_left at the left boundary and bisect_right at the right boundary include every tied entry on both inclusive endpoints.
  • Duplicate identical entries (["pin_7", "phishing", 300] twice): Set-based and prev_index unique-post queries count "pin_7" once, whereas count_violations_by_policy_in_range counts every matching row.
  • Point interval (start_time == end_time): Narrows [lo, hi) to entries at that exact timestamp, agreeing with count_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_policy undercounts count_violations_by_policy_in_range, while counting raw entries overcounts count_unique_posts_*.
  • Flipping bisect_left and bisect_right: Using bisect_right on start_time or bisect_left on end_time drops entries sitting on the boundary (causing count_unique_posts_in_range(50, 50) to return 0 instead of 1).
  • Building set(posts[lo:hi]) on each range call: Works on tiny inputs, yet degrades to O(n) per wide query (O(n * q) overall) and times out under heavy range workloads.
  • Computing prev_index per (post_id, policy) pair instead of per post_id: If pin_10 triggers "malware" and "harassment" inside the same interval, count_unique_posts_in_range must still count pin_10 once.
  • 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_range avoid scanning every record inside wide time intervals when thousands of range queries arrive? Our prev_index + merge sort tree structure already answers arbitrary online intervals in O(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 to O(log n)). When all queries arrive up front as an offline batch, sort queries by hi, sweep left to right keeping a Fenwick tree (a compact array supporting O(log n) point updates and prefix sums) with +1 only at each post's most recent index, and answer all q queries in O((n + q) log n) time and O(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] in O(1) amortized time because appending at the tail never alters prev_index of 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), achieving O(log^2 n) amortized append and O(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 M servers via a deterministic hash function) by hash(post_id) mod M. Because all entries for a given post_id land on one shard, get_policies_for_post hits a single machine, and count_unique_posts_* results across the M shards are mutually disjoint so an aggregator node simply sums the M integer counts! count_violations_by_policy_in_range likewise sums exact counts across all M shards. If you instead partition by time ranges so narrow windows hit one shard, exact multi-shard count_unique_posts_in_range requires shuffling post IDs or merging per-shard HyperLogLog sketches when approximate counts are acceptable.

Follow-up questions

Similar questions

More Pinterest interview questions

All 161 Pinterest questions →