Thermal Throttling Simulator for Multicore Processors

Hard · Coding & Algorithms · Software Engineer · Online Assessment

Problem Statement

Implement an event-driven thermal management simulator for a processor with multiple cores sharing a passive heat sink alongside optional per-core active fans:

def simulate_overheat_controller(
    passiveCapacity: float,
    activeCapacityPerCore: float,
    coreIds: List[str],
    operations: List[List],
) -> List[List[str]]:

Every item in operations arrives in strictly increasing timestamp order and takes one of two forms:

  • ["set", timestamp, coreId, loadWatts] — queues a workload request in watts for coreId.
  • ["tick", timestamp] — advances physics across the elapsed interval, applies shutdown/restart logic, selects active fans for the next interval, and emits status changes.

Return one List[str] per "tick". Each inner list contains "<coreId>=<status>" entries in ascending lexicographical coreId order only for cores whose post-tick status differs from their status at the end of the preceding tick (compared against "idle" on the first tick). The three possible statuses are:

  • "idle" — running without an active fan for the upcoming interval.
  • "cooling" — running with an active fan enabled for the upcoming interval.
  • "shutdown" — thermally tripped off.

Initial Conditions & Queued Workloads

  • Before any event runs, every core in coreIds is running at 20.0 °C with 0.0 W active workload, no active fan, and status "idle".
  • A "set" event performs zero thermal calculation and never splits a time interval; it only records loadWatts in a pending map for coreId. When multiple "set" events target the same core between two ticks, only the latest loadWatts is kept.

Five-Step Execution at Each "tick"

  1. Advance temperatures over the interval just ending:
    • The very first "tick" sets the time origin (elapsed = 0.0 s). Each later "tick" uses elapsed = timestamp - previous_tick_timestamp seconds, governed throughout by the workloads and active-fan set finalized at the previous tick.
    • If k active fans were enabled during this interval, mechanical vibration reduces the shared passive sink budget to: text effective_passive = passiveCapacity * (1 - penalty(k) / 100) where penalty(0) = 0 and penalty(k) = sum(10 / F[i] for i = 1..k) using F = [1, 2, 3, 5, 8, 13, ...] (F[1] = 1, F[2] = 2, F[i] = F[i - 1] + F[i - 2]).
    • Every core c—including shut-down cores whose workload is 0.0 W—requests demand(c) = load(c) + 2.0 W from the passive sink. Letting total_demand be the sum of demand(c) across all cores:
      • If total_demand <= effective_passive, every core receives share(c) = demand(c).
      • Otherwise, every core receives share(c) = effective_passive * demand(c) / total_demand.
    • Each core in the previous tick's active-fan set receives an extra activeCapacityPerCore W (0.0 W otherwise), giving net heating power net(c) = load(c) - share(c) - active_watts(c).
    • Each watt of net heat shifts temperature by 0.02 °C per second, clamped at an ambient floor of 20.0 °C: text temp(c) = max(20.0, temp(c) + 0.02 * net(c) * elapsed)
  2. Enforce thermal shutdowns (>= 80.0 °C):
    • Any running core with temp(c) >= 80.0 transitions to "shutdown", resets load(c) = 0.0, and drops any pending "set" request queued for c.
  3. Apply remaining pending "set" requests:
    • For a running core c, set load(c) to its queued loadWatts.
    • For an already shut-down core c, treat the queued "set" as a single-shot restart attempt: if temp(c) < 50.0 (strictly below 50.0 °C), c resumes running with load(c) = loadWatts; otherwise (temp(c) >= 50.0), the attempt fails and c stays shut down at 0.0 W.
    • Clear the pending map completely so rejected restart attempts do not carry over.
  4. Select active fans from scratch for the upcoming interval:
    • Shut-down cores are never eligible.
    • Seed selected with all running cores satisfying temp(c) > 60.0 (strictly above 60.0 °C).
    • Repeat until a pass adds zero cores:
      • Recompute effective_passive for k = len(selected) and share(c) using current workloads.
      • Add every unselected running core whose unassisted heating rate 0.02 * (load(c) - share(c)) is strictly above 0.5 °C/s (> 0.5).
  5. Record status transitions:
    • Compare each core's new status against its status from the previous tick and emit "<coreId>=<status>" sorted by coreId for changed cores only.

Examples

Example 1

  • Input:
    • passiveCapacity = 50, activeCapacityPerCore = 20, coreIds = ["c2", "c1"]
    • operations = [["tick", 2], ["set", 3, "c1", 18], ["tick", 5], ["set", 6, "c2", 78], ["tick", 10]]
  • Output: [[], [], ["c2=cooling"]]
  • Explanation:
    • At t = 2 (elapsed = 0) and t = 5 (c1 = 18 W, total passive demand 20 + 2 = 22 <= 50 W), passive cooling covers full demand so both cores stay "idle".
    • At t = 10, applying c2 = 78 W raises demands to 20 + 80 = 100 W. With k = 0, c2 gets 40 W passive cooling and heats at 0.02 * (78 - 40) = 0.76 > 0.5 °C/s, turning on c2's fan (k = 1, 10% vibration penalty -> 45 W passive, leaving c1 at 0.18 <= 0.5 °C/s). Only "c2" changed status.

Example 2

  • Input:
    • passiveCapacity = 40, activeCapacityPerCore = 10, coreIds = ["p2", "p1"]
    • operations = [["set", 0.5, "p1", 55], ["set", 0.8, "p2", 41], ["tick", 1], ["tick", 131], ["set", 135, "p1", 10], ["tick", 141]]
  • Output: [["p1=cooling", "p2=cooling"], ["p1=shutdown"], []]
  • Explanation:
    • At t = 1, demands are 57 + 43 = 100 W. At k = 0, p1 heats at 0.644 > 0.5 °C/s while p2 is 0.476 °C/s; selecting p1 (k = 1, 10% penalty -> 36 W passive) pushes p2's unassisted rate to 0.5104 > 0.5 °C/s, cascading p2 into "cooling" too.
    • Over [1, 131] (130 s with k = 2, 15% penalty -> 34 W passive), p1 climbs to 86.612 >= 80.0 °C and shuts down while p2 reaches 62.588 °C (> 60.0 °C, staying "cooling").
    • At t = 141, p1 has cooled only to 86.292 >= 50.0 °C, so its restart request is discarded and no statuses change.

Constraints

  • 1 <= len(coreIds) < 1024; all core IDs are unique non-empty strings.
  • passiveCapacity > 0 and activeCapacityPerCore > 0.
  • 1 < len(operations) < 1024; timestamps are strictly increasing positive floats with up to millisecond precision.
  • 0 <= loadWatts <= 32768 with at most three decimal places.

Step-by-step walkthrough

  1. Restate the problem and map out the controller state

    We simulate a multicore thermal controller across a chronological list of operations—either ["set", timestamp, coreId, loadWatts] or ["tick", timestamp]—and return one list of "coreId=status" strings per tick. Each tick's list is sorted alphabetically by coreId and contains only the cores whose status ("idle", "cooling", or "shutdown") changed compared with the end of the previous tick.

    To keep every rule crystal clear, track four per-core fields plus two controller-wide structures:

    Per-core state (initialized for every core in sorted coreIds):
      temp[core]   = 20.0      (Celsius; clamped so it never drops below 20.0)
      load[core]   = 0.0       (watts currently generating heat; 0.0 when shut down)
      status[core] = "idle"    (status reported at the previous tick)
      core in shutdown         (True when shut down; False when running)
    
    Controller state across ticks:
      active       = set()     (running cores given active cooling for the CURRENT interval)
      pending      = {}        (coreId -> latest loadWatts queued since the last tick)
    

    Notice that a set command never touches temp, load, or active right away—it simply writes pending[coreId] = loadWatts (so multiple sets before a tick naturally keep only the last value). All thermal physics and status transitions happen at tick operations.

  2. Why we can jump straight from tick to tick instead of stepping per second

    A naive simulation advances time in tiny slices (say every millisecond) to update temperatures. With millisecond timestamps and gaps of thousands of seconds, stepping through time would take millions of iterations—and we do not need it!

    Why? Between two consecutive ticks, nothing in the physical formula changes: load only updates at ticks, active (and therefore its size k) only updates at ticks, and no core shuts down mid-interval. Every core c therefore experiences a constant heating or cooling rate r_c = 0.02 * net_heat_c across the entire elapsed window:

    Case A: net_heat >= 0 (heating)        Case B: net_heat < 0 (cooling toward 20.0 C floor)
    Temp ^                                 Temp ^
         |          /                           | \
         |       /                              |   \
    20 C +----/-----------------> time     20 C +-----\=================> time (clamped at 20.0)
    
    • If net_heat >= 0, the core starts at >= 20.0 and rises linearly, never touching the 20.0 floor.
    • If net_heat < 0, the core cools linearly; if it reaches 20.0 mid-interval, its rate is still negative so it stays pinned at 20.0 for the rest of the interval.

    In both cases, one single formula gives the exact end-of-interval temperature in O(1) operations:

    temp[core] = max(20.0, temp[core] + 0.02 * net_heat * elapsed)
    
  3. Separate the old interval from the new interval: the five phases of a tick

    Almost every bug on this problem comes from mixing up the state that governed the interval just ending with the state being chosen for the interval about to start. Each tick executes five phases in strict order:

    tick(now):
      [Phase 1: Advance temps]     Use OLD load & OLD active set over elapsed = now - last_tick
                |                  (elapsed = 0.0 on the very first tick)
                v
      [Phase 2: Shut down >= 80]   Running cores with temp >= 80.0 -> shutdown, load = 0, drop pending
                |
                v
      [Phase 3: Apply pending]     Running core -> load = new_load
                |                  Shutdown core -> restart ONLY if temp < 50.0; clear pending map
                v
      [Phase 4: Choose cooling]    Recompute NEW active set from scratch for the NEXT interval
                |
                v
      [Phase 5: Diff statuses]     Emit "core=status" where new_status != status[core]
    

    Check why this order is essential: - Applying pending before Phase 1 would make a newly requested workload heat the past interval before the tick even arrived. - Choosing active before Phase 1 would cool the past interval using fans that were only just turned on now. - Clearing pending = {} at the end of Phase 3 guarantees that a failed restart (temp >= 50.0) is discarded as a one-time request rather than lingering for future ticks.

  4. Compute vibration penalties and proportional passive cooling

    Let's write three small helper functions for shared passive cooling:

    1. vibration_penalties(max_k): Precomputes vibrationPenalty(k) for k = 0 .. len(cores). Pay close attention to the Fibonacci sequence in the statement: Fib = [1, 2, 3, 5, 8, 13, ...] starts with 1, 2 (not 1, 1), so k = 1 penalizes 10/1 = 10% and k = 2 penalizes 10/1 + 10/2 = 15%. Even for huge k, the infinite sum of 10 / Fib[i] converges below 23.6%, so effective passive capacity always stays above 76.4% of passiveCapacity.
    2. effective_capacity(passive_capacity, penalties, active_count): Applies 1 - penalties[k] / 100.
    3. passive_shares(capacity, load): Every core—including shutdown cores whose load[core] is 0.0—requests load[core] + 2.0 watts of passive cooling. If total_demand <= capacity, every core gets its full demand; otherwise every core receives the same proportional fraction capacity * demand / total_demand.
    from typing import Dict, List
    
    BASE_DEMAND = 2.0
    
    
    def vibration_penalties(max_k: int) -> List[float]:
        """Precompute penalties[k] = sum(10 / Fib[i] for i = 1..k) with Fib = [1, 2, 3, 5, 8, ...]."""
        # penalties[k]: percentage passive-capacity loss when k active-cooling channels are on
        penalties = [0.0]
        # Note: the specification starts Fib at 1, 2, 3, 5 (NOT 1, 1, 2), so k=2 gives 10/1 + 10/2 = 15.0.
        fib = 1
        next_fib = 2
        for _ in range(max_k):
            penalties.append(penalties[-1] + 10.0 / fib)
            fib, next_fib = next_fib, fib + next_fib
        return penalties
    
    
    def effective_capacity(
        passive_capacity: float, penalties: List[float], active_count: int
    ) -> float:
        """Return shared passive cooling watts remaining after vibration from active_count channels."""
        # Sum of 10 / Fib[i] converges below 23.6, so effective capacity always stays positive (> 76.4%).
        return passive_capacity * (1.0 - penalties[active_count] / 100.0)
    
    
    def passive_shares(capacity: float, load: Dict[str, float]) -> Dict[str, float]:
        """Compute passive cooling watts allocated to each core by proportional demand."""
        # Shutdown cores stay in `load` with 0.0 W, so they still claim BASE_DEMAND (2 W) here.
        total_demand = 0.0
        for core_load in load.values():
            total_demand += core_load + BASE_DEMAND
    
        # shares: {core_id: passive_watts_received}
        shares: Dict[str, float] = {}
        for core, core_load in load.items():
            demand = core_load + BASE_DEMAND
            # Use <= because exact tie (total_demand == capacity) still satisfies every core's full demand.
            if total_demand <= capacity:
                shares[core] = demand
            else:
                shares[core] = capacity * demand / total_demand
        return shares
    
  5. Find the active-cooling set with a monotone fixed-point loop

    In Phase 4, we decide which running cores receive active cooling for the upcoming interval using a monotone fixed-point loop (a loop that starts with a required seed set and only ever adds elements until an entire pass adds nothing new):

    Seed: selected = { running cores with temp > 60.0 }
              |
              v
    Recompute effective passive capacity & passive shares for k = len(selected)
              |
              v
    Find unselected running cores with unassisted rate 0.02 * (load - share) > 0.5
              |
         +----+----+
         |         |
      any new?   none new? ---> return selected (minimal stable active set!)
         |
         +--> add to selected, repeat!
    

    Why is this guaranteed to find a unique smallest set and finish quickly? Turning on more active channels increases len(selected), which raises the vibration penalty, shrinks effective_capacity, and lowers (never raises) every core's shares[core]. Lower passive cooling can only increase each core's unassisted heating rate 0.02 * (load[core] - shares[core]). That means no previously selected core ever stops needing cooling, and at most len(running) + 1 passes can run before newly_added is empty.

    from typing import Dict, List, Set
    
    HOT_ABOVE = 60.0
    MAX_RATE = 0.5
    DEGREES_PER_WATT_SECOND = 0.02
    
    
    def choose_active_cooling(
        passive_capacity: float,
        penalties: List[float],
        load: Dict[str, float],
        temp: Dict[str, float],
        running: List[str],
    ) -> Set[str]:
        """Find the minimal stable set of running cores requiring active cooling for the next interval."""
        # Step 1: Seed with every running core strictly hotter than 60.0 C.
        selected: Set[str] = set()
        for core in running:
            if temp[core] > HOT_ABOVE:
                selected.add(core)
    
        # Steps 2-4: Monotone fixed-point loop. Adding channels increases vibration and lowers passive
        # shares, which can only raise heating rates, so `selected` only grows until a pass adds nothing.
        while True:
            capacity = effective_capacity(passive_capacity, penalties, len(selected))
            shares = passive_shares(capacity, load)
            newly_added: List[str] = []
            for core in running:
                if core in selected:
                    continue
                unassisted_rate = DEGREES_PER_WATT_SECOND * (load[core] - shares[core])
                if unassisted_rate > MAX_RATE:
                    newly_added.append(core)
            if not newly_added:
                return selected
            selected.update(newly_added)
    
  6. Process set commands and run the five tick phases

    Now we wire up simulate_overheat_controller. Sorting coreIds once at the start means every loop over cores automatically produces "core=status" entries in alphabetical order. Double-check the exact comparison operators at every boundary:

    • Shutdown check: temp[core] >= 80.0 (at least 80.0 shuts down).
    • Restart check: temp[core] < 50.0 (strictly below 50.0; 50.0 refuses to restart).
    • Hot check in choose_active_cooling: temp[core] > 60.0 (strictly above 60.0).
    • Rate check in choose_active_cooling: unassisted_rate > 0.5 (strictly above 0.5).
    def _apply_shutdowns_and_pending(
        cores: List[str],
        temp: Dict[str, float],
        load: Dict[str, float],
        shutdown: Set[str],
        pending: Dict[str, float],
    ) -> None:
        """Illustration of Phases 2 and 3 inside each tick."""
        # Phase 2: Shut down any running core at or above 80.0 C and drop its pending ordinary load.
        for core in cores:
            if core not in shutdown and temp[core] >= 80.0:
                shutdown.add(core)
                load[core] = 0.0
                pending.pop(core, None)
    
        # Phase 3: Apply pending loads; for an already-shutdown core, treat as a one-time restart check.
        for core, new_load in pending.items():
            if core not in shutdown:
                load[core] = new_load
            elif temp[core] < 50.0:
                shutdown.remove(core)
                load[core] = new_load
    
  7. Trace Example 2 tick by tick

    Let's trace passiveCapacity = 40, activeCapacityPerCore = 10, coreIds = ['p2', 'p1'], and operations = [['set', 0.5, 'p1', 55], ['set', 0.8, 'p2', 41], ['tick', 1], ['tick', 131], ['set', 135, 'p1', 10], ['tick', 141]]:

    Op                  Interval Step (Old State)         Post-Pending Cooling Choice     Emitted Diff
    ------------------  --------------------------------  ------------------------------  ------------------------------
    set(t=0.5, p1=55)   pending = {'p1': 55}              (no thermal step on set)        -
    set(t=0.8, p2=41)   pending = {'p1': 55, 'p2': 41}    (no thermal step on set)        -
    tick(t=1)           first tick -> elapsed = 0.0       loads: p1=55, p2=41 (demands    ['p1=cooling', 'p2=cooling']
                        temps stay p1=20.0, p2=20.0       57, 43 -> total 100 W)
                                                          k=0: cap=40 -> rate(p1)=0.644
                                                          -> add 'p1'; k=1: cap=36 ->
                                                          rate(p2)=0.5104 -> add 'p2'
    tick(t=131)         elapsed = 130s, old k=2 (15%!)    p1 >= 80 C -> shutdown, load=0  ['p1=shutdown']
                        cap=34 -> share(p1)=19.38,        p2 is 62.59 > 60 C -> seeded
                        temp(p1) -> 86.61 C (>= 80!)      into selected -> active={'p2'}
                        temp(p2) -> 62.59 C (< 80)
    set(t=135, p1=10)   pending = {'p1': 10}              (no thermal step on set)        -
    tick(t=141)         elapsed = 10s, old active={'p2'}  p1 at 86.29 >= 50 C -> restart  []
                        temp(p1) -> 86.29 C               refused & dropped; p2 at 61.91
                        temp(p2) -> 61.91 C               > 60 C stays 'cooling'
    

    Collecting the three tick outputs yields [['p1=cooling', 'p2=cooling'], ['p1=shutdown'], []], matching Example 2.

  8. Complete solution

    from typing import Any, Dict, List, Optional, Set, Tuple
    
    # Physical constants and strict/non-strict thermal thresholds from the specification.
    START_TEMP = 20.0               # minimum and initial core temperature in degrees Celsius
    RESTART_BELOW = 50.0            # shutdown core restarts only if temp < 50.0 (strictly below)
    HOT_ABOVE = 60.0                # running core forces active cooling if temp > 60.0 (strictly above)
    SHUTDOWN_AT = 80.0              # running core shuts down if temp >= 80.0 (at least 80.0)
    MAX_RATE = 0.5                  # unselected core adds active cooling if rate > 0.5 C/s (strictly above)
    DEGREES_PER_WATT_SECOND = 0.02  # temperature change in C per second per watt of net heat
    BASE_DEMAND = 2.0               # fixed passive-cooling demand in watts for every core (even shut down)
    
    
    def vibration_penalties(max_k: int) -> List[float]:
        """Precompute penalties[k] = sum(10 / Fib[i] for i = 1..k) with Fib = [1, 2, 3, 5, 8, ...]."""
        # penalties[k]: percentage passive-capacity loss when k active-cooling channels are on
        penalties = [0.0]
        # Note: the specification starts Fib at 1, 2, 3, 5 (NOT 1, 1, 2), so k=2 gives 10/1 + 10/2 = 15.0.
        fib = 1
        next_fib = 2
        for _ in range(max_k):
            penalties.append(penalties[-1] + 10.0 / fib)
            fib, next_fib = next_fib, fib + next_fib
        return penalties
    
    
    def effective_capacity(
        passive_capacity: float, penalties: List[float], active_count: int
    ) -> float:
        """Return shared passive cooling watts remaining after vibration from active_count channels."""
        # Sum of 10 / Fib[i] converges below 23.6, so effective capacity always stays positive (> 76.4%).
        return passive_capacity * (1.0 - penalties[active_count] / 100.0)
    
    
    def passive_shares(capacity: float, load: Dict[str, float]) -> Dict[str, float]:
        """Compute passive cooling watts allocated to each core by proportional demand."""
        # Shutdown cores stay in `load` with 0.0 W, so they still claim BASE_DEMAND (2 W) here.
        total_demand = 0.0
        for core_load in load.values():
            total_demand += core_load + BASE_DEMAND
    
        # shares: {core_id: passive_watts_received}
        shares: Dict[str, float] = {}
        for core, core_load in load.items():
            demand = core_load + BASE_DEMAND
            # Use <= because exact tie (total_demand == capacity) still satisfies every core's full demand.
            if total_demand <= capacity:
                shares[core] = demand
            else:
                shares[core] = capacity * demand / total_demand
        return shares
    
    
    def choose_active_cooling(
        passive_capacity: float,
        penalties: List[float],
        load: Dict[str, float],
        temp: Dict[str, float],
        running: List[str],
    ) -> Set[str]:
        """Find the minimal stable set of running cores requiring active cooling for the next interval."""
        # Step 1: Seed with every running core strictly hotter than 60.0 C.
        selected: Set[str] = set()
        for core in running:
            if temp[core] > HOT_ABOVE:
                selected.add(core)
    
        # Steps 2-4: Monotone fixed-point loop. Adding channels increases vibration and lowers passive
        # shares, which can only raise heating rates, so `selected` only grows until a pass adds nothing.
        while True:
            capacity = effective_capacity(passive_capacity, penalties, len(selected))
            shares = passive_shares(capacity, load)
            newly_added: List[str] = []
            for core in running:
                if core in selected:
                    continue
                unassisted_rate = DEGREES_PER_WATT_SECOND * (load[core] - shares[core])
                if unassisted_rate > MAX_RATE:
                    newly_added.append(core)
            if not newly_added:
                return selected
            selected.update(newly_added)
    
    
    def simulate_overheat_controller(
        passiveCapacity: float,
        activeCapacityPerCore: float,
        coreIds: List[str],
        operations: List[List],
    ) -> List[List[str]]:
        # Sort core IDs once so every per-tick transition list is already in alphabetical order.
        cores = sorted(coreIds)
        penalties = vibration_penalties(len(cores))
    
        # temp: {core_id: current_celsius} (never drops below 20.0)
        temp: Dict[str, float] = {}
        # load: {core_id: active_watts} (0.0 initially and while shut down)
        load: Dict[str, float] = {}
        # status: {core_id: 'idle' | 'cooling' | 'shutdown'} reported after the previous tick
        status: Dict[str, str] = {}
        for core in cores:
            temp[core] = START_TEMP
            load[core] = 0.0
            status[core] = "idle"
    
        shutdown: Set[str] = set()             # core IDs currently in shutdown state
        active: Set[str] = set()               # core IDs cooled during the interval ending at this tick
        pending: Dict[str, float] = {}         # {core_id: last_load_watts} queued since previous tick
        last_tick_time: Optional[float] = None # timestamp of previous tick (None before the first tick)
        results: List[List[str]] = []
    
        for op in operations:
            # A `set` only overwrites the pending map (last-write-wins) without splitting the interval.
            if op[0] == "set":
                core_id = op[2]
                load_watts = op[3]
                pending[core_id] = load_watts
                continue
    
            now = op[1]
            if last_tick_time is None:
                elapsed = 0.0  # first tick establishes the time origin and advances by 0 seconds
            else:
                elapsed = now - last_tick_time
            last_tick_time = now
    
            # Phase 1: Advance temperatures over `elapsed` using the PREVIOUS tick's loads and active set.
            # Because rates are constant inside the interval, one linear step with a 20.0 C floor is exact.
            capacity = effective_capacity(passiveCapacity, penalties, len(active))
            shares = passive_shares(capacity, load)
            for core in cores:
                net_heat = load[core] - shares[core]
                if core in active:
                    net_heat -= activeCapacityPerCore
                updated_temp = temp[core] + DEGREES_PER_WATT_SECOND * net_heat * elapsed
                temp[core] = max(START_TEMP, updated_temp)
    
            # Phase 2: Shut down any running core at or above 80.0 C and drop its pending ordinary load.
            for core in cores:
                if core not in shutdown and temp[core] >= SHUTDOWN_AT:
                    shutdown.add(core)
                    load[core] = 0.0
                    pending.pop(core, None)
    
            # Phase 3: Apply pending loads; for an already-shutdown core, treat as a one-time restart check.
            for core, new_load in pending.items():
                if core not in shutdown:
                    load[core] = new_load
                elif temp[core] < RESTART_BELOW:
                    shutdown.remove(core)
                    load[core] = new_load
            # Clear pending whether restarts succeeded or failed (failed restarts do not stay queued).
            pending = {}
    
            # Phase 4: Recompute active cooling from scratch for the upcoming interval.
            running: List[str] = []
            for core in cores:
                if core not in shutdown:
                    running.append(core)
            active = choose_active_cooling(passiveCapacity, penalties, load, temp, running)
    
            # Phase 5: Emit "coreId=status" only for cores whose status changed since the last tick.
            changes: List[str] = []
            for core in cores:
                if core in shutdown:
                    new_status = "shutdown"
                elif core in active:
                    new_status = "cooling"
                else:
                    new_status = "idle"
    
                if new_status != status[core]:
                    changes.append(f"{core}={new_status}")
                    status[core] = new_status
            results.append(changes)
    
        return results
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Imagine a row of CPU cores sharing one central cooling duct (passive cooling), where each core also has its own emergency mini-fan (active cooling) bolted to the same metal frame. Turning on a mini-fan cools that core, but its vibration rattles the shared frame and weakens the central duct for everyone—which can push a neighboring core's heating rate past the danger line so its fan must turn on too! Meanwhile, workload changes (set) sit in an inbox with last-write-wins behavior (only the newest value queued for a core before the next clock pulse matters), and the controller only updates physics and decisions at tick timestamps using event-driven simulation (jumping directly from one tick timestamp to the next in a single formula rather than stepping millisecond by millisecond).

Why do simpler approaches break down? Stepping time forward second by second or millisecond by millisecond is far too slow when timestamps jump by thousands of seconds, and it is unnecessary because loads and active fans stay completely constant between ticks. Applying a set workload immediately—or advancing temperatures with the newly chosen fan set instead of the previous tick's fan set—rewrites history by heating or cooling an interval before that change actually took effect. Finally, checking active cooling in a single pass misses the vibration chain reaction; we need a monotone fixed-point loop (a loop that starts with hot cores above 60.0 C and repeatedly adds any core heating faster than 0.5 C/s until an entire pass adds zero new cores).

Here is the 2-core vibration cascade from Example 2 at t = 1 (passiveCapacity = 40 W, both cores at 20.0 C, pending loads p1 = 55 W, p2 = 41 W, so passive demands are 57 W and 43 W, totaling 100 W):

Round 1 (k = 0 fans on):
  effective capacity = 40.0 W
  share(p1) = 40.0 * 57/100 = 22.80 W -> rate(p1) = 0.02 * (55 - 22.80) = 0.6440 C/s > 0.5 -> ADD 'p1'
  share(p2) = 40.0 * 43/100 = 17.20 W -> rate(p2) = 0.02 * (41 - 17.20) = 0.4760 C/s <= 0.5 (safe for now!)

Round 2 (k = 1 fan on -> 10 / Fib[1] = 10% vibration penalty):
  effective capacity drops to 40.0 * 0.90 = 36.0 W
  share(p2) shrinks to 36.0 * 43/100 = 15.48 W
  rate(p2) rises to 0.02 * (41 - 15.48) = 0.5104 C/s > 0.5 -> ADD 'p2'!

Round 3 (k = 2 fans on): no unselected running cores remain -> stable set {'p1', 'p2'} -> ['p1=cooling', 'p2=cooling']

Complexity

Let n be the number of cores (len(coreIds)), m be the number of operations (len(operations)), and r (1 <= r <= n + 1) be the number of fixed-point rounds needed during choose_active_cooling at a tick.

  • Time: O(n log n + m * n * r), which is O(n log n + m * n^2) in the worst case. Sorting coreIds once at startup takes O(n log n). Each set operation is a single O(1) dictionary write. Each tick performs O(n) work to advance temperatures, check shutdowns, apply pending loads, and diff statuses, plus r selection passes of O(n) each. Because every pass either adds at least one core to selected or terminates, r <= n + 1 (and in practice r is tiny because 10 / Fib[k] shrinks exponentially). Runtime does not depend at all on how large the timestamp gaps are.
  • Space: O(n) auxiliary memory (beyond the output list of tick diffs) to store cores, the precomputed penalties array, the per-core temp, load, and status dictionaries, and the shutdown, active, and pending sets/maps.

Edge cases

  • First tick advances by 0 seconds: last_tick_time starts as None, so the first tick sets the time origin (elapsed = 0.0), leaves every core at 20.0 C, applies any set commands that arrived before that first tick, and chooses initial active cooling.
  • Multiple set commands to the same core before a tick: Overwriting pending[core_id] implements last-write-wins automatically; an earlier set(c1, 100) followed by set(c1, 0) leaves c1 at 0 W.
  • Core shuts down on the same tick it has a pending load: Phase 2 runs before Phase 3 and calls pending.pop(core, None), discarding the ordinary load update so a newly overheated core stays shut down at 0 W.
  • Failed restart request (temp >= 50.0): A set targeting a shut-down core is a one-time restart attempt (like p1 at 86.292 C in Example 2); if temp[core] is 50.0 or higher at the next tick, the request fails and pending = {} forgets it until a brand-new set arrives later.
  • Shutdown cores still consume 2 W of passive demand: Keeping shut-down cores in load with 0.0 W ensures 0.0 + 2.0 = 2.0 W stays in total_demand, which reduces passive shares for running cores when cooling is oversubscribed.
  • Exact boundary ties (50.0, 60.0, 80.0, 0.5, and 20.0 floor): 80.0 C shuts down (>=), whereas 50.0 C does not restart (<), 60.0 C does not force cooling (>), and 0.5 C/s does not force cooling (>). Negative net heat clamps cleanly at 20.0 C via max(20.0, ...).

Common mistakes

  • Applying set loads immediately instead of queueing in pending: Updating load[core] before Phase 1 heats the interval preceding the next tick with a workload that was not active yet.
  • Advancing temperatures using the newly computed active set: Active cooling chosen in Phase 4 takes physical effect during the next interval, not the interval that just ended.
  • Starting Fibonacci at 1, 1, 2, 3 instead of 1, 2, 3, 5: Using [1, 1, 2, ...] makes the two-channel penalty 10/1 + 10/1 = 20% instead of the specified 10/1 + 10/2 = 15%.
  • Running only one pass when selecting active cooling: Without the while True fixed-point loop, secondary cores pushed above 0.5 C/s by the vibration penalty of earlier cores are missed.
  • Excluding shut-down cores from passive_shares: Dropping shut-down cores removes their 2 W base demand and over-allocates passive cooling to running cores.
  • Sorting core IDs numerically instead of lexicographically: Output order is standard string order (sorted(coreIds)), where "c10" precedes "c2".

Alternative approaches

  • Sort unselected running cores by load (O(n log n) per tick instead of O(n * r)): At any fixed active count k, every core receives demand * factor where factor = min(1.0, capacity / total_demand) is identical across all cores. An unselected core's unassisted rate 0.02 * (load * (1 - factor) - 2 * factor) increases monotonically with load. Sorting unselected running cores in descending order of load lets us sweep from highest load downward in one linear pass while incrementing k, turning worst-case O(n^2) selection into O(n log n).

Follow-up questions

  • When hundreds of cores run and each set updates just a handful of workloads, how can you avoid scanning every core repeatedly during cooling selection? Maintain total_demand incrementally in O(1) time per load update (total_demand += new_load - old_load) instead of re-summing all n cores. Because any core's passive share is (load[core] + 2) * min(1.0, capacity / total_demand), you never need to materialize a full shares dictionary—any single core's share is computable in O(1) from total_demand and k. Keeping running cores in a balanced search tree ordered by load (O(log n) updates) lets cooling selection inspect only the highest-load candidates rather than scanning idle cores, while Phase 1 temperature advancement still touches each core once to check 80.0 C and 60.0 C.
  • How would you guarantee identical threshold decisions across C++, Rust, and Python implementations despite floating-point rounding? Every input and physical constant in the model is a rational number (an exact ratio of two integers numerator / denominator): workloads and timestamps have at most three decimal places, 10 / Fib[i] is an integer fraction, and each step uses only addition, subtraction, multiplication, and division. Computing with exact rationals (such as Python's fractions.Fraction or big-integer rational structs) guarantees bit-for-bit identical threshold checks (< 50, > 60, >= 80, > 0.5) across languages, at the cost of growing denominators over long runs. Where fixed word width is needed, fixed-point arithmetic (representing milliwatts and micro-degrees as 64/128-bit integers with explicit division rounding rules) or IEEE-754 float64 with sorted summation order and fused multiply-add disabled keeps results deterministic.
  • How could you add rich thermal telemetry for debugging cascade events without altering the transition-only return contract? Keep simulate_overheat_controller's return signature unchanged and accept an optional telemetry_sink list or structured callback parameter. At each tick, emit a snapshot recording timestamp, elapsed, effective_capacity, total_demand, per-core (start_temp, end_temp, load, passive_share, net_heat), and the exact trigger for every selected fan ("seeded: temp > 60.0" vs. "cascade round j: rate > 0.5"). Decoupling diagnostic snapshots from status diffs preserves full backward compatibility while making multi-round vibration cascades effortless to inspect.

Follow-up questions

Similar questions

More Optiver interview questions

All 76 Optiver questions →