Skip to main content

Leet Code: Problem: 355. Design Twitter

Problem Statement:

Design basic twitter which lets user follow and unfollow other users and show the latest new feed related to the current user and the user followers. Implement the following APIs

void postTweet(int userId, int tweetId):
    Stores the tweetId against the user ID.

void follow(int followerId, int followeeId):
    Marks that follower ID as following followee ID

void unfollow(int followerId, int followeeId):
    Marks that follower ID as unfollowing followee ID

vector<int> getNewsFeed(int userId):
    Returns the set of the latest 10 tweetIDs which include the current user tweetIDs and tweetIDs of the user that the follower if following.


Approach to the problem:
  1. First we need to store the user IDs of the people a particular user is following
  2. To store that we can use map. To optimize things instead of storing list of followers, it is better to store them in a set for quicker access.
  3. So the followers data structure looks like unordered_map<int, unordered_set<int>>
  4. Second data structure is to store the tweet ids against the user id.
  5. Here the catch to get the latest tweets from the user we have to store a counter along with tweet ID to recognize how latest the tweet is.
  6. Larger the count, latest is the tweet ID
  7. After that we use priority queue to get the latest tweet IDs among current user and that user id followers.
Solution in C++:

class Twitter {
public:
    /** Initialize your data structure here. */
    Twitter() {
        time = 0;
    }
    /** Compose a new tweet. */
    void postTweet(int userId, int tweetId) {
        ++time;
        tweets[userId].push_back(make_pair(tweetId, time));
    }
    struct comp{
        bool operator()(const pair<int, int> &a, const pair<int, int> &b){
            return a.first < b.first;
        }
    };
    /** 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> res;
        priority_queue<pair<int,int>, vector<pair<int, int>>, comp> pq;
        auto user_tweets = tweets[userId];
        for(auto it = user_tweets.begin(); it != user_tweets.end(); ++it){
            pq.push(make_pair(it->second, it->first));
        }
        auto folowe = followers[userId];
        
        for(auto it = folowe.begin(); it != folowe.end(); ++it){
            if(*it == userId)
                continue;
            auto user_tweets = tweets[*it];
            for(auto iter = user_tweets.begin(); iter != user_tweets.end(); ++iter){
                pq.push(make_pair(iter->second, iter->first));
            }
        }
        int i = 0;
        while(!pq.empty() && i < 10){
            ++i;
            res.push_back(pq.top().second);
            pq.pop();
        }
        return res;
    }
    /** Follower follows a followee. If the operation is invalid, it should be a no-op. */
    void follow(int followerId, int followeeId) {
        followers[followerId].insert(followeeId);
    }
    /** Follower unfollows a followee. If the operation is invalid, it should be a no-op. */
    void unfollow(int followerId, int followeeId) {
        followers[followerId].erase(followeeId);
    }
private:
    long long time;
    unordered_map<int, unordered_set<int>> followers;
    unordered_map<int, vector<pair<int, int>>> tweets;
};


Comments

Popular posts from this blog

Leet Code: Problem #710 Random Pick with Blacklist

Given a blacklist  B containing unique integers from [0, N) , write a function to return a uniform random integer from [0, N) which is NOT  in B . Optimize it such that it minimizes the call to system’s Math.random() . Note: 1 <= N <= 1000000000 0 <= B.length < min(100000, N) [0, N)  does NOT include N. See interval notation . Example 1: Input: ["Solution","pick","pick","pick"] [[1,[]],[],[],[]] Output: [null,0,0,0] Example 2: Input: ["Solution","pick","pick","pick"] [[2,[]],[],[],[]] Output: [null,1,1,1] Example 3: Input: ["Solution","pick","pick","pick"] [[3,[1]],[],[],[]] Output: [null,0,0,2] Example 4: Input: ["Solution","pick","pick","pick"] [[4,[2]],[],[],[]] Output: [null,1,3,1] Explanation of Input Syntax: The input is two lists: the subroutines called and their argume...

Creating Self Signed SSL Certificates for HTTPS Communication

Self Signed CA: Create Private Key for Self Signed CA openssl ecparam -genkey -name secp256r1 | openssl ec -out ca.key     Create CA Certificate for Self Signed CA openssl req -new -x509 -days 36500 -key ca.key -out ca.pem -subj "/C=IN/ST=Karnataka/L=Bengaluru/O=company name/OU=Prod Operations Department/CN=prodops .domain.com   Verify the content of CA certificate openssl x509 -in ca.pem -noout -text Client CERTIFICATE: CLIENT_ID="<Client-Product>" e.g. CLIENT_ID="ClientID" CLIENT_SERIAL="<Client-Release-Number>" e.g. CLIENT_SERIAL="6889" Create Private Key for Client openssl ecparam -genkey -name secp256r1 | openssl ec -out  ${CLIENT_ID}_${CLIENT_SERIAL}.key                   Generate the Certificate Signing Request CSR openssl req -new -key ${CLIENT_ID}_${CLIENT_SERIAL}.key -out ${CLIENT_ID}_${CLIENT_SERIAL}.csr -subj "/C=IN/ST=Karnataka/L=Bengalur...

Tree Data Structure related must solve programming questions: Part - 1

LeetCode Problem #687 Given a binary tree find the longest possible path with same node values. The length of the path is determined the number of edges between the node. Example 1: Input: 5 / \ 4 5 / \ \ 1 1 5 Output:  2   Example 2: Input: 1 / \ 4 5 / \ \ 4 4 5 Output:  2 Solution in C++: /**  * Definition for a binary tree node.  * struct TreeNode {  *     int val;  *     TreeNode *left;  *     TreeNode *right;  *     TreeNode() : val(0), left(nullptr), right(nullptr) {}  *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}  *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}  * };  */ class Solution ...