OpenAI questions

Chat Activity Counter

OpenAIPhone screenMedium

Chat events arrive as a stream, and ChatTracker answers questions about recent activity. A chat is identified by the pair (user_id, chat_id): the same chat_id under two users is two different chats. Time is a whole number of minutes.

Memory must not grow with the length of the event history or with the number of chats ever seen; it follows the events that can still count.

Part 1: Recent message count

Implement:

  • process_event(user_id, chat_id, timestamp) records one message sent in a chat. Returns nothing.
  • get_recent_message(user_id, chat_id) returns how many messages that chat has in the recent window.

The latest time is the largest timestamp among all events processed so far, across every user and chat. A message at time m is recent when latest - m < 15, that is, when m lies in the 15 minutes latest - 14 through latest. The window moves with the latest time of the whole stream, not with the chat that is being asked about.

Return 0 for a chat that has no recent messages, for a chat never seen, and before any event.

  1. Example 1
    init
    []
    operations
    [["process_event",[1,10,0]],["process_event",[1,10,5]],["process_event",[1,10,14]],["get_recent_message",[1,10]],["process_event",[2,20,15]],["get_recent_message",[1,10]],["get_recent_message",[2,20]],["get_recent_message",[1,20]],["get_recent_message",[3,30]]]
    Output
    [null,null,null,3,null,2,1,0,0]

    Why: The messages at 0, 5 and 14 are all within 14 minutes of the latest time 14, so the count is 3. The event at 15 for another chat moves the latest time to 15, which drops the message at 0 (15 minutes old) and leaves 2. Chat 20 of user 2 has 1, and chats that never appeared return 0.

Constraints

  • 1 <= number of calls <= 2 * 10^5
  • 0 <= timestamp <= 10^9, in whole minutes
  • timestamp never decreases from one process_event call to the next (equal timestamps are allowed)
  • user_id and chat_id are integers
Import your own questions
Paste a question you were asked and get a full problem: statement, tests and a checked solution.
Import a question
Chat Activity Counter: OpenAI interview question | LoopCoach