KatInterview

Single-Threaded CPU: Exclusive Runtimes and Stack Snapshot

Stacks & QueuesAuto-graded · 23 test cases
MediumAuto-gradedStacks & Queuesstacksimulationinterval-reasoning

Last 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:

  1. How much time did each function spend actually running (not waiting for children to return)?
  2. Which functions were on the call stack at a specific moment?

Input

ParameterTypeDescription
num_funcsintNumber of distinct function IDs in the program. IDs are 0 through num_funcs - 1.
eventsList[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_timeintThe timestamp to inspect.

Output

Return a dictionary with exactly these two keys:

  • "durations" — a list of length num_funcs where durations[i] is the total exclusive time (in milliseconds) spent executing function i. Exclusive time counts only the intervals when function i was 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 at query_time, ordered from the bottom of the stack to the top. If no function is active at query_time, return an empty list.

Interval Convention

Treat every function call as a half-open interval [begin_time, end_time):

  • A BEGIN event at time t means the function starts executing at t (inclusive).
  • An END event at time t means the function stopped executing before t (exclusive). The duration of that call is end_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 BEGIN at query_time → that function is in stack_q.
  • An END at query_time → that function is not in stack_q.
  • When both share the same timestamp, the END is 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 <= 100
  • 0 <= len(events) <= 500
  • Every BEGIN has a matching END; 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.