Reconstruct Call Events from Profiler Snapshots
Stacks & QueuesAuto-graded · 20 test casesLast updated
Tests stack trace interpretation, event inference from sparse data, and algorithmic reasoning about nesting and correctness.
You are working with output from a sampling profiler that periodically captures the call stack. Each snapshot records a timestamp and the active call stack at that moment, represented as a list where the first element is the outermost (root) function and the last element is the innermost (currently executing) function.
Your task is to reconstruct a sequence of function entry and exit events from these snapshots. Between any two consecutive snapshots, an unknown number of calls and returns may have occurred, but you can infer a plausible sequence by comparing the stacks.
Reconstruction Rules:
-
For the first snapshot, emit a start event for each function in its stack, from outermost to innermost, all at that snapshot's timestamp.
-
For each subsequent snapshot, compare its stack with the previous snapshot's stack:
- Find the longest prefix of positions where both stacks have the same function name (positional matching from index 0).
- Functions in the previous stack beyond this common prefix have exited: emit end events for them in reverse order (innermost to outermost), all at the current snapshot's timestamp.
- Functions in the current stack beyond this common prefix have been entered: emit start events for them in forward order (outermost to innermost), all at the current snapshot's timestamp.
-
After processing all snapshots, leave the final stack's functions open (do not emit end events for them).
Implement a function that takes a list of snapshots and returns a list of events. Each snapshot is a tuple (timestamp, stack) where timestamp is a float and stack is a list of function name strings. Each event is a tuple (timestamp, event_type, function_name) where event_type is 's' for start or 'e' for end.
Important: Function names are compared positionally. If the same function name appears at different depths in the two stacks, they are treated as distinct call frames. For example, recursive calls like ['f', 'f', 'f'] → ['f', 'f'] should correctly end only the deepest 'f'.
Constraints:
0 ≤ len(snapshots) ≤ 10^4- Snapshots are ordered by timestamp in non-decreasing order
0 ≤ len(stack) ≤ 100for each snapshot- Function names are non-empty strings
- All timestamps are non-negative floats
Examples
Example 1
Input: reconstruct_trace([[0, ['a', 'b', 'a', 'c']], [1, ['a', 'a', 'b', 'c']]])
Output: [[0, 's', 'a'], [0, 's', 'b'], [0, 's', 'a'], [0, 's', 'c'], [1, 'e', 'c'], [1, 'e', 'a'], [1, 'e', 'b'], [1, 's', 'a'], [1, 's', 'b'], [1, 's', 'c']]
Example 2
Input: reconstruct_trace([[2.5, ['main', 'work']], [3, ['main', 'work', 'leaf']], [4, ['main']]])
Output: [[2.5, 's', 'main'], [2.5, 's', 'work'], [3, 's', 'leaf'], [4, 'e', 'leaf'], [4, 'e', 'work']]
Hints
Hint 1
Compare stacks position by position from the outermost frame to find where they first differ
Hint 2
Frames that existed in the previous stack but not in the current one (beyond the common prefix) must have exited
Hint 3
The order of events at the same timestamp matters for correct nesting: emit all exits before all entries
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The core insight is that sampling profilers only give us periodic snapshots, not the actual sequence of calls and returns. We must infer the most likely events between snapshots by finding what changed.
The key technique is to compute the longest common prefix (LCP) between consecutive stacks, comparing function names position by position from the root. Positions within the common prefix represent functions that remained active across both snapshots. Positions beyond the divergence point represent changes:
-
Handle the first snapshot: Since there's no previous state, every function in the first stack must have just started. Emit start events for all functions from outermost to innermost.
-
Process each subsequent snapshot:
- Compare with the previous stack position by position to find the LCP length
- Functions in the previous stack beyond the common prefix have exited: emit end events in reverse order (innermost first, to maintain proper nesting)
- Functions in the current stack beyond the common prefix have been entered: emit start events in forward order (outermost first)
- All these events share the current snapshot's timestamp
-
After the last snapshot: The profiler only tells us these functions were active at that time, not when they ended, so we leave them open.
Why positional comparison is crucial: Consider ['a', 'b', 'a'] → ['a', 'a', 'b']. The first 'a' at position 0 matches in both, but position 1 differs ('b' vs 'a'). This means everything from position 1 onward changed. A naive approach that only checks "is this name still somewhere in the stack?" would produce incorrect nesting.
Correctness: After processing each snapshot, the sequence of opens minus closes leaves exactly that snapshot's stack open, in order. This invariant holds because:
- Initially, opening all functions in snapshot 0 leaves exactly snapshot 0's stack open
- At each step, closing from innermost to the divergence point in LIFO order is valid nesting, leaving the common prefix open
- Then opening the new suffix extends it to exactly the current snapshot's stack
Time Complexity: O(S) where S is the total number of frames across all snapshots. Each frame is visited a constant number of times: once during LCP comparison and once when emitted as an event.
Space Complexity: O(S) for the output list. We only maintain a reference to the previous stack, which is O(1) auxiliary space.
Implementation
from typing import List, Tuple
def reconstruct_trace(snapshots: List[Tuple[float, List[str]]]) -> List[Tuple[float, str, str]]:
events = []
if not snapshots:
return events
timestamp, previous = snapshots[0]
for name in previous:
events.append((timestamp, "s", name))
for timestamp, current in snapshots[1:]:
common = 0
limit = min(len(previous), len(current))
while common < limit and previous[common] == current[common]:
common += 1
for i in range(len(previous) - 1, common - 1, -1):
events.append((timestamp, "e", previous[i]))
for i in range(common, len(current)):
events.append((timestamp, "s", current[i]))
previous = current
return events