Identify the Most Common Function Call in Application Logs
Arrays & HashingModel answerLast updated
Determine which function name occurs most often in a list of log entries and report its occurrence count.
You're analyzing application logs where each entry records a function name that was invoked. Your task is to identify which function appears most frequently.
Write a function that accepts a list of function names (strings) and returns a tuple containing the most common function name and how many times it occurred.
Example:
Input: ["login", "search", "login", "checkout", "search", "login"]
Output: ("login", 3)
Requirements:
- If the input is empty, return
None - If multiple functions tie for the highest frequency, return the one that appeared earliest in the log sequence
- Treat function names as case-sensitive exact matches
Follow-up questions you should be prepared to discuss:
- How would you extend this to return the top k most frequent functions?
- How would you handle logs arriving as a continuous stream?
- What if the log data is distributed across multiple machines?
Hints
Hint 1
Use a hash map to track how many times each function name appears as you iterate through the logs
Hint 2
After counting, scan through your frequency map to find the maximum count; remember to handle the tie-breaking rule
Hint 3
Python dictionaries maintain insertion order (since 3.7), which helps implement the earliest-appearance tie-breaker naturally
Model answer
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Model Answer
Clarifying Questions
Before implementing, I'd confirm several details:
- Empty input handling: Return
Nonerather than throwing an error - Tie resolution: When multiple functions have the same maximum count, return whichever appeared first in the original sequence
- String comparison: Treat entries exactly as given; "Login" and "login" are distinct
- Return format: A tuple
(function_name, count)
Approach
This is fundamentally a frequency analysis problem. The optimal strategy uses a hash map:
- Count phase: Iterate through the log entries once, maintaining a map from function name to occurrence count
- Find maximum: Scan the map to identify the entry with the highest count
Why this works for tie-breaking: In Python 3.7+, dictionaries preserve insertion order. When we iterate over the map in step 2, we encounter functions in the order they first appeared. Using a strict greater-than comparison (> not >=) means we only update our answer when we find a strictly higher count, so the earliest function to reach the maximum count is selected.
Example walkthrough:
For ["login", "search", "login", "checkout", "search", "login"]:
After counting:
login: 3search: 2checkout: 1
The maximum is 3, so we return ("login", 3).
Complexity Analysis
- Time: O(n) where n is the number of log entries. Counting requires one pass through the input. Scanning the map takes O(u) where u is distinct function names, and u ≤ n.
- Space: O(u) to store the frequency map
An alternative approach using sorting would take O(n log n) time and wouldn't preserve the first-appearance ordering needed for tie-breaking.
Implementation
from typing import Dict, Iterable, Optional, Tuple
def most_frequent_call(logs: Iterable[str]) -> Optional[Tuple[str, int]]:
"""
Identify the most frequently occurring function call in logs.
Ties are resolved by returning the function that appeared earliest.
Returns None if logs are empty.
"""
# Build frequency map
frequency: Dict[str, int] = {}
for function_name in logs:
frequency[function_name] = frequency.get(function_name, 0) + 1
if not frequency:
return None
# Find maximum, with earliest-appearance tie-breaking
max_function, max_count = None, 0
for function_name, count in frequency.items():
if count > max_count: # strict comparison preserves first occurrence
max_function, max_count = function_name, count
return max_function, max_count
Note: While collections.Counter(logs).most_common(1) achieves the same result and has identical tie-breaking behavior, interviewers typically want to see the manual counting implementation to verify you understand the underlying mechanics.
Edge Cases
- Empty list: Returns
Noneas specified - Single entry: Returns
(entry, 1) - All unique functions: Every count is 1, so the first entry wins
- All identical: Returns
(entry, n) - Tie scenario: With
["a", "b", "b", "a"], both have count 2, but "a" appeared first, so return("a", 2)
Follow-up: Top-k Functions
To retrieve the k most frequent functions:
import heapq
from typing import List, Tuple
def top_k_calls(logs: Iterable[str], k: int) -> List[Tuple[str, int]]:
"""Return up to k functions with highest frequency."""
if k <= 0:
return []
frequency = {}
for function_name in logs:
frequency[function_name] = frequency.get(function_name, 0) + 1
# nlargest maintains insertion order for ties (stable sort)
return heapq.nlargest(k, frequency.items(), key=lambda x: x[1])
Complexity: O(u log k) where u is distinct functions. When k is small relative to u, this is more efficient than full sorting.
Alternative for very large datasets: Bucket sort by frequency runs in O(n) time since counts are bounded by n. Create buckets indexed by count, place functions in their corresponding bucket, then read from highest bucket downward.
Follow-up: Streaming Data
Bounded stream (fits in memory): Maintain the running frequency map and update it with each new log entry. To answer "current most frequent" in O(1), track the leader incrementally—only update when a function's count surpasses the current maximum.
Sliding time window: Keep counts bucketed by time period (e.g., per second). As time advances, add the newest bucket and remove the expired one. This bounds memory usage.
Approximate counting for unbounded distinct functions: When the number of unique function names exceeds memory:
- Count-Min Sketch: Probabilistic data structure using sublinear space; may overestimate but never underestimates
- Space-Saving algorithm: Maintains exactly k counters and guarantees finding all items with frequency above n/k
Follow-up: Distributed Logs
For logs spread across many servers:
- Map phase: Each machine computes local frequency counts
- Shuffle: Partition data by
hash(function_name)so all counts for a given function reach the same reducer - Reduce phase: Each reducer sums counts for its assigned functions and outputs its local top-k
- Final merge: Combine the reducer top-k lists to produce the global top-k
Critical insight: Partitioning by function name ensures correctness. A common mistake is merging per-machine top-k lists without this step—a function could rank 11th on every machine but be 1st globally.
Common Mistakes
- Using
>=instead of>in the comparison, which breaks the tie-breaker - Assuming dictionary iteration order is random (true in Python ≤3.6)
- Not handling the empty input case
- For distributed scenarios, attempting to merge local top-k without key-based partitioning