← 返回 openai 的题目列表Implement an in-memory TTL cache (optionally LRU)
类型:online_judge
Problem: Implement an in-memory TTL cache (optionally LRU)
Implement an in-memory TTLCache that supports per-key expiration (TTL) and returns None for expired items.
Required APIs
set(key: str, value: str, ttl_ms: int, now_ms: int) -> None
Store key=value at now_ms with expiration at now_ms + ttl_ms.
get(key: str, now_ms: int) -> Optional[str]
Return value if present and not expired; otherwise None.
delete(key: str) -> None
Optional extensions:
Add capacity and evict by LRU when exceeding capacity.
Add cleanup(now_ms) to proactively remove expired items.
Make it thread-safe using Lock/RLock.
Constraints
ttl_ms can be 0 (immediate expiry).
Re-setting the same key overwrites both value and ttl.
Example
set("a","x", 100, 0)
get("a", 50) → "x"
get("a", 150) → None
Implement it and include tests for edge cases.
Example
Input
set a x 100 0
get a 50
get a 150
Output
x
None