Skip to main content

Logger Rate Limiter

LeetCode Link

Problem Description​

Visit LeetCode for the full problem description.


Solutions​

Solution 1: C# (Best: 405 ms)​

MetricValue
Runtime405 ms
Memory63.1 MB
Date2022-02-09
Solution
public class Logger {

private Dictionary<string, int> old;
private Dictionary<string, int> latest;
private int init_time = 0;

/** Initialize your data structure here. */
public Logger()
{
old = new Dictionary<string, int>();
latest = new Dictionary<string, int>();
}

/** 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 bool ShouldPrintMessage(int timestamp, string message)
{
if(timestamp>=init_time+10)
{
init_time = timestamp;
old = latest;
latest = new Dictionary<string, int>();
}
if(latest.ContainsKey(message))
{
return false;
}
if(old.ContainsKey(message) && old[message]+10 > timestamp)
return false;

latest.Add(message, timestamp);
return true;
}
}

/**
* Your Logger object will be instantiated and called as such:
* Logger obj = new Logger();
* bool param_1 = obj.ShouldPrintMessage(timestamp,message);
*/
πŸ“œ 1 more C# submission(s)

Submission (2022-02-08) β€” 415 ms, 63.5 MB​

public class Logger {

private Dictionary<string, int> d;
/** Initialize your data structure here. */
public Logger()
{
d = new Dictionary<string, int>();
}

/** 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 bool ShouldPrintMessage(int timestamp, string message)
{
if (d.ContainsKey(message))
{
if (timestamp < d[message] + 10)

return false;
else
{
d[message] = timestamp;
return true;
}
}
else
{
d[message] = timestamp;
return true;
}
}
}

/**
* Your Logger object will be instantiated and called as such:
* Logger obj = new Logger();
* bool param_1 = obj.ShouldPrintMessage(timestamp,message);
*/

Complexity Analysis​

ApproachTimeSpace
SolutionTo be analyzedTo be analyzed