355. Design Twitter
Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.
Approach
The problem asks us to design a simplified Twitter-like system. The core functionalities are posting tweets, following/unfollowing users, and retrieving a personalized news feed. The news feed for a user must contain the 10 most recent tweets from themselves and the users they follow, ordered from most recent to least recent. The main challenge is to efficiently generate this news feed, especially when a user follows many others who post frequently.
Solution
Design Twitter in Python
import collections
import heapq
from typing import List
class Twitter:
def __init__(self):
"""
Initializes your twitter object.
"""
self.time = 0
# defaultdict simplifies handling of new users.
# userTweets: userId -> deque of (time, tweetId) pairs
self.userTweets = collections.defaultdict(collections.deque)
# following: followerId -> set of followeeIds
self.following = collections.defaultdict(set)
# Max number of tweets to store per user
self.tweet_limit = 10
def postTweet(self, userId: int, tweetId: int) -> None:
"""
Composes a new tweet with ID tweetId by the user userId.
"""
# Add tweet with a global timestamp to the user's tweet deque (most recent first).
self.userTweets[userId].appendleft((self.time, tweetId))
self.time += 1
# We only need the 10 most recent tweets per user for news feed generation.
if len(self.userTweets[userId]) > self.tweet_limit:
self.userTweets[userId].pop()
def getNewsFeed(self, userId: int) -> List[int]:
"""
Retrieves the 10 most recent tweet IDs in the user's news feed.
"""
# Use a min-heap to perform a k-way merge of tweet lists.
# Python's heapq is a min-heap, so we store negative time to simulate a max-heap.
min_heap = []
# The user's own tweets are part of the news feed.
# Create a set of users to fetch tweets from.
users_to_check = self.following[userId].copy()
users_to_check.add(userId)
# Initialize the heap with the most recent tweet from each relevant user.
for u_id in users_to_check:
if self.userTweets[u_id]:
# Get the most recent tweet (at index 0 of the deque).
time, tweetId = self.userTweets[u_id][0]
# Push (neg_time, tweetId, userId, index_of_tweet_in_deque).
heapq.heappush(min_heap, (-time, tweetId, u_id, 0))
news_feed = []
# Extract up to 10 most recent tweets.
while min_heap and len(news_feed) < self.tweet_limit:
neg_time, tweetId, u_id, tweet_idx = heapq.heappop(min_heap)
news_feed.append(tweetId)
# If the user has more tweets, push their next most recent tweet to the heap.
next_tweet_idx = tweet_idx + 1
if next_tweet_idx < len(self.userTweets[u_id]):
next_time, next_tweetId = self.userTweets[u_id][next_tweet_idx]
heapq.heappush(min_heap, (-next_time, next_tweetId, u_id, next_tweet_idx))
return news_feed
def follow(self, followerId: int, followeeId: int) -> None:
"""
The user with ID followerId started following the user with ID followeeId.
"""
# A user cannot follow themselves.
if followerId != followeeId:
self.following[followerId].add(followeeId)
def unfollow(self, followerId: int, followeeId: int) -> None:
"""
The user with ID followerId started unfollowing the user with ID followeeId.
"""
# Use discard to avoid an error if followerId is not following followeeId.
self.following[followerId].discard(followeeId)
Design Twitter in Java
import java.util.*;
class Twitter {
// A global timestamp to order tweets chronologically.
private long time;
// Stores follower -> set of followees.
private Map<Integer, Set<Integer>> following;
// Stores user -> deque of their 10 most recent tweets (time, tweetId).
private Map<Integer, Deque<int[]>> userTweets;
// Maximum number of tweets to retrieve for the news feed.
private static final int NEWS_FEED_SIZE = 10;
public Twitter() {
time = 0;
following = new HashMap<>();
userTweets = new HashMap<>();
}
public void postTweet(int userId, int tweetId) {
// Get or create the tweet deque for the user.
userTweets.computeIfAbsent(userId, k -> new ArrayDeque<>());
// Add the new tweet with timestamp to the front.
userTweets.get(userId).addFirst(new int[]{(int)time++, tweetId});
// We only need to store 10 most recent tweets per user.
if (userTweets.get(userId).size() > NEWS_FEED_SIZE) {
userTweets.get(userId).removeLast();
}
}
public List<Integer> getNewsFeed(int userId) {
// Max-heap to merge k sorted lists of tweets. Ordered by time descending.
// Heap stores {time, tweetId, userId, iterator for user's tweets}
PriorityQueue<int[]> maxHeap = new PriorityQueue<>((a, b) -> b[0] - a[0]);
// Get the set of users to fetch tweets from (user themselves + followees).
Set<Integer> usersToFetch = following.getOrDefault(userId, new HashSet<>());
usersToFetch.add(userId);
// Map to keep track of iterators for each user's tweet deque.
Map<Integer, Iterator<int[]>> iterators = new HashMap<>();
for (int u_id : usersToFetch) {
if (userTweets.containsKey(u_id)) {
iterators.put(u_id, userTweets.get(u_id).iterator());
}
}
// Initialize the heap with the most recent tweet from each relevant user.
for (int u_id : usersToFetch) {
if (iterators.containsKey(u_id) && iterators.get(u_id).hasNext()) {
int[] tweet = iterators.get(u_id).next();
maxHeap.offer(new int[]{tweet[0], tweet[1], u_id});
}
}
List<Integer> newsFeed = new ArrayList<>();
// Extract up to 10 tweets from the heap.
while (!maxHeap.isEmpty() && newsFeed.size() < NEWS_FEED_SIZE) {
int[] top = maxHeap.poll();
int tweetId = top[1];
int u_id = top[2];
newsFeed.add(tweetId);
// If the user has more tweets, push the next one to the heap.
if (iterators.get(u_id).hasNext()) {
int[] nextTweet = iterators.get(u_id).next();
maxHeap.offer(new int[]{nextTweet[0], nextTweet[1], u_id});
}
}
return newsFeed;
}
public void follow(int followerId, int followeeId) {
// A user cannot follow themselves.
if (followerId != followeeId) {
following.computeIfAbsent(followerId, k -> new HashSet<>()).add(followeeId);
}
}
public void unfollow(int followerId, int followeeId) {
if (following.containsKey(followerId)) {
following.get(followerId).remove(followeeId);
}
}
}
Design Twitter in C++
class Twitter {
private:
// A global timestamp to order tweets chronologically.
long long time;
// Stores follower -> set of followees.
std::unordered_map<int, std::unordered_set<int>> following;
// Stores user -> deque of their 10 most recent tweets (time, tweetId).
std::unordered_map<int, std::deque<std::pair<int, int>>> userTweets;
// Maximum number of tweets to store per user.
const int TWEET_LIMIT = 10;
public:
Twitter() {
time = 0;
}
void postTweet(int userId, int tweetId) {
// Add the new tweet to the front of the user's tweet deque.
userTweets[userId].push_front({(int)time++, tweetId});
// Ensure we only store the last 10 tweets.
if (userTweets[userId].size() > TWEET_LIMIT) {
userTweets[userId].pop_back();
}
}
vector<int> getNewsFeed(int userId) {
// Max-heap to merge k sorted lists of tweets.
// The heap stores tuples of (time, tweetId, userId, tweetIndex).
std::priority_queue<std::tuple<int, int, int, int>> maxHeap;
// Get the set of users to fetch tweets from (user themselves + followees).
std::unordered_set<int> usersToFetch = following[userId];
usersToFetch.insert(userId);
// Initialize the heap with the most recent tweet from each relevant user.
for (int u_id : usersToFetch) {
if (!userTweets[u_id].empty()) {
auto& tweet = userTweets[u_id][0];
maxHeap.push({tweet.first, tweet.second, u_id, 0});
}
}
vector<int> newsFeed;
// Extract up to 10 tweets from the heap.
while (!maxHeap.empty() && newsFeed.size() < TWEET_LIMIT) {
auto top = maxHeap.top();
maxHeap.pop();
int t_time = std::get<0>(top);
int t_id = std::get<1>(top);
int u_id = std::get<2>(top);
int t_idx = std::get<3>(top);
newsFeed.push_back(t_id);
// If the user has more tweets, push the next one to the heap.
int next_t_idx = t_idx + 1;
if (next_t_idx < userTweets[u_id].size()) {
auto& next_tweet = userTweets[u_id][next_t_idx];
maxHeap.push({next_tweet.first, next_tweet.second, u_id, next_t_idx});
}
}
return newsFeed;
}
void follow(int followerId, int followeeId) {
// A user cannot follow themselves.
if (followerId != followeeId) {
following[followerId].insert(followeeId);
}
}
void unfollow(int followerId, int followeeId) {
following[followerId].erase(followeeId);
}
};
Design Twitter in TypeScript
type Tweet = {
time: number;
tweetId: number;
};
type HeapNode = {
time: number;
tweetId: number;
userId: number;
tweetIndex: number;
};
// Helper Max-Priority Queue for merging tweets
class MaxPriorityQueue {
private heap: HeapNode[] = [];
private getParentIndex(i: number): number { return Math.floor((i - 1) / 2); }
private getLeftChildIndex(i: number): number { return 2 * i + 1; }
private getRightChildIndex(i: number): number { return 2 * i + 2; }
private swap(i: number, j: number): void {
[this.heap[i], this.heap[j]] = [this.heap[j], this.heap[i]];
}
private siftUp(i: number): void {
let parentIndex = this.getParentIndex(i);
while (i > 0 && this.heap[i].time > this.heap[parentIndex].time) {
this.swap(i, parentIndex);
i = parentIndex;
parentIndex = this.getParentIndex(i);
}
}
private siftDown(i: number): void {
let maxIndex = i;
const leftIndex = this.getLeftChildIndex(i);
if (leftIndex < this.heap.length && this.heap[leftIndex].time > this.heap[maxIndex].time) {
maxIndex = leftIndex;
}
const rightIndex = this.getRightChildIndex(i);
if (rightIndex < this.heap.length && this.heap[rightIndex].time > this.heap[maxIndex].time) {
maxIndex = rightIndex;
}
if (i !== maxIndex) {
this.swap(i, maxIndex);
this.siftDown(maxIndex);
}
}
push(node: HeapNode): void {
this.heap.push(node);
this.siftUp(this.heap.length - 1);
}
pop(): HeapNode | undefined {
if (this.heap.length === 0) return undefined;
this.swap(0, this.heap.length - 1);
const popped = this.heap.pop();
if (this.heap.length > 0) {
this.siftDown(0);
}
return popped;
}
isEmpty(): boolean {
return this.heap.length === 0;
}
}
class Twitter {
private time: number;
private following: Map<number, Set<number>>;
private userTweets: Map<number, Tweet[]>; // Using array as a deque
private readonly TWEET_LIMIT = 10;
constructor() {
this.time = 0;
this.following = new Map();
this.userTweets = new Map();
}
postTweet(userId: number, tweetId: number): void {
if (!this.userTweets.has(userId)) {
this.userTweets.set(userId, []);
}
const tweets = this.userTweets.get(userId)!;
// Add to front
tweets.unshift({ time: this.time++, tweetId });
// Keep only 10 most recent
if (tweets.length > this.TWEET_LIMIT) {
tweets.pop();
}
}
getNewsFeed(userId: number): number[] {
const maxHeap = new MaxPriorityQueue();
const usersToFetch = new Set<number>();
usersToFetch.add(userId);
if (this.following.has(userId)) {
this.following.get(userId)!.forEach(id => usersToFetch.add(id));
}
usersToFetch.forEach(uId => {
if (this.userTweets.has(uId)) {
const tweets = this.userTweets.get(uId)!;
if (tweets.length > 0) {
const latestTweet = tweets[0];
maxHeap.push({ time: latestTweet.time, tweetId: latestTweet.tweetId, userId: uId, tweetIndex: 0 });
}
}
});
const newsFeed: number[] = [];
while (!maxHeap.isEmpty() && newsFeed.length < this.TWEET_LIMIT) {
const top = maxHeap.pop()!;
newsFeed.push(top.tweetId);
const nextTweetIndex = top.tweetIndex + 1;
const userTweetList = this.userTweets.get(top.userId)!;
if (nextTweetIndex < userTweetList.length) {
const nextTweet = userTweetList[nextTweetIndex];
maxHeap.push({ time: nextTweet.time, tweetId: nextTweet.tweetId, userId: top.userId, tweetIndex: nextTweetIndex });
}
}
return newsFeed;
}
follow(followerId: number, followeeId: number): void {
if (followerId === followeeId) return;
if (!this.following.has(followerId)) {
this.following.set(followerId, new Set());
}
this.following.get(followerId)!.add(followeeId);
}
unfollow(followerId: number, followeeId: number): void {
if (this.following.has(followerId)) {
this.following.get(followerId)!.delete(followeeId);
}
}
}
More Medium LeetCode answers
Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.
LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.