Leetcode 355: Design Twitter

grid47
grid47
Exploring patterns and algorithms
Oct 2, 2024 8 min read

A sequence of tweets appearing on a glowing timeline, with interactions and retweets softly illuminating.
Solution to LeetCode 355: Design Twitter Problem

Design a simplified version of Twitter where users can post tweets, follow/unfollow other users, and view the most recent tweets in their news feed.
Problem
Approach
Steps
Complexity
Input: The input consists of a sequence of method calls to the Twitter object. Each method is represented as a list where the first element is the method name and the subsequent elements are the parameters passed to the method.
Example: ["Twitter", "postTweet", "getNewsFeed", "follow", "postTweet", "getNewsFeed", "unfollow", "getNewsFeed"] [[ ], [1, 10], [1], [1, 3], [3, 20], [1], [1, 3], [1]]
Constraints:
• 1 <= userId, followerId, followeeId <= 500
• 0 <= tweetId <= 104
• All tweets have unique IDs.
• At most 3 * 10^4 calls will be made to postTweet, getNewsFeed, follow, and unfollow.
Output: Each method call may return different outputs, for example, the postTweet function does not return anything, while getNewsFeed will return the 10 most recent tweet IDs.
Example: [null, null, [10], null, null, [20, 10], null, [10]]
Constraints:
• The output of getNewsFeed should contain the tweet IDs in order of the most recent to least recent.
Goal: Design a Twitter system with basic functionality such as posting tweets, following/unfollowing users, and retrieving the latest tweets in a user's feed.
Steps:
• Create a User class that stores tweets and followed users.
• Create a Twitter class that handles posting tweets, following/unfollowing users, and retrieving the news feed with the 10 most recent tweets.
Goal: Constraints related to user IDs, tweet IDs, and the maximum number of calls.
Steps:
• At most 3 * 10^4 calls will be made.
• The user IDs, tweet IDs, and followers should be within the specified ranges.
Assumptions:
• Users may follow and unfollow other users multiple times.
• Tweets are posted by the user or the users they follow.
Input: ["Twitter", "postTweet", "getNewsFeed", "follow", "postTweet", "getNewsFeed", "unfollow", "getNewsFeed"] [[ ], [1, 10], [1], [1, 3], [3, 20], [1], [1, 3], [1]]
Explanation: In this example, User 1 posts a tweet with ID 10, follows User 3, and receives tweets from User 3 in their feed. After unfollowing User 3, User 1 only sees their own tweets.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus