Single-Threaded CPU: Exclusive Runtimes and Stack Snapshot
Stacks & QueuesAuto-graded · 23 test casesLast updated
Tests stack simulation and interval reasoning by computing per-function exclusive execution time and reconstructing the active call stack at a query timestamp from a sorted event log.
Single-Threaded CPU: Exclusive Runtimes and Stack Snapshot
A single-threaded program runs one function at a time. When a function calls another, the caller pauses and resumes only after the callee returns. You are given a structured execution log for such a program and must answer two questions:
- How much time did each function spend actually running (not waiting for children to return)?
- Which functions were on the call stack at a specific moment?
Input
| Parameter | Type | Description |
|---|---|---|
num_funcs | int | Number of distinct function IDs in the program. IDs are 0 through num_funcs - 1. |
events | List[str] | Execution log. Each entry has the form "t,TYPE,id" where t is a non-negative integer timestamp (milliseconds), TYPE is either BEGIN or END, and id is a valid function ID. The list is sorted by t. When two entries share the same timestamp, any END entry appears before any BEGIN entry. Every BEGIN has exactly one matching END; calls may nest arbitrarily but never overlap (single-threaded). |
query_time | int | The timestamp to inspect. |
Output
Return a dictionary with exactly these two keys:
"durations"— a list of lengthnum_funcswheredurations[i]is the total exclusive time (in milliseconds) spent executing functioni. Exclusive time counts only the intervals when functioniwas directly on top of the stack, not the time spent inside functions it called."stack_q"— a list of function IDs representing the call stack atquery_time, ordered from the bottom of the stack to the top. If no function is active atquery_time, return an empty list.
Interval Convention
Treat every function call as a half-open interval [begin_time, end_time):
- A
BEGINevent at timetmeans the function starts executing att(inclusive). - An
ENDevent at timetmeans the function stopped executing beforet(exclusive). The duration of that call isend_time - begin_time.
Applying this to stack_q: a function is considered active at query_time if and only if its BEGIN has occurred at or before query_time and its END has not yet occurred at query_time. Concretely:
- A
BEGINatquery_time→ that function is instack_q. - An
ENDatquery_time→ that function is not instack_q. - When both share the same timestamp, the
ENDis processed first (per the log ordering guarantee), so the ending function is absent while any new caller starting at that same timestamp is present.
Constraints
1 <= num_funcs <= 1000 <= len(events) <= 500- Every
BEGINhas a matchingEND; nesting is valid (no interleaving across different call branches). - Timestamps are non-negative integers.
-10^6 <= query_time <= 10^9- The log may be empty; in that case return all-zero durations and an empty
stack_q. - Your solution must run in O(n) time where n =
len(events), using O(num_funcs + call_depth) space.
Examples
Example 1
Input: function_runtimes_and_snapshot(3, ['0,BEGIN,0', '2,BEGIN,1', '5,END,1', '7,END,0'], 3)
Output: {'durations': [4, 3, 0], 'stack_q': [0, 1]}
Example 2
Input: function_runtimes_and_snapshot(2, ['1,BEGIN,0', '3,END,0', '3,BEGIN,1', '6,END,1'], 3)
Output: {'durations': [2, 3], 'stack_q': [1]}
Example 3
Input: function_runtimes_and_snapshot(1, ['2,BEGIN,0', '5,END,0'], 0)
Output: {'durations': [3], 'stack_q': []}
Hints
Hint 1
Think of execution as a sequence of gaps between consecutive events. During each gap the stack doesn't change, so the entire gap belongs to whichever function is on top — charge it there. You never need to store a per-call start time.
Hint 2
For durations, two event types need slightly different treatment: a BEGIN charges the current top for the gap that just closed, then pushes the new function; an END charges the current top for the gap that just closed, then pops it. In both cases, advance your 'last seen timestamp' to the current event's time.
Hint 3
For stack_q, replay the log a second time applying only events with timestamp ≤ query_time, then stop. Because END precedes BEGIN at equal timestamps, the half-open rule falls out naturally from the log's own ordering — no extra tie-breaking code is needed.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Core insight: gap-based accounting
The log is a sequence of timestamped events. Between any two consecutive events the call stack is completely static — only one function is running, whichever is on top. That means the entire time gap [prev_time, current_time) belongs exclusively to that function. There is no need to record a start time for each call or subtract child durations after the fact.
Process events in order while tracking prev_time (the timestamp of the most recently handled event) and a call stack:
- BEGIN at time
t: if the stack is non-empty, the function currently on top was running fromprev_timeup to (not including)t, so addt - prev_timeto its duration. Then push the new function and setprev_time = t. - END at time
t: the function on top was running fromprev_timetot, so addt - prev_timeto its duration. Then pop it and setprev_time = t. - Empty stack at a BEGIN: the gap is idle time; nobody is charged.
Recursion is handled automatically — each frame shares one durations[id] slot, and whichever frame is on top at any moment receives the gap.
Interval convention
Every call occupies a half-open interval [begin_time, end_time). A BEGIN at t means the function is executing at t; an END at t means it stopped before t. Duration is therefore end_time - begin_time with no +1 adjustment.
Building stack_q
In a second linear pass, replay every event whose timestamp is ≤ query_time and stop. The log's built-in tie-break rule (END precedes BEGIN at equal timestamps) already enforces the half-open semantics:
- An
ENDat exactlyquery_timefires before anyBEGINat the same timestamp, so that function is popped and absent fromstack_q. - A
BEGINatquery_timeis applied, so that function is present.
No additional tie-break code is needed.
Why it is correct
- Every millisecond between the first and last event falls in exactly one inter-event gap.
- During that gap the stack is fixed, so the top function is the unique running function.
- Parents are charged only for gaps where they sit on top; child calls block the parent from being on top during that time, so child time is never double-counted.
- The snapshot pass applies exactly the events visible at
query_timeunder half-open semantics.
Edge cases
- Back-to-back events at the same timestamp: gap length is zero, so
0is added to durations. Correct. query_timebefore the first event: no events satisfyt ≤ query_time, sostack_q = [].query_timeat or after the last event: all BEGINs have matching ENDs already applied, sostack_q = [].- Empty log:
durations = [0] * num_funcs,stack_q = []. - Malformed nesting: raises
ValueErrorrather than silently returning wrong totals.
Complexity
- Time: O(n) — two linear passes over the log; each event is parsed and processed in O(1).
- Space: O(num_funcs + call_depth) — the
durationsarray plus the call stack, which is bounded by the maximum nesting depth. No per-call records are stored.
Reference solution
from typing import List, Dict
def function_runtimes_and_snapshot(
num_funcs: int, events: List[str], query_time: int
) -> Dict[str, List[int]]:
durations: List[int] = [0] * num_funcs
stack: List[int] = []
prev_time: int | None = None
# Pass 1 — exclusive durations via gap-based accounting.
#
# Between any two consecutive events the stack is constant, so the entire
# gap [prev_time, t) belongs exclusively to whoever is on top.
#
# BEGIN at t: charge the gap to the current top (the about-to-be parent),
# then push the new function.
# END at t: charge the gap to the current top (the returning function),
# then pop it.
for entry in events:
t_str, kind, id_str = entry.split(",")
t = int(t_str)
fid = int(id_str)
if kind == "BEGIN":
if stack and prev_time is not None:
durations[stack[-1]] += t - prev_time
stack.append(fid)
prev_time = t
elif kind == "END":
if not stack or stack[-1] != fid:
raise ValueError("Invalid call nesting")
if prev_time is not None:
durations[fid] += t - prev_time
stack.pop()
prev_time = t
else:
raise ValueError(f"Unknown event type: {kind!r}")
# Pass 2 — stack_q at query_time.
#
# Replay the log applying every event with t <= query_time, then stop.
# The log's built-in tie-break rule (END before BEGIN at equal timestamps)
# already enforces half-open semantics:
# END at query_time -> popped before we finish -> absent from stack_q
# BEGIN at query_time -> pushed -> present in stack_q
stack_q: List[int] = []
for entry in events:
t_str, kind, id_str = entry.split(",")
t = int(t_str)
fid = int(id_str)
if t > query_time:
break
if kind == "BEGIN":
stack_q.append(fid)
else:
if stack_q and stack_q[-1] == fid:
stack_q.pop()
return {"durations": durations, "stack_q": stack_q}