KatInterview

Find Accounts With Five Distinct Contacts in a Week

Arrays & HashingAuto-graded · 15 test cases
MediumAuto-gradedArrays & Hashingsliding-windowhash-mapgrouping

Last 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 trailing Z may appear, as in "2023-01-01T10:00:00Z". Within one input, all timestamps use the same style (all with Z, 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^5
  • caller_id and receiver_id are integers.
  • Timestamps are valid ISO 8601 strings in UTC and are parseable by datetime.fromisoformat (after mapping a trailing Z to +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.