A usable solution for a Logger. Use message queue of a 10 seconds window.

  • 0

    The top solution is really elegant.

    However, for a Logger, we have to consider its volume. We don't want its space blew up.

    We need keep a window of 10 seconds. Remove messages older than 10 seconds.

    Share my simple solution, nothing fancy.

    public class Logger {

    // Algo thinking Queue
    // time = O(N)
    class TimeMsg {
        int timestamp;
        String msg;
        public TimeMsg(int timestamp, String msg) {
            this.timestamp = timestamp;
            this.msg = msg;
    /** Initialize your data structure here. */
    private static final int MAX_TIME_WINDOW = 10;
    Queue<TimeMsg> msgQueue;
    public Logger() {
        msgQueue = new LinkedList<>();
    /** Returns true if the message should be printed in the given timestamp, otherwise returns false.
        If this method returns false, the message will not be printed.
        The timestamp is in seconds granularity. */
    public boolean shouldPrintMessage(int timestamp, String message) {
        while (!msgQueue.isEmpty() && timestamp - msgQueue.peek().timestamp >= MAX_TIME_WINDOW) {
        Iterator<TimeMsg> iter = msgQueue.iterator();
        while (iter.hasNext()) {
            TimeMsg tm = iter.next();
            if (tm.msg.equals(message)) return false;
        msgQueue.offer(new TimeMsg(timestamp, message));
        return true;


Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.