- Decide the key that represents the information needed later.
- Update its count or stored state while scanning the input.
- Use constant-time expected lookups to detect matches or assemble the result.
Code notes
- 34 lines of Java from the credited upstream file 635.java.
- The implementation visibly relies on sequence storage, hash lookup, ordered lookup.
- 1 loop block detected.
Complexity
Expected hash operations are constant time, but the surrounding scan and the number of stored keys determine total work and memory.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class LogSystem {2 public LogSystem() {3 granularityToIndices.put("Year", 4);4 granularityToIndices.put("Month", 7);5 granularityToIndices.put("Day", 10);6 granularityToIndices.put("Hour", 13);7 granularityToIndices.put("Minute", 16);8 granularityToIndices.put("Second", 19);9 }10 11 public void put(int id, String timestamp) {12 idAndTimestamps.add(new Pair<>(id, timestamp));13 }14 15 public List<Integer> retrieve(String start, String end, String granularity) {16 List<Integer> ans = new ArrayList<>();17 final int index = granularityToIndices.get(granularity);18 final String s = start.substring(0, index);19 final String e = end.substring(0, index);20 21 for (Pair<Integer, String> idAndTimestamp : idAndTimestamps) {22 final String timestamp = idAndTimestamp.getValue();23 final String t = timestamp.substring(0, index);24 if (t.compareTo(s) >= 0 && t.compareTo(e) <= 0)25 ans.add(idAndTimestamp.getKey());26 }27 28 return ans;29 }30 31 private Map<String, Integer> granularityToIndices = new HashMap<>();32 private List<Pair<Integer, String>> idAndTimestamps = new ArrayList<>();33}34