Reconstruct Function Entry/Exit Events from Call Stack Snapshots
Stacks & QueuesAuto-graded · 23 test casesLast updated
Tests ability to compute positional diffs between consecutive call stack snapshots and emit correctly ordered START/END events using a stack-based mental model.
Problem Description
A profiler periodically records the call stack of a running program. Each recording is a list of function names ordered from the outermost caller at index 0 down to the function actively executing at the last index. These recordings are collected at regular intervals and stored in order.
Your job is to reconstruct a minimal sequence of execution events from those recordings. An event is one of:
"START <name>"— the function<name>was called"END <name>"— the function<name>returned
The sequence must be consistent with a real execution: functions open and close in a properly nested order, like balanced parentheses.
Producing the Event Sequence
Process the recordings one transition at a time.
Opening transition (before the first recording): Treat the state before any recording as an empty call stack. Emit a START event for each function in the first recording, going from index 0 to the last index.
Between consecutive recordings A and B: Find the length of their longest common prefix — the largest index k such that A[0..k-1] and B[0..k-1] are identical element by element. Then:
- Emit
ENDevents for every frame inAat indexkand beyond, going from the deepest frame back toward indexk(leaf to root). - Emit
STARTevents for every frame inBat indexkand beyond, going from indexktoward the deepest frame (root to leaf).
Closing transition (after the last recording): Treat the state after the last recording as returning to an empty call stack. Emit an END event for each function still in the last recording, going from the deepest frame back to index 0.
Important Details
- Compare frames by position, not by name. If
A[i] == B[i]at the same depth they are the same activation; ifA[i] != B[i]at depthi, thenA[i]and all deeper frames inAhave exited, andB[i]and all deeper frames inBare new. This correctly handles recursion (repeated function names at different depths). - An empty recording means the program was observed idle at that moment. The entire previous stack closes, and the next non-empty recording opens fresh from the root — even if it happens to contain the same names as before.
- All
ENDevents for the previous recording must appear before anySTARTevents for the next recording.
Constraints
0 <= len(samples) <= 10^50 <= len(samples[i]) <= 100- Each function name is a non-empty string of printable characters with no spaces.
- Empty recordings may appear anywhere in the list, including at the start or end.
Examples
Example 1
Input: generate_trace([['main', 'f1'], ['main', 'f2']])
Output: ['START main', 'START f1', 'END f1', 'START f2', 'END f2', 'END main']
Example 2
Input: generate_trace([['root', 'worker', 'task'], ['root', 'worker', 'task'], ['root', 'worker']])
Output: ['START root', 'START worker', 'START task', 'END task', 'END worker', 'END root']
Example 3
Input: generate_trace([[], ['main', 'f'], [], ['main']])
Output: ['START main', 'START f', 'END f', 'END main', 'START main', 'END main']
Hints
Hint 1
Think of each transition as a diff between two stacks. The longest common prefix tells you the boundary: everything above it stays untouched, everything below it on the left closes, everything below it on the right opens.
Hint 2
You do not need a separate stack data structure. The previous recording already is your 'active stack'. Track only that reference as you iterate.
Hint 3
Handle the first and last recordings as transitions from/to an empty list. This unifies all three cases — start, middle, end — into the same diff logic and eliminates special-case bugs.
Worked solution
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Core Idea
Each snapshot is a complete picture of the call stack at one instant. To build the event log, you only need to describe what changed between consecutive pictures — a diff.
Two call stacks always agree on some prefix from the root outward. Everything inside that shared prefix is still executing, so it produces no events. Frames in the old stack below the shared prefix have returned: emit END for each one, from the deepest back toward the divergence point. Frames in the new stack below the shared prefix have been called: emit START for each one, from the divergence point down to the leaf.
Treat the boundary conditions the same way: the state before the first snapshot is an empty stack, and the state after the last snapshot is also an empty stack. With that framing every situation — opening, middle transitions, closing — uses identical logic.
Why Positional Comparison Is Required
The common prefix is found by comparing previous[i] with current[i] at the same depth, not by matching names anywhere in the list. This matters for recursive calls. If the stack is ["f", "f", "g"] and the next snapshot is ["f", "f"], the LCP has length 2 and only g closes. A name-based lookup would incorrectly match the second f against some f deeper in the other stack.
Why the Output Is Correctly Nested
Call stacks are strictly nested by nature: frame at depth k can only be live if every frame at depths 0 through k-1 is live. This means:
- Once the stacks diverge at position
common, every frame deeper inprevioushas definitely returned. - Every frame deeper in
currentwas definitely entered after that divergence.
Closing leaf-to-root and then opening root-to-leaf mirrors real call/return order and keeps the output well nested: every END closes the most recent unmatched START.
Balance
Each frame is opened exactly once — when it first appears below the divergence point. It is closed exactly once — either when it later falls below a new divergence point, or at the final flush. The number of START and END events is always equal.
Algorithm
- Return
[]immediately ifsamplesis empty. - Set
previous = samples[0]. Emit"START name"for each frame inpreviousfrom index 0 to the end. - For each subsequent snapshot
current:- Walk index
commonforward as long asprevious[common] == current[common], stopping at the shorter length. - Emit
"END name"forprevious[common:]in reverse order. - Emit
"START name"forcurrent[common:]in forward order. - Set
previous = current.
- Walk index
- Emit
"END name"for every frame inpreviousin reverse order (the final flush).
Edge Cases
- Empty input: returns
[]. - All snapshots empty: no events are produced.
- Empty snapshot in the middle: LCP length is 0, so the entire previous stack closes. The next non-empty snapshot reopens from the root, even if the function names are the same — the idle gap makes them distinct activations.
- One stack is a prefix of the other: only ENDs or only STARTs are emitted for that transition.
- Single snapshot: open everything, then immediately close everything.
Complexity
Let N be the number of snapshots and D the maximum stack depth (at most 100 in this problem).
- Time: O(N · D). Each transition scans at most
Dframes for the LCP and emits at most2Devents. Summed over all transitions the total work is proportional to the sum of all snapshot lengths, bounded byN · D. - Space: O(N · D) for the output list, which is unavoidable. Working memory beyond the output is O(1) —
previousis just a reference to an existing list insamples.
Reference Solution
from typing import List
def generate_trace(samples: List[List[str]]) -> List[str]:
events: List[str] = []
if not samples:
return events
# Treat the state before the first snapshot as an empty stack.
# Open every frame in the first snapshot from root to leaf.
previous = samples[0]
events.extend("START " + name for name in previous)
for current in samples[1:]:
# Find the longest common prefix by positional comparison.
common = 0
limit = min(len(previous), len(current))
while common < limit and previous[common] == current[common]:
common += 1
# Close frames that are no longer active, deepest first.
for name in reversed(previous[common:]):
events.append("END " + name)
# Open frames that are newly active, shallowest first.
for name in current[common:]:
events.append("START " + name)
previous = current
# Treat the state after the last snapshot as an empty stack.
# Close every remaining frame from leaf to root.
for name in reversed(previous):
events.append("END " + name)
return events