Taro Logo

Design Twitter

Medium
Asked by:
X
Meesho
PDD Holdings
1 view
Topics:
ArraysGraphs

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 <= 500
  • 0 <= tweetId <= 104
  • All the tweets have unique IDs.
  • At most 3 * 104 calls will be made to postTweet, getNewsFeed, follow, and unfollow.
  • A user cannot follow himself.

Solution


Clarifying Questions

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:

  1. Can a user follow themselves, and if so, how should that affect their news feed?
  2. What should happen if a user requests a news feed when they follow no one and have posted no tweets themselves?
  3. When retrieving the 10 most recent tweets for the news feed, should a user's own tweets be included alongside the tweets of the users they follow?
  4. Can a user unfollow someone they aren't currently following, or follow someone they are already following multiple times, and how should these idempotent or invalid operations be handled?
  5. Are tweet IDs guaranteed to be globally unique and monotonically increasing in the order they are posted, or could an older tweet have a higher ID?

Brute Force Solution

Approach

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:

  1. Whenever a user writes a new message, record the message along with who wrote it and the exact moment it happened in your giant notebook.
  2. Whenever two users decide to follow each other, note down this friendship in your records so you remember who is connected to whom.
  3. When a user asks to see their latest news feed, open up your notebook and read through every single message ever written by anyone on the platform.
  4. For each message you read, check the author to see if they are either the user asking for the feed or someone that user currently follows.
  5. If the message belongs to a friend or the user themselves, keep it on a separate pile of relevant messages.
  6. After going through every message in the entire history of the platform, sort your pile of kept messages to figure out which ones were posted most recently.
  7. Finally, take the top ten most recent messages from that sorted pile and hand them over as the news feed.

Code Implementation

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)

Big(O) Analysis

Time Complexity
O(T + F log F) – To generate a news feed, we must scan through all T total tweets ever posted in the platform's history and check if the author is followed by the user. If a user follows F people and these authors account for M matching tweets, we must then sort these M tweets to find the 10 most recent. This scan and sort process leads to approximately T plus M log M operations, which simplifies to O(T + F log F) where T is the total number of global tweets.
Space Complexity
O(M + U) – To generate the news feed, the algorithm allocates a temporary pile to gather all matching messages and another list to hold the sorted results. The extra memory required is driven by this auxiliary pile, which scales with the total number of messages M stored in the system, plus the number of users U and their follow relationships. Therefore, as the volume of platform activity grows, the auxiliary space increases proportionally to store these intermediate results.

Optimal Solution

Approach

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:

  1. Keep a running notebook for every user that records every message they post, stamped with the exact time it was created so we always know the order.
  2. Keep a separate list for every user that tracks everyone else they choose to follow.
  3. Whenever a user posts a new message, add it to the top of their personal notebook.
  4. When a user wants to view their news feed, collect all the messages they have posted themselves, plus all the messages posted by anyone they follow.
  5. Combine all these collected messages together into one big pile.
  6. Sort the pile by the timestamp and pick the ten most recent messages to present as the news feed.
  7. When a user decides to follow or unfollow someone, simply update their personal list of followed accounts so future news feeds reflect the change accurately.

Code Implementation

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)

Big(O) Analysis

Time Complexity
O(U * T * log T) – To generate a news feed, we collect all tweets from the user and everyone they follow, where U represents the number of followed users and T represents the maximum number of tweets per user. Gathering these tweets requires checking U lists, resulting in U * T total collected messages. We then sort this combined pile by timestamp using a comparison sort, which takes (U * T) * log(U * T) time. As T and U grow, this operation approximates U * T * log T because sorting dominates the linear collection cost.
Space Complexity
O(U * T + F) – To analyze the auxiliary space, let U be the total number of users, T be the maximum number of tweets stored per user, and F be the total number of follow relationships across all users. The system maintains persistent internal data structures consisting of hash maps and lists for every user's personal notebook of tweets and their individual set of followed accounts. When a user requests their news feed, a temporary collection pile gathers up to 10 * K tweets, where K is the number of followed users, bounded by the total system users. Therefore, the auxiliary space complexity is dominated by the storage of all tweets and follow connections, simplifying to O(U * T + F).

Edge Cases

Retrieving a news feed for a user who follows no one and has posted no tweets
How to Handle:
Return an empty list since there are no valid tweets to display.
A user tries to follow themselves
How to Handle:
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
How to Handle:
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
How to Handle:
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
How to Handle:
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
How to Handle:
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
How to Handle:
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
How to Handle:
Store tweets in a hash map per user and cap the stored history or optimize feed retrieval using a k-way merge approach.