Problem 1348

Abstract / Summary

Given a list of tweet timestamps, count how many tweets have each frequency of occurrence per minute.

Note

The full problem description, including helpful examples, can be found on LeetCode.

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;
    }
};
32 lines | 974 bytes | submitted September 29, 2023 | GitHub   tab size 4

Difficulty

This problem is ranked as
easy medium hard

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
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
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.
LeetCode profile | GitHub repo

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);
}
  • next caps the interval at endTime to avoid overshooting the final segment.
  • lower_bound finds the first timestamp not less than current.
  • upper_bound finds the first timestamp greater than next.
  • 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 both lower_bound and upper_bound return 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 min call adjusts next so that the window never exceeds endTime, correctly handling a trailing partial segment.
  • The loop condition current <= endTime guarantees that even when startTime equals endTime, 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.

written by openai gpt

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.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 26 | median = 7 | μ = 7.04 | σ = 0.85

Complexity Analysis

Time: loglinear
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
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
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
24 links | 15 authors | 6 languages

Videos

3 videos   did my crawler come up with invalid videos ? drop me a line.

Solved On The Same Day

5 medium 4 hard
10 solutions   September 29, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • 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