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:

Example 1
Input: postTweet(1, 5), getNewsFeed(1), follow(1, 2), postTweet(2, 6), getNewsFeed(1), unfollow(1, 2), getNewsFeed(1)
Output: [5], [6, 5], [5]
Example 2
Input: postTweet(1, 101), postTweet(2, 201), postTweet(1, 102), postTweet(3, 301), postTweet(2, 202), follow(1, 2), follow(1, 3), getNewsFeed(1)
Output: [202, 301, 102, 201, 101]
Solution

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], so a user always sees their own tweets. Then user 1 follows user 2, user 2 posts tweet 6, and the feed becomes [6, 5], because 6 came later. After the unfollow, tweet 6 drops out again.

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]. Yet nothing about the ids says which came first, since 301 was posted before 202. So how does the class know the order?

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.

Example 2: user 1 has t0: 101 and t2: 102, user 2 has t1: 201 and t4: 202, user 3 has t3: 301. User 1 follows users 2 and 3. The heap starts with each user's newest tweet, t4: 202 on top. The feed for user 1 is 202, 301, 102, 201, 101.

On the left, under "tweets by user, oldest to newest", each box shows a time stamp and a tweet id, so t4: 202 is tweet 202, posted at time 4. The newest tweet in the whole feed has to be the last box of one of the three lists, outlined in teal. Of t2: 102, t4: 202 and t3: 301, the newest is t4: 202, so 202 comes first.

Then 202 leaves, and the next older tweet from user 2's list, t1: 201, takes its place among the candidates. The newest candidate is now t3: 301. Repeating these two moves, taking the newest and bringing in the one before it from the same list, gives the feed in the bottom box: 202, 301, 102, 201, 101.

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 call takes the counter's value as the tweet's time stamp and adds 1, so stamps never repeat and always grow.

Storing tweets and follows

Where does each user's data live? Tweets go in a HashMap from user id to a list of {time stamp, tweet id} pairs. A new tweet is added at the end, so the list stays in posting order with no sorting at all.

Follows go in a second HashMap, from user id to a HashSet of the ids that user follows. A set adds and removes an id in one step on average, and following the same user twice still leaves one entry.

What about a user following themselves? Their own tweets are always in their feed, so follow ignores that call. The feed adds the user's own list separately, so no follow or unfollow can hide it.

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[]>, where each entry is {time stamp, tweet id, user id, position in that user's list}. A PriorityQueue gives back its smallest entry first, so a comparator that compares two entries' stamps in reverse turns it into a max-heap:

Java
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 has these parts:

  • time: the shared counter. Each postTweet stores its value as the time stamp and adds 1.
  • tweets: 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 with computeIfAbsent.
  • following: from user id to the set of ids that user follows. The methods follow and unfollow add to it and remove from it.
  • getNewsFeed: copies the user's set of followees into sources and adds the user, so the stored set stays unchanged. Then it fills heap with each source's newest tweet and takes entries out into feed.
  • FEED_SIZE: the 10 that ends the merge.

The main method runs both examples, asks user 2 of Example 2 for a feed too, then tries a user with 12 tweets, a follow of oneself, a user with nothing, and a follow made twice.

Java
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:

Output
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] and [5], match the expected output. The line for Example 2, user 1, is [202, 301, 102, 201, 101], the order traced in the picture. Right below it, user 2 gets only [202, 201]: user 1 follows user 2, but not the other way round.

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) and unfollow(4, 4) the same 10 tweets come back, because getNewsFeed adds the user to sources itself.

User 9 has no tweets and follows nobody, so the heap starts empty and the feed is []. On the last line user 9 has followed user 4 twice, yet each tweet from 412 to 403 shows up once, since the set holds user 4 only once.

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 HashMap lookup plus one add to the end of an ArrayList or one add or remove on a 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 Merge K Sorted Lists.