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 ID tweetId by the user userId. Each call to this function will be made with a unique tweetId.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 ID followerId started following the user with ID followeeId.void unfollow(int followerId, int followeeId) The user with ID followerId started unfollowing the user with ID followeeId.Example 1:
Input ["Twitter", "postTweet", "getNewsFeed", "follow", "postTweet", "getNewsFeed", "unfollow", "getNewsFeed"] [[], [1, 5], [1], [1, 2], [2, 6], [1], [1, 2], [1]] Output [null, null, [5], null, null, [6, 5], null, [5]] Explanation Twitter twitter = new Twitter(); twitter.postTweet(1, 5); // User 1 posts a new tweet (id = 5). twitter.getNewsFeed(1); // User 1's news feed should return a list with 1 tweet id -> [5]. return [5] twitter.follow(1, 2); // User 1 follows user 2. twitter.postTweet(2, 6); // User 2 posts a new tweet (id = 6). twitter.getNewsFeed(1); // User 1's news feed should return a list with 2 tweet ids -> [6, 5]. Tweet id 6 should precede tweet id 5 because it is posted after tweet id 5. twitter.unfollow(1, 2); // User 1 unfollows user 2. twitter.getNewsFeed(1); // User 1's news feed should return a list with 1 tweet id -> [5], since user 1 is no longer following user 2.
Constraints:
1 <= userId, followerId, followeeId <= 5000 <= tweetId <= 1043 * 104 calls will be made to postTweet, getNewsFeed, follow, and unfollow.When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:
Imagine you have a giant notebook where you write down every single action that happens on the platform, like who posts what message and who becomes friends with whom. The brute force approach relies on simply flipping through this entire notebook from start to finish every time someone asks for their recent news feed.
Here's how the algorithm would work step-by-step:
class Twitter:
def __init__(self):
self.global_tweet_notebook = []
self.friendship_records = {}
def post_tweet(self, user_identifier: int, tweet_identifier: int) -> None:
current_timestamp = len(self.global_tweet_notebook)
tweet_record = {"user": user_identifier, "tweet": tweet_identifier, "time": current_timestamp}
self.global_tweet_notebook.append(tweet_record)
def get_news_feed(self, user_identifier: int) -> list[int]:
relevant_message_pile = []
# We scan every historical message to find content belonging to the user or their followed accounts.
for message_record in self.global_tweet_notebook:
tweet_author = message_record["user"]
is_self = (tweet_author == user_identifier)
is_followed = tweet_author in self.friendship_records.get(user_identifier, set())
if is_self or is_followed:
relevant_message_pile.append(message_record)
# Sorting the collected relevant messages by timestamp ensures the most recent ones come first.
relevant_message_pile.sort(key=lambda record: record["time"], reverse=True)
top_ten_tweets = []
for message_record in relevant_message_pile:
if len(top_ten_tweets) < 10:
top_ten_tweets.append(message_record["tweet"])
return top_ten_tweets
def follow(self, follower_identifier: int, followee_identifier: int) -> None:
# We maintain a friendship graph to quickly look up who a specific user currently follows.
if follower_identifier not in self.friendship_records:
self.friendship_records[follower_identifier] = set()
self.friendship_records[follower_identifier].add(followee_identifier)
def unfollow(self, follower_identifier: int, followee_identifier: int) -> None:
# Removing a followee ensures future news feeds omit their future and past posts accordingly.
if follower_identifier in self.friendship_records:
self.friendship_records[follower_identifier].discard(followee_identifier)To design Twitter efficiently, we need to treat users as individual channels that keep track of their own messages and their friend connections. When someone asks for their recent news feed, we gather the most recent messages from them and everyone they follow, and then simply pick the absolute newest ones to show them.
Here's how the algorithm would work step-by-step:
class Twitter:
def __init__(self):
self.global_timestamp = 0
self.user_messages = {}
self.user_following = {}
def post_tweet(self, user_identifier: int, tweet_identifier: int) -> None:
# Global timestamp ensures global ordering of tweets across all users.
if user_identifier not in self.user_messages:
self.user_messages[user_identifier] = []
self.user_messages[user_identifier].append((self.global_timestamp, tweet_identifier))
self.global_timestamp += 1
def get_news_feed(self, user_identifier: int) -> list[int]:
if user_identifier not in self.user_following:
self.user_following[user_identifier] = {user_identifier}
else:
self.user_following[user_identifier].add(user_identifier)
collected_tweets = []
for followed_user in self.user_following[user_identifier]:
if followed_user in self.user_messages:
collected_tweets.extend(self.user_messages[followed_user])
# Sorting ensures the most recent tweets appear first in the feed.
collected_tweets.sort(key=lambda tweet_data: tweet_data[0], reverse=True)
return [tweet_identifier for timestamp, tweet_identifier in collected_tweets[:10]]
def follow(self, follower_identifier: int, followee_identifier: int) -> None:
if follower_identifier not in self.user_following:
self.user_following[follower_identifier] = {follower_identifier}
self.user_following[follower_identifier].add(followee_identifier)
def unfollow(self, follower_identifier: int, followee_identifier: int) -> None:
# Users cannot unfollow themselves to maintain their own tweets in the feed.
if follower_identifier in self.user_following and follower_identifier != followee_identifier:
self.user_following[follower_identifier].discard(followee_identifier)| Case | How to Handle |
|---|---|
| Retrieving a news feed for a user who follows no one and has posted no tweets | Return an empty list since there are no valid tweets to display. |
| A user tries to follow themselves | Check if the follower and followee IDs are identical and ignore the operation to prevent self-following cycles. |
| A user tries to unfollow someone they are not currently following | Ensure the unfollow logic checks for existence in the follow set before attempting removal to avoid errors. |
| A user follows someone, unfollows them, and the news feed is subsequently requested | The feed generation must dynamically query the current follow set so that newly unfollowed user tweets are excluded. |
| More than ten tweets exist across the user and all followed users combined | Collect all relevant tweets, sort or use a min-heap by timestamp, and strictly slice to the ten most recent ones. |
| Multiple tweets are posted at the exact same logical timestamp | Use a global monotonically increasing sequence counter to guarantee a deterministic ordering among simultaneous posts. |
| Repeated follow and unfollow calls for the same user pair | Utilize a set data structure for the follower relationships to ensure idempotency and prevent duplicate entries. |
| Extremely large volume of tweets and high frequency of operations over time | Store tweets in a hash map per user and cap the stored history or optimize feed retrieval using a k-way merge approach. |