Problem Description
Design a logger system that receives a stream of messages with timestamps. For each unique message, it should be printed at most once every 10 seconds. That is, if a message is printed at timestamp t, the same message should not be printed again until t + 10. All messages arrive in chronological (non-decreasing) order.
Key Insights
- Use a hash table (dictionary) to store the most recent timestamp when each message was printed.
- Check if the current timestamp is at least 10 seconds later than the stored timestamp before printing the message.
- The messages are in chronological order, so no need for extra data structures to handle reordering.
- The approach efficiently handles streaming input with constant time lookups.
Space and Time Complexity
Time Complexity: O(1) average per message (dictionary lookup and update)
Space Complexity: O(n) in the worst case, where n is the number of unique messages
Solution
Maintain a hash table where keys are messages and values are the next allowed timestamp when the message can be printed. When a new message arrives with a given timestamp, check:
- If the message is not stored in the hash table, print it and set the allowed timestamp as current timestamp + 10.
- If the current timestamp is greater than or equal to the stored allowed timestamp, update the allowed timestamp and print the message.
- Otherwise, do not print the message. This approach is efficient because it only requires constant time operations per call and uses minimal additional space.