Chat Activity Tracker with a Rolling 15-Minute Window
Data Structure DesignAuto-graded · 22 test casesLast updated
Simulate a chat activity tracker with a closed rolling window, touch/close liveness rules, and out-of-order events, using bounded-memory eviction.
You are simulating an in-memory, single-threaded service that tracks chat activity. It processes a list of operations in order and reports the results of the queries.
Events
Each event has four fields:
user(string): the user who owns the chat.chat(int): a chat id that is unique only within its user, so a chat is identified by the pair(user, chat).ts(int): the event time in whole minutes.kind(string): either"touch"or"close".
The window
Let T be the largest ts seen so far across all ingested events from all users. The active window is the closed interval [T - 14, T]. For example, if T = 20, the window is [6, 20], and an event at minute 6 still counts.
Events can arrive out of order, so an event's ts may be smaller than T. T never decreases. An event whose ts falls below T - 14 is outside the window and has no effect. An event can also fall out of the window later, when another event moves T forward.
Operations
operations is a list of operation names and arguments is a parallel list holding each operation's arguments. Process them in order.
"ingest"with arguments[user, chat, ts, kind]: record one event and updateTfirst. It produces no output."count_recent"with arguments[user, chat]: output the number of touch events of that chat whosetsis in[T - 14, T]. Close events are not counted. Several touches with the sametseach count separately. Output0for an unknown chat or if nothing has been ingested yet."count_live"with arguments[user]: output the number of that user's chats that are live right now. Output0for an unknown user or if nothing has been ingested yet.
Live chats
A chat is live if and only if both conditions hold:
- It has at least one touch with
tsin[T - 14, T]. - There is no close for that chat with a
tsstrictly greater than the chat's latest touchts.
The comparison uses timestamps, never arrival order. A close with the same ts as the latest touch does not end the chat. A later touch with a ts at least as large as every close reactivates a closed chat. Closes whose ts has fallen out of the window can be ignored, because they can never be strictly greater than a touch that is still in the window.
Output
Return a list of integers containing the results of every count_recent and count_live operation, in the order the operations appear. ingest adds nothing to the list.
Constraints
operationsandargumentshave the same length, and every operation name is one of the three above.- Every
ingestprovides all four arguments, withkindeither"touch"or"close". - Timestamps are integers and may arrive in any order, but
Tis defined as the running maximum. - Memory should stay proportional to the events inside the current window, not to the whole history.
- Aim for efficient ingestion and queries (roughly logarithmic ingestion, and queries that cost at most the number of the queried user's recently active chats).
Examples
Example 1
Input: run_chat_tracker(['ingest', 'count_recent', 'count_live', 'ingest', 'count_live', 'ingest', 'count_live'], [['alice', 1, 2, 'touch'], ['alice', 1], ['alice'], ['alice', 1, 8, 'close'], ['alice'], ['alice', 1, 8, 'touch'], ['alice']])
Output: [1, 1, 0, 1]
Example 2
Input: run_chat_tracker(['ingest', 'ingest', 'count_live', 'ingest', 'count_live', 'count_recent'], [['alice', 1, 10, 'close'], ['alice', 1, 7, 'touch'], ['alice'], ['alice', 1, 12, 'touch'], ['alice'], ['alice', 1]])
Output: [0, 1, 2]
Hints
Hint 1
Keep per-chat state small: a map from timestamp to touch count, plus only the largest close timestamp. Older closes can never matter.
Hint 2
Because events can arrive out of order, use a min-heap keyed by timestamp to evict everything older than T - 14 whenever T advances, and drop chats that become empty.
Hint 3
A chat is live exactly when it has some touch left in the window and its largest close is not strictly greater than its largest touch. The window holds at most 15 distinct timestamps, so checking this per chat is cheap.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Per chat (user, chat) we keep only what the rules need:
- a dictionary mapping each touch timestamp to how many touches happened at it;
- the largest close timestamp seen for the chat (smaller closes can never be strictly greater than a touch when the larger one is not).
We also keep an index from each user to their chats that currently have state, and a global min-heap of (ts, kind, user, chat) for every stored event.
Ingest. Update T to the running maximum, then compute cutoff = T - 14. Pop every heap entry with ts < cutoff and remove the matching touch bucket or close value. Delete a chat from the user's index once it has no touches and no close. After eviction, an incoming event is stored only if ts >= cutoff, since an older event is outside the window already. A stored event is also pushed on the heap.
count_recent. Return the sum of the touch counts for the chat. Eviction has already removed everything outside the window, and closes are never counted.
count_live. Walk the user's chats that still have state. A chat is live if it has at least one touch and either has no close or its close timestamp is at most its largest touch timestamp. The window holds at most 15 distinct timestamps, so this check is constant time per chat.
Why it is correct
T only grows, so an event outside the window can never return, and evicting or ignoring it is safe. Liveness is defined purely by timestamps, so late arrivals are handled naturally: a late close with a larger timestamp than the latest touch ends the chat, and a late touch with a timestamp at least as large as every close reactivates it. The strict comparison (close > latest touch ends it) means an equal timestamp leaves the chat live. Expired closes are safe to drop, since they are older than every touch still in the window.
Complexity
ingest: O(log n) amortized, where n is the number of stored events, because each event is pushed and popped once.count_recent: O(1) per touch bucket sum, at most 15 buckets.count_live: O(c), where c is the number of the user's chats with events in the window.- Memory: O(number of events inside the current window), because eviction runs on every ingest.
Reference solution
import heapq
from collections import defaultdict
from typing import List
def run_chat_tracker(operations: List[str], arguments: List[List]) -> List[int]:
current_max = None
touches = {} # (user, chat) -> {ts: count}
closes = {} # (user, chat) -> largest close ts in window
chats_by_user = defaultdict(set)
heap = [] # (ts, kind_code, user, chat); kind_code 0=touch, 1=close
results = []
def evict(cutoff):
while heap and heap[0][0] < cutoff:
ts, code, user, chat = heapq.heappop(heap)
key = (user, chat)
if code == 0:
per_ts = touches.get(key)
if per_ts is not None:
per_ts.pop(ts, None)
if not per_ts:
del touches[key]
else:
if closes.get(key) == ts:
del closes[key]
if key not in touches and key not in closes:
chats_by_user[user].discard(chat)
if not chats_by_user[user]:
del chats_by_user[user]
def is_live(key):
per_ts = touches.get(key)
if not per_ts:
return False
close_ts = closes.get(key)
return close_ts is None or close_ts <= max(per_ts)
for op, args in zip(operations, arguments):
if op == "ingest":
user, chat, ts, kind = args
current_max = ts if current_max is None else max(current_max, ts)
cutoff = current_max - 14
evict(cutoff)
if ts >= cutoff:
key = (user, chat)
if kind == "touch":
per_ts = touches.setdefault(key, {})
per_ts[ts] = per_ts.get(ts, 0) + 1
heapq.heappush(heap, (ts, 0, user, chat))
else:
if key not in closes or ts > closes[key]:
closes[key] = ts
heapq.heappush(heap, (ts, 1, user, chat))
chats_by_user[user].add(chat)
elif op == "count_recent":
user, chat = args
per_ts = touches.get((user, chat))
results.append(sum(per_ts.values()) if per_ts else 0)
elif op == "count_live":
user = args[0]
total = 0
for chat in chats_by_user.get(user, ()):
if is_live((user, chat)):
total += 1
results.append(total)
else:
raise ValueError("unknown operation")
return results