Design Twitter

Medium · Design · Hash Table · Linked List · Design · Heap (Priority Queue)

Problem

Design a small social network where users post tweets, follow each other and read a news feed of the latest tweets.

Implement the class Twitter:

Recency is the order in which postTweet was called, not the size of the tweet id.

Tests call the methods in sequence: ops[i] is a name and vals[i] its arguments; the first call creates the object. The answer is the list of return values, with None for methods that return nothing.

Examples

Input: Twitter(), postTweet(1,50), postTweet(2,7), follow(1,2), getNewsFeed(1), unfollow(1,2), getNewsFeed(1)
Output: [null, null, null, null, [7, 50], null, [50]]

Tweet 7 was posted after 50, so it comes first. After the unfollow only user 1's own tweet is left.

Input: Twitter(), postTweet(3,4), getNewsFeed(2)
Output: [null, null, []]

User 2 follows nobody and has posted nothing.

Input: Twitter(), postTweet(1,900), postTweet(1,5), getNewsFeed(1)
Output: [null, null, null, [5, 900]]

Tweet 5 was posted last, so it is first even though its id is smaller.

Constraints

Approaches

Follow-up

With millions of followers, merging at read time gets expensive for popular accounts, while pushing every tweet into each follower's stored feed at post time ("fan-out on write") gets expensive for accounts with many followers. Real systems mix the two: push for ordinary accounts, pull for the very popular ones at read time.

Related problems

Start free on Cariara · Coding problems · System design studio

Starting Python
No results yet.

          
↑↓ move ↵ open esc close

Labs

Loading labs…

Run with your own input

Starting Python

Loading Python…