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. Your design should support the following methods:
- postTweet(userId, tweetId): Compose a new tweet.
- getNewsFeed(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.
- follow(followerId, followeeId): Follower follows a followee.
- unfollow(followerId, followeeId): Follower unfollows a followee.
Example:
Twitter twitter = new Twitter(); // User 1 posts a new tweet (id = 5). twitter.postTweet(1, 5); // User 1's news feed should return a list with 1 tweet id -> [5]. twitter.getNewsFeed(1); // User 1 follows user 2. twitter.follow(1, 2); // User 2 posts a new tweet (id = 6). twitter.postTweet(2, 6); // 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.getNewsFeed(1); // User 1 unfollows user 2. twitter.unfollow(1, 2); // User 1's news feed should return a list with 1 tweet id -> [5], // since user 1 is no longer following user 2. twitter.getNewsFeed(1);
This is an algorithm design problem. As we have mentioned in Design Twitter system design blog, we need at least two objects, user and tweets, and two relations, user - user, and user-tweets. To simplify here, we use a map with key the userId and value a set of his/her followers to represent the user-user relation. For the news feed part, we use another map with the key userId and value a map of all tweets he/she has posted. The key in the value map is the number of tweets, which is used to represent the time order of the tweets.
To get the most recent tweets. We use a priority queue for the map.entry of all tweets a user's followers have. Note the user needs to follow him/herself so that his/her own posts will be shown in the news feed.
public class Twitter { private Map> twitterFeeds; private Map > followers; private int numTweets; /** Initialize your data structure here. */ public Twitter() { twitterFeeds = new HashMap<>(); followers = new HashMap<>(); numTweets = 0; } /** Compose a new tweet. */ public void postTweet(int userId, int tweetId) { follow(userId, userId); if (!twitterFeeds.containsKey(userId)) { twitterFeeds.put(userId, new HashMap<>()); } twitterFeeds.get(userId).put(++numTweets, tweetId); } /** 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. */ public List getNewsFeed(int userId) { List rst = new ArrayList<>(); PriorityQueue
No comments:
Post a Comment