Skip to main content

Count Mentions Per User - Solution & Explanation

MediumArrayMathSortingSimulation14 min readAsked at: Microsoft, Visa, Bcg +1
Practice this problem

Problem Statement

You are given an integer numberOfUsers representing the total number of users and an array events of size n x 3.

Each events[i] can be either of the following two types:

  1. Message Event: ["MESSAGE", "timestampi", "mentions_stringi"]
    • This event indicates that a set of users was mentioned in a message at timestampi.
    • The mentions_stringi string can contain one of the following tokens:
      • id<number>: where <number> is an integer in range [0,numberOfUsers - 1]. There can be multiple ids separated by a single whitespace and may contain duplicates. This can mention even the offline users.
      • ALL: mentions all users.
      • HERE: mentions all online users.
  2. Offline Event: ["OFFLINE", "timestampi", "idi"]
    • This event indicates that the user idi had become offline at timestampi for 60 time units. The user will automatically be online again at time timestampi + 60.

Return an array mentions where mentions[i] represents the number of mentions the user with id i has across all MESSAGE events.

All users are initially online, and if a user goes offline or comes back online, their status change is processed before handling any message event that occurs at the same timestamp.

Note that a user can be mentioned multiple times in a single message event, and each mention should be counted separately.

 

Example 1:

Input: numberOfUsers = 2, events = [["MESSAGE","10","id1 id0"],["OFFLINE","11","0"],["MESSAGE","71","HERE"]]

Output: [2,2]

Explanation:

Initially, all users are online.

At timestamp 10, id1 and id0 are mentioned. mentions = [1,1]

At timestamp 11, id0 goes offline.

At timestamp 71, id0 comes back online and "HERE" is mentioned. mentions = [2,2]

Example 2:

Input: numberOfUsers = 2, events = [["MESSAGE","10","id1 id0"],["OFFLINE","11","0"],["MESSAGE","12","ALL"]]

Output: [2,2]

Explanation:

Initially, all users are online.

At timestamp 10, id1 and id0 are mentioned. mentions = [1,1]

At timestamp 11, id0 goes offline.

At timestamp 12, "ALL" is mentioned. This includes offline users, so both id0 and id1 are mentioned. mentions = [2,2]

Example 3:

Input: numberOfUsers = 2, events = [["OFFLINE","10","0"],["MESSAGE","12","HERE"]]

Output: [0,1]

Explanation:

Initially, all users are online.

At timestamp 10, id0 goes offline.

At timestamp 12, "HERE" is mentioned. Because id0 is still offline, they will not be mentioned. mentions = [0,1]

 

Constraints:

  • 1 <= numberOfUsers <= 100
  • 1 <= events.length <= 100
  • events[i].length == 3
  • events[i][0] will be one of MESSAGE or OFFLINE.
  • 1 <= int(events[i][1]) <= 105
  • The number of id<number> mentions in any "MESSAGE" event is between 1 and 100.
  • 0 <= <number> <= numberOfUsers - 1
  • It is guaranteed that the user id referenced in the OFFLINE event is online at the time the event occurs.

Approach Overview

Problem Overview: You receive a sequence of events where users can mention other users. The task is to compute how many times each user gets mentioned. The main challenge is that events must be processed in the correct chronological order and different event types can change how mentions are counted.

Approach 1: Direct Simulation (Naive) (Time: O(n * m), Space: O(m))

The most straightforward strategy is to iterate through the events and simulate the system exactly as described. For each event, parse the mention information and update a counter array or hash map for the mentioned users. If an event references multiple users, iterate through each referenced ID and increment their counters. This works but becomes inefficient when mention rules require repeatedly checking many users (for example broadcasting to all users or evaluating conditions across the entire user list). Because each event can trigger operations over many users, the worst‑case runtime grows to O(n * m) where n is the number of events and m is the number of users.

Approach 2: Sorting + Simulation (Time: O(n log n), Space: O(n + m))

A better approach sorts all events by their timestamp first. This guarantees that mentions are processed in the exact order they occur. After sorting, iterate through the events once and simulate the system state. Maintain a data structure such as an array or hash map to store the mention count for each user. When processing an event, parse the mention tokens and update counts immediately. Sorting ensures that earlier actions always affect later ones correctly, which avoids complicated backtracking logic.

This approach relies on a combination of sorting and step‑by‑step simulation. Each event is processed once after sorting, so the dominant cost is the sort itself: O(n log n). Mention updates are constant time using array indexing or hash lookups, which keeps the simulation efficient even when many users exist. Storing counts and event data requires O(n + m) space.

The key insight is that chronological ordering removes ambiguity. Once events are sorted, the problem becomes a deterministic scan of the event list. This pattern appears frequently in problems combining array processing with time‑based state updates.

Recommended for interviews: The sorting + simulation approach is the expected solution. Interviewers want to see that you first enforce chronological order and then maintain a simple state while scanning the events. Explaining the naive simulation briefly shows you understand the baseline, but implementing the sorted simulation demonstrates stronger algorithmic judgment and cleaner complexity.

Solution

We sort the events in ascending order of timestamps. If the timestamps are the same, we place OFFLINE events before MESSAGE events.

Then we simulate the occurrence of events, using the online_t array to record the next online time for each user and a variable lazy to record the number of mentions that need to be applied to all users.

We traverse the event list and handle each event based on its type:

  • If it is an ONLINE event, we update the online_t array.
  • If it is an ALL event, we increment lazy by one.
  • If it is a HERE event, we traverse the online_t array. If a user's next online time is less than or equal to the current time, we increment that user's mention count by one.
  • If it is a MESSAGE event, we increment the mention count of the mentioned user by one.

Finally, if lazy is greater than 0, we add lazy to the mention count of all users.

The time complexity is O(n + m times log m log M + L), and the space complexity is O(n). Here, n and m are the total number of users and events, respectively, while M and L are the maximum value of the timestamps and the total length of all mentioned strings, respectively.

Code

Python

Java

C++

Go

TypeScript

Rust

Try this approach in the editor →

Detailed Complexity Analysis

ApproachTimeSpaceWhen to Use
Direct Simulation (Naive)O(n * m)O(m)Small input sizes or when mention rules require scanning all users
Sorting + SimulationO(n log n)O(n + m)General case where events must be processed chronologically

Video Solution

Count Mentions Per User | Simple | Straight Forward Explanation | Dry Run | Leetcode 3433 | MIKcodestorywithMIK5,692 views views

Watch 9 more video solutions →

Frequently Asked Questions

Is Count Mentions Per User easy or hard?
Count Mentions Per User is considered a Medium difficulty problem. The implementation is straightforward once events are processed in chronological order, but recognizing the need to sort and correctly simulate the mention rules adds moderate complexity.
Count Mentions Per User Python/Java solution
Most implementations first sort the events and then iterate through them while updating a mention counter array or map. Python often uses lists and dictionaries, while Java uses arrays or HashMap. The same sorting + simulation strategy works in C++, Go, TypeScript, and Rust.
How to solve Count Mentions Per User in O(n)?
Pure O(n) time is generally not achievable if events are not already sorted by timestamp. The common solution sorts events first and then performs a linear simulation. If the input is guaranteed to be pre‑sorted chronologically, the algorithm becomes a single O(n) scan with constant‑time mention updates.
What is the best approach for Count Mentions Per User?
The most effective solution sorts the events by timestamp and then simulates them sequentially. Sorting guarantees chronological correctness while a simple counter structure tracks mentions for each user. This approach runs in O(n log n) time due to sorting and uses O(n + m) space for events and mention counts.
Is Count Mentions Per User asked at Google/Amazon/Meta?
Problems combining event ordering and simulation patterns appear frequently in interviews at companies like Google, Amazon, and Meta. While this exact question may vary, the underlying concepts—sorting events, maintaining state, and processing sequential updates—are common interview topics.
What data structure is used in Count Mentions Per User?
The solution typically uses arrays or hash maps to track mention counts per user. Arrays provide O(1) indexing when user IDs are bounded, while hash maps work well when IDs are sparse. The algorithm also relies on sorting the event list before simulation.
What is the time complexity of Count Mentions Per User?
The optimal approach runs in O(n log n) time. The cost comes from sorting the events by timestamp before processing them. After sorting, the simulation step processes each event once, which is O(n). Space complexity is typically O(n + m).

Ready to solve this problem?

Practice Count Mentions Per User with our built-in code editor and test cases.

Practice on FleetCode