Design a simplified version of Twitter where users can post tweets, follow and unfollow other users, and pull a personalized feed of the newest tweets from themselves and the people they follow.
Implement the class Twitter. postTweet(userId, tweetId) publishes a new tweet by the given user. getNewsFeed(userId) returns the ids of the ten most recent tweets in the user's feed, ordered from most recent to least recent, where the feed contains tweets posted by the user and by everyone the user follows. follow(followerId, followeeId) makes the follower start following the followee. unfollow(followerId, followeeId) makes the follower stop following the followee.
A user does not follow themselves, and following someone twice or unfollowing someone you do not follow has no effect.
Example 1
Input: operations = ["Twitter", "postTweet", "getNewsFeed", "follow", "postTweet", "getNewsFeed", "unfollow", "getNewsFeed"] args = [[], [1, 5], [1], [1, 2], [2, 6], [1], [1, 2], [1]]
Output: [null, null, [5], null, null, [6, 5], null, [5]]
User 1 posts tweet 5, so the feed is [5]. User 1 follows user 2, who posts tweet 6, so the feed becomes [6, 5] with the newest first. After user 1 unfollows user 2, the feed returns to [5].
Example 2
Input: operations = ["Twitter", "postTweet", "postTweet", "getNewsFeed"] args = [[], [1, 101], [1, 102], [1]]
Output: [null, null, null, [102, 101]]
User 1 posts tweet 101 then tweet 102. The feed lists them newest first as [102, 101].
Constraints
1 <= userId, followerId, followeeId <= 5000 <= tweetId <= 10^4 and all tweetId values are unique.At most 3 * 10^4 total calls will be made to postTweet, getNewsFeed, follow, and unfollow.See the step-by-step animation, the intuition, and clean code in every language — free, no credit card.
FDE Coach is a cohort-based program in frontend, backend, AWS, and AI where you build real products and get referred to 200+ hiring partners. The free live workshop is the fastest way to see how we teach.
750+ engineers trained · frontend, backend, AWS & AI