LeetCode solutions

3721. Count Mentions Per User

My accepted Python solution to LeetCode problem 3721, Count Mentions Per User, running in 51ms.

  • Difficulty: Medium
  • Python
  • Runtime 51ms
  • Memory 17.8MB

Read the problem on LeetCode View on GitHub

Python

Accepted on LeetCode — runtime 51ms, memory 17.8MB, accepted 2025-12-30.

python
class Solution:
    def countMentions(self, numberOfUsers: int, events: List[List[str]]) -> List[int]:
        mentions = [0] * numberOfUsers
        # Track when each user comes back online (0 = already online)
        online_at = [0] * numberOfUsers
        
        # Sort events by timestamp, OFFLINE before MESSAGE if same timestamp
        events = sorted(events, key=lambda e: (int(e[1]), 0 if e[0] == "OFFLINE" else 1))
        
        for event in events:
            event_type = event[0]
            timestamp = int(event[1])
            
            if event_type == "OFFLINE":
                user_id = int(event[2])
                online_at[user_id] = timestamp + 60
            else:  # MESSAGE
                mention_str = event[2]
                
                if mention_str == "ALL":
                    for i in range(numberOfUsers):
                        mentions[i] += 1
                elif mention_str == "HERE":
                    for i in range(numberOfUsers):
                        if online_at[i] <= timestamp:
                            mentions[i] += 1
                else:
                    # Parse individual ids
                    ids = mention_str.split()
                    for id_str in ids:
                        if id_str.startswith("id"):
                            user_id = int(id_str[2:])
                            mentions[user_id] += 1
        
        return mentions

Source