Circular Worker Assignment and Top-K Load

Hard · Coding & Algorithms · Software Engineer · Technical Screen

Problem Statement

A document-ingestion cluster runs m parallel workers (indexers), numbered 0 through m - 1. Over time, n documents arrive in strictly increasing timestamp order (queue_time[0] < queue_time[1] < ... < queue_time[n - 1]). Each assigned document occupies a single worker exclusively for processing_time[i] time units.

Implement the scheduler simulation and workload summary:

def simulate_document_assignment(
    m: int,
    queue_time: List[int],
    processing_time: List[int],
    k: int,
) -> Dict[str, object]:

Each document i (0 <= i < n) is routed at arrival timestamp t = queue_time[i] using these rules:

  1. Preferred worker: Start probing at base = i % m.
  2. Availability: A worker is free at timestamp t if it has not yet handled any document or its previous assignment finished at or before t (finish_time <= t).
  3. Circular fallback: Check base; if busy, continue probing (base + 1) % m, (base + 2) % m, ..., (base + m - 1) % m and assign document i to the first free worker encountered. That worker becomes occupied until t + processing_time[i].
  4. Drop on saturation: If all m workers are still busy at timestamp t (finish_time > t everywhere), document i is discarded immediately and never processed later.

Given k (1 <= k <= m), return a dictionary with four entries:

  • "total_processed": integer count of documents successfully assigned to a worker.
  • "most_processed_indexer": integer ID of the worker that handled the highest number of documents (if several workers tie for the maximum, any tied worker ID is valid; examples break ties by smallest worker ID).
  • "top_indexers": list of k distinct worker IDs with the largest processed-document counts (any ordering or valid tie choice is permitted; examples sort by descending count and then ascending worker ID).
  • "percentage": float (0.0 to 100.0) giving the share of all n arriving documents—dropped ones included— that were handled by top_indexers (0.0 when n == 0).

Examples

Example 1

Input:

m = 2
queue_time = [1, 2, 4, 5]
processing_time = [8, 3, 2, 4]
k = 1

Output:

{
    "total_processed": 3,
    "most_processed_indexer": 1,
    "top_indexers": [1],
    "percentage": 50.0,
}

Explanation: - Document 0 (t = 1, base = 0): worker 0 is free and stays busy until 1 + 8 = 9. - Document 1 (t = 2, base = 1): worker 1 is free and stays busy until 2 + 3 = 5. - Document 2 (t = 4, base = 0): worker 0 (until 9) and worker 1 (until 5) are both busy, so document 2 is dropped. - Document 3 (t = 5, base = 1): worker 1 finishes at 5 <= 5 and takes document 3 until 5 + 4 = 9. - Counts are [1, 2]: 3 documents succeeded, worker 1 leads with 2 documents, and top_indexers = [1] handled 2 out of all 4 arrivals (50.0%).

Example 2

Input:

m = 3
queue_time = [0, 1, 2, 4, 6]
processing_time = [3, 10, 10, 2, 5]
k = 2

Output:

{
    "total_processed": 5,
    "most_processed_indexer": 0,
    "top_indexers": [0, 1],
    "percentage": 80.0,
}

Explanation: - Documents 0, 1, and 2 land on workers 0, 1, and 2, finishing at times 3, 11, and 12. - Document 3 (t = 4, base = 0) reuses worker 0 (3 <= 4), occupying it until 6. - Document 4 (t = 6, base = 1) finds workers 1 (11 > 6) and 2 (12 > 6) busy, wraps around to worker 0 (6 <= 6), and occupies it until 11. - Counts are [3, 1, 1]: worker 0 handled 3 documents, workers 1 and 2 tie at 1 each ([0, 1] or [0, 2] are both valid), and 4 / 5 = 80.0%.

Constraints

  • 1 <= m <= 100,000
  • 0 <= n == len(queue_time) == len(processing_time) <= 100,000
  • queue_time is strictly increasing (queue_time[i] < queue_time[i + 1]).
  • processing_time[i] >= 1
  • 1 <= k <= m

Step-by-step walkthrough

  1. Restate the rules and output dictionary

    We have m parallel indexers numbered 0 to m - 1, and n documents arriving at strictly increasing times queue_time[0] < queue_time[1] < ... < queue_time[n - 1].

    When document i arrives at arrival_time = queue_time[i]:

    1. Its preferred indexer is base = i % m.
    2. An indexer is available if it has never run a job or its current job finishes at or before arrival_time (free_time <= arrival_time).
    3. We check indexers in cyclic order base, base + 1, ..., m - 1, 0, ..., base - 1 and assign the document to the first available indexer, making it busy until arrival_time + processing_time[i].
    4. If no indexer is available at arrival_time, the document is dropped.

    The judge expects a dictionary with four exact keys:

    Key Value
    "total_processed" Number of documents assigned (not dropped)
    "most_processed_indexer" Indexer ID with the highest processed count
    "top_indexers" List of k indexer IDs with the highest counts
    "percentage" 100.0 * (sum of top_k counts) / n (or 0.0 if n == 0)

    Two subtle details to lock down up front:

    • Tie-breaking and type for "top_indexers": Although any valid tie-break among equal-count workers is allowed, callers compare "top_indexers" as a list of k distinct worker IDs. Sorting by (-counts[j], j) (most documents first, smaller indexer ID on ties) produces a clean, deterministic list such as [0, 1] in Example 2.
    • Denominator of "percentage": We measure the top k workers' share out of every arriving document (dropped ones included), dividing by n = len(queue_time) rather than total_processed.
  2. Brute force and why scanning is O(n * m)

    A direct simulation keeps free_time[j] for each indexer j and scans step = 0, 1, ..., m - 1 around the circle (base + step) % m until it finds free_time[j] <= arrival_time.

    That scan is simple and serves as the reference oracle in the tests, but whenever almost all indexers are busy, one document inspects up to m indexers. Across n documents, that takes O(n * m) time. To bring each document down to O(log m), we need a data structure that answers: "Who is the leftmost indexer at or after start_id whose free_time <= arrival_time?" without touching busy ranges.

  3. Key idea: a tournament tree (segment tree) of free times

    Think of organizing the m indexers into a binary tournament bracket (called a min-segment tree). Each leaf stores one indexer's free_time, and each parent box stores the minimum (earliest) free_time among its two children:

    Example for m = 3 (padded to leaf_capacity = 4):
    
                      [node 1: min(0..3) = -inf]
                      /                        \
        [node 2: min(0..1) = 3]        [node 3: min(2..3) = -inf]
             /            \                 /               \
       [leaf 4]        [leaf 5]        [leaf 6]          [leaf 7]
       idx 0: 3       idx 1: 11       idx 2: -inf       pad 3: +inf
    

    Why this bracket makes queries fast:

    • If a parent box says min = 3 and a document arrives at arrival_time = 2, then nobody in that entire group is free by time 2 (3 > 2). We skip the whole group in O(1) time!
    • Conversely, if a parent box has min <= arrival_time, at least one indexer inside that group is free. Checking the left child before the right child walks straight down to the smallest free indexer ID!
    • Unused padding leaves (idx >= m) hold MISSING = +inf, so they never beat a real timestamp and can never be chosen. Real indexers start at FREE = -inf, meaning free at any arrival time.
  4. Build the tree and update one indexer

    We pad m up to leaf_capacity (the smallest power of two >= m) and store the whole bracket in a flat list self.tree of length 2 * leaf_capacity, where node = 1 is the root and node's children sit at 2 * node and 2 * node + 1.

    When an indexer gets a new job finishing at free_time, only its leaf and the O(log m) ancestors directly above it can change:

    FREE = float("-inf")
    MISSING = float("inf")
    
    
    class FreeTimeTree:
        """Min-segment tree over m indexers.
        Leaf (leaf_capacity + j) holds the timestamp when indexer j next becomes free;
        every internal node holds min(left_child, right_child) over its leaf range.
        """
    
        def __init__(self, m: int):
            # Round m up to a power of two so leaves sit cleanly at indices [leaf_capacity, 2 * leaf_capacity).
            self.leaf_capacity = 1
            while self.leaf_capacity < m:
                self.leaf_capacity *= 2
    
            # tree[1] is the root; tree[2 * node] and tree[2 * node + 1] are node's children.
            self.tree = [MISSING] * (2 * self.leaf_capacity)
            for indexer_id in range(m):
                self.tree[self.leaf_capacity + indexer_id] = FREE
    
            # Build internal minimums bottom-up from the leaves.
            for node in range(self.leaf_capacity - 1, 0, -1):
                left_min = self.tree[2 * node]
                right_min = self.tree[2 * node + 1]
                self.tree[node] = min(left_min, right_min)
    
        def update_free_time(self, indexer_id: int, free_time: float) -> None:
            """Set indexer_id's next free timestamp and refresh ancestor minimums along the root path."""
            node = self.leaf_capacity + indexer_id
            self.tree[node] = free_time
            node //= 2
            while node >= 1:
                left_min = self.tree[2 * node]
                right_min = self.tree[2 * node + 1]
                self.tree[node] = min(left_min, right_min)
                node //= 2
    
  5. Search for the first free indexer at or after `start_id`

    _search(node, node_lo, node_hi, start_id, arrival_time) looks inside the leaf range [node_lo, node_hi] covered by node:

    1. Prune: If node_hi < start_id (the whole range lies left of start_id) or self.tree[node] > arrival_time (every indexer in this range finishes strictly after arrival_time), return -1 immediately.
    2. Base case: If node_lo == node_hi, we reached a single leaf that is >= start_id and has free_time <= arrival_time — return node_lo.
    3. Recurse left, then right: Try the left child [node_lo, mid] first; only if it returns -1 do we try the right child [mid + 1, node_hi].
        def first_available(self, start_id: int, arrival_time: int) -> int:
            """Return the smallest indexer ID >= start_id with free_time <= arrival_time, or -1 if none."""
            return self._search(1, 0, self.leaf_capacity - 1, start_id, arrival_time)
    
        def _search(
            self,
            node: int,
            node_lo: int,
            node_hi: int,
            start_id: int,
            arrival_time: int,
        ) -> int:
            # Prune if this subtree lies completely before start_id, or if even its earliest
            # indexer finishes strictly after arrival_time (note: == arrival_time IS available).
            if node_hi < start_id or self.tree[node] > arrival_time:
                return -1
    
            # Reaching a leaf that passed the checks above means this leaf is the leftmost match.
            if node_lo == node_hi:
                return node_lo
    
            mid = (node_lo + node_hi) // 2
            left_child = 2 * node
            right_child = 2 * node + 1
    
            # Always try the left half first so we pick the smallest available indexer ID.
            found_id = self._search(left_child, node_lo, mid, start_id, arrival_time)
            if found_id == -1:
                found_id = self._search(right_child, mid + 1, node_hi, start_id, arrival_time)
            return found_id
    

    Why does _search run in O(log m) time even though it has two recursive calls? At most one node per level straddles start_id; every other node we enter lies completely at or after start_id, and the first such node whose minimum is <= arrival_time is guaranteed to contain the answer, so the recursion descends straight down to one leaf and stops!

  6. Handle circular wrap-around in two queries

    The cyclic probe order starting from base is simply two left-to-right segments:

    Indexers:   0    1   ...  base-1 | base   base+1  ...  m-1
                |<--- Pass 2 ------->| |<------ Pass 1 ------>|
    
    1. Pass 1: Call tree.first_available(base, arrival_time) to check [base, m - 1].
    2. Pass 2: If Pass 1 returns -1, nobody in [base, m - 1] is free, so calling tree.first_available(0, arrival_time) can only find an indexer in [0, base - 1] (or return -1 if all m indexers are busy).
    def pick_indexer(tree: FreeTimeTree, base: int, arrival_time: int) -> int:
        """Find the first free indexer in cyclic order: base, base+1, ..., m-1, 0, ..., base-1."""
        # Pass 1: check indexers from base up to m - 1.
        chosen_id = tree.first_available(base, arrival_time)
        if chosen_id == -1:
            # Pass 2: nobody in [base, m - 1] is free, so wrap around and check from 0.
            chosen_id = tree.first_available(0, arrival_time)
        return chosen_id
    
  7. Run the simulation, rank indexers, and trace Example 2

    Now we step through i = 0 .. n - 1, update the chosen indexer's free_time and counts, then sort (-counts[j], j) to extract most_processed_indexer, top_indexers, and percentage.

    Let's trace Example 2 (m = 3, queue_time = [0, 1, 2, 4, 6], processing_time = [3, 10, 10, 2, 5], k = 2):

    Initial leaves (idx 0, 1, 2, pad 3): [-inf, -inf, -inf, +inf], root min = -inf
    
    i = 0, t = 0, p = 3, base = 0 % 3 = 0:
      Pass 1 from 0 -> idx 0 (-inf <= 0). Update idx 0 to 0 + 3 = 3.
      leaves = [3, -inf, -inf, +inf], counts = [1, 0, 0]
    
    i = 1, t = 1, p = 10, base = 1 % 3 = 1:
      Pass 1 from 1 -> idx 1 (-inf <= 1). Update idx 1 to 1 + 10 = 11.
      leaves = [3, 11, -inf, +inf], counts = [1, 1, 0]
    
    i = 2, t = 2, p = 10, base = 2 % 3 = 2:
      Pass 1 from 2 -> idx 2 (-inf <= 2). Update idx 2 to 2 + 10 = 12.
      leaves = [3, 11, 12, +inf], counts = [1, 1, 1]
    
    i = 3, t = 4, p = 2, base = 3 % 3 = 0:
      Pass 1 from 0 -> idx 0 (3 <= 4). Update idx 0 to 4 + 2 = 6.
      leaves = [6, 11, 12, +inf], counts = [2, 1, 1]
    
    i = 4, t = 6, p = 5, base = 4 % 3 = 1:
      Pass 1 from 1 -> -1 (11 > 6 and 12 > 6).
      Pass 2 from 0 -> idx 0 (6 <= 6). Update idx 0 to 6 + 5 = 11.
      leaves = [11, 11, 12, +inf], counts = [3, 1, 1]
    

    Sorting (-counts[j], j) gives [(-3, 0), (-1, 1), (-1, 2)]:

    • total_processed = 5
    • most_processed_indexer = 0
    • top_indexers = [0, 1]
    • percentage = 100.0 * (3 + 1) / 5 = 80.0
  8. Complete solution

    from typing import Any, Dict, List, Optional, Set, Tuple
    
    # FREE (-inf) means an indexer has no active job and is available at any arrival time.
    # MISSING (+inf) fills unused power-of-two leaf slots so they are never chosen.
    FREE = float("-inf")
    MISSING = float("inf")
    
    
    class FreeTimeTree:
        """Min-segment tree over m indexers.
        Leaf (leaf_capacity + j) holds the timestamp when indexer j next becomes free;
        every internal node holds min(left_child, right_child) over its leaf range.
        """
    
        def __init__(self, m: int):
            # Round m up to a power of two so leaves sit cleanly at indices [leaf_capacity, 2 * leaf_capacity).
            self.leaf_capacity = 1
            while self.leaf_capacity < m:
                self.leaf_capacity *= 2
    
            # tree[1] is the root; tree[2 * node] and tree[2 * node + 1] are node's children.
            self.tree = [MISSING] * (2 * self.leaf_capacity)
            for indexer_id in range(m):
                self.tree[self.leaf_capacity + indexer_id] = FREE
    
            # Build internal minimums bottom-up from the leaves.
            for node in range(self.leaf_capacity - 1, 0, -1):
                left_min = self.tree[2 * node]
                right_min = self.tree[2 * node + 1]
                self.tree[node] = min(left_min, right_min)
    
        def update_free_time(self, indexer_id: int, free_time: float) -> None:
            """Set indexer_id's next free timestamp and refresh ancestor minimums along the root path."""
            node = self.leaf_capacity + indexer_id
            self.tree[node] = free_time
            node //= 2
            while node >= 1:
                left_min = self.tree[2 * node]
                right_min = self.tree[2 * node + 1]
                self.tree[node] = min(left_min, right_min)
                node //= 2
    
        def first_available(self, start_id: int, arrival_time: int) -> int:
            """Return the smallest indexer ID >= start_id with free_time <= arrival_time, or -1 if none."""
            return self._search(1, 0, self.leaf_capacity - 1, start_id, arrival_time)
    
        def _search(
            self,
            node: int,
            node_lo: int,
            node_hi: int,
            start_id: int,
            arrival_time: int,
        ) -> int:
            # Prune if this subtree lies completely before start_id, or if even its earliest
            # indexer finishes strictly after arrival_time (note: == arrival_time IS available).
            if node_hi < start_id or self.tree[node] > arrival_time:
                return -1
    
            # Reaching a leaf that passed the checks above means this leaf is the leftmost match.
            if node_lo == node_hi:
                return node_lo
    
            mid = (node_lo + node_hi) // 2
            left_child = 2 * node
            right_child = 2 * node + 1
    
            # Always try the left half first so we pick the smallest available indexer ID.
            found_id = self._search(left_child, node_lo, mid, start_id, arrival_time)
            if found_id == -1:
                found_id = self._search(right_child, mid + 1, node_hi, start_id, arrival_time)
            return found_id
    
    
    def pick_indexer(tree: FreeTimeTree, base: int, arrival_time: int) -> int:
        """Find the first free indexer in cyclic order: base, base+1, ..., m-1, 0, ..., base-1."""
        # Pass 1: check indexers from base up to m - 1.
        chosen_id = tree.first_available(base, arrival_time)
        if chosen_id == -1:
            # Pass 2: nobody in [base, m - 1] is free, so wrap around and check from 0.
            chosen_id = tree.first_available(0, arrival_time)
        return chosen_id
    
    
    def simulate_document_assignment(
        m: int,
        queue_time: List[int],
        processing_time: List[int],
        k: int,
    ) -> Dict[str, object]:
        n = len(queue_time)
        tree = FreeTimeTree(m)
        # counts[j]: number of documents successfully assigned to indexer j.
        counts = [0] * m
        total_processed = 0
    
        # Phase 1: simulate each arriving document in chronological order.
        for i in range(n):
            arrival_time = queue_time[i]
            base = i % m
            chosen_id = pick_indexer(tree, base, arrival_time)
            if chosen_id == -1:
                # All m indexers are busy at arrival_time; drop this document.
                continue
    
            finish_time = arrival_time + processing_time[i]
            tree.update_free_time(chosen_id, finish_time)
            counts[chosen_id] += 1
            total_processed += 1
    
        # Phase 2: rank all m indexers by (-processed_count, indexer_id) so higher counts come
        # first and ties consistently go to smaller indexer IDs (e.g. [0, 1] when 1 and 2 tie).
        ranked_pairs = []
        for indexer_id in range(m):
            ranked_pairs.append((-counts[indexer_id], indexer_id))
        ranked_pairs.sort()
    
        ranked_ids = []
        for neg_count, indexer_id in ranked_pairs:
            ranked_ids.append(indexer_id)
        top_indexers = ranked_ids[:k]
    
        # Phase 3: compute percentage out of ALL n queued documents (dropped ones included).
        top_total = 0
        for indexer_id in top_indexers:
            top_total += counts[indexer_id]
        percentage = (100.0 * top_total / n) if n > 0 else 0.0
    
        return {
            "total_processed": total_processed,
            "most_processed_indexer": ranked_ids[0],
            "top_indexers": top_indexers,
            "percentage": percentage,
        }
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Imagine m checkout clerks standing in a row, each holding a sign showing the timestamp when their current customer will finish. Document i wants to check clerks starting at base = i % m, moving right to m - 1, and wrapping back to 0 .. base - 1 until it spots a sign <= arrival_time. Instead of walking past thousands of busy clerks one by one, imagine grouping clerks in pairs, pairs of pairs, and so on like a sports tournament bracket, where each manager above a group holds a sign showing the earliest finish time in that group. When a document arrives at arrival_time, any group whose manager's sign is strictly greater than arrival_time has zero free clerks and can be skipped in a single glance, while a group with min <= arrival_time lets us step straight down to its leftmost free clerk!

A naive loop checks (base + step) % m for step = 0, 1, ..., m - 1 on every document. Whenever almost all m indexers are busy, each document checks nearly all m indexers before wrapping to a free one or getting dropped. Across n documents, that linear scan takes O(n * m) time, which bogs down when n and m are large.

Using a segment tree (a binary tree over an array where each internal node stores an aggregate—here the minimum value—of its child range) turns both circular lookups and single-indexer finish-time updates into O(log m) tree walks. Let's trace Example 1 (m = 2, k = 1, queue_time = [1, 2, 4, 5], processing_time = [8, 3, 2, 4]):

  1. Start with leaf free times [-inf, -inf] and counts = [0, 0].
  2. Doc 0 (t = 1, base = 0): picks indexer 0, sets leaf 0 to 1 + 8 = 9. Leaves: [9, -inf], counts = [1, 0].
  3. Doc 1 (t = 2, base = 1): picks indexer 1, sets leaf 1 to 2 + 3 = 5. Leaves: [9, 5], counts = [1, 1].
  4. Doc 2 (t = 4, base = 0): root minimum min(9, 5) = 5 > 4, so both Pass 1 and Pass 2 prune immediately and drop Doc 2!
  5. Doc 3 (t = 5, base = 1): leaf 1 has free_time = 5 <= 5, so indexer 1 takes Doc 3 until 9 (counts = [1, 2]), giving total_processed = 3, top_indexers = [1], and percentage = 100.0 * 2 / 4 = 50.0 (the dropped arrival still counts in denominator n = 4).

Complexity

  • Time: O((m + n) log m). Building the segment tree initializes an array of at most 4 * m entries in O(m) time. Each of the n arriving documents runs at most two first_available tree searches (O(log m) each, visiting at most a constant number of nodes per tree level) and at most one update_free_time point update (an update to a single leaf and its O(log m) ancestors up to the root). Ranking the m indexers at the end sorts m tuples in O(m log m) time.
  • Space: O(m). Rounding m up to leaf_capacity < 2 * m creates a tree array of 2 * leaf_capacity < 4 * m numbers, and counts plus ranked_pairs each store m entries.

Edge cases

  • Job completes at the exact arrival time (free_time == arrival_time): Availability requires completion no later than arrival_time, so _search only prunes when self.tree[node] > arrival_time, treating == as free.
  • All indexers busy (dropped documents): Both Pass 1 (start_id = base) and Pass 2 (start_id = 0) return -1. The document is dropped (total_processed does not increment), yet n in 100.0 * top_total / n still includes it.
  • Empty document list (n = 0): Guarding if n > 0 else 0.0 avoids a ZeroDivisionError and returns 0.0 with total_processed = 0.
  • m is not a power of two: Extra leaves m .. leaf_capacity - 1 stay initialized to MISSING = +inf, which is greater than every finite arrival_time and can never be selected.
  • First arrival at t = 0 (or even negative t): Initializing real leaves to FREE = -inf ensures every indexer is available before its first job, regardless of how small queue_time[0] is.
  • k = m: top_indexers includes all m indexers, so top_total == total_processed and percentage == 100.0 * total_processed / n.

Common mistakes

  • Dividing percentage by total_processed instead of n: The specification measures top-k throughput as a share of every arriving document—dropped ones included—so the denominator must be len(queue_time).
  • Returning top_indexers as a Python set: Callers inspect got['top_indexers'] as an indexable list/tuple sequence (such as [1] or [0, 1]), and _same compares lists/tuples rather than sets. Returning a deterministically sorted list ((-counts[j], j)) passes both exact and tie-tolerant checks.
  • Searching from indexer 0 instead of base = i % m: If base = 1 is busy while both 0 and 2 are free, cyclic order must choose 2 before wrapping around to 0.
  • Using a single min-heap keyed only by finish_time to pick indexers: That picks whichever indexer finished earliest in time, ignoring the circular i % m preference rule completely.
  • Forgetting Pass 2 (wrap-around): Checking only [base, m - 1] misses free indexers in [0, base - 1].

Alternative approaches

  • Two min-heaps with unrolled circular slots (O((n + m) log m) time, O(m) space): Keep busy indexers in a (finish_time, j) min-heap and free indexers in a min-heap keyed by i + (j - i) % m (their next position in [i, i + m) on an unrolled number line). Because queue_time increases monotonically, waking finished indexers before each arrival and popping the minimum slot achieves the same O((n + m) log m) complexity with slightly less boilerplate, though the segment tree is easier to reason about without modular heap invariants.
  • Partial selection with heapq.nsmallest(k, ranked_pairs) (O(m log k) ranking): Replaces the final O(m log m) sort with O(m + k log m) or O(m log k), though O(m log m) is already dominated by or equal to the tree build + simulation when n >= m.

Follow-up questions

  • Does the segment-tree scheduler still work if multiple documents can arrive at the exact same timestamp? As long as simultaneous arrivals are routed in array index order i and processing_time[i] > 0, the exact same FreeTimeTree logic works unchanged: assigning a worker at timestamp t updates its leaf to t + processing_time[i] > t, so later arrivals at the same timestamp t skip it automatically. (If zero-duration jobs processing_time[i] == 0 were also permitted, a worker could finish instantaneously at t and accept another arrival at t.)
  • How would you change the design if arriving documents wait in a FIFO buffer instead of being dropped when all workers are busy? Add a FIFO queue (a First-In, First-Out buffer serving the earliest waiting arrival next) alongside a min-heap of (finish_time, indexer_id) completion events. Before routing a new arrival at timestamp t, pop every completion event with finish_time <= t in chronological order and immediately hand that freed worker the head of the waiting queue starting at finish_time; only when the waiting queue is empty does the new arrival probe circularly from i % m.
  • How could you report the top-k workers and their share on the fly after every arrival without re-sorting all m workers? Maintain (-counts[j], j) inside a balanced binary search tree (an ordered set supporting O(log m) insert, delete, and rank lookups) together with the running sum top_total of its smallest k tuples. Each assignment increments counts[chosen_id] by 1, repositions that single worker in the tree, and updates top_total in O(log m) time rather than O(m log m).

Follow-up questions

Similar questions

More Glean interview questions

All 41 Glean questions →