Suppress repeat log messages printed within 10 seconds of their last printed occurrence
MongoDBSoftware Engineer · OtherLast updated
Coding practice question: process a time-ordered stream of log messages and decide which ones are printed when the same text may print at most once every 10 seconds. It tests tracking state across a stream, exact boundary handling at the 10-second mark, and correctly ignoring suppressed events.
A logging component receives a stream of messages, each with an arrival timestamp in seconds. To keep the output readable, a message is printed only if the same message text has not been printed during the previous 10 seconds. Given the stream in arrival order, return, for each event, whether it is printed.
Function Signature
def should_print_messages(timestamps: list[int], messages: list[str]) -> list[bool]:
Rules
- Events are processed in order;
timestamps[i]andmessages[i]describe eventi. - The first occurrence of any message text is always printed.
- If a message text was last printed at time
t, a later event with the same text is printed only if its timestamp is at leastt + 10. - Only printed events count: a suppressed event does not change when that message may print again.
- Different message texts are independent of each other, and several events may share a timestamp.
- Two events carry the same message exactly when their strings are identical.
- The result has the same length as the input; entry
iisTrueif eventiis printed andFalseotherwise.
Constraints
1 <= len(timestamps) == len(messages) <= 10^40 <= timestamps[i] <= 10^9, and timestamps are non-decreasing1 <= len(messages[i]) <= 30- Messages contain only lowercase English letters and digits.
Examples
Example 1
timestamps = [0, 4, 9, 10, 10, 15]
messages = ["disk", "cpu", "disk", "disk", "cpu", "cpu"]
output = [True, True, False, True, False, True]
disk prints at 0, is suppressed at 9, and prints again at 10. cpu prints at 4, is suppressed at 10, and prints again at 15; the earliest time it could have printed again was 14.
Example 2
timestamps = [5, 12, 15]
messages = ["a", "a", "a"]
output = [True, False, True]
The suppressed event at 12 does not push the next allowed time beyond 15.
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.