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", or None when "type" == "r".
  • "depends_on": None, or a 1-based integer line index d (1 <= d <= len(batch)) within the same batch indicating that line d must 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:

  1. Strict batch barriers: Every operation in batch b must execute before any operation in batch b + 1. Empty batches emit nothing while keeping their 1-based batch index so subsequent batches retain their original numbers.
  2. 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 smallest 1-based line number next.
  3. Exclusive bus with 1 ms spacing: Each operation completes instantaneously once started, at most one operation may start at a given millisecond, the very first operation may start at 0, and any two consecutive operations across the entire run must start at least 1 ms apart (t_next >= t_prev + 1).
  4. Read-after-write (RAW) cooldown (10 ms): If register r is written at timestamp t_w, no subsequent read of register r (even in a later batch) may start earlier than t_w + 10. Write-after-read and write-after-write on the same register require only the normal 1 ms gap, and reading a register that has never been written incurs no cooldown.
  5. 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 most 10^5.
  • Within any single batch, all "register" IDs are pairwise distinct.
  • Write operations always have "depends_on": None and an integer "value".
  • Read operations always have "value": None, and "depends_on" is either None or a valid 1-based line index in the same batch with no dependency cycles.

Step-by-step walkthrough

  1. 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_on link 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, where batches[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_on is a 1-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}, with 1-based batch and line numbers.

    We will build the core scheduler first, and also provide parse_batches and execute_operations_from_file for plain-text batch scripts.

  2. Translate every timing rule into a lower bound on start time

    Each operation takes 0 ms of duration, so "all operations in batch k have finished" simply means every operation in batch k has started. That turns all the hardware rules into clean rules on start times:

    1. One operation at a time + 1 ms minimum gap: the very first operation can start at t = 0, and every operation after that must start at t >= prev_start + 1. Running batches sequentially on this single timeline satisfies batch boundaries automatically.
    2. Read-after-write (RAW) hazard (10 ms): if register r was previously written at t_write, any later read of r must satisfy t >= t_write + 10. Only the most recent write to r matters (if r was written at 1 and again at 5, waiting until 5 + 10 = 15 automatically satisfies 1 + 10 = 11). Write-after-read and write-after-write only need the 1 ms gap.
    3. 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]
    
    1. Intra-batch dependency (depends_on): if line a has depends_on = d, line d (in the same batch) must execute before line a. Because no register appears twice in the same batch, this is purely an ordering constraint inside that batch.
  3. 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:

    1. Order each batch (batch_order): find the 1-based execution order of lines inside the batch that obeys every depends_on rule while staying as close to 1, 2, ..., k as possible.
    2. 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) (if r was ever written).

    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 + 1 and t_write + 10 smaller (never larger) for every operation that comes later. Delaying an operation needlessly can never unlock a future operation sooner.

  4. 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 line 1 waiting on line 3), 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 (heapq in Python — a priority queue where heappop always removes the minimum number).

    Notice how clean the graph is: each read has at most one depends_on line. That means we don't even need an array of prerequisite counts — any line with depends_on is None starts in ready_heap, and as soon as line d runs, every line listed in dependents[d] has its single prerequisite satisfied and enters ready_heap immediately!

    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_order
    
  5. Assign timestamps across batches

    Now we maintain just two variables across the entire run:

    • earliest_slot: starts at 0, updated to start_time + 1 after every operation.
    • last_write_time: dictionary mapping register -> start_time of its latest write.

    Watch out for one subtle Python trap when checking last_write_time: a write at t = 0 stores last_write_time[r] = 0, which is falsy in Python, while a register that was never written has no entry at all. Always test if register in last_write_time: — never if last_write_time.get(register): (which misses writes at t = 0) and never last_write_time.get(register, 0) (which pretends every untouched register was written at t = 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 schedule
    
  6. Trace 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] = 13
    

    Finally, parsing the text file and calling read_reg / write_reg is a thin wrapper around schedule_register_operations. Blank lines are ignored, p or P starts a new batch list, and optional read_reg / write_reg parameters 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 batches
    
  7. Full 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 most O(N log N)). Inside a batch of k lines, each line is pushed into and popped from ready_heap once at O(log k) per heap operation, and assigning timestamps does O(1) dictionary lookups and updates per operation. Parsing the text file is O(file_size).
  • Space: O(N + R). Building the output schedule stores N dictionaries, dependents and ready_heap hold at most K + 1 entries for the current batch, and last_write_time stores one integer timestamp for each of the R written registers (R <= N).

Edge cases

  • Empty input [] or empty batches (leading/trailing p, or p twice in a row): empty batches schedule zero operations, while enumerate(batches, start=1) preserves the exact 1-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 (even t = 0).
  • Writing a register at t = 0 and reading it later: last_write_time[r] is 0, so a read in the next batch still waits until 0 + 10 = 10.
  • Multiple writes to the same register (t = 0, then t = 1): last_write_time[r] is overwritten with 1, so a subsequent read waits until 1 + 10 = 11.
  • Write after read (r then w on the same register): no 10 ms wait — only read-after-write is a hazard, so the write runs after the standard 1 ms gap.
  • Chained dependencies (1 depends on 2, 2 depends on 3): only line 3 starts in ready_heap, unlocking 2, which unlocks 1, producing order 3, 2, 1.

Common mistakes

  • Using last_write_time.get(r, 0) or if last_write_time.get(r):: 0 is a valid timestamp! .get(r, 0) falsely treats never-written registers as written at t = 0 (delaying early reads to t = 10), whereas if last_write_time.get(r): treats 0 as False and skips the 10 ms wait for writes at t = 0. Always check if register in last_write_time:.
  • Resetting last_write_time or the clock at batch boundaries: the 10 ms hardware hazard persists across batches (20 w 25 at t = 1 in Batch 1 delays 20 r in Batch 2 to t = 11).
  • Appending delayed lines to the end of a queue instead of a min-heap: if line 1 depends on line 3 in a 4-line batch, line 1 becomes ready right after line 3 and must run before line 4 (2, 3, 1, 4), not after 4.
  • Counting p separator lines or failing to reset line numbers per batch: depends_on is 1-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 account batch_start, any last_write_time[r] + 10 hazard, and release[dep] + 1), then sort the batch by (release[line], line). On Example 1's Batch 2, that schedules 10 r at t = 10 ahead of 20 r at t = 11, finishing Batch 2 at 11 ms instead of 12 ms (and all three batches at 12 ms instead of 13 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 k determines when reads in Batch k + 1 are allowed to start! For example, if Batch 1 is [1 w 5, 2 w 6] and Batch 2 is [2 r], running 1 w 5 at t = 0 and 2 w 6 at t = 1 forces 2 r to wait until 11 ms, whereas writing register 2 first at t = 0 lets 2 r run at 10 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 until t0 + entry["time"] / 1000.0 seconds before calling read_reg or write_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_on index against 1 .. len(batch) and verify len(execution_order) == len(batch) after Kahn's loop, raising a ValueError before touching hardware on any invalid batch. For multi-gigabyte logs, stream one batch at a time up to the next p/P barrier while carrying only earliest_slot and last_write_time forward; evicting entries with write_time <= earliest_slot - 10 caps last_write_time at 10 registers and bounds memory to O(largest_batch).

Follow-up questions

Similar questions

More Ixana interview questions

All 1 Ixana questions →