KatInterview

Repeat Visitors Across UTC Days in an Event Feed

Arrays & HashingAuto-graded · 13 test cases
MediumAuto-gradedArrays & Hashinghashingdatetimetimezone

Last updated

Normalize ISO 8601 timestamps to UTC dates and use hashing to find users active on at least two distinct UTC calendar days.

Repeat Visitors Across UTC Days in an Event Feed

You are given a feed of visit events in no particular order. Each event is a two-element list [user_id, timestamp], where timestamp is an ISO 8601 string. A user is a repeat visitor if their events fall on at least two different calendar days.

Return the ids of all repeat visitors.

Rules

  • The calendar day of an event is its UTC date. Convert every timestamp to UTC first, then take the date. The date written in the string is not necessarily the UTC date, because a timestamp may carry a UTC offset such as -05:00 or +05:30.
  • A trailing Z means UTC.
  • A timestamp with no offset is treated as already being in UTC.
  • Several events may be identical, or may fall on the same day. Extra events on a day the user has already visited do not count as a new day.
  • Events may appear in any order.
  • Return the user ids as a list sorted in ascending order (standard string comparison), with each id appearing once. If nobody qualifies, return an empty list.

Function

Implement find_repeat_visitors(events), where events is a list of [user_id, timestamp] pairs, and return a sorted list of strings.

Constraints

  • 0 <= len(events) <= 10^5
  • user_id is a non-empty string.
  • Every timestamp is a valid ISO 8601 date-time string, with or without an offset or a trailing Z, and with or without fractional seconds.
  • Malformed timestamps do not appear in the input.
  • The whole input fits in memory.
  • Aim for roughly linear time in the number of events.

Examples

Example 1

Input: find_repeat_visitors([['u1', '2024-01-01T23:30:00-05:00'], ['u1', '2024-01-02T04:30:00Z'], ['u1', '2024-01-02T05:00:00Z'], ['u2', '2024-01-02T00:10:00Z'], ['u2', '2024-01-02T23:55:00Z'], ['u3', '2024-01-03T00:00:00Z']])

Output: []

Hints

Hint 1

Decide what a 'day' means first: convert each timestamp to UTC before taking its date. Reading the date directly off the string gives wrong answers for events with offsets.

Hint 2

You do not need to store every date for each user. A dictionary from user to the first UTC date seen is enough; the user qualifies as soon as a different date shows up.

Hint 3

Python's datetime.fromisoformat does not accept a trailing 'Z' in older versions, so rewrite it as '+00:00'. If the parsed value has no tzinfo, attach UTC before converting. Finish by sorting the qualifying ids.