Monday, October 17, 2016

Design Twitter (Leetcode)

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:
  1. postTweet(userId, tweetId): Compose a new tweet.
  2. getNewsFeed(userId): 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.
  3. follow(followerId, followeeId): Follower follows a followee.
  4. unfollow(followerId, followeeId): Follower unfollows a followee.
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);


This is an algorithm design problem. As we have mentioned in Design Twitter system design blog, we need at least two objects, user and tweets, and two relations, user - user, and user-tweets. To simplify here, we use a map with key the userId and value a set of his/her followers to represent the user-user relation. For the news feed part, we use another map with the key userId and value a map of all tweets he/she has posted. The key in the value map is the number of tweets, which is used to represent the time order of the tweets.

To get the most recent tweets. We use a priority queue for the map.entry of all tweets a user's followers have. Note the user needs to follow him/herself so that his/her own posts will be shown in the news feed.


public class Twitter {
    private Map> twitterFeeds;
    private Map> followers;
    private int numTweets;

    /** Initialize your data structure here. */
    public Twitter() {
        twitterFeeds = new HashMap<>();
        followers = new HashMap<>();
        numTweets = 0;
    }

    /** Compose a new tweet. */
    public void postTweet(int userId, int tweetId) {
        follow(userId, userId);
        if (!twitterFeeds.containsKey(userId)) {
            twitterFeeds.put(userId, new HashMap<>());
        }
        twitterFeeds.get(userId).put(++numTweets, 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. */
    public List getNewsFeed(int userId) {
        List rst = new ArrayList<>();
        PriorityQueue> temp = new PriorityQueue<>(new Comparator>() {
            @Override
            public int compare(Map.Entry e1, Map.Entry e2) {
                return e1.getKey() - e2.getKey();
            }
        });
        if (followers.containsKey(userId)) {
            for (int followee : followers.get(userId)) {
                if (twitterFeeds.containsKey(followee)) {
                    for (Map.Entry entry : twitterFeeds.get(followee).entrySet()) {
                        temp.add(entry);
                        if (temp.size() > 10) {
                            temp.poll();
                        }
                    }
                }
            }
        }
        
        while (!temp.isEmpty()) {
            rst.add(temp.poll().getValue());
        }
        Collections.reverse(rst);
        return rst;
    }

    /** Follower follows a followee. If the operation is invalid, it should be a no-op. */
    public void follow(int followerId, int followeeId) {
        if (!followers.containsKey(followerId)) {
            followers.put(followerId, new HashSet<>());
        }
        followers.get(followerId).add(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) {
            if (followers.containsKey(followerId)) {
                followers.get(followerId).remove(followeeId);
            }
        }
           
    }
}


No comments:

Post a Comment