Design Twitter
Difficulty: Medium · Pattern: Heap & Priority Queue · LeetCode #355
Design a simplified Twitter:
postTweet(userId, tweetId): the user posts a new tweet (tweet ids are unique).getNewsFeed(userId): return the 10 most recent tweet ids from the user and everyone they follow, newest first.follow(followerId, followeeId)/unfollow(followerId, followeeId). A user cannot unfollow themselves, and unfollowing someone you don't follow does nothing.
Example
text
postTweet(1, 5); getNewsFeed(1) → [5]
follow(1, 2); postTweet(2, 6); getNewsFeed(1) → [6, 5]
unfollow(1, 2); getNewsFeed(1) → [5]Hints
- Give every tweet a global, increasing timestamp so tweets from different users can be compared.
- Each user's tweet list is already sorted by time. The feed is a k-way merge of those lists, stopped after 10 items.
Approach
State:
tweets[u]: list of(time, id)in posting order.following[u]: a set of followees.- A global
timecounter.
getNewsFeed(u): put the latest tweet of each user in {u} ∪ following[u] into a max-heap keyed by time. Pop 10 times, and each pop pushes that user's previous tweet. That's O(F + 10 log F) for F followees, instead of merging every tweet from every followee.
Follow and unfollow are set operations. Ignore self-follows/unfollows, since the user is always implicitly in their own feed.
Complexity
Time: post/follow/unfollow O(1); getNewsFeed O(F + 10 log F) with a heap. Space: O(tweets + follows).
Python solution
import heapq
from collections import defaultdict
class Twitter:
def __init__(self):
self.time = 0
self.tweets = defaultdict(list)
self.following = defaultdict(set)
def postTweet(self, userId, tweetId):
self.time += 1
self.tweets[userId].append((self.time, tweetId))
def getNewsFeed(self, userId):
heap = []
for u in self.following[userId] | {userId}:
if self.tweets[u]:
j = len(self.tweets[u]) - 1
t, tid = self.tweets[u][j]
heap.append((-t, tid, u, j))
heapq.heapify(heap)
feed = []
while heap and len(feed) < 10:
_, tid, u, j = heapq.heappop(heap)
feed.append(tid)
if j > 0:
t, nid = self.tweets[u][j - 1]
heapq.heappush(heap, (-t, nid, u, j - 1))
return feed
def follow(self, followerId, followeeId):
if followerId != followeeId:
self.following[followerId].add(followeeId)
def unfollow(self, followerId, followeeId):
self.following[followerId].discard(followeeId)JavaScript solution
class Twitter {
constructor() { this.time = 0; this.tweets = new Map(); this.following = new Map(); }
postTweet(userId, tweetId) {
if (!this.tweets.has(userId)) this.tweets.set(userId, []);
this.tweets.get(userId).push([++this.time, tweetId]);
}
getNewsFeed(userId) {
// Small k-way merge: at most 10 pops, so a linear scan over the candidate heads is fine.
const users = [userId, ...(this.following.get(userId) || [])];
const ptr = new Map(users.map((u) => [u, (this.tweets.get(u) || []).length - 1]));
const feed = [];
while (feed.length < 10) {
let bestU = null, bestT = -1;
for (const u of users) { const j = ptr.get(u); if (j >= 0) { const t = this.tweets.get(u)[j][0]; if (t > bestT) { bestT = t; bestU = u; } } }
if (bestU === null) break;
const j = ptr.get(bestU);
feed.push(this.tweets.get(bestU)[j][1]);
ptr.set(bestU, j - 1);
}
return feed;
}
follow(a, b) { if (a === b) return; if (!this.following.has(a)) this.following.set(a, new Set()); this.following.get(a).add(b); }
unfollow(a, b) { this.following.get(a)?.delete(b); }
}