13. Design Twitter
mediumAsked at RedisImplement a simplified Twitter with postTweet, getNewsFeed, follow, unfollow; Redis loves it because the optimal solution is the Redis fan-out-on-read pattern.
By Alex Chen, Founder, InterviewChamp.AI · Last verified
Problem
Design Twitter where users can post a tweet, follow/unfollow, and retrieve the 10 most recent tweets across themselves and the users they follow.
Constraints
1 <= userId, followeeId, tweetId <= 500Up to 3 * 10^4 calls
Examples
Example 1
postTweet(1,5); getNewsFeed(1)[5]Example 2
follow(1,2); postTweet(2,6); getNewsFeed(1)[6,5]Approaches
1. Re-scan every tweet on read
On getNewsFeed walk every tweet and filter by follow set.
- Time
- O(total tweets)
- Space
- O(total tweets)
// Maintain global tweet list, scan and filter on every getNewsFeed.Tradeoff:
2. Per-user list + heap merge
Each user has a list of their tweets (timestamped). On getNewsFeed push the user's heads onto a heap and pop 10. This is the per-user inbox + ZRANGEBYSCORE pattern in real Redis Twitter clones.
- Time
- O(k log F) per feed
- Space
- O(tweets)
class Twitter {
constructor() {
this.t = 0;
this.tweets = new Map(); // userId -> [{ ts, id }]
this.follows = new Map(); // userId -> Set
}
postTweet(uid, tid) {
if (!this.tweets.has(uid)) this.tweets.set(uid, []);
this.tweets.get(uid).push({ ts: this.t++, id: tid });
}
getNewsFeed(uid) {
const ids = new Set([uid, ...(this.follows.get(uid) || [])]);
const all = [];
for (const u of ids) for (const tw of this.tweets.get(u) || []) all.push(tw);
return all.sort((a, b) => b.ts - a.ts).slice(0, 10).map(t => t.id);
}
follow(uid, fid) {
if (!this.follows.has(uid)) this.follows.set(uid, new Set());
this.follows.get(uid).add(fid);
}
unfollow(uid, fid) { this.follows.get(uid)?.delete(fid); }
}Tradeoff:
Redis-specific tips
Redis interviewers want you to compare fan-out-on-write (materialized inbox per user) vs fan-out-on-read (merge on query); name LPUSH/LRANGE for the inbox approach.
Solve it now
Free. No sign-up. Python and JavaScript run instantly in your browser.
Practice these live with InterviewChamp.AI
Drill Design Twitter and other Redis interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →