KatInterview

Count Active Users in Trailing Time Window

Heaps, Sorting & SearchAuto-graded · 24 test cases
MediumAuto-gradedHeaps, Sorting & Searchbinary-searchtime-seriessliding-window

Last updated

Tests binary search on sorted lists to efficiently count distinct entities with at least one event in a sliding time range.

You are given activity logs for multiple users. Each user has a chronologically ordered list of event timestamps (in seconds). Your task is to determine how many distinct users had at least one event during a specific trailing time window.

Write a function that takes:

  • events: A list where events[i] contains all event timestamps for user i, sorted in ascending order
  • query_time: A timestamp in seconds

Return the count of distinct users who had at least one event in the inclusive time range [query_time - 86400, query_time] (the 24-hour period ending at query_time).

Notes:

  • 86400 seconds equals 24 hours
  • Both endpoints of the time window are inclusive
  • Events occurring after query_time should be ignored
  • Each user contributes at most 1 to the count, regardless of how many events they had in the window
  • Event lists may be empty

Constraints

  • 0 <= len(events) <= 10^5 (number of users)
  • 0 <= len(events[i]) <= 10^5 (events per user)
  • 0 <= events[i][j] <= 10^9 (timestamp values)
  • events[i] is sorted in ascending order
  • 0 <= query_time <= 10^9

Examples

Example 1

Input: count_active_users([[100, 200, 300], [150, 250], [400]], 300)

Output: 2

Example 2

Input: count_active_users([[0, 86400], [1, 86401], [500]], 86400)

Output: 3

Example 3

Input: count_active_users([], 100000)

Output: 0

Example 4

Input: count_active_users([[10, 20], [20, 30], [30]], 30)

Output: 3

Hints

Hint 1

For each user, you need to check if any timestamp falls within the window [query_time - 86400, query_time]. Since the timestamps are sorted, can you do better than scanning all of them?

Hint 2

Use binary search to find the boundaries of the valid range. bisect_left and bisect_right from Python's bisect module can help locate the first and last valid timestamps efficiently.

Hint 3

If bisect_left(timestamps, window_start) gives index L and bisect_right(timestamps, query_time) gives index R, then the user was active if L < R. Why does this work?