Problem · Stack

Convert Stack Samples to Trace Events

Learn this problem
MediumAnthropicFULLTIMEPHONE SCREEN

Problem statement

A sampling profiler records the active call stack at several moments. You are given two parallel arrays:

  • timestamps[i] is the timestamp of sample i.
  • stacks[i] lists the active functions in sample i, from the outermost call to the innermost call.

Sample Transitions

Convert the samples into an ordered trace of function events.

  • For the first sample, emit a start event for every function from outermost to innermost.
  • Between adjacent samples, the longest common stack prefix remains active.
  • Emit end events for functions removed from the previous stack, from innermost to outermost.
  • Then emit start events for functions added by the current stack, from outermost to innermost.

Do not synthesize end events after the final sample. Any functions in the final sampled stack are still active.

Recursive calls at different stack depths are different active calls, even when they have the same function name.

Event Format

Return the events in order. Represent each event as [eventType, functionName], where eventType is "start" or "end".

Function

convertStackSamples(timestamps: int[], stacks: String[][]) → String[][]

Examples

Example 1

timestamps = [1,2,3]stacks = [["main"],["main","f1","f2","f3"],["main"]]return = [["start","main"],["start","f1"],["start","f2"],["start","f3"],["end","f3"],["end","f2"],["end","f1"]]

main starts with the first sample. The second sample starts f1, f2, and f3. The third sample removes those three calls, so they end from innermost to outermost. main remains active in the final sample, so no end event is emitted for it.

More Anthropic problems

drafts saved locally
public String[][] convertStackSamples(int[] timestamps, String[][] stacks) {
  // write your code here
}
timestamps[1,2,3]
stacks[["main"],["main","f1","f2","f3"],["main"]]
expected[["start", "main", "start", "f1", "start", "f2", "start", "f3", "end", "f3", "end", "f2", "end", "f1"]]
checking account