# 355-design-twitter Try it on leetcode ## 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:

 

Example 1:

Input
["Twitter", "postTweet", "getNewsFeed", "follow", "postTweet", "getNewsFeed", "unfollow", "getNewsFeed"]
[[], [1, 5], [1], [1, 2], [2, 6], [1], [1, 2], [1]]
Output
[null, null, [5], null, null, [6, 5], null, [5]]

Explanation
Twitter twitter = new Twitter();
twitter.postTweet(1, 5); // User 1 posts a new tweet (id = 5).
twitter.getNewsFeed(1);  // User 1's news feed should return a list with 1 tweet id -> [5]. return [5]
twitter.follow(1, 2);    // User 1 follows user 2.
twitter.postTweet(2, 6); // User 2 posts a new tweet (id = 6).
twitter.getNewsFeed(1);  // User 1's news feed should return a list with 2 tweet ids -> [6, 5]. Tweet id 6 should precede tweet id 5 because it is posted after tweet id 5.
twitter.unfollow(1, 2);  // User 1 unfollows user 2.
twitter.getNewsFeed(1);  // User 1's news feed should return a list with 1 tweet id -> [5], since user 1 is no longer following user 2.

 

Constraints:

## Solution(Python) ```Python from heapq import * from collections import defaultdict, deque class Twitter: # Each user has a separate min heap # if size of heap is lesser than 10 keep pushing tweets and when it's full, poppush # use a defaultdict to associate user id's to their heaps def __init__(self): """ Initialize your data structure here. """ self.following = defaultdict(set) self.user_tweets = defaultdict(deque) self.post = 0 def postTweet(self, userId, tweetId): """ 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): """ 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) ```