🧭 Do not search for the first 15 minutes. When stuck: re-read the requirements → define I/O → choose the data structure → trace a small example by hand → write code.
You are given a chronological log of user activity. Each entry is a
(timestamp, user) pair, and the timestamps arrive in non-decreasing order.
Implement active_users(logs, window), which reports — at the moment each log
entry occurs — how many distinct users were active during the last window units
of time.
logs = [
(1, "A"),
(2, "B"),
(3, "A"),
(7, "C"),
(8, "A"),
]
(timestamp, user) pair.window is an integer of at least 1.Return a list the same length as the input. The i-th value is the number of
distinct users appearing within the recent window interval, measured from the
i-th entry's timestamp.
active_users(logs, 5)
# [1, 2, 2, 2, 2]
Walking through each result:
(2, 7], so only the entries at 3 and 7 count → A, C → 2(3, 8], so the entries at 3, 7, 8 count → A, C, A → 2With the current timestamp written as t, the interval you inspect is:
(t - window, t]
t — is included.For example with window = 5 and t = 7 the interval is (2, 7], so an entry at
timestamp 2 is excluded while entries at 3, 4, 5, 6, 7 are included.
window = 1 the interval is (t - 1, t], so only entries sharing the
current timestamp can fall inside it.Implement active_users(logs, window).