Design a simplified version of Twitter where users can post tweets, follow/unfollow another user, and retrieve the 10 most recent tweet ids in the user’s news feed. Your design should support the following methods:
postTweet(int userId, int tweetId)
: Compose a new tweet.getNewsFeed(int 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 themselves. Tweets must be ordered from most recent to least recent.follow(int followerId, int followeeId)
: Follower follows a followee. If the operation is invalid, it should be a no-op.unfollow(int followerId, int followeeId)
: Follower unfollows a followee. If the operation is invalid, it should be a no-op.import java.util.*;
class Twitter {
private static int timestamp = 0;
private Map<Integer, Set<Integer>> userFollows;
private Map<Integer, List<Tweet>> userTweets;
private class Tweet {
int id;
int time;
Tweet(int id) {
this.id = id;
this.time = Twitter.timestamp++;
}
}
/** Initialize your data structure here. */
public Twitter() {
userFollows = new HashMap<>();
userTweets = new HashMap<>();
}
/** Compose a new tweet. */
public void postTweet(int userId, int tweetId) {
userTweets.putIfAbsent(userId, new ArrayList<>());
userFollows.putIfAbsent(userId, new HashSet<>()); // Ensure user exists in follows list even if they follow no one.
userTweets.get(userId).add(new Tweet(tweetId));
}
/** Retrieve the 10 most recent tweet ids in the user's news feed. */
public List<Integer> getNewsFeed(int userId) {
PriorityQueue<Tweet> pq = new PriorityQueue<>((a, b) -> b.time - a.time);
if (userTweets.containsKey(userId)) {
pq.addAll(userTweets.get(userId));
}
if (userFollows.containsKey(userId)) {
for (int followeeId : userFollows.get(userId)) {
if (userTweets.containsKey(followeeId)) {
pq.addAll(userTweets.get(followeeId));
}
}
}
List<Integer> res = new ArrayList<>();
int n = 0;
while (!pq.isEmpty() && n < 10) {
res.add(pq.poll().id);
n++;
}
return res;
}
/** Follower follows a followee. */
public void follow(int followerId, int followeeId) {
userFollows.putIfAbsent(followerId, new HashSet<>());
userFollows.get(followerId).add(followeeId);
}
/** Follower unfollows a followee. */
public void unfollow(int followerId, int followeeId) {
if (userFollows.containsKey(followerId) && followerId != followeeId) {
userFollows.get(followerId).remove(followeeId);
}
}
}
userFollows
: A map where the key is userId
and the value is a set of userIds
that the user follows.userTweets
: A map where the key is userId
and the value is a list of Tweet
objects representing the tweets that the user has posted.id
and time-stamp
.postTweet
Method:
getNewsFeed
Method:
follow
and unfollow
Methods:
userFollows
map.Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?