Taro Logo

Count Mentions Per User

Medium
Asked by:
BCG
0 views
Topics:
ArraysStrings

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.

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. How are the events structured and formatted in the input list, and are they guaranteed to be sorted chronologically by timestamp?
  2. What is the exact duration that a user remains offline after receiving an offline status update?
  3. Can multiple offline events or a message event occur for the same user at the exact same timestamp, and if so, how should ties in time be resolved (e.g., does offline take precedence over messages)?
  4. How do user mentions get formatted within a message (e.g., specific prefixes like 'idX' or '@all' / '@here'), and can a single message mention the same user multiple times?
  5. What should be returned if the number of users is zero or if there are no events provided in the input?

Brute Force Solution

Approach

This problem simulates a messaging system that tracks user online statuses and counts mentions per user. Events are processed in chronological order, with offline state changes taking priority over messages occurring at the same timestamp. Each user's mention count is incremented according to the mention type: specific user IDs, all users, or only those currently online.

Here's how the algorithm would work step-by-step:

  1. Sort all events primarily by their integer timestamp in ascending order, and secondarily prioritizing OFFLINE events before MESSAGE events when timestamps tie.
  2. Initialize an array to count mentions for each user and an array to track the timestamp when each user becomes online again.
  3. Iterate through the sorted events and handle OFFLINE events by updating the corresponding user's next online time to the current timestamp plus 60.
  4. Handle MESSAGE events with the 'ALL' token by incrementing the mention count for every user regardless of online status.
  5. Handle MESSAGE events with the 'HERE' token by incrementing mentions only for users whose next online time is less than or equal to the current timestamp.
  6. Handle MESSAGE events containing individual 'id<number>' tokens by parsing each user ID and incrementing their mention count accordingly.
  7. Return the array containing total mentions for each user.

Code Implementation

def count_mentions_per_user(numberOfUsers: int, events: list[list[str]]) -> list[int]:
    # Sort events primarily by timestamp and secondarily so OFFLINE events come before MESSAGE events
    events.sort(key=lambda event: (int(event[1]), 0 if event[0] == "OFFLINE" else 1))
    
    mentions = [0] * numberOfUsers
    next_online_time = [0] * numberOfUsers
    
    for event_type, timestamp_str, data in events:
        current_time = int(timestamp_str)
        # Process offline event by recording when the user will be online again
        if event_type == "OFFLINE":
            user_id = int(data)
            next_online_time[user_id] = current_time + 60
        else:
            # Handle message mentions for all users, online users, or specific user IDs
            if data == "ALL":
                for user_idx in range(numberOfUsers):
                    mentions[user_idx] += 1
            elif data == "HERE":
                for user_idx in range(numberOfUsers):
                    if current_time >= next_online_time[user_idx]:
                        mentions[user_idx] += 1
            else:
                tokens = data.split()
                for token in tokens:
                    target_id = int(token[2:])
                    mentions[target_id] += 1
                    
    # Return the aggregated mention counts for all users
    return mentions

Big(O) Analysis

Time Complexity
O(E log E + E * U + T) – Sorting the events takes O(E log E) time, where E is the number of events. For each event, processing 'ALL' or 'HERE' takes O(U) time where U is numberOfUsers, and processing explicit IDs takes time proportional to the total number of mention tokens T. With the given constraints, this runs well within limits.
Space Complexity
O(U + E) – The state requires O(U) space to track mention counts and online recovery times for each user, plus O(E) auxiliary space used internally to sort the events list.

Optimal Solution

Approach

This solution tracks the number of mentions each user receives across a series of events. We sort events primarily by timestamp and secondarily so that offline status changes are processed before messages. For each message, mentions are incremented according to the token specification, checking users' online status when necessary.

Here's how the algorithm would work step-by-step:

  1. Sort all events primarily by their integer timestamp in ascending order.
  2. Ensure offline events take precedence over message events when timestamps are equal.
  3. Initialize an array to count mentions and another to track when each user becomes online again.
  4. Iterate through each event and update the user's return-to-online time for offline events.
  5. For message events, increment counts for all users on 'ALL', currently online users on 'HERE', or specified users by parsing their IDs.
  6. Return the final array of mention counts.

Code Implementation

def count_mentions(number_of_users: int, events: list[list[str]]) -> list[int]:
    # Sort events by timestamp; process OFFLINE events before MESSAGE events if timestamps tie
    events.sort(key=lambda event: (int(event[1]), 0 if event[0] == "OFFLINE" else 1))
    mention_counts = [0] * number_of_users
    online_at = [0] * number_of_users
    
    for event_type, timestamp_str, content in events:
        current_time = int(timestamp_str)
        # Process offline events by recording the time when the user returns online
        if event_type == "OFFLINE":
            user_id = int(content)
            online_at[user_id] = current_time + 60
        else:
            # Handle message events based on token types ALL, HERE, or individual IDs
            if content == "ALL":
                for user_idx in range(number_of_users):
                    mention_counts[user_idx] += 1
            elif content == "HERE":
                for user_idx in range(number_of_users):
                    if online_at[user_idx] <= current_time:
                        mention_counts[user_idx] += 1
            else:
                tokens = content.split()
                for token in tokens:
                    user_id = int(token[2:])
                    mention_counts[user_id] += 1
                    
    return mention_counts

Big(O) Analysis

Time Complexity
O(E log E + E * U) – Sorting the events takes O(E log E) time, where E is the number of events. For each event, processing tokens or iterating across all U users takes at most O(U) operations, resulting in O(E * U) overall for the event processing loop.
Space Complexity
O(U + E) – We store mention counts and online return times for U users, which takes O(U) space, while sorting the E events requires up to O(E) auxiliary space.

Edge Cases

Users mentioned via the all broadcast keyword
How to Handle:
Increment the mention count for every single user regardless of their online status.
Users mentioned via the here broadcast keyword
How to Handle:
Increment the mention count only for users who are currently online at that timestamp.
Multiple offline events for the same user overlapping or occurring closely
How to Handle:
Update the user's online availability timestamp to the latest offline time plus the mandatory duration.
A message mentions a specific user ID who is currently offline
How to Handle:
Increment the mention count for that user anyway since offline status only affects broadcast mentions.
Events arrive out of chronological order
How to Handle:
Sort the events array primarily by timestamp before processing to ensure correct temporal sequence.
Events occur at the exact same timestamp
How to Handle:
Sort offline events before message events when timestamps match to properly reflect state changes.
Maximum number of users and events scaling up to hundreds of thousands
How to Handle:
Maintain an explicit online availability array and process events in linearithmic time complexity via sorting.
Timestamps exceeding standard integer limits
How to Handle:
Use 64-bit integers for all timestamp calculations to prevent potential overflow issues during large time additions.