Your team is debugging a program’s performance. A tracing tool records all function calls and returns, producing a sequence of events.
Your task is to analyze these raw traces and determine which call stack occurs most frequently.
Finding the most frequent call stack will help identify where the main slowdown may be occurring.
Input
- An array of strings, each representing a traced function call or return.
- Function calls are prefixed by
"->"(e.g.-> main). - Function returns are prefixed by
"<-"(e.g.<- main).
Output
- Return the call stack string (functions joined by
"->") that appears most frequently. - If there’s a tie, return the one that first reached the top frequency.
Call Stack Definition
- A call stack represents the sequence of active function calls at any time.
- Example:
Ifmain()callshandleEvents(), which callshandleClickEvent(),
then the current call stack ismain->handleEvents->handleClickEvent. - Returning from a function simply pops the top frame—it does not create a new stack identity.
Example
traces = [
"-> main",
"-> handleEvents",
"-> handleClickEvent",
"<- handleClickEvent",
"<- handleEvents",
"-> handleEvents",
"<- handleEvents",
"<- main"
]
Output:"main->handleEvents->handleClickEvent"
Because this stack occurred twice, which is the highest frequency.
Constraints
- The trace is guaranteed to be well-formed: every function call has a corresponding return.
This problem tests understanding of stack simulation and frequency counting under nested call conditions.
The key idea is to maintain a dynamic stack that records the current function calls.
Each time a new call happens, join the current stack into a string (e.g., "main->handleEvents->click") and count its occurrences.
When a return occurs, pop the function from the stack.
Algorithm Outline
- Initialize an empty
stackand a frequencydict. - For each trace:
- If it starts with
"->", push the function name to the stack.- Convert the current stack into a string joined by
"->"and increment its frequency.
- Convert the current stack into a string joined by
- If it starts with
"<-", pop the top function from the stack.
- If it starts with
- Return the stack string with the highest frequency; if tied, return the first one that reached that frequency.
Complexity
- Time: O(n) — single pass through traces
- Space: O(n) — to store active stack and frequency map
The VOprep team has long accompanied candidates through various major company OAs and VOs, including Roblox, Google, Amazon, Citadel, SIG, providing real-time voice assistance, remote practice, and interview pacing reminders to help you stay smooth during critical moments. If you are preparing for these companies, you can check out our customized support plans—from coding interviews to system design, we offer full guidance to help you succeed.