Problem Description
Design a log storage system that supports inserting log entries with unique IDs and timestamp strings, and retrieving the IDs of all logs whose timestamps fall within a specified range (inclusive). The retrieval is based on a given granularity, i.e. Year, Month, Day, Hour, Minute, or Second, which determines the level of precision for the range query.
Key Insights
- Store logs in a simple data structure such as a list or array.
- Convert the timestamps into strings; due to fixed-length and zero padding, lexicographical string comparisons are valid.
- Use a mapping to determine the slice length for each granularity, e.g. "Year" corresponds to the first 4 characters, "Month" corresponds to the first 7 characters, etc.
- During retrieval, compare the relevant substring of each stored timestamp against the start and end query timestamp slices.
- The inclusive nature of the query simplifies checking conditions.
Space and Time Complexity
Time Complexity: O(N) per retrieval query, where N is the number of logs stored (since each log is checked). In the worst case, all log entries are examined. Space Complexity: O(N) where N is the number of logs stored.
Solution
We implement a LogSystem class that supports putting log entries and retrieving them using a specified granularity.
- Data Structures:
- Use a list/array to store log entries as tuples (or objects) containing the timestamp and log ID.
- A dictionary/map is used to store the mapping from granularity string to the substring index (e.g., "Year" => 4, "Month" => 7, etc.).
- For the put() method, simply append the new log entry into the list.
- For the retrieve() method, compute the substring length based on the provided granularity. Then iterate over all stored logs and compare the sliced timestamp against the sliced start and end query values. If it falls within the bounds, include the log ID in the result.
- Since the timestamps have fixed width with leading zeros, slicing and lexicographical comparisons are both valid and simple.