Design Log Storage System — Timestamp Range Retrieval

Sanjeev SharmaSanjeev Sharma
2 min read

Advertisement

Problem

Design a log storage system:

  • put(id, timestamp) — store log with string timestamp "2017:01:01:23:59:59"
  • retrieve(s, e, gra) — return all IDs where s <= timestamp <= e at given granularity

Granularities: Year, Month, Day, Hour, Minute, Second — truncate timestamp at specified level.


Key Insight — Truncate and Compare Strings

Map granularity to prefix lengths: Year→4, Month→7, Day→10, Hour→13, Minute→16, Second→19. Truncate all timestamps to that prefix and compare.


Solutions

Python

class LogSystem:
    def __init__(self):
        self.logs = []
        self.gra_map = {'Year': 4, 'Month': 7, 'Day': 10, 'Hour': 13, 'Minute': 16, 'Second': 19}

    def put(self, id: int, timestamp: str) -> None:
        self.logs.append((timestamp, id))

    def retrieve(self, s: str, e: str, gra: str) -> list:
        g = self.gra_map[gra]
        return [lid for ts, lid in self.logs if s[:g] <= ts[:g] <= e[:g]]

JavaScript

class LogSystem {
    constructor() { this.logs=[]; this.g={'Year':4,'Month':7,'Day':10,'Hour':13,'Minute':16,'Second':19}; }
    put(id, ts) { this.logs.push([ts, id]); }
    retrieve(s, e, gra) {
        const g = this.g[gra];
        return this.logs.filter(([ts]) => ts.slice(0,g)>=s.slice(0,g) && ts.slice(0,g)<=e.slice(0,g)).map(x=>x[1]);
    }
}

Java

import java.util.*;
class LogSystem {
    List<long[]> logs = new ArrayList<>();
    Map<String,Integer> gm = Map.of("Year",4,"Month",7,"Day",10,"Hour",13,"Minute",16,"Second",19);
    List<String> ts = new ArrayList<>();
    public void put(int id, String timestamp) { logs.add(new long[]{id}); ts.add(timestamp); }
    public List<Integer> retrieve(String s, String e, String gra) {
        int g = gm.get(gra); List<Integer> res = new ArrayList<>();
        for (int i=0;i<ts.size();i++) {
            String t=ts.get(i).substring(0,g);
            if (t.compareTo(s.substring(0,g))>=0 && t.compareTo(e.substring(0,g))<=0) res.add((int)logs.get(i)[0]);
        }
        return res;
    }
}

C++

#include <vector>
#include <string>
#include <unordered_map>
using namespace std;
class LogSystem {
    vector<pair<string,int>> logs;
    unordered_map<string,int> gm{{"Year",4},{"Month",7},{"Day",10},{"Hour",13},{"Minute",16},{"Second",19}};
public:
    void put(int id, string ts) { logs.push_back({ts, id}); }
    vector<int> retrieve(string s, string e, string gra) {
        int g = gm[gra]; vector<int> res;
        for (auto& [ts, id] : logs) if (ts.substr(0,g)>=s.substr(0,g) && ts.substr(0,g)<=e.substr(0,g)) res.push_back(id);
        return res;
    }
};

C

/* C: array of (timestamp_str, id), strcmp with length limit for granularity */

Advertisement

Sanjeev Sharma

Written by

Sanjeev Sharma

Full Stack Engineer · E-mopro