Stack Trace Event Stream from Periodic Samples
Stacks & QueuesModel answerLast updated
Convert a sequence of call stack snapshots into function entry and exit events with configurable debouncing to filter transient frames.
You're building a profiler that periodically captures snapshots of an application's call stack. Your task is to reconstruct the timeline of function entries and exits from these snapshots.
You receive a sequence of samples in chronological order. Each sample is a pair (timestamp, stack) where the stack is an ordered list of function names from the outermost caller to the innermost currently-executing function.
Write a function profiling_events(samples, n) that returns a list of events (timestamp, type, function) where type is either "START" or "END".
Behavior
When n = 1, compare consecutive stacks directly: emit END events for functions removed from the tail (innermost first), then START events for functions added to the tail (outermost first). Functions in the common prefix remain and produce no events.
When n > 1, apply per-frame debouncing. Each frame is identified by its depth and function name within a valid stack prefix. A frame becomes confirmed after appearing at the same depth with the same ancestor chain for n consecutive samples; emit its START at the timestamp of the first sample in that sequence. Similarly, a confirmed frame ends after being absent or replaced for n consecutive samples; emit its END at the timestamp when the absence began (innermost first). Shorter appearances or absences are transient noise and produce no events.
When multiple frames in a stable prefix all reach the confirmation threshold simultaneously, they all start at the same timestamp. When a parent frame ends, all its descendants must also end. At the end of input, close all remaining confirmed frames at the last timestamp seen.
Constraints
1 ≤ n ≤ len(samples) ≤ 100,000- Timestamps are strictly increasing integers
- Each stack contains unique, non-empty function names
- Stack depth ≤ 1,000
- The initial state is an empty stack
Example 1: n = 1
Samples: (10, ["A", "B"]), (20, ["A", "C"]), (30, [])
Events:
(10, START, A)
(10, START, B)
(20, END, B)
(20, START, C)
(30, END, C)
(30, END, A)
Example 2: n = 2
Samples:
(10, ["A", "B"])
(20, ["A", "C"])
(30, ["A", "C"])
(40, [])
(50, [])
Events:
(10, START, A) — A appears for 2+ samples starting at 10
(20, START, C) — C appears for 2 samples starting at 20
(40, END, C) — C absent for 2 samples starting at 40
(40, END, A) — A absent for 2 samples starting at 40
Note: B never becomes confirmed (only 1 sample)
Output Order
When multiple events share a timestamp, output END events innermost-first, followed by START events outermost-first.
Hints
Hint 1
Track how many consecutive samples each frame has been present or absent at its specific depth position
Hint 2
The longest matching prefix between consecutive stacks tells you which frames survived unchanged
Hint 3
When a parent frame's absence is confirmed, all descendant frames must also end at that same timestamp
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Solution
The core challenge is tracking per-frame confirmation independently while respecting the hierarchical nature of call stacks.
Approach
Frame Identity: A frame is uniquely identified by both its depth and its complete ancestor path. The frame "B" at depth 1 under parent "A" is distinct from "B" at depth 1 under parent "X".
Key Insight: Presence and absence runs form prefix shapes. If a frame at depth d matches between consecutive samples, every ancestor at depth < d also matches. This means we can efficiently update runs by computing the longest common prefix (LCP) between samples.
Three-Phase Processing:
-
Track runs: For each new sample, compute the LCP with the previous sample. Frames within the LCP continue their existing presence runs; frames beyond the LCP start fresh runs at the current sample index.
-
End frames: Check absence duration for each active frame by comparing with the current sample. The LCP with active frames tells us which are still present. Frames beyond that LCP are absent. When absence duration reaches
n, emitENDevents deepest-first, using the timestamp where absence began. -
Start frames: After ending frames, if the current stack extends the remaining active stack, check presence runs for the extension. Frames whose runs have reached length
nemitSTARTevents outermost-first, each using the timestamp from the start of its run.
Delayed Confirmation: Events are discovered out of chronological order because confirmation requires seeing n samples. We collect events with their intended timestamps, then sort at the end: primarily by timestamp, then ENDs before STARTs, with depth-based ordering for tie-breaking.
End of Input: Any frames still active after processing all samples are closed at the final timestamp, deepest-first.
Why Per-Frame Debouncing Works
When the stack transitions from ["A", "B"] to ["A", "C"], frame "A" at depth 0 keeps its presence run intact because the LCP length is 1. Meanwhile, "B" at depth 1 starts its absence run and "C" at depth 1 starts a fresh presence run. This prevents outer frames from being reset by churn in inner frames.
When a stack ["A", "B"] first appears and persists for n samples, both frames reach the threshold on the same sample. Since "B"'s presence run can't be longer than "A"'s (it's a deeper prefix), they both start at the run's first timestamp.
Complexity
Time: O(S · D + E log E) where S is the number of samples, D is maximum stack depth, and E is the number of events. Each sample requires LCP computation (linear in depth) and checking active frames. The final sort is O(E log E).
Space: O(D + E) for tracking runs and storing events.
Edge Cases
- Empty stacks count as all frames being absent
- When
nequals total samples, only frames present in every sample confirm - Transient absences followed by returns reset the absence counter
- Multiple frames at the same depth under different parents are handled correctly via path comparison
Implementation
def profiling_events(samples, n):
events = []
prev_stack = []
run_start = [] # sample index where each depth's current run started
active_stack = []
absent_start = [] # sample index where absence began, or -1 if present
def longest_common_prefix(stack1, stack2):
length = 0
for i in range(min(len(stack1), len(stack2))):
if stack1[i] != stack2[i]:
break
length += 1
return length
for idx, (ts, stack) in enumerate(samples):
stack = list(stack)
# Update presence runs
prefix_len = longest_common_prefix(prev_stack, stack)
run_start = run_start[:prefix_len]
run_start.extend([idx] * (len(stack) - prefix_len))
prev_stack = stack
# Update absence tracking
active_prefix_len = longest_common_prefix(active_stack, stack)
for d in range(active_prefix_len):
absent_start[d] = -1
for d in range(active_prefix_len, len(active_stack)):
if absent_start[d] == -1:
absent_start[d] = idx
# End frames with confirmed absences
cutoff = len(active_stack)
for d in range(active_prefix_len, len(active_stack)):
if idx - absent_start[d] + 1 >= n:
cutoff = d
break
for d in range(len(active_stack) - 1, cutoff - 1, -1):
events.append((samples[absent_start[d]][0], 1, d, "END", active_stack[d]))
active_stack = active_stack[:cutoff]
absent_start = absent_start[:cutoff]
# Start frames with confirmed presence
if stack[:len(active_stack)] == active_stack:
for d in range(len(active_stack), len(stack)):
run_length = idx - run_start[d] + 1
if run_length >= n:
events.append((samples[run_start[d]][0], 0, d, "START", stack[d]))
active_stack.append(stack[d])
absent_start.append(-1)
else:
break
# Close remaining frames
if samples:
last_ts = samples[-1][0]
for d in range(len(active_stack) - 1, -1, -1):
events.append((last_ts, 1, d, "END", active_stack[d]))
# Sort: timestamp, then type (END before START), then depth order
events.sort(key=lambda e: (e[0], e[1], e[2] if e[3] == "END" else -e[2]))
return [(ts, event_type, fn) for ts, _, _, event_type, fn in events]
This solution handles all the requirements including debouncing, transient filtering, hierarchical dependencies, and proper timestamp assignment for delayed confirmations.