15% off all plans & roadmaps Use code
See plansDesign Twitter
- LeetCode 355
- Medium
- Heap (Priority Queue) Patterns
- K-way Merge
Updated
TL;DR: Build a Twitter class with post, follow, unfollow and a news feed of the 10 newest tweets. Keep each user's tweets in posting order and merge the followed users' lists with a max-heap. A feed then never touches more than about 10 tweets plus one head per source.
Problem
Implement a Twitter class that stores tweets and follow relationships. The constructor takes no arguments and starts an empty service. Every tweetId is unique, and tweets are ordered by when their postTweet calls happen: a later call means a more recent tweet.
postTweet(userId, tweetId)records a tweet byuserId. It returns nothing.follow(followerId, followeeId)makesfollowerIdfollowfolloweeId. It returns nothing.unfollow(followerId, followeeId)removes that relationship if it exists. It returns nothing.getNewsFeed(userId)returns up to the 10 most recent tweet IDs posted byuserIdor by any useruserIdcurrently follows, newest first. If there are no eligible tweets, return an empty list. This call does not change any stored state.
Example 1
Input: ["Twitter", "postTweet", "postTweet", "getNewsFeed", "follow", "postTweet", "getNewsFeed", "unfollow", "getNewsFeed"] [[],[7,501],[7,502],[7],[7,12],[12,880],[7],[7,12],[7]] Output: [null,null,null,[502,501],null,null,[880,502,501],null,[502,501]] Explanation: User 7 first sees their own two tweets. After following user 12, user 7 also sees tweet 880. Unfollowing user 12 removes it again.
Example 2
Input: ["Twitter", "follow", "postTweet", "postTweet", "getNewsFeed", "unfollow", "getNewsFeed", "unfollow", "getNewsFeed"] [[],[4,9],[9,31],[4,44],[4],[4,9],[4],[4,9],[22]] Output: [null,null,null,null,[44,31],null,[44],null,[]] Explanation: A follow created before either tweet is posted still lets user 4 see user 9's tweet. The second unfollow does nothing, and user 22 has no eligible tweets.
Example 3
Input: ["Twitter", "postTweet", "follow", "postTweet", "follow", "postTweet", "getNewsFeed", "unfollow", "getNewsFeed"] [[],[15,700],[3,15],[3,701],[3,15],[15,702],[3],[3,15],[3]] Output: [null,null,null,null,null,null,[702,701,700],null,[701]] Explanation: User 3 follows user 15, and the repeated follow changes nothing. The first feed lists the three tweets in reverse posting order. After the unfollow, only user 3's own tweet remains.
Constraints
- The first operation is
Twitter, and its argument list is empty. 1 <= operations.length <= 10^5.- Every later operation is
postTweet,getNewsFeed,follow, orunfollow. userId,followerId, andfolloweeIdare integers.tweetIdis an integer, and everytweetIdis unique across allpostTweetcalls.followerId != followeeIdfor everyfollowandunfollowcall.unfollowmay name a relationship that does not exist. Such a call is valid and has no effect.
Constraints that matter
- Up to 10^5 operations means a feed call cannot afford to sort every eligible tweet each time. A user who follows many busy accounts would make that cost grow with the whole history.
- The feed holds at most 10 tweets, so work should depend on 10 and on the number of sources, not on the total number of tweets stored.
- Every
tweetIdis unique, and posting order defines recency. A global counter gives each tweet a strict timestamp, so ties never happen. unfollowmay target a relationship that does not exist, andfollowmay repeat. Store followees in a set so both calls are safe and idempotent.followerId != followeeId, so a user is never in their own follow set. You still add the user as a source yourself in every feed call.
Hints
Hint 1
The feed is a merge.
Hint 2
Store each user's tweets as (timestamp, tweetId) pairs in a per-user list, and each user's followees in a set.
Solution
Intuition
The feed is a merge. Each eligible user owns a list of tweets already sorted by time, because you append in posting order. You want the 10 newest across several sorted lists. That is the k-way merge pattern.
Picture a stack of sorted mail trays, one per followed account, each with the newest letter on top. You keep a small tray of the current top letters, always pull out the newest one, and slide the next older letter from that same account's pile into the tray. The heap is the tray of tops, and the per-user lists are the piles.
The output is tiny and fixed. Only 10 tweets are ever returned, yet the history can be huge. Any solution that touches every eligible tweet pays for work the answer never uses. The signal for a heap is several sorted sources where you need only the first few merged items.
A max-heap works because the newest unseen tweet overall is always the newest unseen tweet of some single user. So the heap needs only one entry per source: that user's newest tweet not yet taken. When you pop an entry, the only new candidate is the next older tweet from the same user. You push it and continue.
That gives a feed cost of about F log F for F sources, with at most 10 pops. Posting and following stay O(1), since they only append to a list or edit a set.
Worked example
Input: operations = ["Twitter", "follow", "postTweet", "postTweet", "getNewsFeed", "unfollow", "getNewsFeed", "unfollow", "getNewsFeed"] arguments = [[], [4, 9], [9, 31], [4, 44], [4], [4, 9], [4], [4, 9], [22]] Output: [null,null,null,null,[44,31],null,[44],null,[]] Explanation: User 4 follows user 9 before any tweet exists. User 9 posts 31 and user 4 posts 44, so user 4's feed is [44, 31]. After unfollowing user 9 only 44 remains. The second unfollow changes nothing, and user 22 has posted nothing and follows nobody, so that feed is empty.
Approach 1: Brute force: collect and sort
Store each user's tweets as (timestamp, tweetId) pairs in a per-user list, and each user's followees in a set. For a feed, gather every tweet from the user and all followees into one list, sort it by timestamp descending, and cut it to 10.
This is correct because the sorted list is exactly the eligible history in recency order. It does far more work than the answer needs.
Steps
- Keep a global counter
timethat increases by 1 on everypostTweet. - On
postTweet, append(time, tweetId)to the author's list. - On
follow, add the followee to the follower's set. Onunfollow, discard it if present. - On
getNewsFeed, build the source set: the user plus the followees. - Append every tweet of every source to one list.
- Sort that list by timestamp, newest first.
- Return the tweet IDs of the first 10 entries.
Dry run
Run the example. follow(4, 9) stores following[4] = {9}. postTweet(9, 31) stores (1, 31) for user 9. postTweet(4, 44) stores (2, 44) for user 4.
First getNewsFeed(4): sources are {4, 9}. The collected list is [(2, 44), (1, 31)] in some order. Sorted descending it is [(2, 44), (1, 31)], so the result is [44, 31].
unfollow(4, 9) empties the set. The next getNewsFeed(4) collects only user 4's list [(2, 44)] and returns [44]. The second unfollow finds nothing to remove. getNewsFeed(22) has source set {22} with no tweets, so it returns [].
Complexity
| Time | O(T log T) per getNewsFeed, O(1) for the other calls |
|---|---|
| Space | O(T) for the feed call, plus O(total tweets + follows) stored |
Let T be the total number of tweets by the user and everyone the user follows. Collecting them touches each tweet once, which is O(T), and sorting costs O(T log T). Posting and following only append to a list or edit a set, so they are O(1). The temporary list holds all T tweets, so a feed call needs O(T) extra space.
PythonTested in our runner
from typing import List, Optional
class Twitter:
def __init__(self):
self.time = 0
self.tweets = {} # userId -> list of (time, tweetId)
self.following = {} # userId -> set of followeeIds
def postTweet(self, userId: int, tweetId: int) -> None:
self.time += 1
self.tweets.setdefault(userId, []).append((self.time, tweetId))
def getNewsFeed(self, userId: int) -> List[int]:
sources = set(self.following.get(userId, set()))
sources.add(userId)
collected = []
for u in sources:
collected.extend(self.tweets.get(u, []))
collected.sort(reverse=True) # newest timestamp first
return [tweetId for _, tweetId in collected[:10]]
def follow(self, followerId: int, followeeId: int) -> None:
self.following.setdefault(followerId, set()).add(followeeId)
def unfollow(self, followerId: int, followeeId: int) -> None:
self.following.get(followerId, set()).discard(followeeId)
JavaTested in our runner
import java.util.*;
class Twitter {
private int time = 0;
private Map<Integer, List<int[]>> tweets = new HashMap<>();
private Map<Integer, Set<Integer>> following = new HashMap<>();
public Twitter() {
}
public void postTweet(int userId, int tweetId) {
time++;
tweets.computeIfAbsent(userId, k -> new ArrayList<>()).add(new int[]{time, tweetId});
}
public int[] getNewsFeed(int userId) {
Set<Integer> sources = new HashSet<>();
sources.add(userId);
Set<Integer> followed = following.get(userId);
if (followed != null) {
sources.addAll(followed);
}
List<int[]> collected = new ArrayList<>();
for (int u : sources) {
List<int[]> list = tweets.get(u);
if (list != null) {
collected.addAll(list);
}
}
collected.sort((a, b) -> b[0] - a[0]); // newest first
int n = Math.min(10, collected.size());
int[] feed = new int[n];
for (int i = 0; i < n; i++) {
feed[i] = collected.get(i)[1];
}
return feed;
}
public void follow(int followerId, int followeeId) {
following.computeIfAbsent(followerId, k -> new HashSet<>()).add(followeeId);
}
public void unfollow(int followerId, int followeeId) {
Set<Integer> set = following.get(followerId);
if (set != null) {
set.remove(followeeId);
}
}
}
C++Tested in our runner
#include <vector>
#include <unordered_map>
#include <unordered_set>
#include <algorithm>
using namespace std;
class Twitter {
int timer = 0;
unordered_map<int, vector<pair<int, int>>> tweets; // user -> (time, tweetId)
unordered_map<int, unordered_set<int>> following;
public:
Twitter() {
}
void postTweet(int userId, int tweetId) {
tweets[userId].push_back({++timer, tweetId});
}
vector<int> getNewsFeed(int userId) {
unordered_set<int> sources;
sources.insert(userId);
auto fit = following.find(userId);
if (fit != following.end()) {
sources.insert(fit->second.begin(), fit->second.end());
}
vector<pair<int, int>> collected;
for (int u : sources) {
auto it = tweets.find(u);
if (it != tweets.end()) {
collected.insert(collected.end(), it->second.begin(), it->second.end());
}
}
sort(collected.begin(), collected.end(), greater<pair<int, int>>());
vector<int> feed;
for (size_t i = 0; i < collected.size() && i < 10; i++) {
feed.push_back(collected[i].second);
}
return feed;
}
void follow(int followerId, int followeeId) {
following[followerId].insert(followeeId);
}
void unfollow(int followerId, int followeeId) {
auto it = following.find(followerId);
if (it != following.end()) {
it->second.erase(followeeId);
}
}
};
JavaScriptTested in our runner
var Twitter = function() {
this.time = 0;
this.tweets = new Map(); // userId -> [[time, tweetId], ...]
this.following = new Map(); // userId -> Set of followeeIds
};
/**
* @param {number} userId
* @param {number} tweetId
* @return {void}
*/
Twitter.prototype.postTweet = function(userId, tweetId) {
this.time++;
if (!this.tweets.has(userId)) this.tweets.set(userId, []);
this.tweets.get(userId).push([this.time, tweetId]);
};
/**
* @param {number} userId
* @return {number[]}
*/
Twitter.prototype.getNewsFeed = function(userId) {
const sources = new Set(this.following.get(userId) || []);
sources.add(userId);
const collected = [];
for (const u of sources) {
const list = this.tweets.get(u);
if (list) {
for (const t of list) collected.push(t);
}
}
collected.sort((a, b) => b[0] - a[0]);
return collected.slice(0, 10).map(t => t[1]);
};
/**
* @param {number} followerId
* @param {number} followeeId
* @return {void}
*/
Twitter.prototype.follow = function(followerId, followeeId) {
if (!this.following.has(followerId)) this.following.set(followerId, new Set());
this.following.get(followerId).add(followeeId);
};
/**
* @param {number} followerId
* @param {number} followeeId
* @return {void}
*/
Twitter.prototype.unfollow = function(followerId, followeeId) {
const set = this.following.get(followerId);
if (set) set.delete(followeeId);
};
GoTested in our runner
import "sort"
type Twitter struct {
time int
tweets map[int][][2]int // user -> list of {time, tweetId}
following map[int]map[int]bool
}
func Constructor() Twitter {
return Twitter{
tweets: map[int][][2]int{},
following: map[int]map[int]bool{},
}
}
func (this *Twitter) postTweet(userId int, tweetId int) {
this.time++
this.tweets[userId] = append(this.tweets[userId], [2]int{this.time, tweetId})
}
func (this *Twitter) getNewsFeed(userId int) []int {
sources := map[int]bool{userId: true}
for f := range this.following[userId] {
sources[f] = true
}
collected := [][2]int{}
for u := range sources {
collected = append(collected, this.tweets[u]...)
}
sort.Slice(collected, func(i, j int) bool {
return collected[i][0] > collected[j][0]
})
feed := []int{}
for i := 0; i < len(collected) && i < 10; i++ {
feed = append(feed, collected[i][1])
}
return feed
}
func (this *Twitter) follow(followerId int, followeeId int) {
if this.following[followerId] == nil {
this.following[followerId] = map[int]bool{}
}
this.following[followerId][followeeId] = true
}
func (this *Twitter) unfollow(followerId int, followeeId int) {
delete(this.following[followerId], followeeId)
}
C#Tested in our runner
public class Twitter {
private int time = 0;
private Dictionary<int, List<int[]>> tweets = new Dictionary<int, List<int[]>>();
private Dictionary<int, HashSet<int>> following = new Dictionary<int, HashSet<int>>();
public Twitter() {
}
public void postTweet(int userId, int tweetId) {
time++;
if (!tweets.ContainsKey(userId)) {
tweets[userId] = new List<int[]>();
}
tweets[userId].Add(new int[] { time, tweetId });
}
public int[] getNewsFeed(int userId) {
var sources = new HashSet<int>();
sources.Add(userId);
if (following.TryGetValue(userId, out var followed)) {
sources.UnionWith(followed);
}
var collected = new List<int[]>();
foreach (var u in sources) {
if (tweets.TryGetValue(u, out var list)) {
collected.AddRange(list);
}
}
collected.Sort((a, b) => b[0].CompareTo(a[0])); // newest first
return collected.Take(10).Select(t => t[1]).ToArray();
}
public void follow(int followerId, int followeeId) {
if (!following.ContainsKey(followerId)) {
following[followerId] = new HashSet<int>();
}
following[followerId].Add(followeeId);
}
public void unfollow(int followerId, int followeeId) {
if (following.TryGetValue(followerId, out var set)) {
set.Remove(followeeId);
}
}
}
Approach 2: Scan the global log backwards
What's slow: the brute force sorts every eligible tweet, even though you keep only 10. The sort is wasted, because tweets are already in posting order.
The insight that fixes it: keep one global log of (author, tweetId) in posting order. Walk it from the newest entry backwards, keep entries whose author is the user or a followee, and stop at 10. No sorting and no timestamps are needed, since position in the log is the time.
Steps
- Keep one list
logof (author, tweetId), appended on everypostTweet. - Keep a set of followees per user, edited by
followandunfollow. - On
getNewsFeed, start an empty result and an index at the last log entry. - Move the index backwards one entry at a time.
- If the entry's author is the user or is in the follow set, add its tweet ID to the result.
- Stop when the result has 10 tweets or the index passes the start of the log.
- Return the result.
Dry run
On the example, the log after both posts is [(9, 31), (4, 44)]. following[4] is {9} for the first feed.
getNewsFeed(4) starts at the last entry (4, 44). Author 4 is the user, so the result becomes [44]. The next entry is (9, 31). Author 9 is followed, so the result becomes [44, 31]. The log is exhausted and the answer is [44, 31].
After unfollow(4, 9) the follow set is empty. The scan takes (4, 44), then skips (9, 31) because 9 is not followed. The result is [44].
For user 22 both entries are skipped and the result is [].
Complexity
| Time | O(N) per getNewsFeed in the worst case, O(1) for the other calls |
|---|---|
| Space | O(1) extra per feed call, plus O(N + follows) stored |
Let N be the total number of tweets ever posted. A feed call visits each log entry at most once and does an O(1) set lookup per entry, so it is O(N) in the worst case. That worst case happens when the user has fewer than 10 eligible tweets and the scan reaches the start of the log.
Posting appends one entry and follow edits one set, so both are O(1). The result holds at most 10 IDs, so extra space per call is constant.
PythonTested in our runner
from typing import List, Optional
class Twitter:
def __init__(self):
self.log = [] # (author, tweetId) in posting order
self.following = {} # userId -> set of followeeIds
def postTweet(self, userId: int, tweetId: int) -> None:
self.log.append((userId, tweetId))
def getNewsFeed(self, userId: int) -> List[int]:
followed = self.following.get(userId, set())
feed = []
for i in range(len(self.log) - 1, -1, -1):
author, tweetId = self.log[i]
if author == userId or author in followed:
feed.append(tweetId)
if len(feed) == 10:
break
return feed
def follow(self, followerId: int, followeeId: int) -> None:
self.following.setdefault(followerId, set()).add(followeeId)
def unfollow(self, followerId: int, followeeId: int) -> None:
self.following.get(followerId, set()).discard(followeeId)
JavaTested in our runner
import java.util.*;
class Twitter {
private List<int[]> log = new ArrayList<>(); // {author, tweetId}
private Map<Integer, Set<Integer>> following = new HashMap<>();
public Twitter() {
}
public void postTweet(int userId, int tweetId) {
log.add(new int[]{userId, tweetId});
}
public int[] getNewsFeed(int userId) {
Set<Integer> followed = following.getOrDefault(userId, Collections.emptySet());
int[] feed = new int[10];
int count = 0;
for (int i = log.size() - 1; i >= 0 && count < 10; i--) {
int[] entry = log.get(i);
if (entry[0] == userId || followed.contains(entry[0])) {
feed[count++] = entry[1];
}
}
return Arrays.copyOf(feed, count);
}
public void follow(int followerId, int followeeId) {
following.computeIfAbsent(followerId, k -> new HashSet<>()).add(followeeId);
}
public void unfollow(int followerId, int followeeId) {
Set<Integer> set = following.get(followerId);
if (set != null) {
set.remove(followeeId);
}
}
}
C++Tested in our runner
#include <vector>
#include <unordered_map>
#include <unordered_set>
using namespace std;
class Twitter {
vector<pair<int, int>> log; // (author, tweetId) in posting order
unordered_map<int, unordered_set<int>> following;
public:
Twitter() {
}
void postTweet(int userId, int tweetId) {
log.push_back({userId, tweetId});
}
vector<int> getNewsFeed(int userId) {
const unordered_set<int>* followed = nullptr;
auto it = following.find(userId);
if (it != following.end()) {
followed = &it->second;
}
vector<int> feed;
for (int i = (int)log.size() - 1; i >= 0 && feed.size() < 10; i--) {
int author = log[i].first;
if (author == userId || (followed && followed->count(author))) {
feed.push_back(log[i].second);
}
}
return feed;
}
void follow(int followerId, int followeeId) {
following[followerId].insert(followeeId);
}
void unfollow(int followerId, int followeeId) {
auto it = following.find(followerId);
if (it != following.end()) {
it->second.erase(followeeId);
}
}
};
JavaScriptTested in our runner
var Twitter = function() {
this.log = []; // [author, tweetId] in posting order
this.following = new Map(); // userId -> Set of followeeIds
};
/**
* @param {number} userId
* @param {number} tweetId
* @return {void}
*/
Twitter.prototype.postTweet = function(userId, tweetId) {
this.log.push([userId, tweetId]);
};
/**
* @param {number} userId
* @return {number[]}
*/
Twitter.prototype.getNewsFeed = function(userId) {
const followed = this.following.get(userId);
const feed = [];
for (let i = this.log.length - 1; i >= 0 && feed.length < 10; i--) {
const author = this.log[i][0];
if (author === userId || (followed && followed.has(author))) {
feed.push(this.log[i][1]);
}
}
return feed;
};
/**
* @param {number} followerId
* @param {number} followeeId
* @return {void}
*/
Twitter.prototype.follow = function(followerId, followeeId) {
if (!this.following.has(followerId)) this.following.set(followerId, new Set());
this.following.get(followerId).add(followeeId);
};
/**
* @param {number} followerId
* @param {number} followeeId
* @return {void}
*/
Twitter.prototype.unfollow = function(followerId, followeeId) {
const set = this.following.get(followerId);
if (set) set.delete(followeeId);
};
GoTested in our runner
type Twitter struct {
log [][2]int // {author, tweetId} in posting order
following map[int]map[int]bool
}
func Constructor() Twitter {
return Twitter{following: map[int]map[int]bool{}}
}
func (this *Twitter) postTweet(userId int, tweetId int) {
this.log = append(this.log, [2]int{userId, tweetId})
}
func (this *Twitter) getNewsFeed(userId int) []int {
followed := this.following[userId] // reading a nil map is safe
feed := []int{}
for i := len(this.log) - 1; i >= 0 && len(feed) < 10; i-- {
author := this.log[i][0]
if author == userId || followed[author] {
feed = append(feed, this.log[i][1])
}
}
return feed
}
func (this *Twitter) follow(followerId int, followeeId int) {
if this.following[followerId] == nil {
this.following[followerId] = map[int]bool{}
}
this.following[followerId][followeeId] = true
}
func (this *Twitter) unfollow(followerId int, followeeId int) {
delete(this.following[followerId], followeeId)
}
C#Tested in our runner
public class Twitter {
private List<int[]> log = new List<int[]>(); // {author, tweetId}
private Dictionary<int, HashSet<int>> following = new Dictionary<int, HashSet<int>>();
public Twitter() {
}
public void postTweet(int userId, int tweetId) {
log.Add(new int[] { userId, tweetId });
}
public int[] getNewsFeed(int userId) {
following.TryGetValue(userId, out var followed);
var feed = new List<int>();
for (int i = log.Count - 1; i >= 0 && feed.Count < 10; i--) {
int author = log[i][0];
if (author == userId || (followed != null && followed.Contains(author))) {
feed.Add(log[i][1]);
}
}
return feed.ToArray();
}
public void follow(int followerId, int followeeId) {
if (!following.ContainsKey(followerId)) {
following[followerId] = new HashSet<int>();
}
following[followerId].Add(followeeId);
}
public void unfollow(int followerId, int followeeId) {
if (following.TryGetValue(followerId, out var set)) {
set.Remove(followeeId);
}
}
}

Solution pattern
K-way Merge
Part of Heap (Priority Queue) Patterns
Approach 3: Per-user lists with a max-heap mergeOptimalK-way Merge
What's slow: the backward scan still reads every tweet by strangers. If the user follows two quiet accounts in a service with 100,000 tweets from others, the scan crosses the whole log to find a handful of results.
The insight that fixes it: give each user their own list, sorted by time because you append. A feed is then a merge of F sorted lists, and you need only the first 10 merged items.
Put the newest tweet of each source in a max-heap keyed by timestamp. Pop the top, record it, and push the next older tweet of that same source. Tweets by unrelated users are never read.
Why it is correct. The heap always holds the newest not-yet-taken tweet from each source, so the global newest remaining tweet must be one of those tops. Popping it and pushing that source's next older tweet keeps this invariant. Since each source list is already in time order, no older tweet can jump ahead of a newer one from another source.
Steps
- Keep a global counter
time. OnpostTweet, append(time, tweetId)to the author's list. - Keep a set of followees per user for
followandunfollow. - On
getNewsFeed, build the source set: the user plus the followees. - For each source with tweets, push its last tweet into the heap as (time, tweetId, source, index).
- While the heap is not empty and the feed has fewer than 10 IDs, pop the entry with the largest time.
- Append its tweet ID to the feed.
- If its index is above 0, push the same source's tweet at index - 1.
- Return the feed.
Dry run
On the example, user 9 holds [(1, 31)] and user 4 holds [(2, 44)]. The first getNewsFeed(4) has sources {4, 9}. The heap starts as [(2, 44, user 4, idx 0), (1, 31, user 9, idx 0)].
Pop (2, 44): feed [44], and index 0 means nothing to push. Pop (1, 31): feed [44, 31]. The heap is empty, so the result is [44, 31].
After unfollow(4, 9), sources are {4}, the heap holds only (2, 44), and the result is [44]. For user 22 no source has tweets, the heap starts empty, and the result is []. The full step table is below.
| Step | Call | Sources | Heap after step (time, id) | Feed |
|---|---|---|---|---|
| 1 | follow(4, 9) | |||
| 2 | postTweet(9, 31) | user 9 list: [(1,31)] | ||
| 3 | postTweet(4, 44) | user 4 list: [(2,44)] | ||
| 4a | getNewsFeed(4): seed | {4, 9} | [(2,44), (1,31)] | [] |
| 4b | pop (2,44) | {4, 9} | [(1,31)] | [44] |
| 4c | pop (1,31) | {4, 9} | [] | [44, 31] |
| 5 | unfollow(4, 9) | |||
| 6a | getNewsFeed(4): seed | {4} | [(2,44)] | [] |
| 6b | pop (2,44) | {4} | [] | [44] |
| 7 | unfollow(4, 9) | no-op | ||
| 8 | getNewsFeed(22): seed | {22} | [] | [] |
Complexity
| Time | O(F log F) per getNewsFeed, O(1) for the other calls |
|---|---|
| Space | O(F) extra per feed call, plus O(total tweets + follows) stored |
Let F be the number of sources: the user plus the followees. Seeding pushes at most F entries, which costs O(F log F) with individual pushes and O(F) with heapify.
The loop pops at most 10 times and pushes at most once per pop. That adds at most 20 heap operations of O(log F) each, which is O(log F). The heap never holds more than F entries, because each pop is replaced by at most one push from the same source.
Posting appends to one list and following edits one set, so both are O(1).
PythonTested in our runner
import heapq
from typing import List, Optional
class Twitter:
def __init__(self):
self.time = 0
self.tweets = {} # userId -> list of (time, tweetId), oldest first
self.following = {} # userId -> set of followeeIds
def postTweet(self, userId: int, tweetId: int) -> None:
self.time += 1
self.tweets.setdefault(userId, []).append((self.time, tweetId))
def getNewsFeed(self, userId: int) -> List[int]:
sources = set(self.following.get(userId, set()))
sources.add(userId)
heap = []
for u in sources:
lst = self.tweets.get(u)
if lst:
i = len(lst) - 1
# negate time so Python's min-heap acts as a max-heap
heap.append((-lst[i][0], lst[i][1], u, i))
heapq.heapify(heap)
feed = []
while heap and len(feed) < 10:
_, tweetId, u, i = heapq.heappop(heap)
feed.append(tweetId)
if i > 0:
t = self.tweets[u][i - 1]
heapq.heappush(heap, (-t[0], t[1], u, i - 1))
return feed
def follow(self, followerId: int, followeeId: int) -> None:
self.following.setdefault(followerId, set()).add(followeeId)
def unfollow(self, followerId: int, followeeId: int) -> None:
self.following.get(followerId, set()).discard(followeeId)
JavaTested in our runner
import java.util.*;
class Twitter {
private int time = 0;
private Map<Integer, List<int[]>> tweets = new HashMap<>();
private Map<Integer, Set<Integer>> following = new HashMap<>();
public Twitter() {
}
public void postTweet(int userId, int tweetId) {
time++;
tweets.computeIfAbsent(userId, k -> new ArrayList<>()).add(new int[]{time, tweetId});
}
public int[] getNewsFeed(int userId) {
Set<Integer> sources = new HashSet<>();
sources.add(userId);
Set<Integer> followed = following.get(userId);
if (followed != null) {
sources.addAll(followed);
}
// entry: {time, tweetId, source, index}; largest time first
PriorityQueue<int[]> heap = new PriorityQueue<>((a, b) -> b[0] - a[0]);
for (int u : sources) {
List<int[]> list = tweets.get(u);
if (list != null && !list.isEmpty()) {
int i = list.size() - 1;
int[] t = list.get(i);
heap.add(new int[]{t[0], t[1], u, i});
}
}
int[] feed = new int[10];
int count = 0;
while (!heap.isEmpty() && count < 10) {
int[] cur = heap.poll();
feed[count++] = cur[1];
if (cur[3] > 0) {
int[] t = tweets.get(cur[2]).get(cur[3] - 1);
heap.add(new int[]{t[0], t[1], cur[2], cur[3] - 1});
}
}
return Arrays.copyOf(feed, count);
}
public void follow(int followerId, int followeeId) {
following.computeIfAbsent(followerId, k -> new HashSet<>()).add(followeeId);
}
public void unfollow(int followerId, int followeeId) {
Set<Integer> set = following.get(followerId);
if (set != null) {
set.remove(followeeId);
}
}
}
C++Tested in our runner
#include <vector>
#include <array>
#include <queue>
#include <unordered_map>
#include <unordered_set>
using namespace std;
class Twitter {
int timer = 0;
unordered_map<int, vector<pair<int, int>>> tweets; // user -> (time, tweetId)
unordered_map<int, unordered_set<int>> following;
public:
Twitter() {
}
void postTweet(int userId, int tweetId) {
tweets[userId].push_back({++timer, tweetId});
}
vector<int> getNewsFeed(int userId) {
unordered_set<int> sources;
sources.insert(userId);
auto fit = following.find(userId);
if (fit != following.end()) {
sources.insert(fit->second.begin(), fit->second.end());
}
// {time, tweetId, source, index}; default max-heap orders by time first
priority_queue<array<int, 4>> heap;
for (int u : sources) {
auto it = tweets.find(u);
if (it != tweets.end() && !it->second.empty()) {
int i = (int)it->second.size() - 1;
heap.push({it->second[i].first, it->second[i].second, u, i});
}
}
vector<int> feed;
while (!heap.empty() && feed.size() < 10) {
array<int, 4> cur = heap.top();
heap.pop();
feed.push_back(cur[1]);
int u = cur[2];
int i = cur[3];
if (i > 0) {
const pair<int, int>& t = tweets[u][i - 1];
heap.push({t.first, t.second, u, i - 1});
}
}
return feed;
}
void follow(int followerId, int followeeId) {
following[followerId].insert(followeeId);
}
void unfollow(int followerId, int followeeId) {
auto it = following.find(followerId);
if (it != following.end()) {
it->second.erase(followeeId);
}
}
};
JavaScriptTested in our runner
class MaxHeap {
constructor() {
this.a = [];
}
size() {
return this.a.length;
}
// each item is [time, tweetId, source, index]; ordered by time
push(item) {
const a = this.a;
a.push(item);
let i = a.length - 1;
while (i > 0) {
const p = (i - 1) >> 1;
if (a[p][0] >= a[i][0]) break;
[a[p], a[i]] = [a[i], a[p]];
i = p;
}
}
pop() {
const a = this.a;
const top = a[0];
const last = a.pop();
if (a.length > 0) {
a[0] = last;
let i = 0;
const n = a.length;
while (true) {
const l = 2 * i + 1;
const r = l + 1;
let m = i;
if (l < n && a[l][0] > a[m][0]) m = l;
if (r < n && a[r][0] > a[m][0]) m = r;
if (m === i) break;
[a[m], a[i]] = [a[i], a[m]];
i = m;
}
}
return top;
}
}
var Twitter = function() {
this.time = 0;
this.tweets = new Map(); // userId -> [[time, tweetId], ...]
this.following = new Map(); // userId -> Set of followeeIds
};
/**
* @param {number} userId
* @param {number} tweetId
* @return {void}
*/
Twitter.prototype.postTweet = function(userId, tweetId) {
this.time++;
if (!this.tweets.has(userId)) this.tweets.set(userId, []);
this.tweets.get(userId).push([this.time, tweetId]);
};
/**
* @param {number} userId
* @return {number[]}
*/
Twitter.prototype.getNewsFeed = function(userId) {
const sources = new Set(this.following.get(userId) || []);
sources.add(userId);
const heap = new MaxHeap();
for (const u of sources) {
const list = this.tweets.get(u);
if (list && list.length > 0) {
const i = list.length - 1;
heap.push([list[i][0], list[i][1], u, i]);
}
}
const feed = [];
while (heap.size() > 0 && feed.length < 10) {
const cur = heap.pop();
feed.push(cur[1]);
if (cur[3] > 0) {
const t = this.tweets.get(cur[2])[cur[3] - 1];
heap.push([t[0], t[1], cur[2], cur[3] - 1]);
}
}
return feed;
};
/**
* @param {number} followerId
* @param {number} followeeId
* @return {void}
*/
Twitter.prototype.follow = function(followerId, followeeId) {
if (!this.following.has(followerId)) this.following.set(followerId, new Set());
this.following.get(followerId).add(followeeId);
};
/**
* @param {number} followerId
* @param {number} followeeId
* @return {void}
*/
Twitter.prototype.unfollow = function(followerId, followeeId) {
const set = this.following.get(followerId);
if (set) set.delete(followeeId);
};
GoTested in our runner
import "container/heap"
type feedItem struct {
time, id, user, idx int
}
type feedHeap []feedItem
func (h feedHeap) Len() int { return len(h) }
func (h feedHeap) Less(i, j int) bool { return h[i].time > h[j].time } // max-heap by time
func (h feedHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] }
func (h *feedHeap) Push(x interface{}) { *h = append(*h, x.(feedItem)) }
func (h *feedHeap) Pop() interface{} {
old := *h
n := len(old)
x := old[n-1]
*h = old[:n-1]
return x
}
type Twitter struct {
time int
tweets map[int][][2]int // user -> list of {time, tweetId}
following map[int]map[int]bool
}
func Constructor() Twitter {
return Twitter{
tweets: map[int][][2]int{},
following: map[int]map[int]bool{},
}
}
func (this *Twitter) postTweet(userId int, tweetId int) {
this.time++
this.tweets[userId] = append(this.tweets[userId], [2]int{this.time, tweetId})
}
func (this *Twitter) getNewsFeed(userId int) []int {
sources := map[int]bool{userId: true}
for f := range this.following[userId] {
sources[f] = true
}
h := &feedHeap{}
for u := range sources {
l := this.tweets[u]
if len(l) > 0 {
i := len(l) - 1
*h = append(*h, feedItem{l[i][0], l[i][1], u, i})
}
}
heap.Init(h)
feed := []int{}
for h.Len() > 0 && len(feed) < 10 {
cur := heap.Pop(h).(feedItem)
feed = append(feed, cur.id)
if cur.idx > 0 {
t := this.tweets[cur.user][cur.idx-1]
heap.Push(h, feedItem{t[0], t[1], cur.user, cur.idx - 1})
}
}
return feed
}
func (this *Twitter) follow(followerId int, followeeId int) {
if this.following[followerId] == nil {
this.following[followerId] = map[int]bool{}
}
this.following[followerId][followeeId] = true
}
func (this *Twitter) unfollow(followerId int, followeeId int) {
delete(this.following[followerId], followeeId)
}
C#Tested in our runner
public class Twitter {
private int time = 0;
private Dictionary<int, List<int[]>> tweets = new Dictionary<int, List<int[]>>();
private Dictionary<int, HashSet<int>> following = new Dictionary<int, HashSet<int>>();
public Twitter() {
}
public void postTweet(int userId, int tweetId) {
time++;
if (!tweets.ContainsKey(userId)) {
tweets[userId] = new List<int[]>();
}
tweets[userId].Add(new int[] { time, tweetId });
}
public int[] getNewsFeed(int userId) {
var sources = new HashSet<int>();
sources.Add(userId);
if (following.TryGetValue(userId, out var followed)) {
sources.UnionWith(followed);
}
// PriorityQueue pops the smallest priority, so use the negated time
var pq = new PriorityQueue<(int id, int user, int idx), int>();
foreach (var u in sources) {
if (tweets.TryGetValue(u, out var list) && list.Count > 0) {
int i = list.Count - 1;
pq.Enqueue((list[i][1], u, i), -list[i][0]);
}
}
var feed = new List<int>();
while (pq.Count > 0 && feed.Count < 10) {
var cur = pq.Dequeue();
feed.Add(cur.id);
if (cur.idx > 0) {
var t = tweets[cur.user][cur.idx - 1];
pq.Enqueue((t[1], cur.user, cur.idx - 1), -t[0]);
}
}
return feed.ToArray();
}
public void follow(int followerId, int followeeId) {
if (!following.ContainsKey(followerId)) {
following[followerId] = new HashSet<int>();
}
following[followerId].Add(followeeId);
}
public void unfollow(int followerId, int followeeId) {
if (following.TryGetValue(followerId, out var set)) {
set.Remove(followeeId);
}
}
}
Common mistakes
- Forgetting to add the user to their own sources in
getNewsFeed. A user with no followees would get an empty feed. Build the source set as the followees plususerId. - Using
following[userId].remove(followeeId)without a guard. It raises an error in Python when the key or the element is missing, andunfollowis allowed to name a missing relationship. Usediscardon a defaulted set, or check for null first. - Using the tweet ID as the ordering key instead of a timestamp. Tweet IDs are unique but not increasing, so the feed would come out in the wrong order. Keep a global counter that increments on every
postTweet. - Pushing every tweet of every source into the heap at the start. That sorts the whole history and removes the benefit of the merge. Push only the last tweet of each source, then push the next older one after each pop.
- Forgetting to push the replacement after a pop (
if i > 0branch missing). A user with three tweets would contribute only one to the feed. After each pop, pushtweets[source][index - 1]when the index is above 0. - In Python, pushing
(time, ...)intoheapqwithout negating the time.heapqis a min-heap, so you would return the oldest tweets first. Push-time, or negate the comparison in a language that takes a comparator. - Storing the feed state inside the object, for example by deleting popped tweets from the user's list.
getNewsFeedmust not change state, so a second call would then return fewer tweets. Track a read position in the heap entry only.
Edge cases
- A user who never posted and follows nobody:
getNewsFeedreturns an empty list. unfollowon a relationship that never existed, or called twice: no effect and no error.- A repeated
follow: the set already holds the followee, so the relationship is unchanged and tweets are not duplicated in the feed. - Following a user before they post: later tweets by that user must appear in the follower's feed.
- More than 10 eligible tweets: only the 10 newest appear, newest first.
- A user follows someone, then unfollows them: that user's older tweets disappear from the feed, but the user's own tweets stay.
Follow-ups interviewers ask
- How would you make getNewsFeed cheaper when a user follows many accounts?
- The heap already limits work to F log F, where F is the number of followees. To do better, cache each user's recent 10 tweets and fan out on write: when a user posts, push the tweet into each follower's precomputed feed. Reads become O(10), and writes cost the number of followers. The trade-off is heavy writes for accounts with many followers, so real systems often mix both.
- Can you do getNewsFeed without a heap?
- Yes. The backward scan of one global log needs no heap and no sort, and it stops after 10 matches. Its worst case is O(N) in the total tweets posted, so it is slower when the user's sources are quiet. The heap version only reads the sources' own lists, so it is better when the service has many more tweets than the user's circle.
- How would you reduce memory if every user posts millions of tweets?
- A feed only ever needs the newest 10 tweets of each source, because a single source cannot contribute more than 10 results. Keep only the last 10 tweets per user in the feed structure, and move older tweets to cold storage. The heap merge then touches at most 10 entries per source, and each source list is capped at a constant size.
Design Twitter FAQ
What is the time complexity of Design Twitter?
With per-user lists and a heap, postTweet, follow and unfollow are O(1). getNewsFeed is O(F log F), where F is the number of sources: the user plus the followees. The heap never holds more than F entries and the feed pops at most 10 times. Space for one feed call is O(F).
Why use a heap for Design Twitter?
The feed merges several lists that are already sorted by time, and you only need the 10 newest results. A max-heap holding one candidate per source gives the newest tweet in O(log F) and reveals the next candidate after each pop. That avoids sorting every eligible tweet. This is the k-way merge pattern.
Can Design Twitter be solved in O(1) extra space?
Not with a heap or a sort, since both need space proportional to the number of sources. The backward scan of a global log uses O(1) extra space per feed call, because it keeps only the result list of at most 10 IDs. The cost is a worst-case O(N) scan. You also still store all tweets and follows, which no solution can avoid.
How do I solve LeetCode 355 in Python?
Keep a counter, a dict from user to a list of (time, tweetId), and a dict from user to a set of followees. In getNewsFeed, push the last tweet of each source into a heapq as (-time, tweetId, user, index). Pop up to 10 times and push the previous tweet of the popped source each time. The Python code on this page does exactly that.
Why does the heap hold only one tweet per user?
A user's newest unseen tweet always beats that user's older ones. So the overall newest unseen tweet must be the newest unseen tweet of some user. After you take it, only that user's next older tweet can become the new candidate. Every other source still shows the same candidate as before.
Does the order of follow and postTweet matter for the feed?
No. The feed is computed from the current follow set and the stored tweets at call time. Following a user before or after they post gives the same feed, and unfollowing hides their tweets immediately. Only the relative order of the posts themselves defines recency.
Asked at
See which companies ask this — Pro
Related problems
- Find K Pairs with Smallest Sums · same technique: K-way Merge
- Kth Smallest Element in a Sorted Matrix · same technique: K-way Merge
- Merge k Sorted Lists · same technique: K-way Merge
- Smallest Range Covering Elements from K Lists · same technique: K-way Merge
- Top K Frequent Elements · same pattern: Heap (Priority Queue) Patterns
- Meeting Rooms II · same pattern: Heap (Priority Queue) Patterns
- Kth Largest Element in an Array · same pattern: Heap (Priority Queue) Patterns
- K Closest Points to Origin · same pattern: Heap (Priority Queue) Patterns
- Reorganize String · same pattern: Heap (Priority Queue) Patterns
- Single-Threaded CPU · same pattern: Heap (Priority Queue) Patterns