355. Design Twitter LeetCode Solution
In this guide, you will get 355. Design Twitter LeetCode Solution with the best time and space complexity. The solution to Design Twitter problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.
Table of Contents
- Problem Statement
- Complexity Analysis
- Design Twitter solution in C++
- Design Twitter solution in Java
- Design Twitter solution in Python
- Additional Resources

Problem Statement of Design Twitter
Design a simplified version of Twitter where users can post tweets, follow/unfollow another user, and is able to see the 10 most recent tweets in the user’s news feed.
Implement the Twitter class:
Twitter() Initializes your twitter object.
void postTweet(int userId, int tweetId) Composes a new tweet with ID tweetId by the user userId. Each call to this function will be made with a unique tweetId.
List getNewsFeed(int userId) Retrieves the 10 most recent tweet IDs in the user’s news feed. Each item in the news feed must be posted by users who the user followed or by the user themself. Tweets must be ordered from most recent to least recent.
void follow(int followerId, int followeeId) The user with ID followerId started following the user with ID followeeId.
void unfollow(int followerId, int followeeId) The user with ID followerId started unfollowing the user with ID followeeId.
Example 1:
Input
[“Twitter”, “postTweet”, “getNewsFeed”, “follow”, “postTweet”, “getNewsFeed”, “unfollow”, “getNewsFeed”]
[[], [1, 5], [1], [1, 2], [2, 6], [1], [1, 2], [1]]
Output
[null, null, [5], null, null, [6, 5], null, [5]]
Explanation
Twitter twitter = new Twitter();
twitter.postTweet(1, 5); // User 1 posts a new tweet (id = 5).
twitter.getNewsFeed(1); // User 1’s news feed should return a list with 1 tweet id -> [5]. return [5]
twitter.follow(1, 2); // User 1 follows user 2.
twitter.postTweet(2, 6); // User 2 posts a new tweet (id = 6).
twitter.getNewsFeed(1); // User 1’s news feed should return a list with 2 tweet ids -> [6, 5]. Tweet id 6 should precede tweet id 5 because it is posted after tweet id 5.
twitter.unfollow(1, 2); // User 1 unfollows user 2.
twitter.getNewsFeed(1); // User 1’s news feed should return a list with 1 tweet id -> [5], since user 1 is no longer following user 2.
Constraints:
1 <= userId, followerId, followeeId <= 500
0 <= tweetId <= 104
All the tweets have unique IDs.
At most 3 * 104 calls will be made to postTweet, getNewsFeed, follow, and unfollow.
A user cannot follow himself.
Complexity Analysis
- Time Complexity: O(n + k\log k), where n = |\texttt{tweets}| and k = \min(10, |\texttt{tweets}|))
- Space Complexity: O(n)
355. Design Twitter LeetCode Solution in C++
struct Tweet {
int id;
int time;
Tweet* next = nullptr;
};
struct User {
int id;
unordered_set<int> followeeIds;
Tweet* tweetHead = nullptr;
User() {}
User(int id) : id(id) {
follow(id);
}
void follow(int followeeId) {
followeeIds.insert(followeeId);
}
void unfollow(int followeeId) {
followeeIds.erase(followeeId);
}
void post(int tweetId, int time) {
Tweet* oldTweetHead = tweetHead;
tweetHead = new Tweet(tweetId, time);
tweetHead->next = oldTweetHead;
}
};
class Twitter {
public:
/** Compose a new tweet. */
void postTweet(int userId, int tweetId) {
if (!users.contains(userId))
users[userId] = User(userId);
users[userId].post(tweetId, time++);
}
/**
* Retrieve the 10 most recent tweet ids in the user's news feed. Each item in
* the news feed must be posted by users who the user followed or by the user
* herself. Tweets must be ordered from most recent to least recent.
*/
vector<int> getNewsFeed(int userId) {
if (!users.contains(userId))
return {};
vector<int> newsFeed;
auto compare = [](const Tweet* a, const Tweet* b) {
return a->time < b->time;
};
priority_queue<Tweet*, vector<Tweet*>, decltype(compare)> maxHeap(compare);
for (const int followeeId : users[userId].followeeIds) {
Tweet* tweetHead = users[followeeId].tweetHead;
if (tweetHead != nullptr)
maxHeap.push(tweetHead);
}
int count = 0;
while (!maxHeap.empty() && count++ < 10) {
Tweet* tweet = maxHeap.top();
maxHeap.pop();
newsFeed.push_back(tweet->id);
if (tweet->next)
maxHeap.push(tweet->next);
}
return newsFeed;
}
/**
* Follower follows a followee.
* If the operation is invalid, it should be a no-op.
*/
void follow(int followerId, int followeeId) {
if (followerId == followeeId)
return;
if (!users.contains(followerId))
users[followerId] = User(followerId);
if (!users.contains(followeeId))
users[followeeId] = User(followeeId);
users[followerId].follow(followeeId);
}
/**
* Follower unfollows a followee.
* If the operation is invalid, it should be a no-op.
*/
void unfollow(int followerId, int followeeId) {
if (followerId == followeeId)
return;
if (const auto it = users.find(followerId);
it != users.cend() && users.contains(followeeId))
it->second.unfollow(followeeId);
}
private:
int time = 0;
unordered_map<int, User> users; // {userId: User}
};
/* code provided by PROGIEZ */
355. Design Twitter LeetCode Solution in Java
class Tweet {
public int id;
public int time;
public Tweet next = null;
public Tweet(int id, int time) {
this.id = id;
this.time = time;
}
}
class User {
private int id;
public Set<Integer> followeeIds = new HashSet<>();
public Tweet tweetHead = null;
public User(int id) {
this.id = id;
follow(id);
}
public void follow(int followeeId) {
followeeIds.add(followeeId);
}
public void unfollow(int followeeId) {
followeeIds.remove(followeeId);
}
public void post(int tweetId, int time) {
final Tweet oldTweetHead = tweetHead;
tweetHead = new Tweet(tweetId, time);
tweetHead.next = oldTweetHead;
}
}
class Twitter {
/** Compose a new tweet. */
public void postTweet(int userId, int tweetId) {
users.putIfAbsent(userId, new User(userId));
users.get(userId).post(tweetId, time++);
}
/**
* Retrieve the 10 most recent tweet ids in the user's news feed. Each item in
* the news feed must be posted by users who the user followed or by the user
* herself. Tweets must be ordered from most recent to least recent.
*/
public List<Integer> getNewsFeed(int userId) {
if (!users.containsKey(userId))
return new ArrayList<>();
List<Integer> newsFeed = new ArrayList<>();
Queue<Tweet> maxHeap = new PriorityQueue<>((a, b) -> Integer.compare(b.time, a.time));
for (final int followeeId : users.get(userId).followeeIds) {
Tweet tweetHead = users.get(followeeId).tweetHead;
if (tweetHead != null)
maxHeap.offer(tweetHead);
}
int count = 0;
while (!maxHeap.isEmpty() && count++ < 10) {
Tweet tweet = maxHeap.poll();
newsFeed.add(tweet.id);
if (tweet.next != null)
maxHeap.offer(tweet.next);
}
return newsFeed;
}
/**
* Follower follows a followee.
* If the operation is invalid, it should be a no-op.
*/
public void follow(int followerId, int followeeId) {
if (followerId == followeeId)
return;
users.putIfAbsent(followerId, new User(followerId));
users.putIfAbsent(followeeId, new User(followeeId));
users.get(followerId).follow(followeeId);
}
/**
* Follower unfollows a followee.
* If the operation is invalid, it should be a no-op.
*/
public void unfollow(int followerId, int followeeId) {
if (followerId == followeeId)
return;
if (users.containsKey(followerId) && users.containsKey(followeeId))
users.get(followerId).unfollow(followeeId);
}
private int time = 0;
private Map<Integer, User> users = new HashMap<>(); // {userId: User}
}
// code provided by PROGIEZ
355. Design Twitter LeetCode Solution in Python
class Twitter:
def __init__(self):
self.timer = itertools.count(step=-1)
self.tweets = collections.defaultdict(deque)
self.followees = collections.defaultdict(set)
def postTweet(self, userId: int, tweetId: int) -> None:
self.tweets[userId].appendleft((next(self.timer), tweetId))
if len(self.tweets[userId]) > 10:
self.tweets[userId].pop()
def getNewsFeed(self, userId: int) -> list[int]:
tweets = list(
heapq.merge(
*
(self.tweets[followee]
for followee in self.followees[userId] | {userId})))
return [tweetId for _, tweetId in tweets[:10]]
def follow(self, followerId: int, followeeId: int) -> None:
self.followees[followerId].add(followeeId)
def unfollow(self, followerId: int, followeeId: int) -> None:
self.followees[followerId].discard(followeeId)
# code by PROGIEZ
Additional Resources
- Explore all LeetCode problem solutions at Progiez here
- Explore all problems on LeetCode website here
Happy Coding! Keep following PROGIEZ for more updates and solutions.