Inferring Call-Trace Events from Sampled Stacks
Hard · Coding & Algorithms · Software Engineer · Onsite
Problem Statement
A sampling profiler periodically pauses a running thread at strictly increasing integer timestamps times[0], times[1], ... and records the active call stack stacks[i] at each pause. Within every snapshot stacks[i], index 0 is the outermost entry point and the last element is the innermost currently executing routine. Recursive calls can place the same function name at multiple stack depths; each depth represents a distinct invocation and must never be deduplicated.
Implement stack_samples_to_events(times: List[int], stacks: List[List[str]]) -> List[List[str]] to translate these discrete stack snapshots into an inferred sequence of [timestamp_str, event_type, function_name] records:
- Initial state: Prior to
times[0], assume no functions are active ([]). Whentimesis empty, return[]. Individual snapshots instacksmay also be empty ([]). - Prefix continuation: At snapshot
(t, curr_stack), comparecurr_stackposition-by-position from index0against the immediately preceding snapshotprev_stackup to their first mismatch. Only this contiguous leading common prefix (0 .. k - 1) stays continuously active across the transition; if an outer frame at indexkchanged, every deeper frame at index>= kinprev_stackis treated as finished even if the same function name reappears incurr_stack. - Transition ordering at timestamp
t:- First emit
[str(t), "END", fn]for every frame inprev_stack[k:]from innermost down to outermost (len(prev_stack) - 1down tok). - Next emit
[str(t), "START", fn]for every frame incurr_stack[k:]from outermost up to innermost (kup tolen(curr_stack) - 1). - Format
str(t)as a plain base-10 decimal string, and use"START"or"END"forevent_type.
- First emit
- Final state: Do not fabricate closing events after the last snapshot—any frames still present in
stacks[-1]remain open when the trace ends.
Examples
Example 1
Input:
times = [5, 12, 25]
stacks = [["app", "parse"], ["app", "parse", "parse"], ["app", "render"]]
Output:
[
["5", "START", "app"],
["5", "START", "parse"],
["12", "START", "parse"],
["25", "END", "parse"],
["25", "END", "parse"],
["25", "START", "render"]
]
Explanation: Starting from [], "app" and "parse" open at t = 5. At t = 12, both leading frames continue and a recursive inner "parse" opens at depth 2. At t = 25, "app" at depth 0 stays open while depths 2 and 1 close innermost-first before "render" opens at depth 1; "app" and "render" remain open afterward.
Example 2
Input:
times = [2, 7, 14, 19]
stacks = [[], ["boot", "load", "verify"], ["boot"], []]
Output:
[
["7", "START", "boot"],
["7", "START", "load"],
["7", "START", "verify"],
["14", "END", "verify"],
["14", "END", "load"],
["19", "END", "boot"]
]
Explanation: Snapshot t = 2 is empty ([] -> []), emitting nothing. Three nested frames start outermost-first at t = 7, the inner two unwind innermost-first at t = 14, and "boot" closes when the stack returns to [] at t = 19.
Example 3
Input:
times = [4, 9]
stacks = [["reqA", "dbQuery"], ["reqB", "dbQuery"]]
Output:
[
["4", "START", "reqA"],
["4", "START", "dbQuery"],
["9", "END", "dbQuery"],
["9", "END", "reqA"],
["9", "START", "reqB"],
["9", "START", "dbQuery"]
]
Explanation: Because index 0 changed from "reqA" to "reqB", the shared prefix length at t = 9 is 0. Even though "dbQuery" appears at depth 1 in both snapshots, "reqA"'s "dbQuery" call must end before "reqA" ends, and "reqB" then opens a fresh "dbQuery" call.
Example 4
Input:
times = [1, 6]
stacks = [["dfs", "step", "dfs", "dfs"], ["dfs", "step", "dfs"]]
Output:
[
["1", "START", "dfs"],
["1", "START", "step"],
["1", "START", "dfs"],
["1", "START", "dfs"],
["6", "END", "dfs"]
]
Explanation: Each "dfs" depth is tracked independently; at t = 6, the prefix ["dfs", "step", "dfs"] of length 3 continues and only the innermost "dfs" at depth 3 closes.
Constraints
0 <= len(times) == len(stacks) <= 100,0000 <= times[0] < times[1] < ... < times[n - 1] <= 10^90 <= sum(len(s) for s in stacks) <= 1,000,000- Every element of
stacks[i]is a non-empty ASCII identifier string.
Step-by-step walkthrough
Understand what sampled call stacks represent
When a program runs, active function calls form a call stack ordered from the outermost caller (depth
0, like"app") to the innermost currently executing function (the top of the stack). A sampling profiler periodically pauses the program at timestampstimes[i]and records the snapshotstacks[i].Our job is to convert those snapshots into inferred
[time_str, "START" | "END", function_name]events following four rules:- Before the first sample, the active stack is empty (
[]). - Between the previous stack and the current stack at time
t, frames in their shared common prefix (matching from depth0upward) remain open. - Old frames above that shared prefix emit
"END"from innermost to outermost, followed by"START"for new frames from outermost to innermost, all stamped withstr(t). - After the final sample, we stop immediately — frames still on the last stack stay open with no invented
"END"event.
Sampled stacks in Example 1 (bottom = depth 0 outermost, top = innermost): before t=5 t=5 t=12 t=25 +-------+ | parse | depth 2 +-------+ +-------+ +--------+ | parse | | parse | | render | depth 1 +-------+ +-------+ +--------+ (empty) | app | | app | | app | depth 0 +-------+ +-------+ +--------+- Before the first sample, the active stack is empty (
Why set differences fail and common-prefix matching works
A tempting shortcut is to compare
set(prev_stack)againstset(curr_stack)(or count how many times each name appears). Both shortcuts fail on two everyday cases:Case 1 — Recursion (repeated function names at different depths): If
["app", "parse", "parse"]becomes["app", "parse"], both stacks contain the exact same set of names{"app", "parse"}! Yet the recursive call at depth2returned while the call at depth1stayed open, so we must emit one["t", "END", "parse"].Case 2 — Changed caller above matching child names (Example 3): Suppose
["reqA", "dbQuery"]becomes["reqB", "dbQuery"]:prev_stack: [ "reqA", "dbQuery" ] curr_stack: [ "reqB", "dbQuery" ] ^ mismatch right at depth 0! (common prefix length = 0)Even though
"dbQuery"sits at depth1in both snapshots,"reqA"could not have finished without its"dbQuery"call finishing first, and"reqB"then launched a new call to"dbQuery".Therefore, a frame's identity is its ordered path from depth
0. Two adjacent snapshots can keep open only their longest common prefix starting at index0. The first mismatch invalidates every deeper frame above it.Pin down the exact event order at timestamp `t`
Suppose
prev_stackandcurr_stackmatch on their firstkeepframes (0 .. keep - 1). At timestampt, the emitted events must behave like valid pops and pushes on a real stack:ENDbeforeSTART: Old calls occupying depthskeep .. len(prev_stack) - 1must be popped off the stack before new calls can be pushed onto those same depths.ENDfrom innermost to outermost (len(prev_stack) - 1down tokeep): A callee must return before the caller that invoked it can return.STARTfrom outermost to innermost (keepup tolen(curr_stack) - 1): A caller must start before it can invoke its callee.
prev_stack: [ main | f , g ] (keep = 1: "main" stays open) <--- pop innermost first: END g, then END f curr_stack: [ main | x , y ] ---> push outermost first: START x, then START yHelper: compute the common prefix length
Walking
depthupward from0while both stacks are in bounds andprev_stack[depth] == curr_stack[depth]findskeepin a single pass with zero list slicing:def common_prefix_length(prev_stack: List[str], curr_stack: List[str]) -> int: """Count leading frames (from outermost depth 0) that match position by position.""" limit = min(len(prev_stack), len(curr_stack)) depth = 0 # Stop at the first difference: once a parent frame changes, every inner frame # above it belongs to a new call even if its function name matches again. while depth < limit and prev_stack[depth] == curr_stack[depth]: depth += 1 return depthNotice why avoiding list slices matters: writing
while open_frames != curr_stack[:len(open_frames)]: open_frames.pop()copies and compares up todepthelements on every single pop, turning one deep return of 50,000 frames into billions of string comparisons (O(depth^2)). Countingcommon_prefix_lengthonce does at mostmin(len(prev_stack), len(curr_stack))comparisons total!Emit events for each sample and trace Example 1
We start with
prev_stack = []. For each(t, curr_stack)pair, we computekeep, formattime_text = str(t)once, emit theENDsuffix in reverse, emit theSTARTsuffix forward, and advanceprev_stack = curr_stack. When the loop ends, we returneventsdirectly so any frames still on the final stack remain open.Let's trace Example 1 (
times = [5, 12, 25],stacks = [["app", "parse"], ["app", "parse", "parse"], ["app", "render"]]):t = 5: prev_stack = [] curr_stack = ["app", "parse"] keep = 0 ENDs = (none: range(-1, -1, -1) is empty) STARTs = depth 0 ("app"), depth 1 ("parse") -> ["5", "START", "app"], ["5", "START", "parse"] t = 12: prev_stack = ["app", "parse"] curr_stack = ["app", "parse", "parse"] keep = 2 ("app" at depth 0 and "parse" at depth 1 both continue) ENDs = (none: range(1, 1, -1) is empty) STARTs = depth 2 ("parse", the recursive inner call) -> ["12", "START", "parse"] t = 25: prev_stack = ["app", "parse", "parse"] curr_stack = ["app", "render"] keep = 1 ("app" at depth 0 continues; depth 1 changed "parse" -> "render") ENDs = depth 2 ("parse"), then depth 1 ("parse") STARTs = depth 1 ("render") -> ["25", "END", "parse"], ["25", "END", "parse"], ["25", "START", "render"] End of input: "app" and "render" remain open (no END events emitted).def stack_samples_to_events(times: List[int], stacks: List[List[str]]) -> List[List[str]]: # events: list of [time_str, "START" | "END", function_name] records. events: List[List[str]] = [] # prev_stack: open frames from the prior sample (outermost -> innermost); starts empty. prev_stack: List[str] = [] for t, curr_stack in zip(times, stacks): # Phase 1: Frames in [0 .. keep - 1] stayed active across both snapshots. keep = common_prefix_length(prev_stack, curr_stack) time_text = str(t) # Phase 2: Disappearing frames must return innermost first (callees before callers) # and before any new frames open at those depths. for depth in range(len(prev_stack) - 1, keep - 1, -1): events.append([time_text, "END", prev_stack[depth]]) # Phase 3: Newly appearing frames must start outermost first (callers before callees). for depth in range(keep, len(curr_stack)): events.append([time_text, "START", curr_stack[depth]]) # Advance state without copying: we only read prev_stack on the next iteration. prev_stack = curr_stack # Frames still present on the final sample stay open — never invent an end time. return eventsFull solution
from typing import Any, Dict, List, Optional, Set, Tuple def common_prefix_length(prev_stack: List[str], curr_stack: List[str]) -> int: """Count leading frames (from outermost depth 0) that match position by position.""" limit = min(len(prev_stack), len(curr_stack)) depth = 0 # Stop at the first difference: once a parent frame changes, every inner frame # above it belongs to a new call even if its function name matches again. while depth < limit and prev_stack[depth] == curr_stack[depth]: depth += 1 return depth def stack_samples_to_events(times: List[int], stacks: List[List[str]]) -> List[List[str]]: # events: list of [time_str, "START" | "END", function_name] records. events: List[List[str]] = [] # prev_stack: open frames from the prior sample (outermost -> innermost); starts empty. prev_stack: List[str] = [] for t, curr_stack in zip(times, stacks): # Phase 1: Frames in [0 .. keep - 1] stayed active across both snapshots. keep = common_prefix_length(prev_stack, curr_stack) time_text = str(t) # Phase 2: Disappearing frames must return innermost first (callees before callers) # and before any new frames open at those depths. for depth in range(len(prev_stack) - 1, keep - 1, -1): events.append([time_text, "END", prev_stack[depth]]) # Phase 3: Newly appearing frames must start outermost first (callers before callees). for depth in range(keep, len(curr_stack)): events.append([time_text, "START", curr_stack[depth]]) # Advance state without copying: we only read prev_stack on the next iteration. prev_stack = curr_stack # Frames still present on the final sample stay open — never invent an end time. return events✅ Submit now — all tests should pass.
Intuition & how it works
Think of a program's call stack as a vertical pile of trays, where each active function call (stack frame) sits on top of the function that called it, and returns by lifting the top tray off first. A sampling profiler (a performance tool that periodically pauses a program to record its active call stack) does not log every call and return in real time — it only hands us snapshots of the tray pile at timestamps t_0, t_1, .... To turn two consecutive snapshots into valid stack actions, we compare the piles from the bottom tray (depth 0) upward until the first position where they differ: the matching bottom portion (common prefix) stayed open continuously, every old tray above that point must have popped from top down (END), and every new tray above that point must have pushed from bottom up (START).
Two naive ideas fail immediately. First, comparing adjacent stacks as sets (set(prev) - set(curr)) or name counts breaks under recursion (a function calling itself, creating distinct frames with the same name at multiple depths like ["app", "parse", "parse"]) and also breaks when an outer caller changes (["reqA", "dbQuery"] -> ["reqB", "dbQuery"] must close and reopen "dbQuery", because "reqA" could not return while its child "dbQuery" stayed running). Second, repeatedly slicing and comparing lists while popping (while open_frames != curr[:len(open_frames)]: ...) does O(depth) work per pop, which degrades to O(depth^2) on deep recursive stacks.
Let's walk through Example 1 (times = [5, 12, 25], stacks = [["app", "parse"], ["app", "parse", "parse"], ["app", "render"]]):
- Before
t = 5:prev_stack = []. - At
t = 5(["app", "parse"]): Common prefix with[]has length0. ZeroENDevents; emit["5", "START", "app"], then["5", "START", "parse"]. - At
t = 12(["app", "parse", "parse"]): Common prefix with["app", "parse"]has length2(depths0and1stay open). Emit["12", "START", "parse"]for the new recursive frame at depth2. - At
t = 25(["app", "render"]): Common prefix with["app", "parse", "parse"]has length1("app"at depth0continues). EmitENDinnermost first for depth2(["25", "END", "parse"]) and depth1(["25", "END", "parse"]), thenSTARTfor depth1(["25", "START", "render"])."app"and"render"stay open at the end.
Complexity
Let S be the number of samples (len(times)), F be the total number of frames across all samples (sum(len(s) for s in stacks)), and E be the number of emitted events.
- Time:
O(S + F). The outer loop runsStimes (accounting forO(1)per-sample work even when samples are empty). At samplei,common_prefix_lengthcompares at mostlen(stacks[i])elements, theENDloop runs at mostlen(stacks[i - 1])times, and theSTARTloop runs at mostlen(stacks[i])times. Summing across allSsamples touches each input frame at most three times, which easily handlesS = 100,000andF = 1,000,000. - Space:
O(E)to store the returnedeventslist (whereE <= 2F, since each frame across the snapshots can start at most once and end at most once). Auxiliary working memory isO(1)becauseprev_stacksimply references the previous sample list without copying it.
Edge cases
- Empty input (
times = [],stacks = []): The loop does not execute and returns[]. - Empty stack samples (
[]): An empty sample at the beginning emits nothing; an empty sample after["a", "b"]haskeep = 0, closing"b"then"a"; another["a"]later starts"a"fresh. Consecutive empty samples emit nothing. - Identical consecutive stacks:
keep == len(prev_stack) == len(curr_stack), so both inner ranges are empty and zero events are emitted. - Recursive calls with the same name:
["a", "a", "a"]->["a"]yieldskeep = 1, emitting two separateEND "a"events (for depths2and1) while keeping depth0open. - Root replacement with identical children:
["main", "f", "g"]->["other", "f", "g"]yieldskeep = 0, emittingEND "g",END "f",END "main", thenSTART "other",START "f",START "g". - Unclosed final frames: Frames remaining on
stacks[-1]are intentionally left open with no syntheticENDevent aftertimes[-1]. - Large timestamps (
tup to10^9):str(t)formats integers in exact base-10 decimal ("1000000000"), avoiding float formatting like"1e+09".
Common mistakes
- Using set difference or bag/counter subtraction: Deduplicating names merges recursive frames and wrongly preserves matching child names after an outer caller changed.
- Matching longest common subsequence instead of longest common prefix: Only a contiguous match anchored at depth
0can stay open on a call stack. - Wrong
ENDorSTARTdirection: EmittingENDoutermost first (orSTARTinnermost first) produces an invalid trace where a caller returns while its callee is still running. - Emitting
STARTbeforeENDat the same timestamp: Old frames abovekeepmust finish before new frames occupy those stack depths. - Appending synthetic
ENDevents after the final sample: The specification explicitly leaves surviving frames open. - Quadratic prefix slicing (
while open_frames != curr[:len(open_frames)]): Slicing and comparing the prefix on every pop turns a single deep unwind ofDframes intoO(D^2)work. - Returning integer timestamps instead of strings: Output entries must be
[str, str, str], so convertstr(t)explicitly.
Alternative approaches
- Explicit
open_framesstack simulation: Maintain a mutable listopen_frames, computekeep = common_prefix_length(open_frames, curr_stack)once per sample,pop()len(open_frames) - keeptimes to emitENDevents, andappend()curr_stack[keep:]one by one to emitSTARTevents. This produces the exact same output inO(S + F)time, usingO(max_depth)extra working space foropen_frames.
Follow-up questions
- If stack snapshots arrive as an unbounded live stream, what state must the converter keep in memory and which events can it emit immediately? A streaming converter only needs to store one list:
prev_stack(the previous sample's frames, takingO(current_depth)memory). As soon as sample(t, curr_stack)arrives, we can immediately emit allENDandSTARTtransitions inferred at timetwithout waiting for future samples (O(1)sample latency). The only thing we cannot know at timetis when currently open frames will eventually end — thoseENDevents can only be emitted prospectively when a future sample omits them (or when an explicit process-exit signal arrives). - Suppose a ring buffer only retains the most recent N stack snapshots; what transitions can still be emitted accurately and what history is permanently lost? From the first retained sample (
t_first,S_first) onward, every transition att_2, t_3, ..., t_N(and any new streaming samples after them) can be emitted with complete accuracy because each step only comparesS_iagainstS_{i-1}. However, keeping only a trailing window of snapshots never reconstructs activity prior tot_first, nor can it recover the true start times of frames already present inS_first: a frame"app"visible inS_firstmight have started att_firstor hours earlier, any calls that started and finished beforet_firstvanished completely, and a function that returned and was re-entered at the same depth beforet_firstis indistinguishable from a single continuous call. Therefore, frames already open inS_firstshould either be emitted with a distinct marker (such asALREADY_OPENatt_first) or have their start time treated as "at or beforet_first" rather than fabricating a falseSTARTatt_first. - Which real function calls and returns can be missed between two profiler samples, and how could runtime support disambiguate them? Because sampling only observes discrete moments, short calls that start and return entirely between
t_{i-1}andt_iare invisible, and ifparse()returns and a second call toparse()is made from the exact same caller depth before the next sample (the ABA problem — when a state changes from A to B and back to A between observations so nothing appears to have changed), common-prefix matching treats both calls as one uninterrupted invocation. Exact start/end timestamps require tracing instrumentation (logging an event on every actual function entry and exit) or tagging each live stack frame with a monotonically increasingcall_idinteger socommon_prefix_lengthcompares(function_name, call_id)pairs instead of bare strings.
Follow-up questions
- If stack snapshots arrive as an unbounded live stream, what state must the converter keep in memory and which events can it emit immediately?
- Suppose a ring buffer only retains the most recent N stack snapshots; what transitions can still be emitted accurately and what history is permanently lost?
- Which real function calls and returns can be missed between two profiler samples, and how could runtime support disambiguate them?
Similar questions
- Time-Limited Credit Ledger
- Bit-Level Inner-Loop Optimizations
- Stateful Banking Ledger Simulation
- Depth-Bounded Multi-Threaded Web Crawler
- Constant-Time LRU Cache
- Timestamped Banking Ledger with Merges and History
- Emit Profiler Events from Confirmed Call-Stack Snapshots
- Debounced Call-Stack Profiling Events
More Anthropic interview questions
- In-Memory Key-Field Store with Expiring Entries and Snapshots Medium
- Direct Two-Person Web Messaging Hard
- Anthropic Recruiter Screen: Lab Motivation, Safety Taxonomy, and Misuse Risks Medium Pro
- Time-Versioned Key-Field Store Hard Pro
- Collaborative Prompt Studio and Model Execution Service Medium Pro
- Anthropic Values Alignment, Integrity Under Friction, and Policy Critique Medium Pro
- Single-GPU and All-GPU Batch Scheduling for Model Inference Hard Pro
- Fleet-Wide Model Artifact Rollout System Hard Pro
- Same-Host Sequential and Concurrent Web Crawler Medium Pro
- Motivation for Anthropic and Perspective on AI Safety Hard Pro