KatInterview

Users Active for a Week Straight: Detect 7-Day Streaks in Event Logs

Arrays & HashingAuto-graded · 15 test cases
MediumAuto-gradedArrays & Hashinghashingdatesstreaks

Last updated

Find users whose event log contains at least seven consecutive UTC calendar days of activity, using per-user day deduplication and a sorted streak scan.

Users Active for a Week Straight

You are given a log of view events. Each event is a list [event_id, user_id, timestamp], where:

  • event_id is a unique integer identifying the event,
  • user_id is an integer identifying the user who generated the event,
  • timestamp is a string in ISO 8601 format, for example "2024-03-01 10:15:00". A string may also end in Z or carry an explicit UTC offset such as +00:00.

Return the ids of all users who were active on at least seven calendar days in a row.

Rules

  • A user is active on a calendar day if they have one or more events on that day. Several events on the same day count as a single active day.
  • The calendar day of an event is its date in UTC.
    • A timestamp with a trailing Z or an explicit offset must be converted to UTC before its date is taken.
    • A timestamp with no timezone information is already in UTC.
  • A streak is a run of calendar days where each day is exactly one day after the previous one, with no missing days. Streaks may cross month and year boundaries.
  • A streak longer than seven days qualifies the user, just as a streak of exactly seven does.
  • Each qualifying user appears once in the result, even if they have several qualifying streaks.
  • Return the user ids sorted in ascending order. If no user qualifies, return an empty list.

Constraints

  • 1 <= len(events) <= 10,000,000
  • event_id values are unique.
  • user_id is an integer.
  • Every timestamp string is parseable by Python's datetime.fromisoformat once a trailing Z is replaced with +00:00.

Examples

Example 1

Input: find_users_with_week_streak([[1, 101, '2024-03-01 10:15:00'], [2, 101, '2024-03-01 18:30:00'], [3, 101, '2024-03-02 09:00:00'], [4, 101, '2024-03-03 14:22:00'], [5, 101, '2024-03-04 11:05:00'], [6, 101, '2024-03-05 16:45:00'], [7, 101, '2024-03-06 20:10:00'], [8, 101, '2024-03-07 08:00:00'], [9, 202, '2024-03-01 12:00:00'], [10, 202, '2024-03-02 12:00:00'], [11, 202, '2024-03-04 12:00:00']])

Output: [101]

Hints

Hint 1

Several events on one day should count once, so first reduce each user's events to a set of distinct UTC dates.

Hint 2

Once a user's dates are sorted and distinct, a streak continues exactly when the gap between neighbouring dates is one day; any other gap resets the streak to 1.

Hint 3

You can stop scanning a user as soon as their streak reaches 7, which also guarantees that each user is reported only once.