Design Twitter

Hard~30 min

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

Implement the Twitter class:

  • Twitter() — Initializes the twitter object.
  • postTweet(userId, tweetId) — Composes a new tweet with ID tweetId by the user userId. Each call to this function will be made with a unique tweetId.
  • getNewsFeed(userId) — Retrieves the 10 most recent tweet IDs in the user's news feed. Each item in the news feed must be posted by users who the user followed or by the user themself. Tweets must be ordered from most recent to least recent.
  • follow(followerId, followeeId) — The user with ID followerId starts following the user with ID followeeId.
  • unfollow(followerId, followeeId) — The user with ID followerId stops following the user with ID followeeId.

Examples

Example 1
Input: ["Twitter","postTweet","getNewsFeed","follow","postTweet","getNewsFeed","unfollow","getNewsFeed"]\n[[],[1,5],[1],[1,2],[2,6],[1],[1,2],[1]]
Output: [null,null,[5],null,null,[6,5],null,[5]]
Explanation: User 1 posts tweet 5. User 1's feed is [5]. User 1 follows user 2. User 2 posts tweet 6. User 1's feed is [6, 5] (most recent first). User 1 unfollows user 2. User 1's feed is [5] (only own tweets).

Constraints

  • 1 <= userId, followerId, followeeId <= 500
  • 0 <= tweetId <= 10^4
  • All the tweets have unique IDs
  • At most 3 * 10^4 calls will be made to postTweet, getNewsFeed, follow, and unfollow
  • Expected time complexity: O(n log k)
Code
Ctrl+EnterRun|Ctrl+⇧+EnterSubmit
Output

Run your code to see results

Use Cmd+Enter to run