LeetCode 355. Design Twitter

Description:

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. Your design should support the following methods:

Example:

Twitter twitter = new Twitter();
// User 1 posts a new tweet (id = 5).
twitter.postTweet(1, 5);
// User 1’s news feed should return a list with 1 tweet id -> [5].
twitter.getNewsFeed(1);
// User 1 follows user 2.
twitter.follow(1, 2);
// User 2 posts a new tweet (id = 6).
twitter.postTweet(2, 6);
// 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.getNewsFeed(1);
// User 1 unfollows user 2.
twitter.unfollow(1, 2);
// User 1’s news feed should return a list with 1 tweet id -> [5],
// since user 1 is no longer following user 2.
twitter.getNewsFeed(1);

Solution:

class Twitter {
private:
    struct Tweet{
        int userID;
        int tweetID;
    }; 
    
    
public:
    /** Initialize your data structure here. */
    Twitter() {
        
    }
    
    /** Compose a new tweet. */
    void postTweet(int userID, int tweetID) {
        allTweet.push_back(Tweet{userID, tweetID});
    }
    
    /** 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) {
        vector<int> result;
        auto findResult = followRelation.find(userID);
        
        if(findResult != followRelation.end()){
            const auto &followee = findResult->second;
            for(auto iter = allTweet.rbegin(); iter != allTweet.rend(); ++iter){
                if(iter->userID == userID || followee.find(iter->userID) != followee.end()){
                    result.push_back(iter->tweetID);
                }
                if(result.size() == 10)break;
            }
        } else{
             for(auto iter = allTweet.rbegin(); iter != allTweet.rend(); ++iter){
                if(iter->userID == userID){
                    result.push_back(iter->tweetID);
                }
                if(result.size() == 10)break;
            }
        }

        return result;
    }
    
    /** Follower follows a followee. If the operation is invalid, it should be a no-op. */
    void follow(int followerID, int followeeID) {
        auto findResult = followRelation.find(followerID);
        if(findResult != followRelation.end()){
            findResult->second.insert(followeeID);
        } else{
            set<int> newSet;
            newSet.insert(followeeID);
            followRelation.insert(move(make_pair(followerID, move(newSet))));
        }
    }
    
    /** Follower unfollows a followee. If the operation is invalid, it should be a no-op. */
    void unfollow(int followerID, int followeeID) {
        followRelation[followerID].erase(followeeID);
    }
    
private:
    list<Tweet> allTweet;
    
    map<int, set<int>> followRelation;
    
    
};

/**
 * Your Twitter object will be instantiated and called as such:
 * Twitter obj = new Twitter();
 * obj.postTweet(userId,tweetId);
 * vector<int> param_2 = obj.getNewsFeed(userId);
 * obj.follow(followerId,followeeId);
 * obj.unfollow(followerId,followeeId);
 */

The naive approach. All posts are stored in a list according to their time. The drawback of this method is that we need to scan the entire post pool every time. This can be very costly when we have many users in the system.

class Twitter {
private:
    
    struct Tweet{
      int tweetId;
      int time;
    };
    
    
public:
    /** Initialize your data structure here. */
    Twitter() {
        
    }
    
    /** Compose a new tweet. */
    void postTweet(int userId, int tweetId) {
        auto findResult = userPost.find(userId);
        
        if(findResult != userPost.end()){
            findResult->second.push_back(Tweet{tweetId, time});
        } else{
            vector<Tweet> newVec;
            newVec.push_back(Tweet{tweetId, time});
            userPost.insert(move(make_pair(userId, move(newVec))));
        }
        
        ++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) {
        vector<Tweet> allPost;
        
        auto userFind = userPost.find(userId);
        if(userFind != userPost.end()){
            for(const auto &tweet : userFind->second){
                allPost.push_back(tweet);
            }
        }
        
        auto followerFind = followRelation.find(userId);
        if(followerFind != followRelation.end()){
            for(const auto &followee : followerFind->second){
                auto followeeFind = userPost.find(followee);
                if(followeeFind != userPost.end()){
                    for(const auto &tweet : followeeFind->second){
                        allPost.push_back(tweet);
                    }
                }
            }
        }
        
        auto sortPred = [](const Tweet &t1, const Tweet &t2){
            return t1.time < t2.time;
        };
        
        sort(allPost.begin(), allPost.end(), sortPred);
        
        vector<int> result;
        for(auto iter = allPost.rbegin(); iter != allPost.rend(); ++iter){
            result.push_back(iter->tweetId);
            if(result.size() == 10)break;
        }
        
        return result;
    }
    
    /** Follower follows a followee. If the operation is invalid, it should be a no-op. */
    void follow(int followerId, int followeeId) {
        // disallow following oneself
        if(followerId == followeeId)return;
        
        auto findResult = followRelation.find(followerId);
        if(findResult == followRelation.end()){
            set<int> newSet;
            newSet.insert(followeeId);
            followRelation.insert(move(make_pair(followerId, move(newSet))));
        } else{
            findResult->second.insert(followeeId);
        }
        
    }
    
    /** Follower unfollows a followee. If the operation is invalid, it should be a no-op. */
    void unfollow(int followerId, int followeeId) {
        // disallow unfollowing oneself
        if(followerId == followeeId)return;
        
        auto findResult = followRelation.find(followerId);
        
        if(findResult != followRelation.end()){
            findResult->second.erase(followeeId);
        }
        
    }
    
private:
    int time = numeric_limits<int>::min();
    map<int, vector<Tweet>> userPost;
    
    // using set to avoid repeated following
    map<int, set<int>> followRelation;
    
    // if using vector<int> to store followRelation, make sure to detect
    // unfollowing a non-existing followee
    
};



/**
 * Your Twitter object will be instantiated and called as such:
 * Twitter obj = new Twitter();
 * obj.postTweet(userId,tweetId);
 * vector<int> param_2 = obj.getNewsFeed(userId);
 * obj.follow(followerId,followeeId);
 * obj.unfollow(followerId,followeeId);
 */

The improved approach, which works better in practice, due to the fact that the number of posts from one user is significantly less than the number of all posts. Now the posts are stored separately under each user’s name. When news feed is needed, we need to collect all posts from all of the user’s followee, and sort them according to time.