635. Design Log Storage System
Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.
Approach
The core of this problem is to design a log storage system that can store logs with timestamps and retrieve them based on a time range. The retrieval process is complicated by a granularity parameter, which dictates the precision of the time range comparison. For instance, a granularity of "Day" means we should only compare the Year, Month, and Day parts of the timestamps, ignoring Hour, Minute, and Second.
Solution
Design Log Storage System in Python
from typing import List
class LogSystem:
def __init__(self):
# List to store (timestamp, id) tuples
self.logs = []
# Dictionary to map granularity to timestamp prefix length
self.indices = {
"Year": 4,
"Month": 7,
"Day": 10,
"Hour": 13,
"Minute": 16,
"Second": 19
}
def put(self, id: int, timestamp: str) -> None:
# Append the new log entry to the list.
self.logs.append((timestamp, id))
def retrieve(self, start: str, end: str, granularity: str) -> List[int]:
result = []
# Get the length of the prefix based on the granularity.
index = self.indices[granularity]
# Truncate the start and end timestamps to the required precision using slicing.
start_prefix = start[:index]
end_prefix = end[:index]
# Iterate through all stored logs.
for log_timestamp, log_id in self.logs:
# Truncate the log's timestamp.
log_prefix = log_timestamp[:index]
# Python's string comparison is lexicographical, which works perfectly here.
# Check if the log's prefix is within the inclusive range.
if start_prefix <= log_prefix <= end_prefix:
result.append(log_id)
return result
# Your LogSystem object will be instantiated and called as such:
# obj = LogSystem()
# obj.put(id,timestamp)
# param_2 = obj.retrieve(start,end,granularity)
Design Log Storage System in Java
class LogSystem {
private List<Pair<String, Integer>> logs;
private Map<String, Integer> indices;
public LogSystem() {
logs = new ArrayList<>();
indices = new HashMap<>();
indices.put("Year", 4);
indices.put("Month", 7);
indices.put("Day", 10);
indices.put("Hour", 13);
indices.put("Minute", 16);
indices.put("Second", 19);
}
public void put(int id, String timestamp) {
// Store the timestamp and id as a pair.
logs.add(new Pair<>(timestamp, id));
}
public List<Integer> retrieve(String start, String end, String granularity) {
List<Integer> result = new ArrayList<>();
// Get the length of the prefix based on the granularity.
int index = indices.get(granularity);
// Truncate the start and end timestamps to the required precision.
String start_prefix = start.substring(0, index);
String end_prefix = end.substring(0, index);
// Iterate through all stored logs.
for (Pair<String, Integer> log : logs) {
String log_timestamp = log.getKey();
int log_id = log.getValue();
// Truncate the log's timestamp.
String log_prefix = log_timestamp.substring(0, index);
// Perform lexicographical comparison on the prefixes.
if (log_prefix.compareTo(start_prefix) >= 0 && log_prefix.compareTo(end_prefix) <= 0) {
result.add(log_id);
}
}
return result;
}
}
// A simple Pair class, as javafx.util.Pair is not available in standard LeetCode environment
class Pair<K, V> {
private K key;
private V value;
public Pair(K key, V value) {
this.key = key;
this.value = value;
}
public K getKey() {
return key;
}
public V getValue() {
return value;
}
}
/**
* Your LogSystem object will be instantiated and called as such:
* LogSystem obj = new LogSystem();
* obj.put(id,timestamp);
* List<Integer> param_2 = obj.retrieve(start,end,granularity);
*/
Design Log Storage System in C++
class LogSystem {
private:
vector<pair<string, int>> logs;
unordered_map<string, int> indices;
public:
LogSystem() {
indices["Year"] = 4;
indices["Month"] = 7;
indices["Day"] = 10;
indices["Hour"] = 13;
indices["Minute"] = 16;
indices["Second"] = 19;
}
void put(int id, string timestamp) {
// Store the timestamp and id as a pair.
logs.emplace_back(timestamp, id);
}
vector<int> retrieve(string start, string end, string granularity) {
vector<int> result;
// Get the length of the prefix based on the granularity.
int index = indices[granularity];
// Truncate the start and end timestamps to the required precision.
string start_prefix = start.substr(0, index);
string end_prefix = end.substr(0, index);
// Iterate through all stored logs.
for (const auto& log : logs) {
string log_timestamp = log.first;
int log_id = log.second;
// Truncate the log's timestamp.
string log_prefix = log_timestamp.substr(0, index);
// Perform lexicographical comparison on the prefixes.
if (log_prefix >= start_prefix && log_prefix <= end_prefix) {
result.push_back(log_id);
}
}
return result;
}
};
/**
* Your LogSystem object will be instantiated and called as such:
* LogSystem* obj = new LogSystem();
* obj->put(id,timestamp);
* vector<int> param_2 = obj->retrieve(start,end,granularity);
*/
Design Log Storage System in TypeScript
class LogSystem {
private logs: [string, number][];
private indices: Map<string, number>;
constructor() {
this.logs = [];
this.indices = new Map<string, number>([
["Year", 4],
["Month", 7],
["Day", 10],
["Hour", 13],
["Minute", 16],
["Second", 19]
]);
}
put(id: number, timestamp: string): void {
// Store the timestamp and id as a tuple.
this.logs.push([timestamp, id]);
}
retrieve(start: string, end: string, granularity: string): number[] {
const result: number[] = [];
// Get the length of the prefix based on the granularity. '!' asserts it's not undefined.
const index = this.indices.get(granularity)!;
// Truncate the start and end timestamps to the required precision.
const startPrefix = start.substring(0, index);
const endPrefix = end.substring(0, index);
// Iterate through all stored logs.
for (const [logTimestamp, logId] of this.logs) {
// Truncate the log's timestamp.
const logPrefix = logTimestamp.substring(0, index);
// Perform lexicographical comparison on the prefixes.
if (logPrefix >= startPrefix && logPrefix <= endPrefix) {
result.push(logId);
}
}
return result;
}
}
/**
* Your LogSystem object will be instantiated and called as such:
* var obj = new LogSystem()
* obj.put(id,timestamp)
* var param_2 = obj.retrieve(start,end,granularity)
*/
More Medium LeetCode answers
Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.
LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.