- Define the priority key and whether the smallest or largest item should lead.
- Push each candidate when it becomes eligible.
- Discard stale entries when necessary and process the best live candidate.
Code notes
- 66 lines of C++ from the credited upstream file 3433.cpp.
- The implementation visibly relies on sequence storage, work queue.
- 6 loop blocks detected.
Complexity
Count heap pushes and pops; each normally contributes a logarithmic factor in the heap size.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1struct OfflineUser {2 int returnTimestamp;3 int userId;4 bool operator>(const OfflineUser& other) const {5 return returnTimestamp > other.returnTimestamp;6 }7};8 9class Solution {10 public:11 vector<int> countMentions(int numberOfUsers, vector<vector<string>>& events) {12 vector<int> ans(numberOfUsers);13 vector<int> online(numberOfUsers, true);14 15 priority_queue<OfflineUser, vector<OfflineUser>, greater<>> offlineQueue;16 int allMentionsCount = 0;17 18 ranges::sort(events, ranges::less{}, [](const vector<string>& event) {19 const int timestamp = stoi(event[1]);20 const char eventType = event[0][0];21 return pair<int, char>{timestamp, -eventType};22 });23 24 for (const vector<string>& event : events) {25 const string eventType = event[0];26 const int timestamp = stoi(event[1]);27 28 while (!offlineQueue.empty() &&29 offlineQueue.top().returnTimestamp <= timestamp)30 online[offlineQueue.top().userId] = true, offlineQueue.pop();31 if (eventType == "MESSAGE") {32 const string mentionsString = event[2];33 if (mentionsString == "ALL") {34 ++allMentionsCount;35 } else if (mentionsString == "HERE") {36 for (int userId = 0; userId < numberOfUsers; ++userId)37 if (online[userId])38 ++ans[userId];39 } else {40 for (const int userId : getUserIds(mentionsString))41 ++ans[userId];42 }43 } else if (eventType == "OFFLINE") {44 const int userId = stoi(event[2]);45 online[userId] = false;46 47 offlineQueue.emplace(timestamp + 60, userId);48 }49 }50 51 52 for (int userId = 0; userId < numberOfUsers; ++userId)53 ans[userId] += allMentionsCount;54 return ans;55 }56 57 private:58 vector<int> getUserIds(const string& s) {59 vector<int> integers;60 istringstream iss(s);61 for (string id; iss >> id;)62 integers.push_back(stoi(id.substr(2)));63 return integers;64 }65};66