LeetCode #355 Medium

Design Twitter

Design Twitter is LeetCode 355 (Medium). Build a Twitter class with four methods:

  • postTweet(userId, tweetId) posts a new tweet.
  • getNewsFeed(userId) returns the IDs of the 10 most recent tweets posted by the user or by anyone they follow, newest first.
  • follow(followerId, followeeId) and unfollow(followerId, followeeId) change who a user follows.

There are up to 3 × 10⁴ calls and 500 users, so a feed request should not have to sort every tweet ever posted.

Constraints
  • 1 <= userId, followerId, followeeId <= 500
  • 0 <= tweetId <= 10⁴
  • All the tweets have unique IDs.
  • At most 3 * 10⁴ calls will be made to postTweet, getNewsFeed, follow, and unfollow.
  • A user cannot follow himself.
designheaphash-tablek-way-merge
Open on LeetCode ↗
02

Intuition

Give every tweet a time from one shared clock. Then each user's own tweets form a list that is already sorted, oldest to newest, and a news feed is just the 10 newest tweets across a few sorted lists: the user's own and those of everyone they follow.

That is a k-way merge, run from the newest end:

  • Heap: holds the newest unused tweet of each user in the feed.
  • Pop: the heap's top is the newest tweet overall, so it goes next in the feed.
  • Refill: push the popped user's next older tweet, so the heap again holds every user's newest unused tweet.

Stop after 10 pops. Everything still in the heap, or never pushed, is older than what was returned.

How to spot this pattern

"The newest few items from several lists that are each already in order" is a k-way merge with a heap, the same idea as Merge k Sorted Lists. Only the head of each list can be next, so the heap holds one item per list.

03

Approach

Try it first

Before reading on, decide what each user should store so that their tweets stay in time order across users. Then work out which tweets a feed request actually has to look at before it knows the newest one. Aim for O(F log F) per feed, where F is the number of users in it.

1

Post with a shared clock

Keep one counter for the whole class. postTweet adds 1 to it and appends (time, tweetId) to the user's list, so every list is in time order and times from different users can be compared.

2

Follow and unfollow with a set

Store each user's followees in a set. follow adds an ID and unfollow removes one with discard. A set ignores a repeated follow, so no user is merged twice.

3

Seed the heap

For the user and each followee with at least one tweet, push their newest tweet as (-time, tweetId, user, index). Python's heapq is a min-heap, so the negative time puts the newest tweet on top. The index remembers where in that user's list the tweet sits.

4

Pop, record, refill

While the heap is not empty and the feed has fewer than 10 tweets:

  • pop the top and append its tweetId to the feed;
  • if that user has an older tweet (index > 0), push it.

The refill keeps one candidate per user in the heap, so the next pop is always the newest tweet not yet in the feed.

04

Code in Python, C++ and Java

▶1class Twitter:
▶2 def __init__(self):
▶3 self.time = 0
▶4 self.tweets = defaultdict(list)
▶5 self.following = defaultdict(set)
▶6 
▶7 def postTweet(self, userId: int, tweetId: int) -> None:
▶8 self.time += 1
▶9 self.tweets[userId].append((self.time, tweetId))
▶10 
▶11 def getNewsFeed(self, userId: int) -> List[int]:
▶12 heap = []
▶13 for user in self.following[userId] | {userId}:
▶14 if self.tweets[user]:
▶15 i = len(self.tweets[user]) - 1
▶16 time, tweet_id = self.tweets[user][i]
▶17 heapq.heappush(heap, (-time, tweet_id, user, i))
▶18 
▶19 feed = []
▶20 while heap and len(feed) < 10:
▶21 _, tweet_id, user, i = heapq.heappop(heap)
▶22 feed.append(tweet_id)
▶23 if i > 0:
▶24 time, prev_id = self.tweets[user][i - 1]
▶25 heapq.heappush(heap, (-time, prev_id, user, i - 1))
▶26 return feed
▶27 
▶28 def follow(self, followerId: int, followeeId: int) -> None:
▶29 self.following[followerId].add(followeeId)
▶30 
▶31 def unfollow(self, followerId: int, followeeId: int) -> None:
▶32 self.following[followerId].discard(followeeId)
callpostTweet(1, 5)user 15t1user 2no tweetsheapnewest firstemptyfeedat most 10user 1 posts 5 at t1
time1
tweets[1]5
Add 1 to the clock and append (t1, 5) to user 1's list. One clock shared by all users puts every tweet in a single global order, and appending keeps each list oldest to newest.
callgetNewsFeed(1)user 15t1user 2no tweetsheapnewest first5t1feedat most 10push user 1's newest: 5
user1
pushed5 (t1)
User 1 is in the feed (it is the user's own list). Push only their newest tweet: an older tweet from the same user can never come out before it.
callgetNewsFeed(1)user 15t1user 2no tweetsheapnewest firstemptyfeedat most 105pop newest: 5 (t1) → feed
popped5t1, user 1
feed[5]
The heap's top is the newest tweet not yet in the feed: 5 at t1. Every other candidate is older, so it is next in the feed. User 1 has no older tweet, so their list is used up.
callgetNewsFeed(1)user 15t1user 2no tweetsheapnewest firstemptyfeedat most 105heap empty → return 1 tweet
getNewsFeed(1)[5]
The heap is empty: every tweet from the users in this feed has been used. Return [5], newest first.
callfollow(1, 2)user 1follows 25t1user 2no tweetsheapnewest firstemptyfeedat most 10user 1 now follows 2
following[1]2
Add 2 to user 1's set of followees. A set ignores a repeated follow, so the same user is never merged into the feed twice.
callpostTweet(2, 6)user 1follows 25t1user 26t2heapnewest firstemptyfeedat most 10user 2 posts 6 at t2
time2
tweets[2]6
Add 1 to the clock and append (t2, 6) to user 2's list. One clock shared by all users puts every tweet in a single global order, and appending keeps each list oldest to newest.
callgetNewsFeed(1)user 1follows 25t1user 26t2heapnewest first5t1feedat most 10push user 1's newest: 5
user1
pushed5 (t1)
User 1 is in the feed (it is the user's own list). Push only their newest tweet: an older tweet from the same user can never come out before it.
callgetNewsFeed(1)user 1follows 25t1user 26t2heapnewest first6t25t1feedat most 10push user 2's newest: 6
user2
pushed6 (t2)
User 2 is in the feed (user 1 follows them). Push only their newest tweet: an older tweet from the same user can never come out before it.
callgetNewsFeed(1)user 1follows 25t1user 26t2heapnewest first5t1feedat most 106pop newest: 6 (t2) → feed
popped6t2, user 2
feed[6]
The heap's top is the newest tweet not yet in the feed: 6 at t2. Every other candidate is older, so it is next in the feed. User 2 has no older tweet, so their list is used up.
callgetNewsFeed(1)user 1follows 25t1user 26t2heapnewest firstemptyfeedat most 1065pop newest: 5 (t1) → feed
popped5t1, user 1
feed[6, 5]
The heap's top is the newest tweet not yet in the feed: 5 at t1. Every other candidate is older, so it is next in the feed. User 1 has no older tweet, so their list is used up.
callgetNewsFeed(1)user 1follows 25t1user 26t2heapnewest firstemptyfeedat most 1065heap empty → return 2 tweets
getNewsFeed(1)[6, 5]
The heap is empty: every tweet from the users in this feed has been used. Return [6, 5], newest first.
callunfollow(1, 2)user 15t1user 26t2heapnewest firstemptyfeedat most 10user 1 stops following 2
following[1]nobody
Remove 2 from user 1's followees. Their tweets stay stored; they just stop being merged into 1's feed.
callgetNewsFeed(1)user 15t1user 26t2heapnewest first5t1feedat most 10push user 1's newest: 5
user1
pushed5 (t1)
User 1 is in the feed (it is the user's own list). Push only their newest tweet: an older tweet from the same user can never come out before it.
callgetNewsFeed(1)user 15t1user 26t2heapnewest firstemptyfeedat most 105pop newest: 5 (t1) → feed
popped5t1, user 1
feed[5]
The heap's top is the newest tweet not yet in the feed: 5 at t1. Every other candidate is older, so it is next in the feed. User 1 has no older tweet, so their list is used up.
callgetNewsFeed(1)user 15t1user 26t2heapnewest firstemptyfeedat most 105heap empty → return 1 tweet
getNewsFeed(1)[5]
The heap is empty: every tweet from the users in this feed has been used. Return [5], newest first.
05

Common pitfalls

Pushing every historical tweet

✗ Wrong
for time, tweet_id in self.tweets[user]:
✓ Right
time, tweet_id = self.tweets[user][i]

Only the newest tweet from each user can be the next feed item. Adding entire histories makes a feed request grow with all stored tweets.

Forgetting the user's own posts

✗ Wrong
for user in self.following[userId]:
✓ Right
for user in self.following[userId] | {userId}:

A user's feed always includes their own tweets even though following themselves is not required.

Returning more than ten items

✗ Wrong
while heap:
✓ Right
while heap and len(feed) < 10:

The feed holds at most 10 tweets. Merging further returns too many IDs and does extra work.

06

Edge cases

Unfollowing someone the user does not follow

discard leaves the set unchanged. set.remove would raise a KeyError here, and the C++ and Java removals are also no-ops.

A user with no tweets and no followees

Nothing is pushed into the heap, so the loop never runs and the feed is [].

07

Complexity

Time
O(F log F) per feed, O(1) for the rest
Space
O(T + R)
F is the number of users in the feed (the user plus their followees), T the number of stored tweets and R the number of follow links. Seeding pushes at most F tweets, and the loop does at most 10 pops and 10 pushes on a heap of at most F entries.
08

Design Twitter FAQ

Why not collect all the tweets and sort them?

It gives the same feed: gather every tweet from the user and their followees, sort by time and keep 10. But a feed request then touches every tweet those users ever posted, up to 3 × 10⁴, and sorts them all to use 10. The heap looks at only one tweet per user plus at most 10 more.

Is this the same as the Twitter system design interview question?

No. The system design version is about servers, storage, caching and fan-out across millions of users. LeetCode 355 is the in-memory core of one feed: a single class with a clock, follow sets and a heap. The merge idea is the same one a real feed service uses when it builds a timeline when the user reads it.