Aggregate Executed Call Sequences across Threads
Data Structure DesignAuto-graded · 14 test casesLast updated
Simulate an execution stream aggregator tracking stack call frequency across threads with custom tie-breaking rules.
You are tasked with building an in-memory aggregation module for a call-stack sampling profiler. As worker threads run, the profiler periodically captures active call stacks, represented as ordered lists of frame strings from the entry frame down to the deepest active function call.
You need to process a sequence of commands given by operations and arguments:
-
"record_sample"withargs = [thread_id, stack]:thread_id(string): identifier of the recorded thread.stack(list of strings): execution path ordered from root to leaf.- Action: Log this sample into the profiler data structures.
- Output:
None(represented asnull).
-
"get_top_overall"withargs = []:- Output: The most frequently recorded call stack across all threads along with its total count as
[stack_list, count]. - If no samples have been recorded yet, return
None.
- Output: The most frequently recorded call stack across all threads along with its total count as
-
"get_top_per_thread"withargs = []:- Output: A dictionary mapping each observed
thread_idto its individual most frequent call stack and sample count as{thread_id: [stack_list, count]}. - If no samples have been recorded yet, return an empty dictionary
{}.
- Output: A dictionary mapping each observed
Tie-Breaking Rule
If two or more call stacks have the same highest frequency (globally or within a specific thread), choose the stack that is lexicographically smaller. Stacks are compared frame by frame from root to leaf using standard ASCII string ordering:
["a", "b"]comes before["a", "c"].["a"]comes before["a", "b"].- An empty call stack
[]comes before any non-empty stack.
Constraints
- $1 \le N \le 100{,}000$ operations in total.
- $1 \le \text{len}(thread_id) \le 32$.
- $0 \le \text{len}(stack) \le 50$. An empty stack
[]indicates an idle thread and is treated as a valid distinct call stack. - Frame names consist of ASCII alphanumeric characters and underscores ($1 \le \text{len}(frame) \le 64$).
Examples
Example 1
Input: stack_profiler(['record_sample', 'record_sample', 'record_sample', 'record_sample', 'get_top_overall', 'get_top_per_thread'], [['worker-1', ['main', 'physics']], ['worker-2', ['main', 'render']], ['worker-1', ['main', 'physics']], ['worker-2', ['main', 'physics']], [], []])
Output: [None, None, None, None, [['main', 'physics'], 3], {'worker-1': [['main', 'physics'], 2], 'worker-2': [['main', 'physics'], 1]}]
Example 2
Input: stack_profiler(['get_top_overall', 'get_top_per_thread'], [[], []])
Output: [None, {}]
Hints
Hint 1
Since lists are mutable and unhashable in Python, convert incoming stack lists to immutable tuples before using them as keys in standard hash maps or Counter objects.
Hint 2
When resolving ties, you want to maximize frequency while minimizing lexicographical order. The tuple key `(-frequency, stack_tuple)` neatly satisfies both conditions simultaneously using standard sorting or min operations.
Hint 3
Empty stacks `[]` map to `()` in Python. Python compares empty tuples as smaller than any non-empty tuple, perfectly respecting the tie-breaking rule.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
To maintain profiling records efficient for lookup and query:
- Hashable Representation: Since stack frames arrive as mutable lists, convert each stack into a tuple
tuple(stack)so it can serve as a key in hash maps (Counter). - Frequency Tracking:
- Maintain a global
Countermappingstack_tuple -> count. - Maintain a dictionary
per_threadmappingthread_id -> Counter(stack_tuple -> count).
- Maintain a global
- Deterministic Selection & Tie-Breaking:
- To query the top element, we evaluate every recorded tuple key using
min(counter, key=lambda k: (-counter[k], k)). - The primary sorting key
-counter[k]ensures the highest count is preferred. - The secondary key
k(the sequence of frame strings) breaks ties using natural lexicographical order (i.e.,"a" < "b",() < ("a",)).
- To query the top element, we evaluate every recorded tuple key using
Complexity Analysis
- Time Complexity:
record_sample: $\mathcal{O}(L)$ where $L$ is the stack depth (up to 50), needed to build and hash the tuple.get_top_overall: $\mathcal{O}(D \cdot L)$ where $D$ is the count of distinct global stacks captured.get_top_per_thread: $\mathcal{O}(P \cdot L)$ where $P$ is the total count of distinct(thread_id, stack)combinations.
- Space Complexity: $\mathcal{O}((D + P) \cdot L)$ to store distinct call stack tuples across overall and per-thread structures.
Python Reference Solution
from collections import Counter
from typing import List
def stack_profiler(operations: List[str], arguments: List[List]) -> List:
overall = Counter()
per_thread = {}
results = []
for operation, args in zip(operations, arguments):
if operation == "record_sample":
thread_id, stack = args
key = tuple(stack)
overall[key] += 1
if thread_id not in per_thread:
per_thread[thread_id] = Counter()
per_thread[thread_id][key] += 1
results.append(None)
elif operation == "get_top_overall":
if not overall:
results.append(None)
else:
best = min(overall, key=lambda k: (-overall[k], k))
results.append([list(best), overall[best]])
elif operation == "get_top_per_thread":
tops = {}
for thread_id, counts in per_thread.items():
best = min(counts, key=lambda k: (-counts[k], k))
tops[thread_id] = [list(best), counts[best]]
results.append(tops)
else:
raise ValueError("unknown operation")
return results