Skip to content
BASA DSA

Design Twitter

MediumHeap / Priority Queue

Implement Twitter: postTweet(userId,tweetId), getNewsFeed(userId), follow(followerId,followeeId), unfollow(followerId,followeeId). The feed returns up to ten most recent tweets by the user and followed users, newest first. Tweets have globally unique IDs.

Example 1

Input
arg 1 = ["Twitter","postTweet","postTweet","getNewsFeed","follow","getNewsFeed","unfollow","getNewsFeed"]
arg 2 = [[],[1,10],[2,20],[1],[1,2],[1],[1,2],[1]]
Output
[null,null,null,[10],null,[20,10],null,[10]]

Explanation

Following user 2 adds newer tweet 20 before 10; unfollowing removes it.

Example 2

Input
arg 1 = ["Twitter","getNewsFeed","follow","postTweet","getNewsFeed"]
arg 2 = [[],[3],[3,3],[3,9],[3]]
Output
[null,[],null,null,[9]]

Explanation

An empty feed returns []; self-follow must not duplicate tweet 9.

Example 3

Input
arg 1 = ["Twitter","postTweet","follow","follow","postTweet","getNewsFeed"]
arg 2 = [[],[2,20],[1,2],[1,2],[2,21],[1]]
Output
[null,null,null,null,null,[21,20]]

Explanation

Following user 2 twice is idempotent; after tweet 21 the feed is [21,20], each once.

Constraints

  • At most 30000 operations
  • User IDs are positive integers
  • Follow is idempotent
  • A user always sees their own tweets

Class contractTwitterArguments: json, json
Loading draft…
SolutionRuns on your device
Loading draft…