Implement Chat Event Counter
Company: OpenAI
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: easy
Interview Round: Technical Screen
Quick Answer: This question evaluates data structures and algorithms competency, focusing on designing efficient in-memory counters and time-windowed event aggregation for (userId, chatId) pairs; it is categorized under Coding & Algorithms and has a practical implementation focus.
Constraints
- 0 <= len(operations) <= 2 * 10^5
- 0 <= timestamp <= 10^9
- userId and chatId are non-empty strings
- For the same (userId, chatId) pair, processEvent timestamps are non-decreasing
- The 15-minute window is inclusive: [T - 900, T]
Examples
Input: [('processEvent', 'u1', 'c1', 100), ('processEvent', 'u1', 'c1', 200), ('processEvent', 'u1', 'c1', 1000), ('getCount', 'u1', 'c1')]
Expected Output: [3]
Explanation: The latest timestamp for ('u1', 'c1') is 1000, so the window is [100, 1000]. Events at 100, 200, and 1000 are all included.
Input: [('getCount', 'u1', 'c1')]
Expected Output: [0]
Explanation: No events were recorded for this pair, so the count is 0.
Input: [('processEvent', 'u1', 'c1', 10), ('processEvent', 'u1', 'c2', 20), ('processEvent', 'u2', 'c1', 30), ('processEvent', 'u1', 'c1', 1000), ('getCount', 'u1', 'c1'), ('getCount', 'u1', 'c2'), ('getCount', 'u2', 'c1'), ('getCount', 'u2', 'c2')]
Expected Output: [1, 1, 1, 0]
Explanation: Pairs are tracked independently. For ('u1', 'c1'), the latest timestamp is 1000, so its window is [100, 1000] and the earlier event at 10 is excluded.
Input: [('processEvent', 'u1', 'c1', 1), ('processEvent', 'u1', 'c1', 100), ('processEvent', 'u1', 'c1', 901), ('processEvent', 'u1', 'c1', 1801), ('getCount', 'u1', 'c1'), ('getCount', 'u1', 'c1')]
Expected Output: [2, 2]
Explanation: After the latest event at 1801, the window is [901, 1801]. Only timestamps 901 and 1801 remain in range. Repeated getCount returns the same value until a new event arrives.
Input: [('processEvent', 'u1', 'c1', 100), ('processEvent', 'u1', 'c1', 100), ('processEvent', 'u1', 'c1', 1000), ('processEvent', 'u1', 'c1', 1000), ('getCount', 'u1', 'c1')]
Expected Output: [4]
Explanation: Duplicate timestamps are allowed. With latest timestamp 1000, the inclusive window is [100, 1000], so all four events are counted.
Input: []
Expected Output: []
Explanation: There are no operations, so there are no getCount results to return.
Hints
- Track each (userId, chatId) pair independently. A hash map keyed by the pair is a good starting point.
- Because timestamps for the same pair never decrease, a deque can store only the events still inside that pair's latest 15-minute window.