Rebuild Call Start/Stop Events from Stack Snapshots
Stacks & QueuesAuto-graded · 19 test casesLast updated
Diff consecutive call-stack snapshots by longest common prefix to produce correctly ordered start and end events, including recursion, empty stacks and final closing.
Rebuild Call Start/Stop Events from Stack Snapshots
A sampling profiler periodically captures the call stack of a running program. Each snapshot is a pair (timestamp, stack). The stack is a list of function names ordered from the outermost caller (index 0) to the innermost function currently running (last index). Snapshots are given in strictly increasing timestamp order.
A visualization tool needs events rather than snapshots. Write a function that turns the snapshots into a flat list of start and end events.
Rules
- A call starts at the timestamp of the first snapshot in which it appears.
- A call ends at the timestamp of the first later snapshot in which it is no longer present.
- A frame in one snapshot is the same call as a frame in the previous snapshot only if it sits at the same depth and all frames below it (its callers) are also the same calls. Equivalently, compare the two stacks position by position from index 0 and find the length of their longest common prefix. Frames inside the common prefix continue. All other frames of the previous stack end, and all other frames of the new stack start. Matching is by position, not by name, so repeated names (recursion) are handled naturally.
- The first snapshot has no predecessor: every frame in it starts at its timestamp.
- Calls still on the stack in the last snapshot are closed at the last snapshot's timestamp.
Event order
For each snapshot transition, emit events at that timestamp in this order:
- All
endevents first, from the innermost ending frame to the outermost ending frame. - Then all
startevents, from the outermost starting frame to the innermost.
When closing the last snapshot's remaining calls, emit their end events innermost first. Events from earlier snapshots always come before events from later ones.
Event format
Each event is a dictionary with exactly these keys:
"timestamp": the integer timestamp"type": either"start"or"end""function": the function name
Input and output
samples: a list of(timestamp, stack)pairs as described above (each pair may be a two-element list).- Return the list of event dictionaries in the required order.
- If
samplesis empty, return an empty list. - A snapshot with an empty stack is valid. It produces no start events itself, but it ends everything that was running in the previous snapshot. If the final snapshot has an empty stack, nothing is closed at the end.
Constraints
0 <= len(samples) <= 10^4- Timestamps are integers and strictly increasing.
0 <= len(stack) <= 100for every snapshot.- Function names are non-empty strings; the same name may appear several times in one stack.
- Total number of frames across all snapshots is at most
10^5.
Examples
Example 1
Input: stack_samples_to_trace_events([[0, ['main']], [1, ['main', 'foo']], [2, ['main', 'foo', 'bar']], [3, ['main', 'baz']], [4, ['main']]])
Output: [{'timestamp': 0, 'type': 'start', 'function': 'main'}, {'timestamp': 1, 'type': 'start', 'function': 'foo'}, {'timestamp': 2, 'type': 'start', 'function': 'bar'}, {'timestamp': 3, 'type': 'end', 'function': 'bar'}, {'timestamp': 3, 'type': 'end', 'function': 'foo'}, {'timestamp': 3, 'type': 'start', 'function': 'baz'}, {'timestamp': 4, 'type': 'end', 'function': 'baz'}, {'timestamp': 4, 'type': 'end', 'function': 'main'}]
Example 2
Input: stack_samples_to_trace_events([[10, []], [11, ['main', 'f']], [12, []]])
Output: [{'timestamp': 11, 'type': 'start', 'function': 'main'}, {'timestamp': 11, 'type': 'start', 'function': 'f'}, {'timestamp': 12, 'type': 'end', 'function': 'f'}, {'timestamp': 12, 'type': 'end', 'function': 'main'}]
Example 3
Input: stack_samples_to_trace_events([[0, ['main', 'recurse', 'recurse']], [1, ['main', 'recurse']], [2, ['main', 'recurse', 'recurse', 'leaf']]])
Output: [{'timestamp': 0, 'type': 'start', 'function': 'main'}, {'timestamp': 0, 'type': 'start', 'function': 'recurse'}, {'timestamp': 0, 'type': 'start', 'function': 'recurse'}, {'timestamp': 1, 'type': 'end', 'function': 'recurse'}, {'timestamp': 2, 'type': 'start', 'function': 'recurse'}, {'timestamp': 2, 'type': 'start', 'function': 'leaf'}, {'timestamp': 2, 'type': 'end', 'function': 'leaf'}, {'timestamp': 2, 'type': 'end', 'function': 'recurse'}, {'timestamp': 2, 'type': 'end', 'function': 'recurse'}, {'timestamp': 2, 'type': 'end', 'function': 'main'}]
Hints
Hint 1
Keep the previous snapshot's stack. For each new snapshot, count how many leading entries are identical in both stacks.
Hint 2
Everything in the previous stack beyond the common prefix ends, and everything in the new stack beyond the common prefix starts. Think carefully about which direction to walk each part to respect nesting.
Hint 3
Do not forget the two boundary cases: the very first snapshot (nothing to compare with, so all frames start) and the final snapshot (all remaining frames must be closed, innermost first).
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Walk through the snapshots while remembering only the previous stack.
- For the first snapshot, every frame is new, so emit
startevents from the outermost frame to the innermost. - For each later snapshot, compute the length
cof the longest common prefix between the previous stack and the new stack.- Frames at indices
< care the same calls and produce no events. - Frames of the previous stack at indices
>= chave ended. Emit theirendevents from the last index down toc(innermost first). - Frames of the new stack at indices
>= chave started. Emit theirstartevents fromcupward (outermost first).
- Frames at indices
- After the last snapshot, close the remaining frames at the last timestamp, innermost first.
- An empty input returns an empty list. Empty stacks need no special handling: the prefix length is 0, so nothing is compared and the loops simply do nothing or process the other stack in full.
Why it is correct
A call's identity is its position plus all of its callers, so the frames that continue between two snapshots are exactly the common prefix. Once two stacks differ at index c, everything above that index in either stack cannot be the same call, even if the names match. This is why recursion works: ["main","recurse","recurse"] followed by ["main","recurse"] ends only the deepest recurse, and it is also why later re-entering the same depth produces a fresh start.
The event order preserves the nesting invariant. A caller must be open for as long as its callee is, so inner calls must end before outer calls (innermost first), and outer calls must start before inner ones (outermost first). Emitting all ends before all starts at a timestamp also guarantees that the stack depth never exceeds what the new snapshot requires.
Complexity
Let N be the number of snapshots and D the maximum stack depth. Each transition costs O(D) for the prefix comparison and event emission, so the total time is O(N * D), bounded by the total number of frames. Output size is also O(N * D) in the worst case. Beyond the output, extra memory is O(1) (only a reference to the previous stack).
Reference solution
from typing import List, Tuple, Dict
def stack_samples_to_trace_events(samples: List[Tuple[int, List[str]]]) -> List[Dict[str, object]]:
if not samples:
return []
events: List[Dict[str, object]] = []
prev_time, prev_stack = samples[0]
for name in prev_stack:
events.append({"timestamp": prev_time, "type": "start", "function": name})
for time, stack in samples[1:]:
common = 0
limit = min(len(prev_stack), len(stack))
while common < limit and prev_stack[common] == stack[common]:
common += 1
# Ends: innermost first.
for i in range(len(prev_stack) - 1, common - 1, -1):
events.append({"timestamp": time, "type": "end", "function": prev_stack[i]})
# Starts: outermost first.
for i in range(common, len(stack)):
events.append({"timestamp": time, "type": "start", "function": stack[i]})
prev_time, prev_stack = time, stack
# Close whatever is still open at the last timestamp.
for i in range(len(prev_stack) - 1, -1, -1):
events.append({"timestamp": prev_time, "type": "end", "function": prev_stack[i]})
return events