- 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
- 23 lines of Java from the credited upstream file 1348.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 TweetCounts {2 public void recordTweet(String tweetName, int time) {3 tweetNameToTimeCount.putIfAbsent(tweetName, new TreeMap<>());4 tweetNameToTimeCount.get(tweetName).merge(time, 1, Integer::sum);5 }6 7 public List<Integer> getTweetCountsPerFrequency(String freq, String tweetName, int startTime,8 int endTime) {9 final int chunkSize = freq.equals("minute") ? 60 : freq.equals("hour") ? 3600 : 86400;10 int[] counts = new int[(endTime - startTime) / chunkSize + 1];11 TreeMap<Integer, Integer> timeCount = tweetNameToTimeCount.get(tweetName);12 13 for (Map.Entry<Integer, Integer> entry : timeCount.subMap(startTime, endTime + 1).entrySet()) {14 final int index = (entry.getKey() - startTime) / chunkSize;15 counts[index] += entry.getValue();16 }17 18 return Arrays.stream(counts).boxed().collect(Collectors.toList());19 }20 21 private Map<String, TreeMap<Integer, Integer>> tweetNameToTimeCount = new HashMap<>();22}23