Problem
Design a simplified Twitter with postTweet, follow, unfollow, and getNewsFeed. The news feed returns the ten most recent tweet ids from the user and the people they follow, newest first.
Original: LeetCode 355: Design Twitter.
Examples
Example 1
`Twitter: postTweet(1, 5), getNewsFeed(1), follow(1, 2), postTweet(2, 6), getNewsFeed(1), unfollow(1, 2), getNewsFeed(1)``[null, [5], null, null, [6, 5], null, [5]]`Constraints
1 <= userId, followerId, followeeId <= 5000 <= tweetId <= 10^4- All the tweets have unique IDs.
- At most
3 * 10^4calls will be made topostTweet,getNewsFeed,follow, andunfollow. - A user cannot follow himself.
Hints
Hint 1
A user should see their own tweets without an explicit follow. follow of yourself can be ignored. unfollow of someone you do not follow is a no-op. Tweet ids are unique.
Hint 2
This is feed aggregation: per-user tweet lists plus a k-way merge, the same idea as merge k sorted lists.
Solution
Tried it yourself? The approach, complexity, and code stay hidden until you choose.
Approach
Brute force. Collect every candidate tweet, sort by time, and take ten.
Optimal. A global clock, a list of (time, tweetId) per user, a set of followees per user, and a heap that starts with each person's latest tweet and walks backwards at most ten steps.
Alternative. A single global list of tweets, filtered by a follow set, is simpler but slower if the system has many tweets from people you do not follow.
Complexity
- Time
- O(k log k)
per getNewsFeed; the other operations are O(1) average
- Space
- O(users + tweets + follow edges)
Code
import heapq
from collections import defaultdict
class Twitter:
def __init__(self) -> None:
self.clock = 0
self.tweets: dict[int, list[tuple[int, int]]] = defaultdict(list)
self.follows: dict[int, set[int]] = defaultdict(set)
def post_tweet(self, user_id: int, tweet_id: int) -> None:
self.tweets[user_id].append((self.clock, tweet_id))
self.clock += 1
def get_news_feed(self, user_id: int) -> list[int]:
people = set(self.follows[user_id])
people.add(user_id)
heap: list[tuple[int, int, int, int]] = []
for u in people:
lst = self.tweets[u]
if lst:
time, tid = lst[-1]
heapq.heappush(heap, (-time, tid, u, len(lst) - 1))
feed: list[int] = []
while heap and len(feed) < 10:
_, tid, u, i = heapq.heappop(heap)
feed.append(tid)
if i > 0:
time, prev = self.tweets[u][i - 1]
heapq.heappush(heap, (-time, prev, u, i - 1))
return feed
def follow(self, follower_id: int, followee_id: int) -> None:
if follower_id != followee_id:
self.follows[follower_id].add(followee_id)
def unfollow(self, follower_id: int, followee_id: int) -> None:
self.follows[follower_id].discard(followee_id)
if __name__ == "__main__":
tw = Twitter()
tw.post_tweet(1, 5)
assert tw.get_news_feed(1) == [5]
tw.follow(1, 2)
tw.post_tweet(2, 6)
assert tw.get_news_feed(1) == [6, 5]
tw.unfollow(1, 2)
assert tw.get_news_feed(1) == [5]
print("ok")import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.PriorityQueue;
import java.util.Set;
public class DesignTwitter {
private int clock = 0;
private final Map<Integer, List<int[]>> tweets = new HashMap<>();
private final Map<Integer, Set<Integer>> follows = new HashMap<>();
void postTweet(int userId, int tweetId) {
tweets.computeIfAbsent(userId, k -> new ArrayList<>()).add(new int[] {clock++, tweetId});
}
List<Integer> getNewsFeed(int userId) {
var heap = new PriorityQueue<int[]>((a, b) -> Integer.compare(b[0], a[0]));
var people = new HashSet<Integer>();
people.add(userId);
people.addAll(follows.getOrDefault(userId, Set.of()));
for (int u : people) {
var list = tweets.get(u);
if (list == null || list.isEmpty()) continue;
int i = list.size() - 1;
int[] t = list.get(i);
heap.offer(new int[] {t[0], t[1], u, i});
}
var feed = new ArrayList<Integer>();
while (!heap.isEmpty() && feed.size() < 10) {
int[] cur = heap.poll();
feed.add(cur[1]);
int i = cur[3] - 1;
if (i >= 0) {
int[] t = tweets.get(cur[2]).get(i);
heap.offer(new int[] {t[0], t[1], cur[2], i});
}
}
return feed;
}
void follow(int followerId, int followeeId) {
if (followerId == followeeId) return;
follows.computeIfAbsent(followerId, k -> new HashSet<>()).add(followeeId);
}
void unfollow(int followerId, int followeeId) {
var set = follows.get(followerId);
if (set != null) set.remove(followeeId);
}
public static void main(String[] args) {
var tw = new DesignTwitter();
tw.postTweet(1, 5);
if (!tw.getNewsFeed(1).equals(List.of(5))) throw new AssertionError();
tw.follow(1, 2);
tw.postTweet(2, 6);
if (!tw.getNewsFeed(1).equals(List.of(6, 5))) throw new AssertionError();
tw.unfollow(1, 2);
if (!tw.getNewsFeed(1).equals(List.of(5))) throw new AssertionError();
System.out.println("ok");
}
}Edge cases
- Official sample: user 1 posts tweet 5 and sees [5]; user 1 follows 2, user 2 posts 6, and user 1 sees [6, 5]; after unfollow, the feed is [5] again.
- A user always sees their own tweets. Following yourself should not duplicate them.
Follow-ups
- A production feed would precompute a per-user timeline, with fan-out on write, instead of merging on read for very popular accounts.
Interview script
"I stamp every tweet with a global time and store it on the author. The news feed is a k-way merge of the user's tweets and their followees' tweets, limited to the ten newest ids."
Source: LeetCode 355: Design Twitter Source: Java SE 17 API: PriorityQueue
Sources (2)
- LeetCode 355: Design Twitterleetcode.com
- Java SE 17 API: PriorityQueuedocs.oracle.com