Design Twitter
Design Twitter is LeetCode 355 (Medium). Build a Twitter class with four methods:
postTweet(userId, tweetId)posts a new tweet.getNewsFeed(userId)returns the IDs of the 10 most recent tweets posted by the user or by anyone they follow, newest first.follow(followerId, followeeId)andunfollow(followerId, followeeId)change who a user follows.
There are up to 3 × 10⁴ calls and 500 users, so a feed request should not have to sort every tweet ever posted.
- 1 <= userId, followerId, followeeId <= 500
- 0 <= tweetId <= 10⁴
- All the tweets have unique IDs.
- At most 3 * 10⁴ calls will be made to postTweet, getNewsFeed, follow, and unfollow.
- A user cannot follow himself.
Intuition
Give every tweet a time from one shared clock. Then each user's own tweets form a list that is already sorted, oldest to newest, and a news feed is just the 10 newest tweets across a few sorted lists: the user's own and those of everyone they follow.
That is a k-way merge, run from the newest end:
- Heap: holds the newest unused tweet of each user in the feed.
- Pop: the heap's top is the newest tweet overall, so it goes next in the feed.
- Refill: push the popped user's next older tweet, so the heap again holds every user's newest unused tweet.
Stop after 10 pops. Everything still in the heap, or never pushed, is older than what was returned.
"The newest few items from several lists that are each already in order" is a k-way merge with a heap, the same idea as Merge k Sorted Lists. Only the head of each list can be next, so the heap holds one item per list.
Approach
Before reading on, decide what each user should store so that their tweets stay in time order across users. Then work out which tweets a feed request actually has to look at before it knows the newest one. Aim for O(F log F) per feed, where F is the number of users in it.
Post with a shared clock
Keep one counter for the whole class. postTweet adds 1 to it and appends (time, tweetId) to the user's list, so every list is in time order and times from different users can be compared.
Follow and unfollow with a set
Store each user's followees in a set. follow adds an ID and unfollow removes one with discard. A set ignores a repeated follow, so no user is merged twice.
Seed the heap
For the user and each followee with at least one tweet, push their newest tweet as (-time, tweetId, user, index). Python's heapq is a min-heap, so the negative time puts the newest tweet on top. The index remembers where in that user's list the tweet sits.
Pop, record, refill
While the heap is not empty and the feed has fewer than 10 tweets:
- pop the top and append its
tweetIdto the feed; - if that user has an older tweet (
index > 0), push it.
The refill keeps one candidate per user in the heap, so the next pop is always the newest tweet not yet in the feed.
Code in Python, C++ and Java
Common pitfalls
Pushing every historical tweet
for time, tweet_id in self.tweets[user]:
time, tweet_id = self.tweets[user][i]
Only the newest tweet from each user can be the next feed item. Adding entire histories makes a feed request grow with all stored tweets.
Forgetting the user's own posts
for user in self.following[userId]:
for user in self.following[userId] | {userId}:A user's feed always includes their own tweets even though following themselves is not required.
Returning more than ten items
while heap:
while heap and len(feed) < 10:
The feed holds at most 10 tweets. Merging further returns too many IDs and does extra work.
Edge cases
discard leaves the set unchanged. set.remove would raise a KeyError here, and the C++ and Java removals are also no-ops.
Nothing is pushed into the heap, so the loop never runs and the feed is [].
Complexity
Design Twitter FAQ
Why not collect all the tweets and sort them?
It gives the same feed: gather every tweet from the user and their followees, sort by time and keep 10. But a feed request then touches every tweet those users ever posted, up to 3 × 10⁴, and sorts them all to use 10. The heap looks at only one tweet per user plus at most 10 more.
Is this the same as the Twitter system design interview question?
No. The system design version is about servers, storage, caching and fan-out across millions of users. LeetCode 355 is the in-memory core of one feed: a single class with a clock, follow sets and a heap. The merge idea is the same one a real feed service uses when it builds a timeline when the user reads it.