Design Twitter - Medium - L

5 minute read

Published:

Question

  • https://leetcode.com/problems/design-twitter/

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

Approach

  • Heaps
  • OOPS

Solution

import java.util.*;

class Twitter {
    Map<Integer, User> users;
    int timeStamp = 0;
    /** Initialize your data structure here. */
    public Twitter() {
        users = new HashMap<>();
    }

    /** Compose a new tweet. */
    public void postTweet(int userId, int tweetId) {
        User user = users.get(userId);
        if (user == null) {
            user = new User(userId);
            users.put(userId, user);
        }
        
        user.postTweet(tweetId, timeStamp);
        timeStamp++;
    }

    /** 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<Integer> getNewsFeed(int userId) {
        User user = users.get(userId);

        return user != null ? user.getNewsFeed() : new LinkedList<>();
    }

    /** Follower follows a followee. If the operation is invalid, it should be a no-op. */
    public void follow(int followerId, int followeeId) {
        User follower = users.get(followerId);
        User followee = users.get(followeeId);
        
        // If any user cannot be found from the existing users
        // We create a new user
        if (follower == null) {
            follower = new User(followerId);
            users.put(followerId, follower);
        }
        
        if (followee == null) {
            followee = new User(followeeId);
            users.put(followeeId, followee);
        }

        follower.follow(followee);
    }

    /** Follower unfollows a followee. If the operation is invalid, it should be a no-op. */
    public void unfollow(int followerId, int followeeId) {
        User follower = users.get(followerId);
        User followee = users.get(followeeId);

        // If any user cannot be found from the existing users
        // We create a new user
        if (follower == null) {
            follower = new User(followerId);
            users.put(followerId, follower);
        }
        
        if (followee == null) {
            followee = new User(followeeId);
            users.put(followeeId, followee);
        }
        
        follower.unfollow(followee);
    }

    /* The class representing the user in Twitter */
    private class User {
        private int id;  // The id of the user
        private Set<User> following;  // The people that this user is following
        private List<Tweet> tweets;  // The tweets that this user has posted

        public User(int id) {
            this.id = id;
            this.following = new HashSet<>();
            this.tweets = new LinkedList<>();
        }

        public int hashCode() {
            return Integer.hashCode(id);
        }

        /* Post a new tweet */
        public void postTweet(int tweetId, int timeStamp) {
            Tweet newTweet = new Tweet(tweetId, this.id, timeStamp);
            tweets.add(newTweet);
        }

        /* Follow a person in the network */
        public void follow(User otherUser) {
            following.add(otherUser);
        }

        /* Unfollow a person in the network */
        public void unfollow(User otherUser) {
            following.remove(otherUser);
        }

        /* Get the newsfeed of this user */
        public List<Integer> getNewsFeed() {
            // The user can see his own tweets as well as tweets from people
            // the he is following. We need to choose among these tweets the 10 latest ones.
            // Therefore, just push all of them to one single priority queue base on the timestamp of each tweet
            // and then take out the top 10 tweets of the queue
            
            PriorityQueue<Tweet> newsFeed = new PriorityQueue<>();
            
            // Get his own tweets
            for (Tweet tweet : tweets) {
                newsFeed.add(tweet);
            }
            
            // Get tweets from people he is following
            for (User user : following) {
                for (Tweet tweet : user.tweets) {
                    newsFeed.add(tweet);
                }
            }
            
            // Get the latest 10 tweets
            int count = 0;
            List<Integer> ans = new LinkedList<>();
            
            while (count < 10 && newsFeed.size() != 0) {
                ans.add(newsFeed.poll().id);
                count++;
            }
            
            return ans;
        }

        public boolean equals(Object otherUser) {
            if (otherUser instanceof  User) {
                User other = (User) otherUser;
                return this.id == other.id;
            }

            return false;
        }
    }

    /* The class represent a tweet */
    private class Tweet implements Comparable<Tweet> {
        private int id;
        private int userId;
        private int timeStamp;  // The timestamp at which this tweet was created

        public Tweet(int id, int userId, int timeStamp) {
            this.id = id;
            this.userId = userId;
            this.timeStamp = timeStamp;
        }
        
        // We solely compare tweets base on their timestamps
        public int compareTo(Tweet other) {
            if (this.timeStamp > other.timeStamp) return -1;
            if (this.timeStamp < other.timeStamp) return 1;
            return 0;
        }
    }
}

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