Problem Description
Design a simplified version of Twitter that supports posting tweets, following/unfollowing other users, and retrieving the 10 most recent tweet IDs in a user's news feed. The news feed should include tweets posted by the user themself and by users they follow, ordered from most recent to least recent.
Key Insights
- Use a global timestamp to order tweets as they are posted.
- Maintain a mapping of each user to the list of tweets they posted.
- Maintain a mapping of each user to the set of users they follow.
- For getNewsFeed, merge tweets from the user and their followees using a heap to efficiently retrieve the 10 most recent tweets.
- Ensure that a user always follows themself to simplify retrieving their own tweets.
Space and Time Complexity
Time Complexity:
- postTweet: O(1)
- follow / unfollow: O(1)
- getNewsFeed: O(N log K) where N is the number of followees and K is the average number of tweets considered (capped at 10 tweets per merge iteration) Space Complexity:
- O(U + T) where U is the number of users (for follow mappings) and T is the total number of tweets stored.
Solution
We use two main data structures: a hash table to store tweets for each user and another hash table for follow relationships. Each tweet is stored as a tuple of (timestamp, tweetId). A global timestamp counter provides a unique ordering. A min-heap (or max-heap using negative timestamp values) is used to merge the tweets from different users efficiently. When retrieving the news feed, we look up the tweet lists for the given user's followees (including self) and use the heap to extract the 10 most recent tweets.