leetcode

Unnamed repository; edit this file 'description' to name the repository.
Log | Files | Refs | README

commit d32710e7fef4c3ef02351ab80d78a0c48b3822cf
parent 952f59b70f923cbe80b9adae8ae727b46aeb3569
Author: Andrew Laack <andrew@laack.co>
Date:   Wed,  9 Jul 2025 14:47:07 -0500

Completed design twitter

Diffstat:
Adesign-twitter/design-twitterV1.py | 89+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
1 file changed, 89 insertions(+), 0 deletions(-)

diff --git a/design-twitter/design-twitterV1.py b/design-twitter/design-twitterV1.py @@ -0,0 +1,89 @@ +# This approach uses a simple list based approach with sorting. +# while there is a nice heap + hashmap based approach, given the limited +# number of insturctions, this approach works quite well given the low +# asymptotic coefficients. + + +class Tweet: + def __init__(self, time, tweetId): + self.time = time + self.tweetId = tweetId + + def __lt__(self, other): + return self.time < other.time + + +class Twitter: + + def __init__(self): + self.tweets = {} + self.following = {} + self.current_time = 0 + + def _add_tweet(self, tweetId, userId): + tweet = Tweet(self.current_time, tweetId) + self.current_time += 1 + self.tweets[userId].add(tweet) + + def postTweet(self, userId: int, tweetId: int) -> None: + + tweets = self.tweets + following = self.following + + if userId in tweets: + self._add_tweet(tweetId, userId) + + else: + tweets[userId] = set() + self._add_tweet(tweetId, userId) + + def getNewsFeed(self, userId: int) -> List[int]: + + tweets = self.tweets + following = self.following + + tweet_ls = [] + + # or current user posts... + if userId in following: + ls = list(following[userId]) + for id in ls: + if id in tweets: + tweet_ls.extend(tweets[id]) + + if userId in tweets: + tweet_ls.extend(tweets[userId]) + + tweet_ls.sort(reverse=True) + + if len(tweet_ls) > 0: + return [tweet.tweetId for tweet in tweet_ls[0:10]] + + return [] + + def follow(self, followerId: int, followeeId: int) -> None: + + tweets = self.tweets + following = self.following + + if followerId in following: + following[followerId].add(followeeId) + else: + following[followerId] = set() + following[followerId].add(followeeId) + + def unfollow(self, followerId: int, followeeId: int) -> None: + + tweets = self.tweets + following = self.following + + if followerId in following: + following[followerId].remove(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)