Repeat Visitors Across UTC Days in an Event Feed
Arrays & HashingAuto-graded · 13 test casesLast 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:00or+05:30. - A trailing
Zmeans 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^5user_idis a non-empty string.- Every
timestampis a valid ISO 8601 date-time string, with or without an offset or a trailingZ, 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.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
- Normalize each timestamp to a UTC date. Replace a trailing
Zwith+00:00sodatetime.fromisoformatcan parse it. If the parsed value has no timezone, mark it as UTC. Convert it to UTC withastimezone, then take.date(). - Track one date per user. Keep a dictionary
first_daymapping each user to the first UTC date seen. When a later event for the same user has a different date, the user has been active on two distinct days, so add them to arepeatset. - Skip decided users. Once a user is in
repeat, their remaining events can be ignored, so we skip parsing them and drop their stored date. - Return
sorted(repeat).
Why it is correct
For a user u, let D(u) be the set of UTC dates of their events. The user qualifies exactly when |D(u)| >= 2.
While a user is undecided, first_day[u] is the only date seen so far, so |D(u)| = 1. A new event with the same date leaves D(u) unchanged, which covers duplicates and same-day repeats. A new event with a different date makes |D(u)| >= 2, and no later event can undo that. The cardinality of a set does not depend on insertion order, so unsorted input is fine.
Converting to UTC before taking the date is essential. For example, 2024-01-01T23:30:00-05:00 is 2024-01-02T04:30:00Z, which falls on January 2 in UTC and not January 1.
Complexity
- Time: O(N) for N events, plus O(R log R) to sort the R qualifying ids.
- Space: O(U) for U distinct users.
Reference solution
from datetime import datetime, timezone
from typing import List
def find_repeat_visitors(events: List[List[str]]) -> List[str]:
first_day = {}
repeat = set()
for user_id, ts in events:
if user_id in repeat:
continue
s = ts.strip()
if s.endswith(("Z", "z")):
s = s[:-1] + "+00:00"
dt = datetime.fromisoformat(s)
if dt.tzinfo is None:
dt = dt.replace(tzinfo=timezone.utc)
day = dt.astimezone(timezone.utc).date()
if user_id in first_day:
if first_day[user_id] != day:
repeat.add(user_id)
del first_day[user_id]
else:
first_day[user_id] = day
return sorted(repeat)