Design Twitter
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.
Examples
Constraints
1 <= userId, followerId, followeeId <= 5000 <= tweetId <= 10^4All the tweets have unique IDs.At most 3 * 10^4 calls will be made in total.
Hash Maps and Max Heap
Approach
Use a global `timestamp` to order tweets. Use a hash map `followers` (userId -> set of followees). Use a hash map `tweets` (userId -> list of [timestamp, tweetId]). For `getNewsFeed`, get the list of users the given `userId` follows (including themselves). Collect the most recent tweet from each of these users and put them in a Max Heap (sorted by timestamp). Then, pop the most recent tweet, add it to the feed, and push the next most recent tweet from the same user into the heap. Repeat this up to 10 times to get the 10 most recent tweets overall.
Complexity Analysis
k is the number of users followed (max 10 items in heap). N is total users, T is total tweets. Note that using max heap algorithm avoids sorting all tweets which would be O(T log T).
class Twitter { private int timestamp; private Map<Integer, Set<Integer>> followMap; private Map<Integer, List<int[]>> tweetMap; // [time, tweetId]
public Twitter() { timestamp = 0; followMap = new HashMap<>(); tweetMap = new HashMap<>(); } public void postTweet(int userId, int tweetId) { if (!tweetMap.containsKey(userId)) { tweetMap.put(userId, new ArrayList<>()); } tweetMap.get(userId).add(new int[]{timestamp++, tweetId}); } public List<Integer> getNewsFeed(int userId) { List<Integer> res = new ArrayList<>(); PriorityQueue<int[]> maxHeap = new PriorityQueue<>((a, b) -> b[0] - a[0]); // [time, tweetId, followeeId, tweetIndex] // Ensure user follows themself follow(userId, userId); Set<Integer> followees = followMap.get(userId); if (followees != null) { for (int followeeId : followees) { if (tweetMap.containsKey(followeeId)) { List<int[]> tweets = tweetMap.get(followeeId); int index = tweets.size() - 1; int[] latestTweet = tweets.get(index); maxHeap.offer(new int[]{latestTweet[0], latestTweet[1], followeeId, index}); } } } while (!maxHeap.isEmpty() && res.size() < 10) { int[] current = maxHeap.poll(); res.add(current[1]); // Add tweetId int followeeId = current[2]; int index = current[3] - 1; // Previous tweet from same user if (index >= 0) { int[] nextTweet = tweetMap.get(followeeId).get(index); maxHeap.offer(new int[]{nextTweet[0], nextTweet[1], followeeId, index}); } } return res; } public void follow(int followerId, int followeeId) { if (!followMap.containsKey(followerId)) { followMap.put(followerId, new HashSet<>()); } followMap.get(followerId).add(followeeId); } public void unfollow(int followerId, int followeeId) { if (followMap.containsKey(followerId) && followerId != followeeId) { followMap.get(followerId).remove(followeeId); } }}