Design Twitter LeetCode Solution

Last updated on January 5th, 2025 at 12:36 am

Here, we see a Design Twitter LeetCode Solution. This Leetcode problem is solved using different approaches in many programming languages, such as C++, Java, JavaScript, Python, etc.

List of all LeetCode Solution

Topics

Design, Hash Table, Heap

Companies

Amazon, Twitter

Level of Question

Medium

Design Twitter LeetCode Solution

Design Twitter LeetCode Solution

1. Problem Statement

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<Integer> 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.

2. Coding Pattern Used in Solution

The coding pattern used in this code is “Top ‘K’ Elements”. This pattern is evident because the getNewsFeed function in all implementations uses a priority queue (heap) to retrieve the top 10 most recent tweets (based on timestamp). The goal is to efficiently fetch the “top K” (in this case, 10) elements from a potentially large dataset of tweets.

3. Code Implementation in Different Languages

3.1 Design Twitter C++

class Twitter {
    private:    
    unordered_map<int, set<int>> fo;
    unordered_map<int, vector<pair<int, int>>> t;
    long long time; 

    public:
    Twitter() {
        time = 0;
    }

    void postTweet(int userId, int tweetId) {
        t[userId].push_back({time++, tweetId});
    }
    vector<int> getNewsFeed(int userId) {
        priority_queue<pair<int, int>> maxHeap; 
        for (auto it=t[userId].begin();it!=t[userId].end();++it)
            maxHeap.push(*it);
        for (auto it1=fo[userId].begin();it1!=fo[userId].end();++it1){
            int usr = *it1;
            for (auto it2=t[usr].begin();it2!=t[usr].end();++it2)
                maxHeap.push(*it2);
        }   
        vector<int> res;
        while(maxHeap.size()>0) {
            res.push_back(maxHeap.top().second);
            if (res.size()==10) break;
            maxHeap.pop();
        }
        return res;
    }

    void follow(int followerId, int followeeId) {
        if (followerId != followeeId)
            fo[followerId].insert(followeeId);
    }

    void unfollow(int followerId, int followeeId) {
        fo[followerId].erase(followeeId);
    }
};

3.2 Design Twitter Java

public class Twitter {
	private static int timeStamp=0;
	private Map<Integer, User> userMap;
	private class Tweet{
		public int id;
		public int time;
		public Tweet next;
		public Tweet(int id){
			this.id = id;
			time = timeStamp++;
			next=null;
		}
	}
	public class User{
		public int id;
		public Set<Integer> followed;
		public Tweet tweet_head;
		public User(int id){
			this.id=id;
			followed = new HashSet<>();
			follow(id);
			tweet_head = null;
		}
		public void follow(int id){
			followed.add(id);
		}
		public void unfollow(int id){
			followed.remove(id);
		}
		public void post(int id){
			Tweet t = new Tweet(id);
			t.next=tweet_head;
			tweet_head=t;
		}
	}

	public Twitter() {
		userMap = new HashMap<Integer, User>();
	}

	public void postTweet(int userId, int tweetId) {
		if(!userMap.containsKey(userId)){
			User u = new User(userId);
			userMap.put(userId, u);
		}
		userMap.get(userId).post(tweetId);

	}

	public List<Integer> getNewsFeed(int userId) {
		List<Integer> res = new LinkedList<>();
		if(!userMap.containsKey(userId))   return res;
		Set<Integer> users = userMap.get(userId).followed;
		PriorityQueue<Tweet> q = new PriorityQueue<Tweet>(users.size(), (a,b)->(b.time-a.time));
		for(int user: users){
			Tweet t = userMap.get(user).tweet_head;
			if(t!=null){
				q.add(t);
			}
		}
		int n=0;
		while(!q.isEmpty() && n<10){
		  Tweet t = q.poll();
		  res.add(t.id);
		  n++;
		  if(t.next!=null)
			q.add(t.next);
		}
		return res;
	}

	public void follow(int followerId, int followeeId) {
		if(!userMap.containsKey(followerId)){
			User u = new User(followerId);
			userMap.put(followerId, u);
		}
		if(!userMap.containsKey(followeeId)){
			User u = new User(followeeId);
			userMap.put(followeeId, u);
		}
		userMap.get(followerId).follow(followeeId);
	}

	public void unfollow(int followerId, int followeeId) {
		if(!userMap.containsKey(followerId) || followerId==followeeId)
			return;
		userMap.get(followerId).unfollow(followeeId);
	}
}

3.3 Design Twitter JavaScript

var Twitter = function() {
    this.followMap = {};
    this.tweetMap = {};
    this.time = 0;
    this.tweetTimeMap = {};
    this.newArrayForKey = function(map, key){
        if(!map[key])
            map[key] = [];
    }
};

Twitter.prototype.postTweet = function(userId, tweetId) {
    this.newArrayForKey(this.tweetMap, userId);
    if(this.tweetMap[userId].indexOf(tweetId) === -1){
        this.tweetMap[userId].push(tweetId);
        this.tweetTimeMap[tweetId] = this.time ++;
    }
};

Twitter.prototype.getNewsFeed = function(userId) {
    var list = [];
    if(this.tweetMap[userId])
        list = list.concat(this.tweetMap[userId]);
    for(var followeeKey in this.followMap[userId]){
        var followeeId = this.followMap[userId][followeeKey];
        if(followeeId != userId && this.tweetMap[followeeId])
            list = list.concat(this.tweetMap[followeeId]);
    }
    that = this;
    return list.sort(function (a, b){
        return that.tweetTimeMap[b] - that.tweetTimeMap[a];
    }).slice(0, 10);
};

Twitter.prototype.follow = function(followerId, followeeId) {
    this.newArrayForKey(this.followMap, followerId);
    if(this.followMap[followerId].indexOf(followeeId) === -1)
        this.followMap[followerId].push(followeeId);
};

Twitter.prototype.unfollow = function(followerId, followeeId) {
    this.newArrayForKey(this.followMap, followerId);
    var index = this.followMap[followerId].indexOf(followeeId);
    if(index !== -1)
        this.followMap[followerId].splice(index, 1);
};

3.4 Design Twitter Python

class Twitter(object):

    def __init__(self):
        self.timer = itertools.count(step=-1)
        self.tweets = collections.defaultdict(collections.deque)
        self.followees = collections.defaultdict(set)

    def postTweet(self, userId, tweetId):
        self.tweets[userId].appendleft((next(self.timer), tweetId))

    def getNewsFeed(self, userId):
        tweets = heapq.merge(*(self.tweets[u] for u in self.followees[userId] | {userId}))
        return [t for _, t in itertools.islice(tweets, 10)]

    def follow(self, followerId, followeeId):
        self.followees[followerId].add(followeeId)

    def unfollow(self, followerId, followeeId):
        self.followees[followerId].discard(followeeId)

4. Space Complexity

Space Complexity
C++O(U + T)
JavaO(U + T)
JavaScriptO(U + T)
PythonO(U + T)

where, U is the number of users and T is the total number of tweets.

Scroll to Top