Infer Execution Events from Call Stack Snapshots
Stacks & QueuesAuto-graded · 22 test casesLast updated
Reconstruct chronological function START and END lifecycle events by evaluating structural differences across consecutive call stack snapshots.
You are building a execution trace reconstructor for a performance profiler. The profiler periodically captures snapshots of the active call stack at specific timestamps.
Given a list of integer timestamps times and a corresponding list of call stack snapshots stacks, infer the sequence of lifecycle events (START and END).
Each element of stacks represents a snapshot ordered from the root caller (outermost frame, index 0) to the active callee (innermost frame, last index).
To derive events between consecutive snapshots:
- Compare the active stack to the preceding stack by finding their longest common prefix. The call stack before the initial snapshot at
times[0]is considered empty ([]). - Any frame in the previous stack located beyond the common prefix length has exited. Emit an
ENDevent for each such frame, starting from the innermost frame and moving outwards to the common prefix boundary. - Any frame in the current stack located beyond the common prefix length is newly invoked. Emit a
STARTevent for each such frame, starting from the prefix boundary and moving innermost (outermost to innermost). - All
ENDevents at timestamp $t$ must precede allSTARTevents at timestamp $t$.
Each event in the returned list must be formatted as a 3-element list of strings: [timestamp_str, event_type, function_name], where timestamp_str is the integer timestamp converted to a decimal string, event_type is either "START" or "END", and function_name is the string identifier of the function frame.
Active frames present in the final snapshot that do not exit remain open; do not synthesize synthetic END events after the last sample timestamp.
Constraints
- $0 \le N \le 10^5$, where $N$ is the length of
timesandstacks. - $\text{len(times)} == \text{len(stacks)}$
- $0 \le \text{times}[i] \le 10^9$, strictly increasing.
- The total number of frame elements across all snapshots does not exceed $10^6$.
- Function identifiers are non-empty ASCII strings.
- Frames with identical names at different stack depths represent separate recursive instances.
Examples
Example 1
Input: infer_stack_events([10, 20, 30], [['main', 'f'], ['main', 'f', 'f'], ['main', 'g']])
Output: [['10', 'START', 'main'], ['10', 'START', 'f'], ['20', 'START', 'f'], ['30', 'END', 'f'], ['30', 'END', 'f'], ['30', 'START', 'g']]
Example 2
Input: infer_stack_events([0], [['main']])
Output: [['0', 'START', 'main']]
Example 3
Input: infer_stack_events([5, 10, 15, 20], [[], ['a', 'b'], ['a'], []])
Output: [['10', 'START', 'a'], ['10', 'START', 'b'], ['15', 'END', 'b'], ['20', 'END', 'a']]
Example 4
Input: infer_stack_events([3, 8], [['a', 'a', 'b'], ['a', 'a', 'b', 'a']])
Output: [['3', 'START', 'a'], ['3', 'START', 'a'], ['3', 'START', 'b'], ['8', 'START', 'a']]
Hints
Hint 1
Frames are identified by their position in the call stack hierarchy (depth + caller chain), not just their function names.
Hint 2
When comparing the current stack to the previous stack, match frames from index 0 upward. The first mismatch marks where frames must be ended and new ones started.
Hint 3
At any given timestamp, end events must process from right-to-left (innermost to outermost) and start events from left-to-right (outermost to innermost) to maintain valid call stack ordering.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The problem requires us to determine lifecycle events (START and END) by tracking changes between consecutive call stack states.
- Stack Hierarchy Matching: A function frame at depth $d$ remains active only if its caller at depth $d-1$ also remains active. Thus, matching frame identity across consecutive snapshots relies strictly on finding the longest common prefix between the prior stack snapshot (
previous_stack) and the current stack snapshot (current_stack). - Ending Vanished Frames: Any frame in
previous_stackat index $i \ge \text{prefix_len}$ has terminated. Because execution stacks unwind from top to bottom (innermost call returns first), we iterate backwards fromlen(previous_stack) - 1down toprefix_lento generateENDevents. - Starting New Frames: Any frame in
current_stackat index $i \ge \text{prefix_len}$ is a newly spawned invocation. Call stacks push frames from bottom to top (caller invokes callee), so we iterate forwards fromprefix_lenup tolen(current_stack) - 1to generateSTARTevents. - State Transition: After processing events for the current timestamp, we update
previous_stack = current_stack.
Complexity Analysis
- Time Complexity: $\mathcal{O}(N + M)$, where $N$ is the number of samples and $M$ is the total number of frame elements across all snapshots. Each frame element is checked during the prefix comparison and results in at most one
STARTand oneENDevent. - Space Complexity: $\mathcal{O}(M)$ to store and return the generated event list.
from typing import List
def infer_stack_events(times: List[int], stacks: List[List[str]]) -> List[List[str]]:
events: List[List[str]] = []
previous_stack: List[str] = []
for time, current_stack in zip(times, stacks):
# Determine the length of the longest matching frame prefix
prefix_len = 0
max_common = min(len(previous_stack), len(current_stack))
while prefix_len < max_common and previous_stack[prefix_len] == current_stack[prefix_len]:
prefix_len += 1
timestamp_str = str(time)
# Innermost to outermost END events for popped frames
for i in range(len(previous_stack) - 1, prefix_len - 1, -1):
events.append([timestamp_str, "END", previous_stack[i]])
# Outermost to innermost START events for pushed frames
for i in range(prefix_len, len(current_stack)):
events.append([timestamp_str, "START", current_stack[i]])
previous_stack = current_stack
return events