Design Twitter (LeetCode 355): Solution and Explanation

Medium
Hash Table
Linked List
Design
Heap

Build a small social feed where users can post tweets, follow and unfollow other users, and request a news feed of the 10 most recent tweet ids from themselves and everyone they follow, newest first.

Variables
No variables to display
DepthFunction Call
Stack empty
0/0

Intuition

Start with the data you need to keep. Each user has a list of tweets they posted, and each user has a set of people they follow. A set is the right choice for follows because following someone twice should have no effect and unfollowing should be quick. To decide which tweets are most recent across different users, you need a global ordering, so every tweet gets a timestamp from a counter that increases on every post.

The interesting operation is the news feed. A brute force collects every tweet from the user and their followees into one list, sorts it by timestamp and takes the first 10. The reference solution does nearly the same thing with a heap: it pushes every relevant tweet keyed by the negated timestamp, so Python's min-heap behaves like a max-heap, and then pops up to 10 entries. That is simple and correct, and since all tweets are pushed, the cost grows with the total number of tweets in the feed.

A sharper version only looks at what it needs. Each user's tweet list is already in time order, so the feed is a merge of sorted lists where you stop after 10 items. Seeding a heap with only the newest tweet of each followee and pushing a user's next older tweet whenever one of theirs is popped brings the feed down to roughly O(F + 10 log F) for F followees. It is worth mentioning in an interview even if you code the simpler version.

Including the user in their own feed is easiest by taking the union of the follow set with the user's own id, which also handles a user who follows themselves without producing duplicates.

Approach: Per-user tweet lists, follow sets and a heap feed

  1. Keep a global time counter, tweets mapping each user to a list of (time, tweetId) pairs, and follows mapping each user to a set of followee ids.
  2. postTweet appends (time, tweetId) to the user's list and increments time.
  3. getNewsFeed builds users as the follow set plus the user, then pushes (-time, tweetId) for every tweet of every such user onto a heap.
  4. It pops from the heap until it has 10 ids or the heap is empty, which yields tweets from newest to oldest.
  5. follow adds the followee to the follower's set, and unfollow uses discard so removing a non-followed user is safe.

Step-by-step example

Twitter(), postTweet(1, 5), getNewsFeed(1), follow(1, 2), postTweet(2, 6), getNewsFeed(1), unfollow(1, 2), getNewsFeed(1)
  1. postTweet(1, 5) stores (0, 5) for user 1 and moves the clock to 1.
  2. getNewsFeed(1) looks at users {1}, pushes (0, 5) and returns [5].
  3. follow(1, 2) adds 2 to user 1's follow set. postTweet(2, 6) stores (1, 6) for user 2.
  4. getNewsFeed(1) looks at users {1, 2}, pushes (0, 5) and (-1, 6), and pops 6 first because it is newer, returning [6, 5].
  5. unfollow(1, 2) removes 2, so the final getNewsFeed(1) only sees user 1 and returns [5].

Code: Python, Java, C++

1class Twitter:
2    def __init__(self):
3        self.time = 0
4        self.tweets = defaultdict(list)  # userId -> [(time, tweetId)]
5        self.follows = defaultdict(set)  # userId -> set of followeeIds
6
7    def postTweet(self, userId: int, tweetId: int) -> None:
8        self.tweets[userId].append((self.time, tweetId))
9        self.time += 1
10
11    def getNewsFeed(self, userId: int) -> List[int]:
12        # Get tweets from user and all followees
13        heap = []
14        users = self.follows[userId] | {userId}
15        for uid in users:
16            for tweet in self.tweets[uid]:
17                heapq.heappush(heap, (-tweet[0], tweet[1]))
18
19        result = []
20        while heap and len(result) < 10:
21            result.append(heapq.heappop(heap)[1])
22        return result
23
24    def follow(self, followerId: int, followeeId: int) -> None:
25        self.follows[followerId].add(followeeId)
26
27    def unfollow(self, followerId: int, followeeId: int) -> None:
28        self.follows[followerId].discard(followeeId)

Time and space complexity

Time

O(T log T) feed, O(1) others

Posting, following and unfollowing are constant time. The feed pushes all T tweets from the user and their followees onto a heap, at O(log T) each, then pops at most 10.

Space

O(U + P + F)

Memory holds every posted tweet (P), every follow relationship (F) and an entry per user (U). A feed call also builds a temporary heap of up to T entries.

Other approaches

K-way merge with one tweet per followee (time O(F + 10 log F) feed, space O(F) per feed)

Seed the heap with only the newest tweet of each followee and the user, then after each pop push that user's next older tweet. The feed touches at most 10 tweets beyond the initial seeds.

Keep only recent tweets per user (time O(F log F) feed, space O(10 × U + F))

Store each user's tweets in a bounded deque of the last 10, since older tweets can never appear in a feed. It caps memory and the size of each merge without changing the results.

Common mistakes

  • Using Python's min-heap with positive timestamps returns the oldest tweets first; negate the time or use a max-heap.
  • Forgetting to include the user's own tweets in their feed.
  • Using remove instead of discard in unfollow, which raises an error when the user was never followed.
  • Ordering tweets by tweet id instead of by post time; ids are arbitrary and do not reflect recency.

Frequently asked questions

How do you get the 10 most recent tweets efficiently?

Treat each followee's tweets as a sorted list and do a k-way merge with a heap, stopping after 10 items. Only the newest tweet of each followee needs to be in the heap at the start.

Why use a global timestamp instead of tweet ids?

Tweet ids are not guaranteed to increase over time. A counter that ticks on every post gives a reliable ordering across all users.

Should a user's feed include their own tweets?

Yes. The feed covers the user and everyone they follow, which the code handles by adding the user's own id to the set of followees for the feed.

What happens when a user unfollows someone?

That user's tweets simply stop being collected in future feeds. Nothing is deleted, so re-following brings them back.