Simple C++ Solution 33ms

  • 0

    Similar to other approaches here. I am using an unordered_map<int, unordered_set<int> > to store the subscription of followers and unordered_map<int, vector<int>> to store user tweets.
    For retrieving newsfeed, I am taking the last 10 tweets of every user followed by the given userid i.e. starting iteration from the end of the vector to the beinning.

    class Twitter {
        /** Initialize your data structure here. */
        Twitter() {
        /** Compose a new tweet. */
        void postTweet(int userId, int tweetId) {
            user_tweets[userId].push_back({tweetId, tweetc});
        /** 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> feed;
            priority_queue<tweet, vector<tweet>, mycomparator> feed_candidates;
            for(int user : subscription[userId])
                int count = 0;
                for(auto it = user_tweets[user].rbegin(); it != user_tweets[user].rend() && count < 10; it++, count++)
            for(int i = 0; i < 10 && !feed_candidates.empty(); i++)
                tweet t =;
            return feed;
        /** Follower follows a followee. If the operation is invalid, it should be a no-op. */
        void follow(int followerId, int followeeId) {
        /** Follower unfollows a followee. If the operation is invalid, it should be a no-op. */
        void unfollow(int followerId, int followeeId) {
        struct tweet{
            int tweetId;
            int time;
            struct mycomparator{
                bool operator() (const tweet &t1, const tweet &t2)
                    return t1.time < t2.time;
            unordered_map<int, unordered_set<int> > subscription;
            unordered_map<int, vector<tweet> > user_tweets;
            int tweetc;

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.