355. Design Twitter

This problem is a combination of Object-oriented Design and “Merge k Sorted List” problem. We can simplify this problem by abstracting the entries (User and Tweet) of Twitter and defining their methods.

class Twitter {
    private static int timestamp = 0;

    private static class User {
        int id;
        Set<Integer> following;
        Tweet head;
        User(int id) {
            this.id = id;
            this.following = new HashSet<>();
            this.head = null;
            // follow himself/herself
            follow(id);
        }

        void follow(int followee) {
            following.add(followee);
        }

        void unfollow(int followee) {
            // cannot unfollow himself/herself
            if (followee != this.id) {
                following.remove(followee);
            }
        }

        void post(int tweetId) {
            Tweet newTweet = new Tweet(tweetId, timestamp);
            timestamp++;
            newTweet.next = head;
            head = newTweet;
        }
    }

    private static class Tweet {
        int id;
        int publishTime;
        Tweet next;
        Tweet(int id, int publishTime) {
            this.id = id;
            this.publishTime = publishTime;
            this.next = null;
        }
    }

    private Map<Integer, User> usersMapping;

    /** Initialize your data structure here. */
    public Twitter() {
        this.usersMapping = new HashMap<>();
    }

    /** Compose a new tweet. */
    public void postTweet(int userId, int tweetId) {
        if (!usersMapping.containsKey(userId)) {
            User newUser = new User(userId);
            usersMapping.put(userId, newUser);
        }
        usersMapping.get(userId).post(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<Integer> getNewsFeed(int userId) {
        List<Integer> res = new ArrayList<>();
        if (!usersMapping.containsKey(userId)) {
            return res;
        }

        PriorityQueue<Tweet> queue = new PriorityQueue<>(new Comparator<Tweet>() {
            @Override
            public int compare(Tweet o1, Tweet o2) {
                return o2.publishTime - o1.publishTime;
            }
        });

        Set<Integer> followingIds = usersMapping.get(userId).following;
        for (int id : followingIds) {
            User followingUser = usersMapping.get(id);
            if (followingUser.head != null) {
                queue.add(followingUser.head);
            }
        }
        while (!queue.isEmpty()) {
            if (res.size() == 10) {
                break;
            }
            Tweet tweet = queue.poll();
            res.add(tweet.id);
            if (tweet.next != null) {
                queue.add(tweet.next);
            }
        }
        return res;
    }

    /** Follower follows a followee. If the operation is invalid, it should be a no-op. */
    public void follow(int followerId, int followeeId) {
        if (!usersMapping.containsKey(followerId)) {
            User newUser = new User(followerId);
            usersMapping.put(followerId, newUser);
        }
        if (!usersMapping.containsKey(followeeId)) {
            User newUser = new User(followeeId);
            usersMapping.put(followeeId, newUser);
        }
        usersMapping.get(followerId).follow(followeeId);
    }

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

/**
 * 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);
 */