← 返回 rippling 的题目列表Design an In-Memory Logger with Search and Deduplication
类型:online_judge
Implement an in-memory Logger class that stores log messages in insertion order. You do not need to consider persistence, concurrency, distributed logging, or production operational concerns; focus on OOP design and optimization trade-offs for different read/write workloads.
Implement the following core operations:
logger = Logger()
logger.add(message: str) -> None
logger.remove(text: str) -> None
logger.truncate(n: int) -> None
logger.capitalize() -> None
logger.messages() -> list[str]
Use the following semantics for this problem:
add(message): append a message to the internal list; duplicate messages are allowed.
remove(text): remove every occurrence of text from every stored message. If text is empty, make no change.
truncate(n): truncate every message to at most n characters. n >= 0.
capitalize(): uppercase the first character of each non-empty message and leave all remaining characters unchanged.
messages(): return all current messages in insertion order without exposing a mutable reference to internal state.
Then implement these query operations:
logger.search(keywords: list[str]) -> list[str]
logger.unique_messages() -> list[str]
search(keywords): return messages containing every supplied keyword, preserving original log order. Matching is case-sensitive. An empty keyword list matches every message.
unique_messages(): return messages with duplicates removed while preserving the first occurrence and its order. This method must not mutate the stored logs.
Finally, discuss:
How would you optimize if reads (search and unique_messages) greatly outnumber writes?
How would you optimize if writes greatly outnumber reads?
How would the design change if duplicates do not matter?
CLI Input Format
The first line contains an integer q, the number of operations. Each following line is one operation:
ADD <message>
REMOVE <text>
TRUNCATE <n>
CAPITALIZE
SEARCH <keyword1>|<keyword2>|...|<keywordK>
UNIQUE
PRINT
Keywords in SEARCH are separated by |. A SEARCH command with no text after it searches all messages.
Every SEARCH, UNIQUE, and PRINT command outputs one JSON array of strings.
Constraints
1 <= q <= 100,000
The total number of characters across all input messages, removal strings, and keywords is at most 1,000,000.
0 <= n <= 1,000,000.
Example
Input:
9
ADD error: disk full
ADD warning: disk nearly full
ADD error: disk full
SEARCH disk|error
REMOVE disk
TRUNCATE 12
CAPITALIZE
UNIQUE
PRINT
Output:
["error: disk full"]
["Error: full","Warning: nea"]
["Error: full","Warning: nea","Error: full"]
Example
Input
6
ADD hello world
ADD hello logger
SEARCH hello
REMOVE hello
PRINT
UNIQUE
Output
["hello world", "hello logger"]
["world", "logger"]
["world", "logger"]