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.
这道题考察的是如何通过 模拟函数调用栈 来分析程序运行轨迹,从而找出 最频繁出现的调用栈,帮助定位性能瓶颈
核心思路是:
- 使用一个 栈 记录当前调用链;
- 每次有函数进入时,组合当前调用栈(用
->连接)并计数; - 每次函数返回时,从栈顶弹出;
- 最后输出出现次数最多的调用栈(若有并列,返回最早达到最高次数的)。
解题关键点
- 用栈模拟嵌套调用;
- 通过字典统计每个调用栈的出现次数;
- 注意“return”不产生新的调用栈,而是回到上一级;
- 考虑性能和边界情况(空栈、重复计数、首个最高频优先)。
这道题不仅考察算法实现能力,也反映候选人是否理解 栈在程序执行过程中的作用 ,以及能否高效模拟复杂的执行序列。
在面试中,考官通常会追问:
- 你如何优化空间占用?
- 如果 traces 非法(比如 return 没有匹配的 call),该如何处理?
- 若要支持并发 trace(多线程),数据结构是否还适用?
VOprep 团队长期陪同学员实战各类大厂 OA 与 VO,包括 Roblox、Google、Amazon、Citadel、SIG 等,提供实时答案助攻、远程陪练与面试节奏提醒,帮助大家在关键时刻不卡壳。
如果你也在准备公司,可以了解一下我们的定制助攻方案——从编程面到系统设计,全程护航上岸。