Rolling-Window Chat Activity Tracker
Data Structure DesignAuto-graded · 13 test casesLast updated
Build a bounded-memory sliding-window aggregator answering distinct-chat, distinct-user, and message-total queries from an operation log in amortized O(1).
Problem Statement
You are implementing the metrics layer of a messaging product. It measures activity inside a moving time window and answers on-demand questions about that window.
You are given an operation log: a list operations of operation names and a parallel list arguments, where arguments[i] holds the parameters for operations[i]. Replay the log in order and return a list results, one entry per operation.
The tracked entity is configured by the first operation, "__init__", whose single argument is the window length w in seconds. An event recorded at time ts is considered live at query time t exactly when t - w < ts <= t (left boundary exclusive, right boundary inclusive). Recorded event timestamps never decrease over the log; query times may be any non-negative integer, including values far past the last recorded event.
Supported operations and their argument lists:
"__init__"with[w]: creates the tracker with window lengthw. ProducesNone."record_message"with[timestamp, chat_id, user_id]: a message fromuser_idinchat_idat unix timetimestamp. ProducesNone."get_active_chat_count"with[current_time]: number of distinct chats with at least one live message in the window ending atcurrent_time."get_active_user_count"with[current_time]: number of distinct users with at least one live message in any chat."get_active_user_count"with[current_time, chat_id]: number of distinct users with at least one live message specifically inchat_id."get_total_messages"with[current_time]: number of live messages across all chats.
For every query operation, produce the integer result. For "__init__" and "record_message", produce None.
Memory must remain proportional to the currently live window: identifiers whose activity drops to zero must be removed, so a long log full of short-lived identifiers does not grow the state without bound.
Constraints
1 <= w <= 10^6.operationscontains exactly one"__init__"entry, at index0; every other operation comes after it.1 <= len(operations) == len(arguments) <= 2 * 10^5.timestampandcurrent_timeare non-negative integers; recorded timestamps are non-decreasing across the log.- Query times are not necessarily non-decreasing and may precede earlier query times (though not earlier than the window they describe allows being evicted — since eviction is monotone in the timestamps recorded, a query only needs to reflect its own time).
chat_idanduser_idare strings of length1to32.- Aim for amortized
O(1)per operation, withO(E)space whereEis the number of live events.
Examples
Example 1
Input: replay_activity_log(['__init__', 'record_message', 'record_message', 'record_message', 'get_total_messages', 'get_active_chat_count', 'get_active_user_count', 'get_active_user_count', 'get_total_messages', 'get_active_user_count', 'get_active_user_count', 'get_active_chat_count', 'get_total_messages'], [[300], [100, 'c1', 'u1'], [150, 'c1', 'u2'], [200, 'c2', 'u1'], [250], [250], [250], [250, 'c1'], [420], [420, 'c1'], [420], [501], [501]])
Output: [None, None, None, None, 3, 2, 2, 2, 2, 1, 2, 0, 0]
Hints
Hint 1
Recorded timestamps only move forward, so the earliest recorded event is always the next one to expire — a single FIFO queue drained from the front is enough, no heap needed.
Hint 2
Distinct counts need presence structures that shrink on expiry: a per-chat map of user to message count, plus a global map from user to the set of chats where they still have live messages.
Hint 3
Every expiry must undo the recording step exactly: decrement the per-chat user count, drop the user from the user's chat set when it hits zero, remove the chat entirely when it has no users left, and delete any container that becomes empty.
Worked solution
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Since recorded timestamps never decrease, the oldest recorded event is always the one that expires first. That means a single FIFO queue of (timestamp, chat_id, user_id) (a collections.deque) is enough to expire events — no heap or balanced tree is needed.
Around the queue we keep layered reference counts:
chat_users[chat]maps a user to how many of that user's messages in this chat are still live.len(chat_users[chat])is the distinct user count for that chat.user_chats[user]is the set of chats where the user has at least one live message.len(user_chats)is the global distinct user count. It tracks chats per user, not messages, so a user stays globally active while present in any chat and disappears only after the last chat drops them.chat_msgs[chat]counts live messages in the chat;len(chat_msgs)is the active chat count.totalis the number of live messages overall.
Each operation first calls _evict(now), popping from the queue's left while the front timestamp is <= now - w — matching the exclusive left edge of (now - w, now]. Each popped event undoes its recording: decrement the per-chat user count, remove the chat from the user's chat set when it hits zero, remove the chat entirely when it has no users left, and delete any container that becomes empty. Recording evicts relative to the new event's timestamp, then pushes the event and increments the layered counters, adding the chat to the user's set only when it is their first live message there.
Why It Is Correct
After _evict(t), the queue holds exactly the events with timestamp in (t - w, t]. Because timestamps are non-decreasing, stopping at the first in-window event is safe. Each counter equals the count over retained events, and every map key has a positive value. Queries return len of those maps or total, giving exact distinct and total counts. Expiring an event reverses recording exactly, so the invariant is preserved across all operations, and the final result list matches each query in order.
Complexity
- Time: Every event enters and leaves the queue once, with constant work per step. The whole log is
O(N)— amortizedO(1)per call, though a single query may drain several events. - Space:
O(E)whereEis the number of live events; empty containers are deleted so expired identifiers do not accumulate.
Reference Solution
from collections import deque
from typing import List, Optional
class _WindowTracker:
def __init__(self, window_size: int) -> None:
self.w = window_size
self.events = deque()
self.chat_users = {}
self.user_chats = {}
self.chat_msgs = {}
self.total = 0
def _evict(self, now: int) -> None:
cutoff = now - self.w
while self.events and self.events[0][0] <= cutoff:
ts, c, u = self.events.popleft()
self.total -= 1
users = self.chat_users[c]
users[u] -= 1
if users[u] == 0:
del users[u]
chats_for_user = self.user_chats[u]
chats_for_user.discard(c)
if not chats_for_user:
del self.user_chats[u]
if not users:
del self.chat_users[c]
del self.chat_msgs[c]
else:
self.chat_msgs[c] -= 1
def record_message(self, ts: int, c: str, u: str) -> None:
self._evict(ts)
self.events.append((ts, c, u))
self.total += 1
users = self.chat_users.setdefault(c, {})
if u not in users:
users[u] = 0
self.user_chats.setdefault(u, set()).add(c)
users[u] += 1
self.chat_msgs[c] = self.chat_msgs.get(c, 0) + 1
def active_chats(self, now: int) -> int:
self._evict(now)
return len(self.chat_msgs)
def active_users(self, now: int, chat_id=None) -> int:
self._evict(now)
if chat_id is None:
return len(self.user_chats)
return len(self.chat_users.get(chat_id, {}))
def total_messages(self, now: int) -> int:
self._evict(now)
return self.total
def replay_activity_log(operations: List[str], arguments: List[List]) -> List[Optional[int]]:
tracker = None
out = []
for op, args in zip(operations, arguments):
if op == "__init__":
tracker = _WindowTracker(*args)
out.append(None)
elif op == "record_message":
tracker.record_message(*args)
out.append(None)
elif op == "get_active_chat_count":
out.append(tracker.active_chats(*args))
elif op == "get_active_user_count":
out.append(tracker.active_users(*args))
elif op == "get_total_messages":
out.append(tracker.total_messages(*args))
else:
raise ValueError(f"unknown operation: {op}")
return out