loading

Design Twitter — Step-by-Step Visualization

mediumLeetCode #355Hash TableLinked ListDesignHeap (Priority Queue)

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.

Algorithm Pattern

Object-Oriented Design & Min-Heap

Key Idea

We need to maintain: 1. A mapping of `userId` to a list of their `tweets`. 2. A mapping of `userId` to a set of `followees`. To generate the news feed (top 10 most recent tweets from followees), we can use a Max-Heap to pull the latest tweets from all followee streams, or simply collect all followee tweets and sort them by a global timestamp.

Step-by-Step Approach

  1. Keep a global `timestamp` to track tweet order.
  2. Use a map `tweets` where `userId -> List<[timestamp, tweetId]>`.
  3. Use a map `follow` where `userId -> Set<userId>`.
  4. For `getNewsFeed(userId)`:
  5. Collect all tweets from `userId` and all users in `follow[userId]`.
  6. Sort them by `timestamp` descending.
  7. Return the top 10 `tweetId`s.
  8. For `follow(followerId, followeeId)`/`unfollow`: Update the `follow` set.
  9. For `postTweet(userId, tweetId)`: Append `[timestamp++, tweetId]` to `tweets[userId]`.

Common Gotchas

  • A user follows themselves implicitly (some implementations require this).
  • Efficiency: For a real system, we'd use a heap for merging pre-sorted tweet lists, but for N=10, sorting a combined list is fine.

Related Problems