Find Accounts With Five Distinct Contacts in a Week
Arrays & HashingAuto-graded · 15 test casesLast updated
Sliding-window distinct counting per group: find callers who reach at least five different receivers within any 7-day span of their call log.
You are given a call log. Each record is a list of three values: [caller_id, receiver_id, call_time].
caller_id(int): the user who placed the call.receiver_id(int): the user who received the call.call_time(str): an ISO 8601 timestamp in UTC, such as"2023-01-01T10:00:00". A trailingZmay appear, as in"2023-01-01T10:00:00Z". Within one input, all timestamps use the same style (all withZ, or all without).
A caller is a frequent caller if some time window of length 7 days contains calls made by that caller to at least 5 different receivers.
Details of the rule:
- The window is rolling. It can start at any moment and is not tied to calendar weeks.
- The window is closed on both ends. Two calls exactly 7 days apart (168 hours) can be in the same window. Calls more than 7 days apart cannot.
- Only distinct receivers count. Five calls to the same receiver count as one.
- Each caller is judged only on their own calls. Calls from different callers are never combined.
- Records may arrive in any order.
Implement the function so that it returns the caller_id of every frequent caller. Each id appears once, and the list is sorted in ascending order. If nobody qualifies, return an empty list.
Constraints
0 <= len(calls) <= 10^5caller_idandreceiver_idare integers.- Timestamps are valid ISO 8601 strings in UTC and are parseable by
datetime.fromisoformat(after mapping a trailingZto+00:00). - Several calls may share the same timestamp.
- Aim for roughly O(n log n) time overall.
Examples
Example 1
Input: find_frequent_callers([[1, 10, '2023-01-01T10:00:00'], [1, 11, '2023-01-02T10:00:00'], [1, 12, '2023-01-03T10:00:00'], [1, 13, '2023-01-04T10:00:00'], [1, 14, '2023-01-05T10:00:00']])
Output: [1]
Hints
Hint 1
Group the records by caller first, then sort each caller's calls by timestamp. Callers never interact with each other.
Hint 2
If a qualifying 7-day window exists, you can slide it so that its right edge is exactly one of the caller's calls. Only windows that end at a call need to be checked.
Hint 3
Use two pointers and a hash map from receiver to the number of calls in the current window, plus a counter of receivers with a positive count. Move the left pointer while the oldest call is more than 7 days before the current one.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
- Parse each timestamp and group the calls by caller, storing
(timestamp, receiver_id)pairs. - For each caller, sort their calls by time.
- Run a sliding window over the sorted calls using two pointers. Keep a dictionary mapping each receiver to the number of calls to them inside the window, and a counter
distinctfor receivers whose count is above zero. - For each new call, add it to the window (incrementing
distinctif the receiver is new). Then move the left pointer forward while the oldest call in the window is more than 7 days before the current call. Decrement counts on eviction, and decrementdistinctwhen a count reaches zero. - If
distinct >= 5at any point, record the caller and stop scanning that caller. - Return the recorded ids sorted.
Why it is correct
- Completeness. Suppose some 7-day window contains calls to 5 distinct receivers, and let
tbe the latest call in it. All calls of that window lie in[t - 7 days, t]. When the scan reachest, our window contains every call in that interval, sodistinctis at least 5. - Soundness. After eviction, every call in our window is within 7 days of the current call. So whenever
distinct >= 5, a real qualifying window exists. - Eviction is safe. Calls are sorted by time, so a call that is too old for the current call is too old for all later ones. The left pointer never needs to move back.
- Distinct count is accurate.
distinctchanges only when a receiver's count moves between 0 and 1, so repeated calls to the same receiver do not inflate it. - Boundary. Eviction uses a strict
>comparison, so calls exactly 7 days apart stay together, which matches the closed window.
Complexity
- Time: O(n log n), dominated by sorting. The sliding-window pass is O(n) since each call enters and leaves the window at most once.
- Space: O(n) for the grouped calls, plus the receiver map for the current window.
Reference solution
from collections import defaultdict
from datetime import datetime, timedelta
from typing import List
def find_frequent_callers(calls: List[list]) -> List[int]:
by_caller = defaultdict(list)
for caller_id, receiver_id, call_time in calls:
ts = datetime.fromisoformat(call_time.replace("Z", "+00:00"))
by_caller[caller_id].append((ts, receiver_id))
result = []
span = timedelta(days=7)
for caller_id, events in by_caller.items():
events.sort()
counts = defaultdict(int)
distinct = 0
left = 0
for ts, receiver_id in events:
counts[receiver_id] += 1
if counts[receiver_id] == 1:
distinct += 1
while ts - events[left][0] > span:
old = events[left][1]
counts[old] -= 1
if counts[old] == 0:
distinct -= 1
left += 1
if distinct >= 5:
result.append(caller_id)
break
return sorted(result)