Skip to content

Commit 7566484

Browse files
committed
Time: 63 ms (32.7%), Space: 18 MB (79.09%) - LeetHub
1 parent ef24efc commit 7566484

File tree

1 file changed

+64
-0
lines changed

1 file changed

+64
-0
lines changed
Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
# time complexity: O(n^2)
2+
# space complexity: O(n)
3+
from typing import List
4+
5+
6+
class Solution:
7+
def countMentions(self, numberOfUsers: int, events: List[List[str]]) -> List[int]:
8+
mentions = [0] * numberOfUsers
9+
onlineUsers = set(range(numberOfUsers))
10+
offlineUsers = {}
11+
12+
events.sort(key=lambda x: (int(x[1]), x[0] == "MESSAGE"))
13+
14+
for event in events:
15+
eventType, timestamp, data = event
16+
timestamp = int(timestamp)
17+
18+
usersToRestore = [
19+
uid for uid, returnTime in offlineUsers.items() if returnTime <= timestamp]
20+
for uid in usersToRestore:
21+
onlineUsers.add(uid)
22+
del offlineUsers[uid]
23+
24+
if eventType == "OFFLINE":
25+
userId = int(data)
26+
onlineUsers.discard(userId)
27+
offlineUsers[userId] = timestamp + 60
28+
29+
elif eventType == "MESSAGE":
30+
mentionedUsers = data.split()
31+
32+
if "ALL" in mentionedUsers:
33+
for user in range(numberOfUsers):
34+
mentions[user] += 1
35+
36+
elif "HERE" in mentionedUsers:
37+
for user in onlineUsers:
38+
mentions[user] += 1
39+
40+
else:
41+
for userStr in mentionedUsers:
42+
if userStr.startswith("id"):
43+
userId = int(userStr[2:])
44+
mentions[userId] += 1
45+
46+
return mentions
47+
48+
49+
numberOfUsers = 2
50+
events = [["MESSAGE", "10", "id1 id0"], [
51+
"OFFLINE", "11", "0"], ["MESSAGE", "71", "HERE"]]
52+
print(Solution().countMentions(numberOfUsers, events))
53+
numberOfUsers = 2
54+
events = [["MESSAGE", "10", "id1 id0"], [
55+
"OFFLINE", "11", "0"], ["MESSAGE", "12", "ALL"]]
56+
print(Solution().countMentions(numberOfUsers, events))
57+
numberOfUsers = 2
58+
events = [["OFFLINE", "10", "0"], ["MESSAGE", "12", "HERE"]]
59+
print(Solution().countMentions(numberOfUsers, events))
60+
numberOfUsers = 3
61+
events = [["MESSAGE", "2", "HERE"], ["OFFLINE", "2", "1"],
62+
["OFFLINE", "1", "0"], ["MESSAGE", "61", "HERE"]]
63+
# expect = [1,0,2]
64+
print(Solution().countMentions(numberOfUsers, events))

0 commit comments

Comments
 (0)