Member-only story
Design Twitter
3 min readSep 28, 2024
Implement a simplified version of Twitter which allows users to post tweets, follow/unfollow each other, and view the 10
most recent tweets within their own news feed.
Users and tweets are uniquely identified by their IDs (integers).
Implement the following methods:
Twitter()
Initializes the twitter object.void postTweet(int userId, int tweetId)
Publish a new tweet with IDtweetId
by the useruserId
. You may assume that eachtweetId
is unique.List<Integer> getNewsFeed(int userId)
Fetches at most the10
most recent tweet IDs in the user's news feed. Each item must be posted by users who the user is following or by the user themself. Tweets IDs should be ordered from most recent to least recent.void follow(int followerId, int followeeId)
The user with IDfollowerId
follows the user with IDfolloweeId
.void unfollow(int followerId, int followeeId)
The user with IDfollowerId
unfollows the user with IDfolloweeId
.
Example 1:
Input:
["Twitter", "postTweet", [1, 10], "postTweet", [2, 20], "getNewsFeed", [1], "getNewsFeed", [2], "follow", [1, 2], "getNewsFeed", [1], "getNewsFeed", [2], "unfollow", [1, 2], "getNewsFeed", [1]]
Output:
[null, null, null, [10], [20], null, [20, 10], [20], null, [10]]
Explanation:
Twitter twitter = new Twitter();
twitter.postTweet(1, 10); // User 1 posts a new tweet with id = 10.
twitter.postTweet(2, 20); // User 2 posts a new tweet with id = 20…