Problem
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 useruserId
. Each call to this function will be made with a uniquetweetId
.List<Integer> getNewsFeed(int userId)
Retrieves the10
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
.
Examples
Example 1:
|
|
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 topostTweet
,getNewsFeed
,follow
, andunfollow
.
Solution
Method 1 - Using Hashmap for Users, Set for Followers and Maxheap for Newsfeed
Intuition
The main idea is to use a combination of a HashMap and a Linked List to efficiently manage users, their tweets, and the follow relationships. The HashMap allows for O(1) access to user objects, while the Linked List enables quick insertion of new tweets at the head, ensuring the most recent tweets are always accessible. This structure is particularly effective for retrieving the latest tweets for a user’s news feed.
Approach
- User Management: Maintain a HashMap mapping user IDs to User objects. Each User object keeps track of the users they follow and their own tweets.
- Posting Tweets: When a user posts a tweet, create a new Tweet node and insert it at the head of the user’s tweet linked list. This ensures the most recent tweet is always at the front.
- Following/Unfollowing: Update the followed set in the User object to add or remove followees.
- News Feed Retrieval:
- For a given user, collect the tweet heads of all users they follow (including themselves).
- Use a max-heap (priority queue) to always retrieve the most recent tweet among all followed users.
- Pop up to 10 tweets from the heap to form the news feed, always pushing the next tweet from the same user if available.
Complexity
- ⏰ Time complexity:
O(N log k)
for news feed retrieval, where N is the total number of tweets and k is the number of followed users. Each tweet insertion and heap operation is efficient due to the data structures used. - 🧺 Space complexity:
O(N + U + F)
, where N is the number of tweets, U is the number of users, and F is the number of follow relationships. Each tweet and user is stored, and the heap for feed retrieval uses extra space.
Code
|
|
|
|
|
|