Skip to main content

Command Palette

Search for a command to run...

Solving Leetcode Interviews in Seconds with AI: Design Twitter

Updated
4 min read

Introduction

In this blog post, we will explore how to solve the LeetCode problem "355" using AI. LeetCode is a popular platform for preparing for coding interviews, and with the help of AI tools like Chatmagic, we can generate solutions quickly and efficiently - helping you pass the interviews and get the job offer without having to study for months.

Problem Statement

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 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.

Explanation

  • Data Structures: Use a defaultdict to store tweets for each user as a list of (timestamp, tweetId) pairs. Use another defaultdict to store followees for each user as a set. A global timestamp counter ensures correct ordering of tweets.
    • News Feed Retrieval: When retrieving the news feed, merge the tweets from the user and their followees, sort them by timestamp in descending order, and return the top 10 tweet IDs.
    • Follow/Unfollow: Maintain a set of followees for each user. Follow operations add to this set, and unfollow operations remove from it.
  • Runtime Complexity: O(k log k) for getNewsFeed, where k is the total number of tweets from the user and their followees. O(1) for postTweet, follow, and unfollow. Storage Complexity: O(N + T), where N is the number of users and T is the total number of tweets.

Code

    from collections import defaultdict
import heapq

class Twitter:
    def __init__(self):
        self.tweets = defaultdict(list)  # userId -> list of (timestamp, tweetId)
        self.followees = defaultdict(set)  # userId -> set of followeeIds
        self.timestamp = 0

    def postTweet(self, userId: int, tweetId: int) -> None:
        self.tweets[userId].append((self.timestamp, tweetId))
        self.timestamp -= 1  # Decrement for reverse chronological order

    def getNewsFeed(self, userId: int) -> list[int]:
        feed = []
        for followeeId in self.followees[userId] | {userId}:  # Include user's own tweets
            for timestamp, tweetId in self.tweets[followeeId]:
                feed.append((timestamp, tweetId))

        feed.sort(key=lambda x: x[0], reverse=True)
        return [tweetId for _, tweetId in feed[:10]]

    def follow(self, followerId: int, followeeId: int) -> None:
        if followerId != followeeId:
            self.followees[followerId].add(followeeId)

    def unfollow(self, followerId: int, followeeId: int) -> None:
        self.followees[followerId].discard(followeeId)

# Your Twitter object will be instantiated and called as such:
# obj = Twitter()
# obj.postTweet(userId,tweetId)
# param_2 = obj.getNewsFeed(userId)
# obj.follow(followerId,followeeId)
# obj.unfollow(followerId,followeeId)

More from this blog

C

Chatmagic blog

2894 posts

Solving Leetcode Interviews in Seconds with AI: Design Twitter