Design Twitter solution explained
Design Twitter asks for a small class that lets users post, follow and unfollow each other, and fetch a feed of the 10 most recent posts from themselves and the people they follow, newest first. Store each user's posts in time order with a global counter as the timestamp, then build the feed by merging the newest end of each relevant user's list with a max-heap and stopping after 10. Posting and following are O(1), and a feed costs O(F + 10 log F) for a user who follows F people.
By Evin JohnPublished 10 min read
The problem in plain words
Build a class for a very small social feed. Users are identified by numbers and appear the first time they are mentioned. A user can publish a post with a given id. A user can start following another user, and can stop following them. Finally, a user can ask for their feed: the ids of the 10 most recent posts written by themselves or by anyone they currently follow, newest first. If fewer than 10 such posts exist, return all of them. Following and unfollowing take effect immediately, including for posts written before the follow.
| Call | Result | Note |
|---|---|---|
| post(1, 101) | User 1's first post | |
| post(2, 201) | User 2 posts | |
| post(1, 102) | User 1's second post, the newest so far | |
| feed(1) | [102, 101] | User 1 follows nobody yet, but always sees their own posts |
| follow(1, 2) | ||
| feed(1) | [102, 201, 101] | User 2's older post now appears in time order |
| follow(1, 1), then unfollow(1, 1) | Must not hide user 1's own posts | |
| feed(1) | [102, 201, 101] | Unchanged |
| unfollow(1, 2) | ||
| feed(1) | [102, 101] | User 2's post is gone from the feed |
| feed(9) | [] | A user nobody has heard of gets an empty feed |
Questions worth asking at the start: can someone follow themselves (treat it as a no-op), can unfollow be called for someone not followed (ignore it), are post ids unique (usually yes), and is the feed size always 10 or a parameter. The last one matters for the complexity discussion later.
What the interviewer is looking for
This is a data-structure design question in the same family as LRU Cache: several small methods, each with its own cost, that have to share state cleanly. The interviewer watches how you choose storage for posts and for follow lists, whether you spot that the feed is a merge of already-sorted lists, and whether you handle the self-follow and unknown-user cases without special-case clutter. It is not the system design question of the same name. If the conversation drifts to servers, caches and fan-out, that is a different interview, covered on the Twitter system design page.
The data you need
- A clock. A counter that goes up by one on every post. It gives a total order with no ties, which wall-clock time cannot promise.
- Posts per user. A map from user to a list of (time, post id) pairs. New posts are appended, so each list is sorted oldest to newest for free.
- Follows per user. A map from user to a set of the users they follow. A set makes follow, unfollow and repeated follows O(1) on average and keeps duplicates out.
Brute force: scan one global timeline
The simplest design keeps every post in a single list in the order it was written. To build a feed, walk that list backward and collect posts whose author is the user or someone they follow, stopping at 10. Posting is O(1) and the code is short. The feed is the problem: if the people you follow have not posted in a long time, the scan walks past every other user's posts to find them, so a feed can cost O(P), where P is the total number of posts on the whole service.
class TwitterSlow:
def __init__(self):
self.timeline = [] # (author, post_id), oldest first, every post
self.following = {} # user -> set of users they follow
def post_tweet(self, user, post_id):
self.timeline.append((user, post_id))
def follow(self, follower, followee):
if follower != followee:
self.following.setdefault(follower, set()).add(followee)
def unfollow(self, follower, followee):
self.following.get(follower, set()).discard(followee)
def get_news_feed(self, user):
wanted = self.following.get(user, set()) | {user}
feed = []
for author, post_id in reversed(self.timeline):
if author in wanted:
feed.append(post_id)
if len(feed) == 10:
break
return feedThe better design: merge per-user lists with a heap
Keep posts per user instead. For a feed, the candidates are the user plus everyone they follow, and each of those authors has a list already sorted by time. Finding the 10 newest posts across several sorted lists is the classic k-way merge. Put the newest post of each author into a max-heap keyed by time. Pop the top, add it to the feed, and push the next-newest post from the same author. Repeat until the feed has 10 posts or the heap is empty. Python's heapq is a min-heap, so the code stores negative times.
import heapq
from collections import defaultdict
from itertools import count
class Twitter:
FEED_SIZE = 10
def __init__(self):
self.clock = count() # a bigger number means a newer post
self.posts = defaultdict(list) # user -> [(time, post_id)], oldest first
self.following = defaultdict(set) # user -> users they follow
def post_tweet(self, user, post_id):
self.posts[user].append((next(self.clock), post_id))
def follow(self, follower, followee):
if follower != followee: # you always see your own posts
self.following[follower].add(followee)
def unfollow(self, follower, followee):
self.following[follower].discard(followee)
def get_news_feed(self, user):
heap = []
for author in self.following[user] | {user}:
mine = self.posts.get(author)
if mine:
i = len(mine) - 1 # start at the author's newest post
time, post_id = mine[i]
heap.append((-time, post_id, author, i))
heapq.heapify(heap)
feed = []
while heap and len(feed) < self.FEED_SIZE:
_, post_id, author, i = heapq.heappop(heap)
feed.append(post_id)
if i > 0: # offer that author's next-newest post
time, older_id = self.posts[author][i - 1]
heapq.heappush(heap, (-time, older_id, author, i - 1))
return feedTwo details carry the correctness. The union with the user's own id means unfollow(1, 1) can never hide user 1's posts, and refusing self-follows keeps the set clean. The heap entries start with a unique negative time, so Python never has to compare the later fields. Building the heap with heapify is O(F), and each of the at most 10 pops and pushes is O(log F).
JavaScript without a heap
JavaScript has no built-in priority queue. You can write one, but there is a simpler option worth knowing: keep one cursor per author and, for each of the 10 feed slots, scan all cursors for the newest post. That is O(10 F). Because the feed size is a fixed 10, this is the same order as the heap's O(F) setup. The heap only wins clearly when the feed size k grows, since the scan costs O(k F) and the heap O(F + k log F). Saying this trade-off out loud is worth more than the heap code itself.
class Twitter {
constructor() {
this.clock = 0;
this.posts = new Map(); // user -> [[time, postId], ...], oldest first
this.following = new Map(); // user -> Set of users they follow
}
postTweet(user, postId) {
if (!this.posts.has(user)) this.posts.set(user, []);
this.posts.get(user).push([this.clock++, postId]);
}
follow(follower, followee) {
if (follower === followee) return;
if (!this.following.has(follower)) this.following.set(follower, new Set());
this.following.get(follower).add(followee);
}
unfollow(follower, followee) {
const set = this.following.get(follower);
if (set) set.delete(followee);
}
getNewsFeed(user) {
// One cursor per author, each starting at that author's newest post.
const cursors = [];
for (const author of [user, ...(this.following.get(user) || [])]) {
const list = this.posts.get(author);
if (list) cursors.push({ list, i: list.length - 1 });
}
const feed = [];
while (feed.length < 10) {
let best = null;
for (const c of cursors) {
if (c.i < 0) continue;
if (best === null || c.list[c.i][0] > best.list[best.i][0]) best = c;
}
if (best === null) break; // every cursor has run out
feed.push(best.list[best.i][1]);
best.i--;
}
return feed;
}
}Cost of each operation
| Operation | Shared timeline | Heap merge | Cursor scan (JavaScript) |
|---|---|---|---|
| post | O(1) | O(1) | O(1) |
| follow / unfollow | O(1) average | O(1) average | O(1) average |
| feed | O(P) worst case | O(F + k log F) | O(k F) |
| Space | O(P + follows) | O(P + follows) | O(P + follows) |
Edge cases to test
- A feed for a user who has never posted or followed anyone: an empty list, and no crash on the missing map entry.
- Following yourself, then unfollowing yourself: your own posts stay in your feed.
- Following the same person twice: their posts appear once, not twice.
- Unfollowing someone you never followed: nothing happens.
- Following someone after they posted: their older posts appear right away, in the right order.
- More than 10 candidate posts: exactly 10 come back, newest first.
Mistakes that cost points
- Collecting every post from every followed user and sorting the lot. It works, but it costs O(N log N) in the number of posts those users ever wrote, which is the thing the heap avoids.
- Using a list instead of a set for follows, so a repeated follow shows posts twice and unfollow is O(F).
- Storing the user in their own follow set and then letting unfollow remove it.
- Using wall-clock time as the timestamp. Two posts in the same millisecond tie, and the order becomes arbitrary.
- Forgetting to push the author's next post after a pop, which caps each author at one post per feed.
Follow-up questions
- Save memory. The feed never needs more than each author's 10 newest posts, so each user's list could be a bounded queue of 10. Mention that this breaks if the feed later needs paging.
- Page through older posts. Return a cursor (the time of the last post shown) and restart the merge below it.
- Delete a post. Mark it as deleted in a map from post id to author and skip marked posts during the merge, or remove it from the author's list in O(n).
- Millions of users. This is where the problem turns into system design: precomputing feeds when a post is written versus merging on read, and handling accounts with huge follower counts. That discussion belongs on the system design walkthrough.
How to explain it out loud
Fictional example
- Candidate
- Each user's posts are appended in time order, so every list is already sorted. I'll stamp them with a counter, not the clock, so there are no ties.
- Candidate
- A feed is the ten newest posts across a handful of sorted lists: me plus everyone I follow. That's a k-way merge.
- Candidate
- I put each author's newest post in a max-heap, pop the newest overall, then push that author's next one. Ten pops and I'm done.
- Interviewer
- Do you really need the heap if it's always ten?
- Candidate
- Not strictly. Scanning every author ten times is also linear in the number of follows. The heap matters if the feed size becomes a parameter.
Related problems
Top K Frequent Elements uses a heap to keep only the best few items, the same instinct as stopping the merge at 10. My Calendar I is another class you build one method at a time, with an ordered structure doing the heavy lifting. From the same set, Car Pooling sweeps sorted events with a running total, and Detonate the Maximum Bombs runs a breadth-first search from every starting point of a graph you build yourself.
Practicing design rounds with Natively
Questions with four methods leave lots of room to ramble, so a written record of your own answer is useful. On Mac or Windows, Natively can read the class outline from a screenshot when you practice, suggest the per-user lists and the heap merge, and write a transcript of the session. Reading it back shows whether you explained the self-follow case and the fixed feed size, or skipped straight to code. The coding interview assistant page explains the setup.
Questions people ask
How do you solve Design Twitter?
Give every post a timestamp from a counter, keep each user's posts in a list and each user's follows in a set. For the feed, merge the newest end of the lists for the user and everyone they follow with a max-heap and stop after 10 posts.
Why use a heap in Design Twitter?
Each author's posts are already sorted by time, so the feed is a k-way merge. A heap finds the newest remaining post across F authors in O(log F), giving O(F + 10 log F) per feed instead of sorting every post.
Can a user follow themselves in Design Twitter?
Treat it as a no-op. Users always see their own posts, so add the user to the author set when building the feed and make sure unfollowing yourself cannot hide your posts.
Is Design Twitter a system design question?
Not in this form. It is an in-memory class with four methods. The system design question with the same name is about servers, storage and fan-out, which is a separate interview.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
