Skip to content

Design Twitter

MediumHeap / Priority Queue
Decode it first. Clues, constraints, pattern and plan before any code.

Build a tiny social feed as a class Twitter:

  • post_tweet(user_id, tweet_id) (postTweet): the user posts a tweet with a unique id.
  • get_news_feed(user_id) (getNewsFeed): return the ids of the 10 most recent tweets posted by the user or anyone they follow, newest first.
  • follow(follower_id, followee_id): the follower starts following the followee.
  • unfollow(follower_id, followee_id): the follower stops following them.

Users always see their own tweets. Following yourself, unfollowing someone you do not follow, and following someone twice should all be harmless.

t = Twitter()
t.post_tweet(1, 5)
t.get_news_feed(1)    →  [5]
t.follow(1, 2)
t.post_tweet(2, 6)
t.get_news_feed(1)    →  [6, 5]
t.unfollow(1, 2)
t.get_news_feed(1)    →  [5]

Constraints

  • 1 <= user_id, follower_id, followee_id <= 500
  • 0 <= tweet_id <= 10^4, and every tweet id is unique.
  • At most 3 * 10^4 calls are made in total.