Convert stack samples to trace events
Company: Anthropic
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Technical Screen
Overview: This question evaluates a candidate's ability to convert chronologically ordered stack samples into start/end trace events, testing stateful stream processing, stack diffing, correct temporal ordering, and frame identity handling in the presence of recursion.
Part 1: Convert Stack Samples to Trace Events
Constraints
- 0 <= len(samples) <= 200000
- Timestamps are nondecreasing integers
- Each stack is ordered from outermost to innermost
- Total number of function names across all samples is at most 200000
- Function names are non-empty strings
Examples
Input: [(1, ['A']), (2, ['A', 'B']), (3, ['A', 'C']), (4, ['A'])]
Expected Output: [('start', 1, 'A'), ('start', 2, 'B'), ('end', 3, 'B'), ('start', 3, 'C'), ('end', 4, 'C')]
Explanation: The first sample starts A. Then B starts. At timestamp 3, B disappears before C appears. A is still active in the last sample, so it has no end event.
Input: [(10, ['main', 'foo']), (20, ['main', 'foo']), (30, ['main'])]
Expected Output: [('start', 10, 'main'), ('start', 10, 'foo'), ('end', 30, 'foo')]
Explanation: The stack is unchanged between 10 and 20, so no new events are emitted there.
Hints
- For each pair of consecutive samples, find the longest common prefix of their stacks.
- Everything removed from the old stack after that prefix ends first, from the back toward the front.
Part 2: Emit Trace Events Only for Frames Lasting at Least N Samples
Constraints
- 0 <= len(samples) <= 200000
- 1 <= n <= 200000
- Timestamps are nondecreasing integers
- Each stack is ordered from outermost to innermost
- Total number of function names across all samples is at most 200000
- Function names are non-empty strings
Examples
Input: ([(1, ['A']), (2, ['A']), (3, ['A', 'B']), (4, ['A', 'B']), (5, ['A']), (6, [])], 2)
Expected Output: [('start', 1, 'A'), ('start', 3, 'B'), ('end', 5, 'B'), ('end', 6, 'A')]
Explanation: A is present in samples 1 and 2, so it qualifies and gets start time 1. B is first seen at 3 and confirmed at 4, so its start time is backdated to 3.
Input: ([(1, ['A']), (2, ['A', 'B']), (3, ['A']), (4, [])], 2)
Expected Output: [('start', 1, 'A'), ('end', 4, 'A')]
Explanation: B appears in only one sample, so it never reaches the threshold and produces no events.
Approach
Time complexity: O(S + E log E)
Space complexity: O(D + E)
Hints
- Track each active depth as a frame record: function name, first seen timestamp, current streak length, and whether its start event has already been emitted.
- When two consecutive samples diverge, only the longest common prefix continues. Everything deeper is either ending now or starting a new pending streak.
Community answers
Answer by [Deleted User]
Answer by raknid_layuj
Answer by andrew.rosses12