C++ 1348.cpp
class TweetCounts {
map<string, map<int, int>> tweets;
public:
void recordTweet(string tweetName, int time) {
tweets[tweetName][time]++;
}
vector<int> getTweetCountsPerFrequency(string freq, string tweetName, int startTime, int endTime) {
auto increment = 60;
if (freq == "hour")
increment = 60*60;
if (freq == "day")
increment = 24*60*60;
auto& times = tweets[tweetName];
vector<int> result;
for (auto current = startTime; current <= endTime; current += increment)
{
auto next = min(current + increment - 1, endTime);
auto from = times.lower_bound(current);
auto to = times.upper_bound(next);
auto count = 0;
for (auto scan = from; scan != to; scan++)
count += scan->second;
result.push_back(count);
}
return result;
}
};
Difficulty
and has an acceptance rate of about 46% (80k+ submissions).
Typical patterns to solve this problem:
- Binary Search
- Design
- Hash Table
- Ordered Set
- Sorting
- String
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided implementation defines a class that stores timestamps for named events and can return the number of occurrences within regular intervals defined by a frequency string. The design relies on nested associative containers to keep the data ordered and to enable efficient range queries.
Data Structure
The core member is a map that associates each event name with another map that records timestamps and their multiplicities.
map<string, map<int, int>> tweets;
The outer map groups data by event name, while the inner map keeps timestamps sorted and aggregates multiple recordings that share the same second. This ordering is crucial for the range-based lookup performed later.
Recording a Tweet
When a new occurrence is reported, the method increments the counter for the exact timestamp inside the inner map.
void recordTweet(string tweetName, int time) {
tweets[tweetName][time]++; // Insert or update the count for `time`
}
Because the inner map automatically creates a key if it does not exist, the code handles the first occurrence of a timestamp without any special case.
Querying Counts per Frequency
The query method translates a textual frequency into a numeric interval length, then iterates over the overall time span, extracting counts for each sub-interval.
Determining the Interval Length
auto increment = 60; // default: minute
if (freq == "hour")
increment = 60*60;
if (freq == "day")
increment = 24*60*60;
The logic defaults to a minute interval and overrides it for hour and day frequencies. The use of auto keeps the type consistent with the integer literals.
Accessing the Relevant Timestamp Map
auto& times = tweets[tweetName];
A reference to the inner map for the requested event name avoids repeated lookups and enables direct iteration.
Scanning Sub-Intervals
The loop steps through the overall range [startTime, endTime] using the computed interval size.
for (auto current = startTime; current <= endTime; current += increment)
{
auto next = min(current + increment - 1, endTime);
auto from = times.lower_bound(current);
auto to = times.upper_bound(next);
auto count = 0;
for (auto scan = from; scan != to; scan++)
count += scan->second;
result.push_back(count);
}
nextcaps the interval atendTimeto avoid overshooting the final segment.lower_boundfinds the first timestamp not less thancurrent.upper_boundfinds the first timestamp greater thannext.- The inner loop aggregates the stored counts for all timestamps that fall inside the current window.
The result vector accumulates the count for each interval in order, matching the expected output format.
Edge Cases Handled
The implementation gracefully manages several boundary conditions:
- When the requested event name has never been recorded,
tweets[tweetName]yields an empty map. The range queries then produce zero counts for every interval because bothlower_boundandupper_boundreturn the same iterator. - If multiple recordings share the same second, the inner map stores the aggregated count, and the inner aggregation loop adds the stored multiplicity, ensuring the total reflects all occurrences.
- The final interval may be shorter than the regular increment. The
mincall adjustsnextso that the window never exceedsendTime, correctly handling a trailing partial segment. - The loop condition
current <= endTimeguarantees that even whenstartTimeequalsendTime, a single interval is processed, returning a count of zero or the appropriate number of tweets for that exact second.
Performance Considerations
The choice of a sorted map for timestamps enables logarithmic lookup for the bounds of each interval. By using lower_bound and upper_bound, the code restricts the inner aggregation loop to only the entries that lie within the current window, avoiding a full scan of all timestamps for the event. This selective traversal reduces the amount of work proportional to the number of intervals rather than the total number of stored timestamps.
Storing the inner map by reference (auto& times) eliminates repeated map lookups across intervals, which saves constant-time overhead. The increment calculation is performed once per query, and the interval size is reused throughout the loop, avoiding redundant computation.
The aggregation of counts within each interval uses a simple integer accumulator, which is efficient in both time and memory. The result vector grows only as needed to hold one entry per interval, matching the number of windows defined by the frequency and the time range.
ELI5 - Simplified Explanation
This code is like a big digital toy box for keeping track of messages. Imagine you have a special notebook where you write down the name of a message and the exact time it was sent. The first part of the code works like a helper who puts these messages into little folders. Each folder has a label for the name of the tweet, and inside that folder, there is a list showing when each message arrived.
The second part of the code is like a librarian who helps count how many messages come in during different pieces of time. First, the librarian checks if you want to look at chunks of time that are one minute, one hour, or even one whole day long. Once the size of the chunk is decided, the librarian walks through the timeline from the start time to the end time. For every chunk, the librarian looks into the specific folder for that tweet name and counts up all the messages that fall within that specific period. After counting everything in one chunk, the librarian moves to the next chunk and does it all over again until reaching the finish line. Every time a count is finished, that number is saved into a growing list that shows exactly how many messages arrived piece by piece.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | |||||||
|---|---|---|---|---|---|---|---|
| author | solutions | ||||||
| www | AlgoMonster | C++ | Python | Java | TS | ||
| WalkCCC | C++ | Python | Java | ||||
| leetcode.ca | C++ | Python | Java | ||||
| Progiez | C++ | Python | Java | ||||
| github | black-shadows | C++ | |||||
| charles-wangkai | Java | ||||||
| everthis | JS | ||||||
| fsq | C++ | ||||||
| JoshCrozier | JS | ||||||
| lkwq007 | Python | ||||||
| lzl124631x | C++ | ||||||
| suxrobGM | C# | ||||||
| varunu28 | Java | ||||||
| wisdompeak | C++ | ||||||
| YuriSpiridonov | Python | ||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||
| WalkCCC | C++, Python, Java | ||||||
| leetcode.ca | C++, Java, Python | ||||||
| Progiez | C++, Java, Python | ||||||
| black-shadows | C++, C++ | ||||||
| charles-wangkai | Java | ||||||
| everthis | JavaScript | ||||||
| fsq | C++ | ||||||
| JoshCrozier | JavaScript | ||||||
| lkwq007 | Python | ||||||
| lzl124631x | C++ | ||||||
| suxrobGM | C# | ||||||
| varunu28 | Java | ||||||
| wisdompeak | C++ | ||||||
| YuriSpiridonov | Python |
Videos
Solved On The Same Day
- problem 464: Can I Win
- problem 729: My Calendar I
- problem 1286: Iterator for Combination
- problem 1387: Sort Integers by The Power Value
- problem 2424: Longest Uploaded Prefix
- problem 327: Count of Range Sum
- problem 699: Falling Squares
- problem 1553: Minimum Number of Days to Eat N Oranges
- problem 1611: Minimum One Bit Operations to Make Integers Zero
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality