Scheduling Register Batches with Timing Hazards
Hard · Coding & Algorithms · Software Engineer · Technical Screen
Problem Statement
A hardware bus controller processes sequences of register reads ("r") and writes ("w") grouped into ordered batches. Implement:
def schedule_register_operations(batches: List[List[Dict[str, object]]]) -> List[Dict[str, object]]:
batches is a list of batches indexed 1 .. len(batches). Each batch is a list of operation dictionaries numbered 1 .. len(batch) in input line order, where every dictionary has four keys:
"type":"w"for a write or"r"for a read."register": integer ID of the target hardware register."value": integer payload written when"type" == "w", orNonewhen"type" == "r"."depends_on":None, or a1-based integer line indexd(1 <= d <= len(batch)) within the same batch indicating that linedmust run before this read.
(When loaded from a plain-text command script, blank lines are skipped, p or P acts as a barrier closing the current batch and opening the next, write lines have the form <register> w <value>, and read lines have the form <register> r or <register> r <depends_on>.)
Your scheduler assigns an integer timestamp time (in logical milliseconds, starting from 0) and an execution order to all operations while enforcing every rule below:
- Strict batch barriers: Every operation in batch
bmust execute before any operation in batchb + 1. Empty batches emit nothing while keeping their1-based batch index so subsequent batches retain their original numbers. - Intra-batch precedence and tie-breaking: Inside a batch, operations may be reordered to honor
"depends_on"links. Whenever multiple unscheduled lines in the active batch have no unmet prerequisite, schedule the line with the smallest1-based line number next. - Exclusive bus with
1 msspacing: Each operation completes instantaneously once started, at most one operation may start at a given millisecond, the very first operation may start at0, and any two consecutive operations across the entire run must start at least1 msapart (t_next >= t_prev + 1). - Read-after-write (RAW) cooldown (
10 ms): If registerris written at timestampt_w, no subsequent read of registerr(even in a later batch) may start earlier thant_w + 10. Write-after-read and write-after-write on the same register require only the normal1 msgap, and reading a register that has never been written incurs no cooldown. - Earliest legal timestamp: Following the execution order fixed by Rules 1 and 2, start each operation at the smallest integer millisecond permitted by Rules 3 and 4.
Return a flat list of scheduled operation dictionaries in execution order, each formatted as:
{
"batch": int, # 1-based batch number
"line": int, # 1-based line number within that batch
"time": int, # scheduled start time in ms
"op": str, # "w" or "r"
"register": int, # target register ID
"value": Optional[int], # written integer for "w", or None for "r"
}
Examples
Example 1
Input:
batches = [
[
{"type": "w", "register": 10, "value": 50, "depends_on": None},
{"type": "w", "register": 20, "value": 25, "depends_on": None},
{"type": "r", "register": 30, "value": None, "depends_on": None},
],
[
{"type": "r", "register": 20, "value": None, "depends_on": None},
{"type": "r", "register": 10, "value": None, "depends_on": None},
],
[
{"type": "w", "register": 20, "value": 99, "depends_on": None},
],
]
Output:
[
{"batch": 1, "line": 1, "time": 0, "op": "w", "register": 10, "value": 50},
{"batch": 1, "line": 2, "time": 1, "op": "w", "register": 20, "value": 25},
{"batch": 1, "line": 3, "time": 2, "op": "r", "register": 30, "value": None},
{"batch": 2, "line": 1, "time": 11, "op": "r", "register": 20, "value": None},
{"batch": 2, "line": 2, "time": 12, "op": "r", "register": 10, "value": None},
{"batch": 3, "line": 1, "time": 13, "op": "w", "register": 20, "value": 99},
]
Walk-through:
Batch 1 runs lines 1, 2, 3 at t = 0, 1, 2 (register 30 has never been written, so reading it needs no cooldown). When Batch 2 begins, the 1 ms bus gap allows t = 3, but register 20 was written at t = 1, pushing its read to 1 + 10 = 11. Register 10 was written at t = 0 (0 + 10 = 10 <= 12), so line 2 runs right away at t = 12. Finally, Batch 3 writes register 20 at t = 13 because write-after-read has no 10 ms penalty.
Example 2
Input:
batches = [
[
{"type": "w", "register": 0, "value": 7, "depends_on": None},
],
[
{"type": "r", "register": 0, "value": None, "depends_on": 3},
{"type": "w", "register": 6, "value": 40, "depends_on": None},
{"type": "r", "register": 9, "value": None, "depends_on": None},
{"type": "w", "register": 8, "value": 12, "depends_on": None},
],
]
Output:
[
{"batch": 1, "line": 1, "time": 0, "op": "w", "register": 0, "value": 7},
{"batch": 2, "line": 2, "time": 1, "op": "w", "register": 6, "value": 40},
{"batch": 2, "line": 3, "time": 2, "op": "r", "register": 9, "value": None},
{"batch": 2, "line": 1, "time": 10, "op": "r", "register": 0, "value": None},
{"batch": 2, "line": 4, "time": 11, "op": "w", "register": 8, "value": 12},
]
Walk-through:
Batch 1 writes register 0 at t = 0. In Batch 2, line 1 must wait for line 3, so ready lines start as {2, 3, 4}. Line 2 runs at t = 1, then line 3 runs at t = 2 and unlocks line 1. Between ready lines {1, 4}, line 1 wins the tie-breaker (1 < 4), waits until 0 + 10 = 10 for register 0's RAW cooldown, and line 4 follows at t = 11.
Constraints
0 <= len(batches) <= 10^4, and the total number of operations across all batches is at most10^5.- Within any single batch, all
"register"IDs are pairwise distinct. - Write operations always have
"depends_on": Noneand an integer"value". - Read operations always have
"value": None, and"depends_on"is eitherNoneor a valid1-based line index in the same batch with no dependency cycles.
Step-by-step walkthrough
Understand the problem and the input/output shapes
We need to compute a canonical schedule across ordered batches: inside each batch, operations run in line order unless a
depends_onlink holds a line back, in which case we always pick the smallest-numbered ready line next, and every operation starts at the earliest millisecond allowed by the bus spacing and read-after-write rules.The entry point
schedule_register_operations(batches)takes already-parsed batches:- Input
batches: a list of batches, wherebatches[b]is a list of operation dictionaries in input line order:{"type": "w" or "r", "register": int, "value": int or None, "depends_on": int or None}(depends_onis a1-based line number inside the same batch). - Output: a flat list of scheduled operations in execution order, each formatted as:
{"batch": int, "line": int, "time": int, "op": "w" or "r", "register": int, "value": int or None}, with1-basedbatchandlinenumbers.
We will build the core scheduler first, and also provide
parse_batchesandexecute_operations_from_filefor plain-text batch scripts.- Input
Translate every timing rule into a lower bound on start time
Each operation takes
0 msof duration, so "all operations in batchkhave finished" simply means every operation in batchkhas started. That turns all the hardware rules into clean rules on start times:- One operation at a time +
1 msminimum gap: the very first operation can start att = 0, and every operation after that must start att >= prev_start + 1. Running batches sequentially on this single timeline satisfies batch boundaries automatically. - Read-after-write (RAW) hazard (
10 ms): if registerrwas previously written att_write, any later read ofrmust satisfyt >= t_write + 10. Only the most recent write tormatters (ifrwas written at1and again at5, waiting until5 + 10 = 15automatically satisfies1 + 10 = 11). Write-after-read and write-after-write only need the1 msgap. - Cross-batch memory: register state does not reset at batch boundaries! A write near the end of Batch 1 still forces a read of the same register in Batch 2 to wait:
Batch 1: [t=0: 10 w 50] [t=1: 20 w 25] [t=2: 30 r] │ ┌──── +10 ms RAW hazard ───────────────────┐ ▼ ▼ Batch 2: earliest_slot is 3, MUST wait until 11 -> [t=11: 20 r] [t=12: 10 r]- Intra-batch dependency (
depends_on): if lineahasdepends_on = d, lined(in the same batch) must execute before linea. Because no register appears twice in the same batch, this is purely an ordering constraint inside that batch.
- One operation at a time +
Split the problem into two clean phases
Trying to choose line order and timestamps simultaneously is messy. Instead, we split the job into two straightforward steps:
- Order each batch (
batch_order): find the1-based execution order of lines inside the batch that obeys everydepends_onrule while staying as close to1, 2, ..., kas possible. - Assign earliest timestamps (
schedule_register_operations): walk through the batches (and each batch's ordered lines), assigning each operation the smallest legal timestamp:- For a write:
start_time = earliest_slot. - For a read:
start_time = max(earliest_slot, last_write_time[r] + 10)(ifrwas ever written).
- For a write:
Why is starting each operation as early as possible guaranteed to be best for a fixed order? Because an earlier start time only makes
prev_start + 1andt_write + 10smaller (never larger) for every operation that comes later. Delaying an operation needlessly can never unlock a future operation sooner.- Order each batch (
Order lines inside a batch with a min-heap (Kahn's algorithm)
When a batch has no dependencies, we want lines in file order
1, 2, ..., k. When dependencies exist (such as line1waiting on line3), we want to always run the smallest line number whose prerequisite has already executed.Ordering items so prerequisites come first is called a topological sort, and doing it by repeatedly picking items with zero unmet prerequisites is Kahn's algorithm. To always pick the smallest available line number in
O(log k)time, we store ready lines in a min-heap (heapqin Python — a priority queue whereheappopalways removes the minimum number).Notice how clean the graph is: each read has at most one
depends_online. That means we don't even need an array of prerequisite counts — any line withdepends_on is Nonestarts inready_heap, and as soon as linedruns, every line listed independents[d]has its single prerequisite satisfied and entersready_heapimmediately!Example 2, Batch 2: line 1: 0 r 3 (needs line 3) line 2: 6 w 40 line 3: 9 r line 4: 8 w 12 Initial state: dependents[3] = [1], ready_heap = [2, 3, 4] Pop 2 -> order = [2] | ready_heap = [3, 4] Pop 3 -> order = [2, 3], unlock 1! | push 1 -> ready_heap = [1, 4] Pop 1 -> order = [2, 3, 1] | ready_heap = [4] <- 1 beats 4! Pop 4 -> order = [2, 3, 1, 4] | ready_heap = []import heapq from typing import Dict, List def batch_order(batch: List[Dict[str, object]]) -> List[int]: """Return 1-based line numbers in execution order using Kahn's algorithm with a min-heap.""" num_lines = len(batch) # dependents[d]: list of 1-based line numbers waiting for line d to execute first dependents: List[List[int]] = [[] for _ in range(num_lines + 1)] # ready_heap: min-heap of 1-based line numbers that have 0 unmet dependencies ready_heap: List[int] = [] # Phase 1: Group lines into immediately ready vs. waiting on a prerequisite line. for line_num in range(1, num_lines + 1): prereq_line = batch[line_num - 1].get("depends_on") if prereq_line is None: ready_heap.append(line_num) else: prereq_idx = int(prereq_line) if not (1 <= prereq_idx <= num_lines): raise ValueError(f"depends_on={prereq_idx} out of range 1..{num_lines}") dependents[prereq_idx].append(line_num) heapq.heapify(ready_heap) # Phase 2: Repeatedly pop the smallest ready line so we stay as close to file order as legal. execution_order: List[int] = [] while ready_heap: line_num = heapq.heappop(ready_heap) execution_order.append(line_num) # Each line depends on at most one prerequisite, so its dependents become ready immediately. for waiting_line in dependents[line_num]: heapq.heappush(ready_heap, waiting_line) # If some lines never entered the heap, they are stuck in a dependency cycle. if len(execution_order) != num_lines: raise ValueError("circular dependency inside a batch") return execution_orderAssign timestamps across batches
Now we maintain just two variables across the entire run:
earliest_slot: starts at0, updated tostart_time + 1after every operation.last_write_time: dictionary mappingregister -> start_timeof its latest write.
Watch out for one subtle Python trap when checking
last_write_time: a write att = 0storeslast_write_time[r] = 0, which is falsy in Python, while a register that was never written has no entry at all. Always testif register in last_write_time:— neverif last_write_time.get(register):(which misses writes att = 0) and neverlast_write_time.get(register, 0)(which pretends every untouched register was written att = 0!).MIN_OP_GAP_MS = 1 RAW_HAZARD_MS = 10 def schedule_register_operations(batches: List[List[Dict[str, object]]]) -> List[Dict[str, object]]: # schedule: list of {"batch", "line", "time", "op", "register", "value"} dicts in run order schedule: List[Dict[str, object]] = [] # earliest_slot: next start time (ms) allowed by the 1 ms minimum gap between any two ops earliest_slot = 0 # last_write_time: maps register_index (int) -> start time (ms) of its most recent write last_write_time: Dict[int, int] = {} for batch_number, batch in enumerate(batches, start=1): ordered_lines = batch_order(batch) for line_num in ordered_lines: op = batch[line_num - 1] op_type = str(op["type"]) register = int(op["register"]) start_time = earliest_slot # Use `in` (not .get(register, 0)) because a write at t=0 is real whereas never-written has no wait. if op_type == "r" and register in last_write_time: hazard_ready_time = last_write_time[register] + RAW_HAZARD_MS if hazard_ready_time > start_time: start_time = hazard_ready_time # Record write start time so future reads (even in later batches) obey the 10 ms hazard. if op_type == "w": last_write_time[register] = start_time # Next operation in this or any later batch must start at least 1 ms after start_time. earliest_slot = start_time + MIN_OP_GAP_MS schedule.append({ "batch": batch_number, "line": line_num, "time": start_time, "op": op_type, "register": register, "value": op.get("value"), }) return scheduleTrace Example 1 and add file parsing
Let's trace all three batches of Example 1 step by step:
Batch Line Operation earliest_slot RAW hazard bound Chosen time last_write_time update ----- ---- ---------- ------------- ------------------------ ----------- ---------------------- 1 1 10 w 50 0 (write: none) 0 last_write[10] = 0 1 2 20 w 25 1 (write: none) 1 last_write[20] = 1 1 3 30 r 2 r30 never written -> none 2 - 2 1 20 r 3 last_write[20]+10 = 11 11 - (jumped from 3 to 11!) 2 2 10 r 12 last_write[10]+10 = 10 <= 12 12 - 3 1 20 w 99 13 (write: none) 13 last_write[20] = 13Finally, parsing the text file and calling
read_reg/write_regis a thin wrapper aroundschedule_register_operations. Blank lines are ignored,porPstarts a new batch list, and optionalread_reg/write_regparameters default to globals while letting unit tests inject mock functions:from typing import List, Optional def parse_batches(text: str) -> List[List[Dict[str, object]]]: """Parse plain-text file contents into a list of batches of operation dicts.""" batches: List[List[Dict[str, object]]] = [[]] for raw_line in text.splitlines(): parts = raw_line.split() if not parts: continue # 'p' or 'P' closes the current batch and opens a fresh batch. if parts[0].lower() == "p": batches.append([]) continue register = int(parts[0]) op_type = parts[1].lower() value: Optional[int] = None depends_on: Optional[int] = None if op_type == "w": value = int(parts[2]) elif len(parts) > 2: depends_on = int(parts[2]) batches[-1].append({ "type": op_type, "register": register, "value": value, "depends_on": depends_on, }) return batchesFull solution
from typing import Any, Dict, List, Optional, Set, Tuple import heapq # Global timing constants in logical milliseconds MIN_OP_GAP_MS = 1 RAW_HAZARD_MS = 10 def batch_order(batch: List[Dict[str, object]]) -> List[int]: """Return 1-based line numbers in execution order using Kahn's algorithm with a min-heap.""" num_lines = len(batch) # dependents[d]: list of 1-based line numbers waiting for line d to execute first dependents: List[List[int]] = [[] for _ in range(num_lines + 1)] # ready_heap: min-heap of 1-based line numbers that have 0 unmet dependencies ready_heap: List[int] = [] # Phase 1: Group lines into immediately ready vs. waiting on a prerequisite line. for line_num in range(1, num_lines + 1): prereq_line = batch[line_num - 1].get("depends_on") if prereq_line is None: ready_heap.append(line_num) else: prereq_idx = int(prereq_line) if not (1 <= prereq_idx <= num_lines): raise ValueError(f"depends_on={prereq_idx} out of range 1..{num_lines}") dependents[prereq_idx].append(line_num) heapq.heapify(ready_heap) # Phase 2: Repeatedly pop the smallest ready line so we stay as close to file order as legal. execution_order: List[int] = [] while ready_heap: line_num = heapq.heappop(ready_heap) execution_order.append(line_num) # Each line depends on at most one prerequisite, so its dependents become ready immediately. for waiting_line in dependents[line_num]: heapq.heappush(ready_heap, waiting_line) # If some lines never entered the heap, they are stuck in a dependency cycle. if len(execution_order) != num_lines: raise ValueError("circular dependency inside a batch") return execution_order def schedule_register_operations(batches: List[List[Dict[str, object]]]) -> List[Dict[str, object]]: # schedule: list of {"batch", "line", "time", "op", "register", "value"} dicts in run order schedule: List[Dict[str, object]] = [] # earliest_slot: next start time (ms) allowed by the 1 ms minimum gap between any two ops earliest_slot = 0 # last_write_time: maps register_index (int) -> start time (ms) of its most recent write last_write_time: Dict[int, int] = {} for batch_number, batch in enumerate(batches, start=1): ordered_lines = batch_order(batch) for line_num in ordered_lines: op = batch[line_num - 1] op_type = str(op["type"]) register = int(op["register"]) start_time = earliest_slot # Use `in` (not .get(register, 0)) because a write at t=0 is real whereas never-written has no wait. if op_type == "r" and register in last_write_time: hazard_ready_time = last_write_time[register] + RAW_HAZARD_MS if hazard_ready_time > start_time: start_time = hazard_ready_time # Record write start time so future reads (even in later batches) obey the 10 ms hazard. if op_type == "w": last_write_time[register] = start_time # Next operation in this or any later batch must start at least 1 ms after start_time. earliest_slot = start_time + MIN_OP_GAP_MS schedule.append({ "batch": batch_number, "line": line_num, "time": start_time, "op": op_type, "register": register, "value": op.get("value"), }) return schedule def parse_batches(text: str) -> List[List[Dict[str, object]]]: """Parse plain-text file contents into a list of batches of operation dicts.""" batches: List[List[Dict[str, object]]] = [[]] for raw_line in text.splitlines(): parts = raw_line.split() if not parts: continue # 'p' or 'P' closes the current batch and opens a fresh batch. if parts[0].lower() == "p": batches.append([]) continue register = int(parts[0]) op_type = parts[1].lower() value: Optional[int] = None depends_on: Optional[int] = None if op_type == "w": value = int(parts[2]) elif len(parts) > 2: depends_on = int(parts[2]) batches[-1].append({ "type": op_type, "register": register, "value": value, "depends_on": depends_on, }) return batches def execute_operations_from_file(file_path: str, read_reg=None, write_reg=None) -> None: """Read a batch file, compute a valid schedule, and invoke read_reg / write_reg in order.""" if read_reg is None: read_reg = globals()["read_reg"] if write_reg is None: write_reg = globals()["write_reg"] with open(file_path, encoding="utf-8") as handle: batches = parse_batches(handle.read()) for entry in schedule_register_operations(batches): if entry["op"] == "w": write_reg(entry["register"], entry["value"]) else: read_reg(entry["register"])✅ Submit now — all tests should pass.
Intuition & how it works
Think of the hardware registers as numbered mailboxes along a narrow workbench. Only one worker can touch a mailbox each millisecond (1 ms minimum gap), and painting a new number on a mailbox (write) leaves wet paint that takes 10 ms to dry before anyone can open that mailbox to read it — a read-after-write (RAW) hazard (a hardware rule preventing a read from seeing stale or unstable data right after a write). Inside each batch, some reads also carry a sticky note saying "run line d before me," which we resolve using Kahn's algorithm (a topological sort — ordering tasks so every prerequisite runs before the task that depends on it) backed by a min-heap (a priority queue that always pops the smallest ready line number in O(log k) time).
Why do simpler shortcuts fail? Executing lines strictly top-to-bottom breaks as soon as line 1 depends on line 3 in the same batch. Resetting the clock or forgetting write history at p separators violates the 10 ms hazard when Batch 2 reads a register that Batch 1 just wrote. Finally, shoving delayed lines to the back of the batch instead of pushing them into a min-heap changes tie-breaking (running line 4 before line 1 even after line 3 has already unlocked line 1).
Here is how Example 2 plays out — Batch 1 writes register 0 ([0 w 7]), and Batch 2 has line 1 reading register 0 after line 3 ([0 r dep=3, 6 w 40, 9 r, 8 w 12]):
Batch 1:
ready_heap = [1] -> pop line 1 (0 w 7):
starts at t = 0, sets last_write_time[0] = 0, earliest_slot = 1
Batch 2 (line 1 waits on line 3):
ready_heap = [2, 3, 4] -> pop line 2 (6 w 40):
starts at t = 1, sets last_write_time[6] = 1, earliest_slot = 2
ready_heap = [3, 4] -> pop line 3 (9 r):
starts at t = 2 (r9 never written), earliest_slot = 3, unlocks line 1 -> ready_heap = [1, 4]
ready_heap = [1, 4] -> pop line 1 (0 r, dep=3):
earliest_slot is 3, but last_write_time[0] + 10 = 0 + 10 = 10
starts at max(3, 10) = 10, earliest_slot = 11
ready_heap = [4] -> pop line 4 (8 w 12):
starts at t = 11, sets last_write_time[8] = 11, earliest_slot = 12
Complexity
Let N be the total number of operations across all batches, K be the maximum number of operations in a single batch (K <= N), and R be the number of distinct registers written.
- Time:
O(N log K)(at mostO(N log N)). Inside a batch ofklines, each line is pushed into and popped fromready_heaponce atO(log k)per heap operation, and assigning timestamps doesO(1)dictionary lookups and updates per operation. Parsing the text file isO(file_size). - Space:
O(N + R). Building the outputschedulestoresNdictionaries,dependentsandready_heaphold at mostK + 1entries for the current batch, andlast_write_timestores one integer timestamp for each of theRwritten registers (R <= N).
Edge cases
- Empty input
[]or empty batches (leading/trailingp, orptwice in a row): empty batches schedule zero operations, whileenumerate(batches, start=1)preserves the exact1-based batch numbers of non-empty batches that follow. - Reading a register that was never written: no RAW hazard applies; the read starts at
earliest_slot(event = 0). - Writing a register at
t = 0and reading it later:last_write_time[r]is0, so a read in the next batch still waits until0 + 10 = 10. - Multiple writes to the same register (
t = 0, thent = 1):last_write_time[r]is overwritten with1, so a subsequent read waits until1 + 10 = 11. - Write after read (
rthenwon the same register): no10 mswait — only read-after-write is a hazard, so the write runs after the standard1 msgap. - Chained dependencies (
1depends on2,2depends on3): only line3starts inready_heap, unlocking2, which unlocks1, producing order3, 2, 1.
Common mistakes
- Using
last_write_time.get(r, 0)orif last_write_time.get(r)::0is a valid timestamp!.get(r, 0)falsely treats never-written registers as written att = 0(delaying early reads tot = 10), whereasif last_write_time.get(r):treats0asFalseand skips the10 mswait for writes att = 0. Always checkif register in last_write_time:. - Resetting
last_write_timeor the clock at batch boundaries: the10 mshardware hazard persists across batches (20 w 25att = 1in Batch 1 delays20 rin Batch 2 tot = 11). - Appending delayed lines to the end of a queue instead of a min-heap: if line
1depends on line3in a 4-line batch, line1becomes ready right after line3and must run before line4(2, 3, 1, 4), not after4. - Counting
pseparator lines or failing to reset line numbers per batch:depends_onis1-based relative to operation lines inside the current batch only. - Forgetting uppercase
P: batch separators are case-insensitive (parts[0].lower() == "p").
Alternative approaches
- Release-time ordering (minimizing idle time inside a single batch): When preserving input line order is not required, you can compute each operation's earliest legal release time
release[line](taking into accountbatch_start, anylast_write_time[r] + 10hazard, andrelease[dep] + 1), then sort the batch by(release[line], line). On Example 1's Batch 2, that schedules10 ratt = 10ahead of20 ratt = 11, finishing Batch 2 at11 msinstead of12 ms(and all three batches at12 msinstead of13 ms).
def release_order(batch, last_write_time, batch_start):
"""Order lines by earliest possible start time (breaking ties by line number)."""
release = {}
for line_num in batch_order(batch):
op = batch[line_num - 1]
ready_at = batch_start
if op["type"] == "r" and op["register"] in last_write_time:
ready_at = max(ready_at, last_write_time[op["register"]] + RAW_HAZARD_MS)
prereq = op.get("depends_on")
if prereq is not None:
ready_at = max(ready_at, release[prereq] + MIN_OP_GAP_MS)
release[line_num] = ready_at
return [line_num for _, line_num in sorted((release[l], l) for l in range(1, len(batch) + 1))]
Follow-up questions
- Does minimizing each batch's finish time greedily guarantee the earliest overall completion time across multiple batches? No, because the order of writes inside Batch
kdetermines when reads in Batchk + 1are allowed to start! For example, if Batch 1 is[1 w 5, 2 w 6]and Batch 2 is[2 r], running1 w 5att = 0and2 w 6att = 1forces2 rto wait until11 ms, whereas writing register2first att = 0lets2 rrun at10 ms. A good heuristic schedules writes earlier when their registers are read in the next batch; finding a guaranteed global optimum across arbitrary batches requires search (such as branch-and-bound over intra-batch orders). - How would you replay the computed schedule against physical hardware registers in real wall-clock time? Compute the exact logical schedule first, record
t0 = time.monotonic(), and before each operation sleep untilt0 + entry["time"] / 1000.0seconds before callingread_regorwrite_reg. A monotonic clock (a timer guaranteed to move strictly forward at a steady rate) is essential here because the system wall clock (time.time()) can jump backward or forward during NTP time syncs. - How would you validate malformed dependency graphs and process multi-gigabyte command logs with bounded memory? Validate every
depends_onindex against1 .. len(batch)and verifylen(execution_order) == len(batch)after Kahn's loop, raising aValueErrorbefore touching hardware on any invalid batch. For multi-gigabyte logs, stream one batch at a time up to the nextp/Pbarrier while carrying onlyearliest_slotandlast_write_timeforward; evicting entries withwrite_time <= earliest_slot - 10capslast_write_timeat10registers and bounds memory toO(largest_batch).
Follow-up questions
- Does minimizing each batch's finish time greedily guarantee the earliest overall completion time across multiple batches?
- How would you replay the computed schedule against physical hardware registers in real wall-clock time?
- How would you validate malformed dependency graphs and process multi-gigabyte command logs with bounded memory?
Similar questions
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger
- Grid Path Scoring with Streak Bonuses
- Place One Hub to Minimize Maximum Grid Distance
- Increment Fixed-Size Digit Array by One
- Increment Digit Array