You are building an in-memory, single-threaded analytics service for ChatGPT chat sessions. It ingests a real-time, globally non-decreasing stream of interaction logs and answers recent-count queries efficiently.
Suppose each log records an interaction:
user_id: strchat_id: int(unique per user)timestamp: int(in minutes)
We frequently need the number of interactions for a given (user_id, chat_id) that occurred in the last 15 minutes, defined as the closed interval [T - 14, T], where T is the largest timestamp seen so far in the entire stream.
Implement:
process_event(user_id: str, chat_id: int, timestamp: int)get_num_recent_interactions(user_id: str, chat_id: int) -> int
Assumptions and requirements:
- Events are non-decreasing in timestamp, and no duplicates.
- Log and query volumes are high, so both operations should be efficient.
- Bounded memory (active-window only): you have enough memory for state proportional to the number of chats/events in the last 15 minutes, but not proportional to total historical events or total chats ever seen.
Part 2:
Suppose each event has an additional field:
event_type: str
There are two event types:
interact: user sends a message and receives a response in a chatend: user explicitly ends a chat session
End events may arrive after arbitrary duration or never.
As we process the real-time logs, we want to know the current number of active sessions for a user. A session is active if it has an interact event within the past 15 minutes, and has not received an end event after the latest interact event.
Modify process_event() and support get_active_session_count(user_id: str) -> int.
Example:
tr = SessionTracker()
tr.process_event("u1", 1, 0, "interact")
print(tr.get_active_session_count("u1")) # 1
tr.process_event("u1", 1, 5, "end")
print(tr.get_active_session_count("u1")) # 0
This problem combines a sliding 15-minute window with efficient per-chat state tracking. In Part 1, the goal is to count recent interactions for each (user_id, chat_id) under a globally non-decreasing timestamp stream, which is typically solved with per-key queues or deques that evict expired events lazily. Part 2 adds session activity tracking: a chat is active only if its latest interact event is still within the last 15 minutes and no later end event has been seen, so the solution needs to maintain per-chat status plus a per-user active-session count. The key challenge is achieving fast updates and queries while keeping memory bounded to the active time window.