Skip to the solution
HardDSA14 min read

Design Twitter feed: how do you fan-out with heap + hash for timeline?

133 views

The problem

Question presented to candidate: "Design a simplified Twitter in Python with post_tweet(user, tweet_id), get_news_feed(user) returning the 10 most recent tweet ids from the user and everyone they follow, newest first, plus follow and unfollow. Then tell me how you would change the design if some users had millions of followers."

What a strong answer should cover:

  • Hash maps: user โ†’ set of followees, user โ†’ list of (time, tweet_id); a global counter as the timestamp.
  • The feed as a k-way merge of sorted lists with a max-heap, stopping after 10: O(f + 10 log f).
  • Fan-out on read vs fan-out on write, the celebrity problem, and the hybrid approach.
  • Edge cases: own tweets included, self-follow ignored, unfollowing a stranger is a no-op, empty feeds.
  • Python details: heapq is a min-heap, so push -time; collections.defaultdict creates entries on read unless you use .get(); set.discard vs set.remove.

Clarifying questions expected:

  • Does the feed include the user's own tweets, and how many tweets?
  • How skewed are follower counts, and what is the read/write ratio?

Code / implementation expected: Yes โ€” a Twitter class with dicts, sets and heapq, in Python 3.

  • system design
  • heap
  • Meta

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

14 min read ยท 14 sections

Python code

Edit the code and run it here. Each printed line with an expected value becomes a test.

PythonTwitter class: post, follow, unfollow and the 10-tweet feed
PythonFan-out on read vs write vs hybrid: work counts on 3000 operations

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 154 of 154 in DSA

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All DSA questions
End of the topic

That was the last DSA question.

Pick another topic