Design Twitter
Build a small news feed that shows the 10 newest tweets from a user and the people they follow.
Design a simplified Twitter, where users post short messages called tweets and follow each other. Each user and each tweet is known by a number, its id. Write a class with four methods:
: the user posts a tweet.postTweet(userId, tweetId) : returns the ids of the 10 most recent tweets posted by the user or by anyone the user follows, newest first. If there are fewer than 10, return them all.getNewsFeed(userId) : the follower starts following the followee.follow(followerId, followeeId) : the follower stops following the followee.unfollow(followerId, followeeId)
Example 1
Output: [5], [6, 5], [5]
Example 2
Output: [202, 301, 102, 201, 101]
The Idea
You have probably scrolled a home feed in a social app: posts from the people you follow, mixed together, with the newest at the top. This problem asks for the machinery behind that feed, on a small scale.
In Example 1, user 1 posts tweet 5 and asks for a feed. User 1 follows nobody yet, but the feed is [5][6, 5]
Example 2 has more going on. Three users post five tweets between them, and user 1 follows users 2 and 3. The feed for user 1 has to put all five tweets in time order: [202, 301, 102, 201, 101]
It has to write the order down. A counter shared by all users stamps each tweet as it is posted: 101 gets time 0, 201 gets time 1, 102 gets time 2, and so on. A bigger stamp means a newer tweet. Each user keeps their own tweets in a list, in the order they were posted, so every list already runs from oldest to newest.
That raises the real question: how do we pick the newest tweets out of several lists without sorting them all together? The picture shows Example 2 after its five posts and two follows.
On the left, under "tweets by user, oldest to newest", each box shows a time stamp and a tweet id, so t4: 202t2: 102t4: 202t3: 301t4: 202
Then 202 leaves, and the next older tweet from user 2's list, t1: 201t3: 301
So the feed is a merge of lists that are each already in time order, with one candidate per list. A structure that always gives back its largest entry first, here the biggest time stamp, is called a max-heap. The box on the right, "heap at the start", holds the three candidates in one.
Solution Approach
Four choices shape the class: how tweets from different users are ordered, how tweets and follows are stored, how the lists are merged into a feed (and why sorting them all does more work), and when the merge stops.
Ordering tweets across users
Which of two tweets is newer, when they belong to different users? One counter for the whole class answers it. Every postTweet
Storing tweets and follows
Where does each user's data live? Tweets go in a HashMap
Follows go in a second HashMapHashSet
What about a user following themselves? Their own tweets are always in their feed, so follow
Merging the lists with a heap
Why not gather every tweet from the user and the people they follow, sort them by time stamp, and keep the first 10? It gives the right answer, but it sorts every tweet those users ever posted, only to show 10.
The merge from Example 2 touches far fewer. Here the max-heap is a Java PriorityQueue<int[]>PriorityQueue
PriorityQueue<int[]> heap = new PriorityQueue<>((a, b) -> Integer.compare(b[0], a[0]));
The heap starts with the newest tweet of each source, one entry per user. When an entry comes out, its user id and position say where the next older tweet of that user is, one position to the left, and that tweet goes in.
Stopping at ten
When is the feed done? After 10 tweets, or sooner if the heap runs empty because every list is used up. So the merge takes at most 10 entries out of the heap, however many tweets the users have posted.
Java Solution
The class DesignTwitter
: the shared counter. Eachtime stores its value as the time stamp and adds 1.postTweet : from user id to that user's list of {time stamp, tweet id} pairs, oldest first. The first post of a user creates the list withtweets .computeIfAbsent : from user id to the set of ids that user follows. The methodsfollowing andfollow add to it and remove from it.unfollow : copies the user's set of followees intogetNewsFeed and adds the user, so the stored set stays unchanged. Then it fillssources with each source's newest tweet and takes entries out intoheap .feed : the 10 that ends the merge.FEED_SIZE
The main
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.PriorityQueue;
import java.util.Set;
public class DesignTwitter {
private static final int FEED_SIZE = 10;
private int time = 0; // one clock for all users
private final Map<Integer, List<int[]>> tweets = new HashMap<>(); // user -> {time, tweetId}
private final Map<Integer, Set<Integer>> following = new HashMap<>(); // user -> followees
public void postTweet(int userId, int tweetId) {
tweets.computeIfAbsent(userId, k -> new ArrayList<>()).add(new int[] {time++, tweetId});
}
public List<Integer> getNewsFeed(int userId) {
Set<Integer> sources = new HashSet<>(following.getOrDefault(userId, Set.of()));
sources.add(userId); // own tweets count too
// Max-heap of {time, tweetId, userId, index in that user's list}, newest on top.
PriorityQueue<int[]> heap = new PriorityQueue<>((a, b) -> Integer.compare(b[0], a[0]));
for (int u : sources) {
List<int[]> list = tweets.get(u);
if (list != null) {
int i = list.size() - 1; // this user's newest tweet
heap.add(new int[] {list.get(i)[0], list.get(i)[1], u, i});
}
}
List<Integer> feed = new ArrayList<>();
while (!heap.isEmpty() && feed.size() < FEED_SIZE) {
int[] top = heap.poll();
feed.add(top[1]);
int i = top[3] - 1; // same user, one tweet older
if (i >= 0) {
int[] older = tweets.get(top[2]).get(i);
heap.add(new int[] {older[0], older[1], top[2], i});
}
}
return feed;
}
public void follow(int followerId, int followeeId) {
if (followerId == followeeId) {
return; // own tweets are always in
}
following.computeIfAbsent(followerId, k -> new HashSet<>()).add(followeeId);
}
public void unfollow(int followerId, int followeeId) {
Set<Integer> followees = following.get(followerId);
if (followees != null) {
followees.remove(followeeId);
}
}
public static void main(String[] args) {
DesignTwitter one = new DesignTwitter(); // Example 1
one.postTweet(1, 5);
System.out.println("Example 1, feed 1: " + one.getNewsFeed(1));
one.follow(1, 2);
one.postTweet(2, 6);
System.out.println("Example 1, feed 2: " + one.getNewsFeed(1));
one.unfollow(1, 2);
System.out.println("Example 1, feed 3: " + one.getNewsFeed(1));
DesignTwitter two = new DesignTwitter(); // Example 2
two.postTweet(1, 101);
two.postTweet(2, 201);
two.postTweet(1, 102);
two.postTweet(3, 301);
two.postTweet(2, 202);
two.follow(1, 2);
two.follow(1, 3);
System.out.println("Example 2, user 1: " + two.getNewsFeed(1));
System.out.println("Example 2, user 2: " + two.getNewsFeed(2));
DesignTwitter more = new DesignTwitter(); // edge cases
for (int id = 401; id <= 412; id++) {
more.postTweet(4, id);
}
System.out.println("12 tweets, user 4: " + more.getNewsFeed(4));
more.follow(4, 4);
more.unfollow(4, 4);
System.out.println("after follow(4, 4) and unfollow(4, 4): " + more.getNewsFeed(4));
more.unfollow(9, 4);
System.out.println("user 9, no tweets, follows nobody: " + more.getNewsFeed(9));
more.follow(9, 4);
more.follow(9, 4);
System.out.println("user 9 follows 4 twice: " + more.getNewsFeed(9));
}
}
Running it prints:
Example 1, feed 1: [5]
Example 1, feed 2: [6, 5]
Example 1, feed 3: [5]
Example 2, user 1: [202, 301, 102, 201, 101]
Example 2, user 2: [202, 201]
12 tweets, user 4: [412, 411, 410, 409, 408, 407, 406, 405, 404, 403]
after follow(4, 4) and unfollow(4, 4): [412, 411, 410, 409, 408, 407, 406, 405, 404, 403]
user 9, no tweets, follows nobody: []
user 9 follows 4 twice: [412, 411, 410, 409, 408, 407, 406, 405, 404, 403]
The three Example 1 feeds, [5][6, 5][5][202, 301, 102, 201, 101][202, 201]
User 4 posted 12 tweets, 401 to 412, and the feed shows 412 down to 403. That is 10 tweets, so 402 and 401 are left out. After follow(4, 4)unfollow(4, 4)getNewsFeedsources
User 9 has no tweets and follows nobody, so the heap starts empty and the feed is []
Complexity
Posting, following and unfollowing touch one list or one set, while a feed's cost depends on how many people the user follows.
- Time of postTweet, follow and unfollow: O(1) on average, because each one is a
lookup plus one add to the end of anHashMap or one add or remove on aArrayList .HashSet - Time of getNewsFeed: O(f log f), where f is the number of users followed, because the newest tweets of the f + 1 sources go into the heap at O(log f) each. Copying the followees adds O(f), and the at most 10 take-outs and put-ins cost O(log f) each.
- Space: O(P + L), because each of the P tweets posted stays in its author's list and each of the L follow links is one set entry, while a feed's heap holds at most f + 1 entries.
The same merge, one candidate per sorted list in a heap, is worked through for linked lists in