Problem description:

Design a simplified version of Twitter where users can post tweets, follow/unfollow another user, and is able to see the 10 most recent tweets in the user’s news feed.

Implement the Twitter class:

  • Twitter() Initializes your twitter object.
  • void postTweet(int userId, int tweetId) Composes a new tweet with ID tweetId by the user userId. Each call to this function will be made with a unique tweetId.
  • List<Integer> getNewsFeed(int userId) Retrieves the 10 most recent tweet IDs in the user’s news feed. Each item in the news feed must be posted by users who the user followed or by the user themself. Tweets must be ordered from most recent to least recent.
  • void follow(int followerId, int followeeId) The user with ID followerId started following the user with ID followeeId.
  • void unfollow(int followerId, int followeeId) The user with ID followerId started unfollowing the user with ID followeeId.

Solution:

I use a dict of (int, deque) to save tweets each user has posted and another dict to point to the users he’s following. Deque can be used because only the most recent tweets matter to us in this system.

I use a post counter as a time stamp to track most recent.
When getNewsFeed is called, I build a min heap of all the tweets of the user first. Then iterate over all the users he follows.
For each other user a user follows, I iterate over all of his tweets from last to first since tweets array will be sorted by default, and if current element if greater than root of min heap, then I do a push if heap’s not full or if it’s full, I do a pushpop.
Since, we only need 10 tweets and each person can at max have only 10 tweets. All the heap operatons can be considered constant.
Hence, the time complexity is O(Number of people a user follows).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
class Twitter:

def __init__(self):
"""
Initialize your data structure here.
"""
# use a map to store the follower, set as container because follower shouldn't duplicate
self.following = defaultdict(set)
self.user_tweets = defaultdict(deque)
self.post = 0

def postTweet(self, userId: int, tweetId: int) -> None:
"""
Compose a new tweet.
"""
self.post += 1
tweets = self.user_tweets[userId]
tweets.append(((self.post), tweetId))
if len(tweets) > 10:
tweets.popleft()

def getNewsFeed(self, userId: int) -> List[int]:
"""
Retrieve the 10 most recent tweet ids in the user's news feed. Each item in the news feed must be posted by users who the user followed or by the user herself. Tweets must be ordered from most recent to least recent.
"""
h = []
u = self.user_tweets[userId]
h.extend(u)
heapify(h)
for user in self.following[userId]:
tweets = self.user_tweets[user]
for x in range(len(tweets) - 1, -1, -1):
if len(h) < 10:
heappush(h, tweets[x])
else:
if h[0][0] < tweets[x][0]:
heappushpop(h, tweets[x])
else:
break
return [heappop(h)[1] for x in range(len(h))][::-1]

def follow(self, followerId, followeeId):
"""
Follower follows a followee. If the operation is invalid, it should be a no-op.
"""
if followerId != followeeId:
self.following[followerId].add(followeeId)

def unfollow(self, followerId, followeeId):
"""
Follower unfollows a followee. If the operation is invalid, it should be a no-op.
"""
if followerId != followeeId:
self.following[followerId].discard(followeeId)
# Your Twitter object will be instantiated and called as such:
# obj = Twitter()
# obj.postTweet(userId,tweetId)
# param_2 = obj.getNewsFeed(userId)
# obj.follow(followerId,followeeId)
# obj.unfollow(followerId,followeeId)

time complexity: $O()$
space complexity: $O()$
reference:
related problem: