Skip to content
AI360Xpert
Back to Heap / Priority Queue
Medium

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

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]]
Twitter twitter = new Twitter(); twitter.postTweet(1, 5); // User 1 posts a new tweet (id = 5). twitter.getNewsFeed(1); // User 1's news feed should return a list with 1 tweet id -> [5]. return [5] twitter.follow(1, 2); // User 1 follows user 2. twitter.postTweet(2, 6); // User 2 posts a new tweet (id = 6). twitter.getNewsFeed(1); // 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.unfollow(1, 2); // User 1 unfollows user 2. twitter.getNewsFeed(1); // User 1's news feed should return a list with 1 tweet id -> [5], since user 1 is no longer following user 2.

Constraints

  • 1 <= userId, followerId, followeeId <= 500
  • 0 <= tweetId <= 10^4
  • All 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

Time Complexity
O(k) for getNewsFeed
Space Complexity
O(N + T)

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).

Solution.java
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);        }    }}