A solution that only keeps part of the messages


  • 22
    S

    A typical (accepted) solution is to keep a hash map of String that maps to the recent time stamp.
    But this way, it needs to keep the record of the entire messages, even when the message is rare.

    Alternatively, I keep a heap to get rid of the old message and set of String to keep the recent messages only. This approach would make sense when the number of logs within 10 minutes time window is not too large and when we have lots of different messages.

    class Log {
        int timestamp;
        String message;
        public Log(int aTimestamp, String aMessage) {
            timestamp = aTimestamp;
            message = aMessage;
        }
    }
    
    public class Logger {
        PriorityQueue<Log> recentLogs;
        Set<String> recentMessages;   
        
        /** Initialize your data structure here. */
        public Logger() {
            recentLogs = new PriorityQueue<Log>(10, new Comparator<Log>() {
                public int compare(Log l1, Log l2) {
                    return l1.timestamp - l2.timestamp;
                }
            });
            
            recentMessages = new HashSet<String>();
        }
        
        /** 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 (recentLogs.size() > 0)   {
                Log log = recentLogs.peek();
                // discard the logs older than 10 minutes
                if (timestamp - log.timestamp >= 10) {
                    recentLogs.poll();
                    recentMessages.remove(log.message);
                } else 
                	break;
            }
            boolean res = !recentMessages.contains(message);
            if (res) {
                recentLogs.add(new Log(timestamp, message));
                recentMessages.add(message);
            }
            return res;
        }
    }
    /**
     * Your Logger object will be instantiated and called as such:
     * Logger obj = new Logger();
     * boolean param_1 = obj.shouldPrintMessage(timestamp,message);
     */

  • 27
    A

    @sculd Made the same way, but a bit simpler as you don't need priority queue here - all messages seem to come in non-descending order, so it looks much conciser:

    public class Logger {
        Queue<Tuple> q = new ArrayDeque<>();
        Set<String> dict = new HashSet<>();
      
        public Logger() {}
        
        public boolean shouldPrintMessage(int timestamp, String message) {
            while (!q.isEmpty() && q.peek().t <= timestamp - 10) {
                Tuple next = q.poll();
                dict.remove(next.msg);
            }
            if (!dict.contains(message)) {
                q.offer(new Tuple(timestamp, message));
                dict.add(message);
                return true;
            }
            return false;
        }
        private static class Tuple {
            int t; 
            String msg;
            public Tuple(int t, String msg) {
                this.t = t;
                this.msg = msg;
            }
        }
    }
    

  • 0
    S

    @anton4 That assumption makes sense :full_moon_with_face:


  • 0
    S

    It seems your code wont update the timestamp of same message in 10 minutes.
    For example, if we have following case:
    1: a
    5: a
    11: a

    With your code, at timestamp 11, "a" will be removed from the recentMessages and the return is true.


  • 0
    E

    @scott.shao.5
    Yes "a" will be removed, but it will be added again in the if(res){...} part

    And my C++ version here

    class Logger {
    public:
        Logger() {
            
        }
        
        bool shouldPrintMessage(int timestamp, string message) {
            while( !pq.empty() ){
                auto p = pq.front();
                if( timestamp - p.first >= 10 ){  // pop off old message
                    pq.pop();
                    map.erase(p.second);
                }
                else break;
            }
            if( map.insert(message).second ){  // if insert() success, it will return true
                pq.emplace(timestamp, message);
                return true;
            }
            return false;
        }
        
    private:
        queue<pair<int, string>> pq; // since timestamp is in non-descending order, we can use queue
        unordered_set<string> map;
    };
    

Log in to reply
 

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