CodingNodes / Heap / Priority Queue / Design Twitter System design Space play · ←→ step · R restart

Problem

Build a tiny version of a social feed. The class Twitter supports four calls:

  • postTweet(userId, tweetId): the user posts a new tweet.
  • getNewsFeed(userId): return the ids of the 10 most recent tweets in that user's feed, newest first. The feed holds the user's own tweets and the tweets of everyone they follow.
  • follow(followerId, followeeId): the follower starts following the followee.
  • unfollow(followerId, followeeId): the follower stops following the followee.

If the feed has fewer than 10 tweets, return all of them.

Constraints

  • 1 ≤ userId, followerId, followeeId ≤ 500
  • 0 ≤ tweetId ≤ 10 000, and all tweet ids are different
  • At most 30 000 calls in total

Examples: pick one to animate

Solutions

TimeO(1) post, O(f log f) feed SpaceO(users + tweets)

Time: A post appends to a list. A feed seeds the heap with one tweet per followed user (f users), then reads at most 10 more tweets. Each heap push or pop costs O(log f).

Space: Every tweet is stored once in its author's list, and the follow sets hold one entry per follow. The heap holds at most one entry per followed user.

Store each user's tweets in a list, oldest first, with a global time stamp from a counter. One user's list is already sorted by time, so building a feed is merging sorted lists. Put the newest tweet of every user in the feed (the user and everyone they follow) into a max-heap ordered by time. Pop the newest, add it to the feed, then push the next older tweet of the same user. After 10 pops (or when the heap is empty) the feed is done, so we never touch more than 10 tweets per user. The heap is an array the code manages itself, drawn here as array and tree.