InterviewPrepKit

Home / Coding / Heap & Priority Queue

Design Twitter

medium Original ↗
Solving tips
  • Store per-user tweet lists (append order) and per-user follow sets; mint a global monotonic timestamp on each tweet since tweetIds carry no time meaning.
  • getNewsFeed is a k-way merge of already-sorted sources: seed a max-heap with each relevant user's newest tweet, pop up to 10 times, and push the popped user's next-older tweet.
  • Union {userId} at read time so a user's own tweets always appear; use discard (not remove) on unfollow to stay a no-op.
  • Aim for O(1) post/follow/unfollow and O(F log F) feeds independent of total tweet count; keep heap tuples all-ints to survive timestamp ties.

Problem

Design a tiny Twitter clone supporting posting, following, and a news feed:

  • postTweet(userId: int, tweetId: int) — user userId posts tweet tweetId (each call is a distinct, newer post; tweetIds are unique per call).
  • getNewsFeed(userId: int) -> List[int] — return the ids of the 10 most recent tweets in userId’s feed, newest first. The feed consists of tweets by the user themself and by everyone they follow.
  • follow(followerId: int, followeeId: int)followerId starts following followeeId.
  • unfollow(followerId: int, followeeId: int)followerId stops following followeeId (a no-op if they weren’t following).

Users are not pre-registered — any id may appear in any call. A user’s own tweets always appear in their feed; a user never needs to follow themself.

Examples

  • postTweet(1, 5); getNewsFeed(1)[5] — your own tweet shows in your feed.
  • Continuing: follow(1, 2); postTweet(2, 6); getNewsFeed(1)[6, 5] — followee’s newer tweet comes first.
  • Continuing: unfollow(1, 2); getNewsFeed(1)[5] — unfollowed tweets disappear from the feed.

Constraints

  • 1 <= userId, followerId, followeeId <= 500
  • 0 <= tweetId <= 10^4
  • At most 3 * 10^4 calls across all methods — so getNewsFeed must not scan every tweet ever posted.

Think about it first

Hint 1 Two pieces of state fall out of the API: who follows whom (a set per user), and what each user has posted (a list per user, in time order). What extra field must a tweet carry so feeds can be merged by recency?
Hint 2 A feed only ever shows 10 tweets. Each followee's tweet list is already sorted by time — so you're merging several sorted lists and keeping just the 10 newest. What classic technique merges k sorted lists efficiently?
Hint 3 Global timestamp counter on every tweet. For `getNewsFeed`, seed a max-heap with each relevant user's latest tweet, then pop up to 10 times; after popping a tweet from user u, push u's next-older tweet. That's a k-way merge that touches at most k + 10 tweets.
Your workspace Not runnable by design — this is your interview scratchpad. Saved on this device.