Design Twitter
MediumHeap
Design a simplified social network Twitter where users post tweets, follow each other, and read a news feed.
Implement the class:
Twitter()creates an empty service.postTweet(user_id, tweet_id)records thatuser_idposted a new tweet with idtweet_id. Every call uses a tweet id that has never been used before.getNewsFeed(user_id)returns a list of at most 10 tweet ids taken from tweets posted byuser_idand by every user thatuser_idcurrently follows. The list is ordered from most recently posted to least recently posted. Recency is the order in whichpostTweetwas called, not the size of the tweet id. Return fewer than 10 ids if fewer tweets qualify, or[]if none do.follow(follower_id, followee_id)makesfollower_idfollowfollowee_id. Following is one-directional. Following someone you already follow has no effect.unfollow(follower_id, followee_id)makesfollower_idstop followingfollowee_id. If they were not following, nothing happens. After unfollowing, all of the followee's tweets (old and new) leave the follower's feed.
A user always sees their own tweets and is never asked to follow or unfollow themselves.
The examples list the calls in order. The output shows each call's return value, with None for the constructor and for methods that return nothing.
Example 1
- Input:
- Twitter(); postTweet(3, 101); postTweet(4, 202); follow(3, 4); getNewsFeed(3); postTweet(3, 50); getNewsFeed(3); getNewsFeed(4)
- Output:
- [None, None, None, None, [202, 101], None, [50, 202, 101], [202]]
- Explanation
- After user 3 follows user 4, user 3's feed holds 202 (newer) then 101. Tweet 50 is posted last, so it leads even though its id is smallest. User 4 follows nobody, so their feed only has their own tweet 202.
Example 2
- Input:
- Twitter(); follow(1, 2); postTweet(2, 7); postTweet(1, 8); getNewsFeed(1); unfollow(1, 2); getNewsFeed(1); getNewsFeed(2)
- Output:
- [None, None, None, None, [8, 7], None, [8], [7]]
- Explanation
- While user 1 follows user 2 the feed shows both tweets, newest first. After unfollowing, user 2's tweet disappears from user 1's feed, but it stays in user 2's own feed.
Constraints
1 <= user_id, follower_id, followee_id <= 5000 <= tweet_id <= 10^4- All tweet ids are unique
follower_id != followee_id- At most
3 * 10^4total calls