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 forcoreId.["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
coreIdsis running at20.0°C with0.0W active workload, no active fan, and status"idle". - A
"set"event performs zero thermal calculation and never splits a time interval; it only recordsloadWattsin a pending map forcoreId. When multiple"set"events target the same core between two ticks, only the latestloadWattsis kept.
Five-Step Execution at Each "tick"
- Advance temperatures over the interval just ending:
- The very first
"tick"sets the time origin (elapsed = 0.0s). Each later"tick"useselapsed = timestamp - previous_tick_timestampseconds, governed throughout by the workloads and active-fan set finalized at the previous tick. - If
kactive fans were enabled during this interval, mechanical vibration reduces the shared passive sink budget to:text effective_passive = passiveCapacity * (1 - penalty(k) / 100)wherepenalty(0) = 0andpenalty(k) = sum(10 / F[i] for i = 1..k)usingF = [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 is0.0W—requestsdemand(c) = load(c) + 2.0W from the passive sink. Lettingtotal_demandbe the sum ofdemand(c)across all cores:- If
total_demand <= effective_passive, every core receivesshare(c) = demand(c). - Otherwise, every core receives
share(c) = effective_passive * demand(c) / total_demand.
- If
- Each core in the previous tick's active-fan set receives an extra
activeCapacityPerCoreW (0.0W otherwise), giving net heating powernet(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 of20.0°C:text temp(c) = max(20.0, temp(c) + 0.02 * net(c) * elapsed)
- The very first
- Enforce thermal shutdowns (
>= 80.0°C):- Any running core with
temp(c) >= 80.0transitions to"shutdown", resetsload(c) = 0.0, and drops any pending"set"request queued forc.
- Any running core with
- Apply remaining pending
"set"requests:- For a running core
c, setload(c)to its queuedloadWatts. - For an already shut-down core
c, treat the queued"set"as a single-shot restart attempt: iftemp(c) < 50.0(strictly below50.0°C),cresumes running withload(c) = loadWatts; otherwise (temp(c) >= 50.0), the attempt fails andcstays shut down at0.0W. - Clear the pending map completely so rejected restart attempts do not carry over.
- For a running core
- Select active fans from scratch for the upcoming interval:
- Shut-down cores are never eligible.
- Seed
selectedwith all running cores satisfyingtemp(c) > 60.0(strictly above60.0°C). - Repeat until a pass adds zero cores:
- Recompute
effective_passivefork = len(selected)andshare(c)using current workloads. - Add every unselected running core whose unassisted heating rate
0.02 * (load(c) - share(c))is strictly above0.5°C/s (> 0.5).
- Recompute
- Record status transitions:
- Compare each core's new status against its status from the previous tick and emit
"<coreId>=<status>"sorted bycoreIdfor changed cores only.
- Compare each core's new status against its status from the previous tick and emit
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) andt = 5(c1 = 18W, total passive demand20 + 2 = 22 <= 50W), passive cooling covers full demand so both cores stay"idle". - At
t = 10, applyingc2 = 78W raises demands to20 + 80 = 100W. Withk = 0,c2gets40W passive cooling and heats at0.02 * (78 - 40) = 0.76 > 0.5°C/s, turning onc2's fan (k = 1,10%vibration penalty ->45W passive, leavingc1at0.18 <= 0.5°C/s). Only"c2"changed status.
- At
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 are57 + 43 = 100W. Atk = 0,p1heats at0.644 > 0.5°C/s whilep2is0.476°C/s; selectingp1(k = 1,10%penalty ->36W passive) pushesp2's unassisted rate to0.5104 > 0.5°C/s, cascadingp2into"cooling"too. - Over
[1, 131](130s withk = 2,15%penalty ->34W passive),p1climbs to86.612 >= 80.0°C and shuts down whilep2reaches62.588°C (> 60.0°C, staying"cooling"). - At
t = 141,p1has cooled only to86.292 >= 50.0°C, so its restart request is discarded and no statuses change.
- At
Constraints
1 <= len(coreIds) < 1024; all core IDs are unique non-empty strings.passiveCapacity > 0andactiveCapacityPerCore > 0.1 < len(operations) < 1024; timestamps are strictly increasing positive floats with up to millisecond precision.0 <= loadWatts <= 32768with at most three decimal places.
Step-by-step walkthrough
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 pertick. Each tick's list is sorted alphabetically bycoreIdand 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
setcommand never touchestemp,load, oractiveright away—it simply writespending[coreId] = loadWatts(so multiplesets before a tick naturally keep only the last value). All thermal physics and status transitions happen attickoperations.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:loadonly updates at ticks,active(and therefore its sizek) only updates at ticks, and no core shuts down mid-interval. Every corectherefore experiences a constant heating or cooling rater_c = 0.02 * net_heat_cacross the entireelapsedwindow: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.0and rises linearly, never touching the20.0floor. - If
net_heat < 0, the core cools linearly; if it reaches20.0mid-interval, its rate is still negative so it stays pinned at20.0for 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)- If
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
tickexecutes 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
pendingbefore Phase 1 would make a newly requested workload heat the past interval before the tick even arrived. - Choosingactivebefore Phase 1 would cool the past interval using fans that were only just turned on now. - Clearingpending = {}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.Compute vibration penalties and proportional passive cooling
Let's write three small helper functions for shared passive cooling:
vibration_penalties(max_k): PrecomputesvibrationPenalty(k)fork = 0 .. len(cores). Pay close attention to the Fibonacci sequence in the statement:Fib = [1, 2, 3, 5, 8, 13, ...]starts with1, 2(not1, 1), sok = 1penalizes10/1 = 10%andk = 2penalizes10/1 + 10/2 = 15%. Even for hugek, the infinite sum of10 / Fib[i]converges below23.6%, so effective passive capacity always stays above76.4%ofpassiveCapacity.effective_capacity(passive_capacity, penalties, active_count): Applies1 - penalties[k] / 100.passive_shares(capacity, load): Every core—including shutdown cores whoseload[core]is0.0—requestsload[core] + 2.0watts of passive cooling. Iftotal_demand <= capacity, every core gets its full demand; otherwise every core receives the same proportional fractioncapacity * 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 sharesFind 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, shrinkseffective_capacity, and lowers (never raises) every core'sshares[core]. Lower passive cooling can only increase each core's unassisted heating rate0.02 * (load[core] - shares[core]). That means no previously selected core ever stops needing cooling, and at mostlen(running) + 1passes can run beforenewly_addedis 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)Process set commands and run the five tick phases
Now we wire up
simulate_overheat_controller. SortingcoreIdsonce at the start means every loop overcoresautomatically produces"core=status"entries in alphabetical order. Double-check the exact comparison operators at every boundary:- Shutdown check:
temp[core] >= 80.0(at least80.0shuts down). - Restart check:
temp[core] < 50.0(strictly below50.0;50.0refuses to restart). - Hot check in
choose_active_cooling:temp[core] > 60.0(strictly above60.0). - Rate check in
choose_active_cooling:unassisted_rate > 0.5(strictly above0.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- Shutdown check:
Trace Example 2 tick by tick
Let's trace
passiveCapacity = 40,activeCapacityPerCore = 10,coreIds = ['p2', 'p1'], andoperations = [['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.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 isO(n log n + m * n^2)in the worst case. SortingcoreIdsonce at startup takesO(n log n). Eachsetoperation is a singleO(1)dictionary write. EachtickperformsO(n)work to advance temperatures, check shutdowns, apply pending loads, and diff statuses, plusrselection passes ofO(n)each. Because every pass either adds at least one core toselectedor terminates,r <= n + 1(and in practiceris tiny because10 / 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 storecores, the precomputedpenaltiesarray, the per-coretemp,load, andstatusdictionaries, and theshutdown,active, andpendingsets/maps.
Edge cases
- First tick advances by
0seconds:last_tick_timestarts asNone, so the firstticksets the time origin (elapsed = 0.0), leaves every core at20.0 C, applies anysetcommands that arrived before that first tick, and chooses initial active cooling. - Multiple
setcommands to the same core before a tick: Overwritingpending[core_id]implements last-write-wins automatically; an earlierset(c1, 100)followed byset(c1, 0)leavesc1at0 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 at0 W. - Failed restart request (
temp >= 50.0): Asettargeting a shut-down core is a one-time restart attempt (likep1at86.292 Cin Example 2); iftemp[core]is50.0or higher at the next tick, the request fails andpending = {}forgets it until a brand-newsetarrives later. - Shutdown cores still consume
2 Wof passive demand: Keeping shut-down cores inloadwith0.0 Wensures0.0 + 2.0 = 2.0 Wstays intotal_demand, which reduces passive shares for running cores when cooling is oversubscribed. - Exact boundary ties (
50.0,60.0,80.0,0.5, and20.0floor):80.0 Cshuts down (>=), whereas50.0 Cdoes not restart (<),60.0 Cdoes not force cooling (>), and0.5 C/sdoes not force cooling (>). Negative net heat clamps cleanly at20.0 Cviamax(20.0, ...).
Common mistakes
- Applying
setloads immediately instead of queueing inpending: Updatingload[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
activeset: 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, 3instead of1, 2, 3, 5: Using[1, 1, 2, ...]makes the two-channel penalty10/1 + 10/1 = 20%instead of the specified10/1 + 10/2 = 15%. - Running only one pass when selecting active cooling: Without the
while Truefixed-point loop, secondary cores pushed above0.5 C/sby the vibration penalty of earlier cores are missed. - Excluding shut-down cores from
passive_shares: Dropping shut-down cores removes their2 Wbase 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 ofO(n * r)): At any fixed active countk, every core receivesdemand * factorwherefactor = min(1.0, capacity / total_demand)is identical across all cores. An unselected core's unassisted rate0.02 * (load * (1 - factor) - 2 * factor)increases monotonically withload. Sorting unselected running cores in descending order ofloadlets us sweep from highest load downward in one linear pass while incrementingk, turning worst-caseO(n^2)selection intoO(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_demandincrementally inO(1)time per load update (total_demand += new_load - old_load) instead of re-summing allncores. Because any core's passive share is(load[core] + 2) * min(1.0, capacity / total_demand), you never need to materialize a fullsharesdictionary—any single core's share is computable inO(1)fromtotal_demandandk. Keeping running cores in a balanced search tree ordered byload(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 check80.0 Cand60.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'sfractions.Fractionor 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-754float64with 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 optionaltelemetry_sinklist or structured callback parameter. At each tick, emit a snapshot recordingtimestamp,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
- 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?
- How would you guarantee identical threshold decisions across C++, Rust, and Python implementations despite floating-point rounding?
- How could you add rich thermal telemetry for debugging cascade events without altering the transition-only return contract?
Similar questions
- Validate Edge Pairs and Serialize Binary Tree
- Elapsed Days Across Extended Gregorian Dates
- Sequential Freight Dispatch Across Scheduled Aircraft
- Core Data Structure Trade-Offs, Invariants, and Workload Selection
- Verifying Functional Equivalence Between Integer Array Routines
- Counting Valid Buy-and-Sell Trade Sequences
More Optiver interview questions
- Peak Rolling Kilometer Speed Across Five-Second Splits Medium
- Probability, Betting Edge, and Arrival Metrics Medium
- Negative Final Price Probability Medium Pro
- Counting Distinct Strings with Duplicate Characters Easy Pro
- Stochastic Process Expectations and Ruin Easy Pro
- Subsequence Sum DP, Indexed Heap Scheduler, and Heuristic k-Selection Medium Pro
- Cognitive Task-Switching Tactics and Two-Week Training Regimen Medium Pro
- Orbital Relay Broadcast and Callback Simulator Medium Pro
- Topic-Filtered News Subscription Engine Hard Pro
- Intraday Mean-Reversion Strategy Backtest Hard Pro