Design Twitter

Solution Code
def getNewsFeed(self, userId: int) -> list[int]:
        res = []
        hp = []
        self.followMap[userId].add(userId) # User sees own tweets
        
        for followeeId in self.followMap[userId]:
            if followeeId in self.tweets:
                index = len(self.tweets[followeeId]) - 1
                time, tweetId = self.tweets[followeeId][index]
                hp.append((time, tweetId, followeeId, index - 1))
        
        heapq.heapify(hp)
        while hp and len(res) < 10:
            time, tweetId, followeeId, idx = heapq.heappop(hp)
            res.append(tweetId)
            if idx >= 0:
                next_time, next_tweet = self.tweets[followeeId][idx]
                heapq.heappush(hp, (next_time, next_tweet, followeeId, idx - 1))
        return res

Time Complexity

O(1) for post, follow, unfollow; O(N log K) for feed

Space Complexity

O(U + T)