Skip to content

355. Design Twitter

Difficulty: Medium

LeetCode Problem View on GitHub


355. Design Twitter

Medium


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

 

Example 1:

Input
["Twitter", "postTweet", "getNewsFeed", "follow", "postTweet", "getNewsFeed", "unfollow", "getNewsFeed"]
[[], [1, 5], [1], [1, 2], [2, 6], [1], [1, 2], [1]]
Output
[null, null, [5], null, null, [6, 5], null, [5]]

Explanation
Twitter twitter = new Twitter();
twitter.postTweet(1, 5); // User 1 posts a new tweet (id = 5).
twitter.getNewsFeed(1);  // User 1's news feed should return a list with 1 tweet id -> [5]. return [5]
twitter.follow(1, 2);    // User 1 follows user 2.
twitter.postTweet(2, 6); // User 2 posts a new tweet (id = 6).
twitter.getNewsFeed(1);  // 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.unfollow(1, 2);  // User 1 unfollows user 2.
twitter.getNewsFeed(1);  // User 1's news feed should return a list with 1 tweet id -> [5], since user 1 is no longer following user 2.

 

Constraints:

  • 1 <= userId, followerId, followeeId <= 500
  • 0 <= tweetId <= 104
  • All the tweets have unique IDs.
  • At most 3 * 104 calls will be made to postTweet, getNewsFeed, follow, and unfollow.
  • A user cannot follow himself.

Solution

class Twitter {
    private HashMap<Integer, HashSet<Integer>> followersMap;
    private HashMap<Integer, Integer> tweetIdMap;
    private HashMap<Integer, ArrayList<Integer>> userMap; 
    private HashMap<Integer, Integer> time;
    private int currTime;

    static class Pair {
        int node, time;
        public Pair(int node, int time) {
            this.node = node;
            this.time = time;
        }
        @Override
        public String toString() {
            return "(" + node + " " + time + ")";
        }
        @Override
        public boolean equals(Object obj) {
            if (this == obj)
                return true;
            if (obj == null || getClass() != obj.getClass())
                return false;
            Pair current = (Pair)(obj);
            return current.node == node && current.time == time; 
        }
        @Override
        public int hashCode() {
            return Objects.hash(node, time);
        }
    }

    static class customSort implements Comparator<Pair> {
        @Override
        public int compare(Pair first, Pair second) {
            return Integer.compare(second.time, first.time);
        }
    }

    public Twitter() {
        followersMap = new HashMap<>();
        tweetIdMap = new HashMap<>(); 
        userMap = new HashMap<>();
        time = new HashMap<>(); 
        currTime = 0;
    }

    public void postTweet(int userId, int tweetId) {
        if (!userMap.containsKey(userId))
            userMap.put(userId, new ArrayList<>());
        userMap.get(userId).add(tweetId);
        tweetIdMap.put(tweetId, userId);
        time.put(tweetId, currTime);
        if (!followersMap.containsKey(userId))
            followersMap.put(userId, new HashSet<>());
        followersMap.get(userId).add(userId);
        currTime++;
        System.out.println(followersMap);
    }

    public List<Integer> getNewsFeed(int userId) {
        System.out.println(followersMap);
        List<Integer> res = new ArrayList<>();
        HashSet<Integer> currFollowers = new HashSet<>();
        currFollowers = followersMap.getOrDefault(userId, new HashSet<>());
        currFollowers.add(userId);
        TreeSet<Pair> set = new TreeSet<>(new customSort());
        for (int ele : currFollowers) {
            ArrayList<Integer> tweetsMade = userMap.get(ele);
            if (tweetsMade == null) continue;
            for (int x : tweetsMade) {
                set.add(new Pair(x, time.get(x)));
            } 
        } 
        while (set.size() > 0 && res.size() < 10) {
            res.add(set.pollFirst().node);
        }
        return res;
    }

    public void follow(int followerId, int followeeId) {
        if (!followersMap.containsKey(followerId))
            followersMap.put(followerId, new HashSet<>());
        followersMap.get(followerId).add(followeeId);  
        followersMap.get(followerId).add(followerId);   
    }

    public void unfollow(int followerId, int followeeId) {
        followersMap.get(followerId).remove(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);
 */

Complexity Analysis

  • Time Complexity: O(?)
  • Space Complexity: O(?)

Approach

Detailed explanation of the approach will be added here