355. Design Twitter
Problem description:
Design a simplified version of Twitter where users can post tweets, follow/unfollow another user, and is able to see the 10 most recent tweets in the user’s news feed.
Implement the Twitter class:
- Twitter() Initializes your twitter object.
void postTweet(int userId, int tweetId)
Composes a new tweet with IDtweetId
by the user userId. Each call to this function will be made with a uniquetweetId
.List<Integer> getNewsFeed(int 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.void follow(int followerId, int followeeId)
The user with IDfollowerId
started following the user with IDfolloweeId
.void unfollow(int followerId, int followeeId)
The user with IDfollowerId
started unfollowing the user with IDfolloweeId
.
Solution:
I use a dict of (int, deque) to save tweets each user has posted and another dict to point to the users he’s following. Deque can be used because only the most recent tweets matter to us in this system.
I use a post counter as a time stamp to track most recent.
When getNewsFeed is called, I build a min heap of all the tweets of the user first. Then iterate over all the users he follows.
For each other user a user follows, I iterate over all of his tweets from last to first since tweets array will be sorted by default, and if current element if greater than root of min heap, then I do a push if heap’s not full or if it’s full, I do a pushpop.
Since, we only need 10 tweets and each person can at max have only 10 tweets. All the heap operatons can be considered constant.
Hence, the time complexity is O(Number of people a user follows).
1 | class Twitter: |
time complexity: $O()$
space complexity: $O()$
reference:
related problem: