Algo-Sim › Low-Level Design

Design Twitter

Medium · Low-Level Design · step through it in Java, Python and C++ on your own input

Post, follow, unfollow, and a news feed of the 10 newest tweets from you and everyone you follow: a k-way merge of sorted lists with a heap.

Problem

Design a small Twitter: postTweet(userId, tweetId), follow(followerId, followeeId), unfollow(followerId, followeeId), and getNewsFeed(userId), which returns the ids of the 10 most recent tweets posted by the user or by anyone they follow, newest first.

Constraints

Edge cases to test

Follow-up questions

Pull or push for the feed?
Pull merges followees’ tweets on read (cheap writes); push fans tweets out to followers’ feeds on write (cheap reads). Real systems mix both, pulling for celebrities.
What is the cost of the merge?
O(f log f) to seed a heap with f followees, then O(log f) per tweet for 10 tweets.

Solution

Java

class Twitter {
    private int time = 0;
    private final Map<Integer, List<int[]>> tweets = new HashMap<>();   // user -> {time, tweetId}, oldest first
    private final Map<Integer, Set<Integer>> follows = new HashMap<>();

    public void postTweet(int userId, int tweetId) {
        tweets.computeIfAbsent(userId, k -> new ArrayList<>()).add(new int[] {time++, tweetId});
    }

    public List<Integer> getNewsFeed(int userId) {
        // Max-heap of each user's newest unread tweet: {time, tweetId, user, index}.
        PriorityQueue<int[]> heap = new PriorityQueue<>((a, b) -> b[0] - a[0]);
        Set<Integer> users = new HashSet<>(follows.getOrDefault(userId, Set.of()));
        users.add(userId);
        for (int u : users) {
            List<int[]> list = tweets.get(u);
            if (list != null) {
                int i = list.size() - 1;
                heap.add(new int[] {list.get(i)[0], list.get(i)[1], u, i});
            }
        }
        List<Integer> feed = new ArrayList<>();
        while (!heap.isEmpty() && feed.size() < 10) {
            int[] top = heap.poll();
            feed.add(top[1]);
            if (top[3] > 0) {
                int[] next = tweets.get(top[2]).get(top[3] - 1);
                heap.add(new int[] {next[0], next[1], top[2], top[3] - 1});
            }
        }
        return feed;
    }

    public void follow(int followerId, int followeeId) {
        if (followerId != followeeId)
            follows.computeIfAbsent(followerId, k -> new HashSet<>()).add(followeeId);
    }

    public void unfollow(int followerId, int followeeId) {
        follows.getOrDefault(followerId, new HashSet<>()).remove(followeeId);
    }
}

Python

import heapq


class Twitter:
    def __init__(self):
        self.time = 0
        self.tweets = {}    # user -> [(time, tweet_id)], oldest first
        self.follows = {}

    def postTweet(self, userId, tweetId):
        self.tweets.setdefault(userId, []).append((self.time, tweetId))
        self.time += 1

    def getNewsFeed(self, userId):
        # Max-heap (negated time) of each user's newest unread tweet.
        heap = []
        users = set(self.follows.get(userId, set())) | {userId}
        for u in users:
            if u in self.tweets:
                i = len(self.tweets[u]) - 1
                t, tid = self.tweets[u][i]
                heapq.heappush(heap, (-t, tid, u, i))
        feed = []
        while heap and len(feed) < 10:
            _, tid, u, i = heapq.heappop(heap)
            feed.append(tid)
            if i > 0:
                t, nid = self.tweets[u][i - 1]
                heapq.heappush(heap, (-t, nid, u, i - 1))
        return feed

    def follow(self, followerId, followeeId):
        if followerId != followeeId:
            self.follows.setdefault(followerId, set()).add(followeeId)

    def unfollow(self, followerId, followeeId):
        self.follows.get(followerId, set()).discard(followeeId)

C++

#include <bits/stdc++.h>
using namespace std;

class Twitter {
  public:
    int time = 0;
    unordered_map<int, vector<vector<int>>> tweets = {}; // user -> {time, tweetId}, oldest first
    unordered_map<int, unordered_set<int>> follows = {};

    void postTweet(int userId, int tweetId) {
        tweets[userId].push_back(vector<int>{time++, tweetId});
    }

    vector<int> getNewsFeed(int userId) {
        // Max-heap of each user's newest unread tweet: {time, tweetId, user, index}.
        priority_queue<vector<int>> heap;
        unordered_set<int> users = follows[userId];
        users.insert(userId);
        for (int u : users) {
            const auto &list = tweets[u];
            if (!list.empty()) {
                int i = int(list.size()) - 1;
                heap.push(vector<int>{list[i][0], list[i][1], u, i});
            }
        }
        vector<int> feed = {};
        while (!heap.empty() && int(feed.size()) < 10) {
            vector<int> top = heap.top();
            heap.pop();
            feed.push_back(top[1]);
            if (top[3] > 0) {
                vector<int> next = tweets[top[2]][top[3] - 1];
                heap.push(vector<int>{next[0], next[1], top[2], top[3] - 1});
            }
        }
        return feed;
    }

    void follow(int followerId, int followeeId) {
        if (followerId != followeeId)
            follows[followerId].insert(followeeId);
    }

    void unfollow(int followerId, int followeeId) {
        follows[followerId].erase(followeeId);
    }
};

More Low-Level Design problems