Design Twitter
Problem
Design a simplified social feed supporting four operations: post a new tweet from a user, have one user follow or unfollow another, and retrieve a user's news feed as the 10 most recent tweet ids from themselves and everyone they follow, most recent first.
Example. If user 1 posts tweet 5, then follows user 2, and user 2 posts tweet 6, user 1's feed returns [6, 5], with 6 first since it is more recent.
Key idea
The naive approach collects every tweet from a user and everyone they follow, then sorts by time for each feed request, repeating the sorting work from scratch every time. Since each user's own tweets are already produced in chronological order, the feed problem is really about merging several already-ordered lists, one per followed user, and taking the top 10 by recency.
Store each user's tweets as a list alongside an increasing timestamp counter so global order is recoverable. To build a feed, gather the most recent tweets from the user and each followed user, and merge those short lists with a max-heap keyed by timestamp: repeatedly pop the most recent tweet across all the lists, advancing that list's pointer, until 10 tweets are collected or every list is exhausted. Following and unfollowing just add or remove an id from a per-user set of followees, and play no part until the next feed request.
Solution
Complexity
- Time: O(F log F) to build one feed, where F is the number of followees, since each contributes at most 10 candidates into the heap merge; O(1) for post, follow, and unfollow.
- Space: O(users + tweets) to store all posted tweets and follow relationships.
Watch out for
- A user's own feed always includes their own tweets, even if they never explicitly follow themselves.
- Only the 10 most recent tweets per followee are ever needed as merge candidates, so there is no reason to pull a followee's entire tweet history into the heap.
Pattern
This is a k-way merge problem in disguise: many individually sorted sources, one per followee, must be combined into a single ranked result, and a heap is the standard tool for merging sorted lists without concatenating and re-sorting everything.