OpenAI VO 面试真题解析:最近 15 分钟交互统计与活跃会话追踪

14次阅读
没有评论

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: str
  • chat_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 chat
  • end: 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

这道题本质上是一个“滑动时间窗口 + 哈希表 / 队列”的设计题。第一部分要求在时间戳单调不减的前提下,快速统计某个 (user_id, chat_id) 在最近 15 分钟内的交互次数,最自然的做法是为每个会话维护一个按时间递增的队列,并在查询或写入时把窗口外的旧事件弹出,从而把单次操作控制在均摊 O(1)。第二部分在此基础上加入 session 状态:除了最近一次 interact 是否仍在 15 分钟窗口内,还要判断它之后是否出现了 end 事件,因此可以为每个 chat 额外记录“最新交互时间”和“是否已结束”的状态,再结合用户维度维护活跃会话数。整体重点是用局部状态替代全量历史,满足高频读写和有界内存的要求。

正文完
 0