Longest Average Calls Leaderboard Since a Cutoff
SQL & DataAuto-graded · 14 test casesLast updated
Filter call records by start time, group by user to get average duration in minutes, then rank with a deterministic tie-break and keep the top 10.
A video-calling team keeps a log of calls. Each record is a dictionary with string values:
call_id: identifier of the calluser_id: identifier of the user who made the callstart_time: when the call began, formattedYYYY-MM-DD HH:MM:SSend_time: when the call ended, in the same format
The team wants a leaderboard of the users whose calls were longest on average within a recent time window. The start of the window is passed in explicitly as window_start, so the result does not depend on the current clock.
Write a function that returns the 10 users with the highest average call duration, measured in minutes.
Rules
- Window filter. A record is counted only if its
start_timeis greater than or equal towindow_start. The boundary is inclusive. Onlystart_timeis compared, so a call that began before the window is ignored even if it ended inside it. Ignored records are skipped entirely. - Every record counts. Each counted record is its own call. Do not deduplicate by
call_id, and do not drop zero-length calls. - Duration. A counted call's duration in minutes is
(end_time - start_time)expressed in seconds, divided by60, as a floating-point number. Do not round or truncate. For example, 45 minutes 30 seconds is45.5. A duration is used as computed, even if it is zero. - Average. For each user, add up the durations of that user's counted calls, starting from
0.0and adding in the order the records appear in the input. Then divide by the number of counted calls. Users with no counted calls do not appear. Use exactly this arithmetic (per-callseconds / 60, summed, then divided by the count), because ties are decided by comparing these resulting floating-point averages for equality. - Ordering. Sort users by average duration, largest first. If two users have equal averages, put the one with the smaller
user_idfirst. Compareuser_idvalues exactly as given, as plain strings (character-by-character, so"10"comes before"9"). - Limit. Return at most 10 users. If fewer qualify, return all of them. If none qualify, return an empty list.
Output
Return a list of dictionaries, one per ranked user, in rank order. Each dictionary has exactly two keys:
user_id: the user's identifier, unchanged from the inputaverage_duration_minutes: the user's average call duration in minutes, as a number
Constraints
- Every record has all four fields.
- All timestamps and
window_startare valid and use the formatYYYY-MM-DD HH:MM:SS. - The number of records can be large, so a single pass over the data is expected.
- The result must follow the filter, arithmetic, ordering and tie-break rules above exactly.
Examples
Example 1
Input: longest_average_calls([{'call_id': '1', 'user_id': '101', 'start_time': '2023-07-01 09:00:00', 'end_time': '2023-07-01 09:45:00'}, {'call_id': '2', 'user_id': '102', 'start_time': '2023-07-01 10:15:00', 'end_time': '2023-07-01 10:40:00'}, {'call_id': '3', 'user_id': '101', 'start_time': '2023-07-02 14:05:00', 'end_time': '2023-07-02 14:25:00'}, {'call_id': '4', 'user_id': '103', 'start_time': '2023-07-02 15:00:00', 'end_time': '2023-07-02 16:30:00'}, {'call_id': '5', 'user_id': '102', 'start_time': '2023-07-03 11:20:00', 'end_time': '2023-07-03 12:00:00'}], '2023-06-27 00:00:00')
Output: [{'user_id': '103', 'average_duration_minutes': 90}, {'user_id': '101', 'average_duration_minutes': 32.5}, {'user_id': '102', 'average_duration_minutes': 32.5}]
Hints
Hint 1
Handle each call independently: parse the start time, skip the record if it is before the window start, and only then look at the end time.
Hint 2
Keep two dictionaries keyed by user: a running total of minutes (add each call's total_seconds() / 60 in input order) and a count of calls. The average is total divided by count.
Hint 3
Once you have per-user averages, sort with a key of (-average, user_id) so larger averages come first and ties fall back to ascending string user_id, then slice the first 10.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This is a filter, aggregate, rank problem, the same shape as WHERE / GROUP BY / ORDER BY / LIMIT in SQL.
- Filter. Parse each record's
start_timeand skip the record if it is earlier thanwindow_start. The check uses the start time only, and a call starting exactly at the boundary is kept. - Measure. For each remaining call, compute
(end - start).total_seconds() / 60. Working in seconds and dividing by 60 keeps fractional minutes that whole-minute truncation would lose. - Aggregate. Keep a running total of minutes (starting from
0.0, adding in input order) and a call count per user in two dictionaries. - Average. For each user, divide the total by the count.
- Rank. Sort by
(-average, user_id). Negating the average gives descending order by average, and the stringuser_idgives a deterministic ascending tie-break. - Limit. Take the first 10 entries and format them as dictionaries.
Why it is correct
- Filtering happens before any accumulation, so calls outside the window affect neither the numerator nor the denominator of any user's average.
- Total divided by count is exactly the mean of the per-call durations.
- Using one fixed arithmetic order (per-call minutes, summed in input order, then divided) means equal averages are detected consistently, so the tie-break applies the same way every time.
- The sort key totally orders users: averages are compared first, and distinct
user_idvalues settle ties, so the top-10 cut is deterministic even when several users tie at the boundary. - Slicing handles the edge cases naturally: fewer than 10 users returns them all, and no qualifying calls returns an empty list.
Complexity
- Time: O(n + u log u), where n is the number of calls and u is the number of distinct users in the window. The scan is linear and the sort is over users only.
- Space: O(u) for the per-user totals and counts.
A heap-based selection (heapq.nsmallest(10, ...) on the same key) would cut ranking to O(u log 10), but it is rarely needed.
Reference solution
from datetime import datetime
from typing import Dict, List
def longest_average_calls(calls: List[Dict[str, str]], window_start: str) -> List[Dict[str, float]]:
cutoff = datetime.fromisoformat(window_start)
total_minutes = {}
call_counts = {}
for call in calls:
start = datetime.fromisoformat(call['start_time'])
if start < cutoff:
continue
end = datetime.fromisoformat(call['end_time'])
uid = call['user_id']
total_minutes[uid] = total_minutes.get(uid, 0.0) + (end - start).total_seconds() / 60
call_counts[uid] = call_counts.get(uid, 0) + 1
ranked = [(uid, total_minutes[uid] / call_counts[uid]) for uid in total_minutes]
ranked.sort(key=lambda item: (-item[1], item[0]))
return [
{'user_id': uid, 'average_duration_minutes': avg}
for uid, avg in ranked[:10]
]