File: logger-rate-limiter/solution.py

Date: 2026-06-06

Time: 17:24

Logger Rate Limiter — LeetCode 359

Purpose

This file implements the solution for LeetCode 359: Logger Rate Limiter. It provides a Logger class that acts as a message deduplication filter with a 10-second cooldown window. Its single responsibility is answering: "should this message be printed right now, given when it was last printed?"

Key Components

Logger class — A stateful rate limiter with two members:

Patterns

Lazy initialization via dict.get with default — Instead of checking message in self.nextallowed and then branching, the code uses self.nextallowed.get(message, 0). A never-seen message returns 0, which any non-negative timestamp will satisfy. This collapses "first time" and "cooldown expired" into a single code path.

Store-next-allowed instead of store-last-seen — Rather than recording the last timestamp a message was printed and computing timestamp - last >= 10 on each call, it precomputes timestamp + 10 at acceptance time. This trades one subtraction per query for one addition per acceptance — a wash computationally, but it makes the comparison timestamp >= self.next_allowed[message] read more naturally.

Dependencies

Flow

1. Caller creates a Logger() instance — next_allowed starts empty.

2. On each shouldPrintMessage(timestamp, message) call:

The entire decision is a single dict lookup + comparison. O(1) per call, O(n) space where n is the number of distinct messages ever seen.

Invariants

Error Handling

None. The problem contract guarantees valid inputs (non-negative integers, non-null strings, non-decreasing timestamps). The code trusts those guarantees entirely — no validation, no exceptions.

Topics to Explore

Beliefs