Design Twitter

IF
AlgoAxiomStaff Engineers
JSTS
Medium20 mins

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

Implement a function that processes an array of operations and an array of arguments:

  • "Twitter" — Initializes the Twitter object.
  • "postTweet" — User userId posts a tweet with tweetId.
  • "getNewsFeed" — Returns a list of the 10 most recent tweet IDs in the user's news feed. The feed includes tweets from the user and from users they follow, ordered from most recent to least recent.
  • "follow" — User followerId starts following user followeeId.
  • "unfollow" — User followerId stops following user followeeId.

Examples

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]]

Explanation: User 1 posts tweet 5. Feed=[5]. User 1 follows user 2. User 2 posts tweet 6. Feed=[6,5]. User 1 unfollows user 2. Feed=[5].

Example 2:

Input: operations = ["Twitter","postTweet","postTweet","follow","getNewsFeed"], args = [[],[1,10],[2,20],[1,2],[1]]

Output: [null,null,null,null,[20,10]]

Explanation: User 1 posts tweet 10, user 2 posts tweet 20. User 1 follows user 2. Feed shows tweet 20 (user 2's) before tweet 10 (user 1's) since it was posted later.

Constraints

  • 1 <= userId, followerId, followeeId <= 500
  • 0 <= tweetId <= 10^4
  • All tweet IDs are unique
  • At most 3 * 10^4 calls to all operations
  • A user can follow themselves (their own tweets always appear in their feed)
Source: Custom Data Structures pattern — AlgoAxiom
JavaScript
Test Case 1
root = [1, 2, 3]
Test Case 2
root = [1, 2, 3, 4, 5]
Idle