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:

  1. Initial state: Prior to times[0], assume no functions are active ([]). When times is empty, return []. Individual snapshots in stacks may also be empty ([]).
  2. Prefix continuation: At snapshot (t, curr_stack), compare curr_stack position-by-position from index 0 against the immediately preceding snapshot prev_stack up to their first mismatch. Only this contiguous leading common prefix (0 .. k - 1) stays continuously active across the transition; if an outer frame at index k changed, every deeper frame at index >= k in prev_stack is treated as finished even if the same function name reappears in curr_stack.
  3. Transition ordering at timestamp t:
    • First emit [str(t), "END", fn] for every frame in prev_stack[k:] from innermost down to outermost (len(prev_stack) - 1 down to k).
    • Next emit [str(t), "START", fn] for every frame in curr_stack[k:] from outermost up to innermost (k up to len(curr_stack) - 1).
    • Format str(t) as a plain base-10 decimal string, and use "START" or "END" for event_type.
  4. 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,000
  • 0 <= times[0] < times[1] < ... < times[n - 1] <= 10^9
  • 0 <= 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

  1. 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 timestamps times[i] and records the snapshot stacks[i].

    Our job is to convert those snapshots into inferred [time_str, "START" | "END", function_name] events following four rules:

    1. Before the first sample, the active stack is empty ([]).
    2. Between the previous stack and the current stack at time t, frames in their shared common prefix (matching from depth 0 upward) remain open.
    3. Old frames above that shared prefix emit "END" from innermost to outermost, followed by "START" for new frames from outermost to innermost, all stamped with str(t).
    4. 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
                      +-------+     +-------+     +--------+
    
  2. Why set differences fail and common-prefix matching works

    A tempting shortcut is to compare set(prev_stack) against set(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 depth 2 returned while the call at depth 1 stayed 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 depth 1 in 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 index 0. The first mismatch invalidates every deeper frame above it.

  3. Pin down the exact event order at timestamp `t`

    Suppose prev_stack and curr_stack match on their first keep frames (0 .. keep - 1). At timestamp t, the emitted events must behave like valid pops and pushes on a real stack:

    1. END before START: Old calls occupying depths keep .. len(prev_stack) - 1 must be popped off the stack before new calls can be pushed onto those same depths.
    2. END from innermost to outermost (len(prev_stack) - 1 down to keep): A callee must return before the caller that invoked it can return.
    3. START from outermost to innermost (keep up to len(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 y
    
  4. Helper: compute the common prefix length

    Walking depth upward from 0 while both stacks are in bounds and prev_stack[depth] == curr_stack[depth] finds keep in 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 depth
    

    Notice why avoiding list slices matters: writing while open_frames != curr_stack[:len(open_frames)]: open_frames.pop() copies and compares up to depth elements on every single pop, turning one deep return of 50,000 frames into billions of string comparisons (O(depth^2)). Counting common_prefix_length once does at most min(len(prev_stack), len(curr_stack)) comparisons total!

  5. Emit events for each sample and trace Example 1

    We start with prev_stack = []. For each (t, curr_stack) pair, we compute keep, format time_text = str(t) once, emit the END suffix in reverse, emit the START suffix forward, and advance prev_stack = curr_stack. When the loop ends, we return events directly 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 events
    
  6. Full 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"]]):

  1. Before t = 5: prev_stack = [].
  2. At t = 5 (["app", "parse"]): Common prefix with [] has length 0. Zero END events; emit ["5", "START", "app"], then ["5", "START", "parse"].
  3. At t = 12 (["app", "parse", "parse"]): Common prefix with ["app", "parse"] has length 2 (depths 0 and 1 stay open). Emit ["12", "START", "parse"] for the new recursive frame at depth 2.
  4. At t = 25 (["app", "render"]): Common prefix with ["app", "parse", "parse"] has length 1 ("app" at depth 0 continues). Emit END innermost first for depth 2 (["25", "END", "parse"]) and depth 1 (["25", "END", "parse"]), then START for depth 1 (["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 runs S times (accounting for O(1) per-sample work even when samples are empty). At sample i, common_prefix_length compares at most len(stacks[i]) elements, the END loop runs at most len(stacks[i - 1]) times, and the START loop runs at most len(stacks[i]) times. Summing across all S samples touches each input frame at most three times, which easily handles S = 100,000 and F = 1,000,000.
  • Space: O(E) to store the returned events list (where E <= 2F, since each frame across the snapshots can start at most once and end at most once). Auxiliary working memory is O(1) because prev_stack simply 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"] has keep = 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"] yields keep = 1, emitting two separate END "a" events (for depths 2 and 1) while keeping depth 0 open.
  • Root replacement with identical children: ["main", "f", "g"] -> ["other", "f", "g"] yields keep = 0, emitting END "g", END "f", END "main", then START "other", START "f", START "g".
  • Unclosed final frames: Frames remaining on stacks[-1] are intentionally left open with no synthetic END event after times[-1].
  • Large timestamps (t up to 10^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 0 can stay open on a call stack.
  • Wrong END or START direction: Emitting END outermost first (or START innermost first) produces an invalid trace where a caller returns while its callee is still running.
  • Emitting START before END at the same timestamp: Old frames above keep must finish before new frames occupy those stack depths.
  • Appending synthetic END events 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 of D frames into O(D^2) work.
  • Returning integer timestamps instead of strings: Output entries must be [str, str, str], so convert str(t) explicitly.

Alternative approaches

  • Explicit open_frames stack simulation: Maintain a mutable list open_frames, compute keep = common_prefix_length(open_frames, curr_stack) once per sample, pop() len(open_frames) - keep times to emit END events, and append() curr_stack[keep:] one by one to emit START events. This produces the exact same output in O(S + F) time, using O(max_depth) extra working space for open_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, taking O(current_depth) memory). As soon as sample (t, curr_stack) arrives, we can immediately emit all END and START transitions inferred at time t without waiting for future samples (O(1) sample latency). The only thing we cannot know at time t is when currently open frames will eventually end — those END events 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 at t_2, t_3, ..., t_N (and any new streaming samples after them) can be emitted with complete accuracy because each step only compares S_i against S_{i-1}. However, keeping only a trailing window of snapshots never reconstructs activity prior to t_first, nor can it recover the true start times of frames already present in S_first: a frame "app" visible in S_first might have started at t_first or hours earlier, any calls that started and finished before t_first vanished completely, and a function that returned and was re-entered at the same depth before t_first is indistinguishable from a single continuous call. Therefore, frames already open in S_first should either be emitted with a distinct marker (such as ALREADY_OPEN at t_first) or have their start time treated as "at or before t_first" rather than fabricating a false START at t_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} and t_i are invisible, and if parse() returns and a second call to parse() 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 increasing call_id integer so common_prefix_length compares (function_name, call_id) pairs instead of bare strings.

Follow-up questions

Similar questions

More Anthropic interview questions

All 254 Anthropic questions →