AAlgoLoopSpaced repetition for LeetCode
MEDIUMDesignLeetCode ↗

Design Twitter

The key idea

Stamp every tweet with a global, monotonically increasing time. A feed is then a k-way merge of the followees' (plus the user's own) tweet lists, newest-first. A max-heap keyed by timestamp pulls the 10 most recent without scanning every tweet.

Problem

Design a simplified version of Twitter where users can post tweets, follow or unfollow another user, and see the 10 most recent tweets in their own news feed.

Implement the Twitter class with these methods:

- postTweet(userId, tweetId) composes a new tweet with id tweetId by the user userId. Each call uses a unique tweetId.
- getNewsFeed(userId) retrieves the 10 most recent tweet ids in the user's news feed. Each item must be posted by users the user follows or by the user themselves. Tweets must be ordered from most recent to least recent.
- follow(followerId, followeeId) makes the user followerId start following the user followeeId.
- unfollow(followerId, followeeId) makes the user followerId stop following the user followeeId.

Constraints

Examples

Input: postTweet(1, 5); getNewsFeed(1) Output: [5]
Input: postTweet(1, 5); follow(1, 2); postTweet(2, 6); getNewsFeed(1) Output: [6, 5]
Input: unfollow(1, 2); getNewsFeed(1) Output: [5]

Complexity

Time: O(F + k log F) Space: O(U + T)

See the full solution

410310
Step-by-step visualization
Start free →

More Design problems