Reconstruct Function Lifetimes from Periodic Stack Snapshots
Stacks & QueuesAuto-graded · 17 test casesLast updated
Tests ability to diff consecutive call-stack snapshots using longest-common-prefix analysis and stack unwinding to produce ordered START/END lifecycle events.
Problem Description
A runtime tracer periodically records the active call stack of a running program. You receive these recordings as a sequence of (timestamp, stack) pairs, where each stack is a list of function names ordered from the outermost caller at index 0 to the deepest active frame at the last index. You also receive a shutdown_time marking when the program terminates.
Your task is to turn these periodic snapshots into a complete, ordered sequence of function lifecycle events — one "START" event when a function frame is entered and one "END" event when it returns.
Reconstruction Rules
- Before the first snapshot, treat the active stack as empty.
- At each snapshot's timestamp, compare the stack recorded there against the stack from the previous snapshot (the previous stack). Find the longest common prefix (LCP): the deepest index
ksuch that every position from0throughk-1holds the same function name in both stacks. The comparison is strictly positional — two frames match only when they share both the same name and the same depth index. - Every frame in the previous stack at depth
kor deeper has exited. Emit"END"events for those frames in inside-out order (deepest frame first, working toward depthk), all at the current timestamp. - Every frame in the current stack at depth
kor deeper is a fresh entry. Emit"START"events for those frames in outside-in order (from depthktoward the deepest new frame), all at the current timestamp. - When
shutdown_timeis reached, close every frame still on the stack by emitting"END"events in inside-out order.
Each event is a tuple with four fields: (timestamp, event_type, function_name, depth), where depth is the 0-based index of that frame in the stack.
At any single timestamp, all "END" events come before all "START" events.
Constraints
0 <= len(samples) <= 10^4- Timestamps in
samplesare strictly increasing integers. shutdown_time > samples[-1][0]whensamplesis non-empty.- Each stack is a list of zero or more non-empty alphanumeric strings.
- The same function name may appear at multiple depths in the same stack (recursive calls).
- Stack depth does not exceed
300.
Examples
Example 1
Input: reconstruct_call_events([[10, ['main', 'foo']], [20, ['main', 'bar']]], 30)
Output: [[10, 'START', 'main', 0], [10, 'START', 'foo', 1], [20, 'END', 'foo', 1], [20, 'START', 'bar', 1], [30, 'END', 'bar', 1], [30, 'END', 'main', 0]]
Example 2
Input: reconstruct_call_events([[100, ['eval', 'eval', 'eval']], [150, ['eval']]], 200)
Output: [[100, 'START', 'eval', 0], [100, 'START', 'eval', 1], [100, 'START', 'eval', 2], [150, 'END', 'eval', 2], [150, 'END', 'eval', 1], [200, 'END', 'eval', 0]]
Hints
Hint 1
Start by asking: between two consecutive snapshots, which frames are shared and which have changed? The longest common prefix tells you exactly where the two stacks diverge — everything at or above that boundary is affected, everything below it is not.
Hint 2
When frames need to close (END events), think about which frame must exit first. A child frame always exits before its caller, so work from the deepest frame back toward the divergence point. When new frames open (START events), callers must start before their callees, so go from the divergence point down to the deepest new frame.
Hint 3
Treat shutdown_time as a final snapshot with an empty stack. That single observation handles all still-open frames at program exit without any special-case code. Also consider what happens with recursive calls — why does positional comparison handle them correctly where a name-only comparison would not?
Worked solution
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Core insight: every transition is a stack diff
Two consecutive snapshots share some bottom portion — the longest common prefix (LCP). Frames inside that prefix were active before and are still active, so they generate no events. Everything above the LCP boundary changes:
- Frames above the LCP in the previous snapshot have returned. They emit
ENDevents from the deepest frame upward (inside-out), because a child must exit before its caller can. - Frames above the LCP in the current snapshot are new invocations. They emit
STARTevents from the shallowest new frame downward (outside-in), because a caller must start before any of its callees.
This is the complete algorithm. Apply it to every consecutive pair of snapshots, then apply it one final time using shutdown_time as the timestamp and an empty list as the "next" stack. That final step closes all frames still open at program exit — no special-case code needed.
Why positional comparison is required
The LCP is computed by matching both name and depth index simultaneously. Consider ["a", "b", "c"] transitioning to ["a", "x", "c"]. The names agree again at depth 2, but the c at depth 2 in the second snapshot is a fresh invocation under x, not the same frame from before. The LCP is 1 (only a matches), so c@2 and b@1 correctly receive END events, and x@1 and c@2 correctly receive START events.
This also handles recursion naturally. ["eval", "eval", "eval"] followed by ["eval"] has an LCP of 1, so only the two deeper recursive frames exit — the outermost eval at depth 0 keeps running undisturbed.
Edge cases
- Empty
samples:previousstays[]; the shutdown loop iterates zero times and returns[]. - Identical consecutive snapshots: the LCP equals the full length; no events are emitted for that transition.
- A snapshot with an empty stack: all currently open frames close at that timestamp; subsequent snapshots start fresh.
- First snapshot:
previousis[], so the LCP is 0 and every frame in the first snapshot gets aSTART. - Divergence at depth 0 (e.g.,
["main"]→["init"]): the entire old stack ends and the entire new stack starts.
Complexity
- Time: O(Σ len(stackᵢ)) — the LCP scan and emission loops together touch each frame a constant number of times across all transitions.
- Space: O(max depth) of working state, plus O(total events) for the returned list. The total number of events is at most 2 × Σ len(stackᵢ).
Reference solution
from typing import List, Tuple
def reconstruct_call_events(
samples: List[Tuple[int, List[str]]],
shutdown_time: int,
) -> List[Tuple[int, str, str, int]]:
events: List[Tuple[int, str, str, int]] = []
previous: List[str] = []
for timestamp, stack in samples:
# Find the longest common prefix by positional name match.
common = 0
limit = min(len(previous), len(stack))
while common < limit and previous[common] == stack[common]:
common += 1
# Frames that exited: innermost first (inside-out).
for depth in range(len(previous) - 1, common - 1, -1):
events.append((timestamp, "END", previous[depth], depth))
# Frames that started: outermost new frame first (outside-in).
for depth in range(common, len(stack)):
events.append((timestamp, "START", stack[depth], depth))
previous = stack
# shutdown_time closes everything still open, as if transitioning to [].
for depth in range(len(previous) - 1, -1, -1):
events.append((shutdown_time, "END", previous[depth], depth))
return events