View on NeetCode
View on LeetCode

Problem

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 <= 10^4
  • All the tweets have unique IDs.
  • At most 3 * 10^4 calls will be made to postTweet, getNewsFeed, follow, and unfollow.

Solution

Approach: HashMap + Min Heap

The key insight is to store tweets with timestamps, use a hashmap for follow relationships, and merge recent tweets from followed users using a min heap.

Implementation

import heapq
from collections import defaultdict

class Twitter:
    def __init__(self):
        self.time = 0
        self.tweets = defaultdict(list)  # userId -> [(time, tweetId)]
        self.following = defaultdict(set)  # userId -> set of followeeIds

    def postTweet(self, userId: int, tweetId: int) -> None:
        self.tweets[userId].append((self.time, tweetId))
        self.time += 1

    def getNewsFeed(self, userId: int) -> List[int]:
        # Max heap of (time, tweetId, userId, index)
        heap = []

        # Add user's own tweets
        if userId in self.tweets and self.tweets[userId]:
            time, tweetId = self.tweets[userId][-1]
            heapq.heappush(heap, (-time, tweetId, userId, len(self.tweets[userId]) - 1))

        # Add followed users' tweets
        for followeeId in self.following[userId]:
            if followeeId in self.tweets and self.tweets[followeeId]:
                time, tweetId = self.tweets[followeeId][-1]
                heapq.heappush(heap, (-time, tweetId, followeeId, len(self.tweets[followeeId]) - 1))

        feed = []
        while heap and len(feed) < 10:
            time, tweetId, user, index = heapq.heappop(heap)
            feed.append(tweetId)

            # Add next tweet from this user
            if index > 0:
                time, tweetId = self.tweets[user][index - 1]
                heapq.heappush(heap, (-time, tweetId, user, index - 1))

        return feed

    def follow(self, followerId: int, followeeId: int) -> None:
        if followerId != followeeId:  # Can't follow yourself
            self.following[followerId].add(followeeId)

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

Complexity Analysis

  • Time Complexity:
    • postTweet: O(1)
    • getNewsFeed: O(f log f + 10 log f) where f is number of followees. Simplified to O(f log f).
    • follow: O(1)
    • unfollow: O(1)
  • Space Complexity: O(n * t + f), where n is users, t is avg tweets per user, f is total follow relationships.

Key Insights

  1. Timestamp Ordering: Using a global timestamp ensures correct chronological ordering across all users.

  2. Merge K Sorted Lists: Getting the news feed is like merging k sorted lists (one per followed user), perfect for a heap.

  3. Lazy Evaluation: We don’t merge all tweets upfront. We use a heap to efficiently get only the top 10.

  4. Self-Follow Prevention: A user shouldn’t follow themselves to avoid duplicate tweets in their feed.

  5. Index Tracking: We store the index in the heap so we can fetch the next older tweet from the same user after popping.