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.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
1 <= userId, followerId, followeeId <= 5003 * 104 calls will be made to postTweet, getNewsFeed, follow, and unfollow.This naive approach involves maintaining three main data structures:
Using these data structures, we can retrieve the latest tweets for any user by filtering the global tweet list according to the follow relationships.
To improve the retrieval of the latest tweets for a user, we utilize a Min-Heap to efficiently manage the fetching of the top 10 most recent tweets. We maintain similar data structures for storing tweets and follow relationships, but enhance the retrieval by using the current timestamp to prioritize recent tweets.