PPractick

DSA interview question

Design Twitter

Medium · Data structures · Topics: heap, design, hash map

The problem

Build a tiny version of Twitter. Users can postTweet(userId, tweetId), follow(followerId, followeeId) and unfollow(...), and getNewsFeed(userId) returns the 10 most recent tweet IDs posted by the user or anyone they follow, newest first. Each user's own tweets are stored in time order, so a news feed is a k-way merge of already-sorted lists (the user plus their followees). A max-heap keyed by timestamp pulls the 10 newest without touching older tweets.

Example: postTweet(1, 5); getNewsFeed(1) → [5]; follow(1, 2); postTweet(2, 6); getNewsFeed(1) → [6, 5]; unfollow(1, 2); getNewsFeed(1) → [5].

Function signature

class Twitter {
public:
    void postTweet(int userId, int tweetId);
    vector<int> getNewsFeed(int userId);          // up to 10 tweet ids, newest first
    void follow(int followerId, int followeeId);
    void unfollow(int followerId, int followeeId);
};

Test cases

OperationsOutputExplanation
post(1,5) feed(1) follow(1,2) post(2,6) feed(1) unfollow(1,2) feed(1)[5] [6, 5] [5]LeetCode's example
user 1 posts tweets 1 to 11, then feed(1)[11, 10, 9, 8, 7, 6, 5, 4, 3, 2]Only the 10 newest
follow(1,1) post(1,7) feed(1)[7]Following yourself must not duplicate
post(2,3) follow(1,2) post(1,4) post(2,8) feed(1)[8, 4, 3]Interleaved by time
feed(9) for a user with nothing[]

(Confirm: "recent" means posting order across all users; unfollowing someone you don't follow is a no-op; users always see their own tweets.)

How interviewers phrase it

Clarifying questions to ask

  1. How many tweets in the feed? (10.)
  2. Should users see their own tweets? (Yes.)
  3. Which operations happen most often: reads or writes? (That decides between merging on read, "pull", and pushing to followers' feeds on write, "fan-out".)

Follow-ups to expect

  1. "How do you order tweets globally?"
  2. "How is the feed built?"
  3. "Why not merge all tweets and sort?"
  4. "What about celebrities with millions of followers?"
  5. "What data structures per user?"

Practise questions like this with a real engineer

On Practick another engineer interviews you live for 60 minutes on a question from this bank. They have the full interviewer guide beside the call: the expected answer to every follow-up, hints to give if you stall, and a scoring rubric. You get the model solution once the session settles. It is free: interview someone for an hour and you have earned your own.

Book a free mock interview

Related questions

All 474 dsa interview questions

DSA mock interviews · System design interview questions · Free mock interview practice · Browse interviewers · Sign in