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

p.s. tweet id does not represent timestamp, you need to keep track of timestamp of each tweet.

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

Analysis:

Create Tweet class, 3 fields, userid, tweetid, timestamp.

map1 - store userid vs. LinkedList<Tweet>, always addFirst() to List (add latest tweet of that user to its linkedlist head)

map2 - store userid vs hashset<integer>, store user set that each user is following.

when trying to get news:

we create a map3 - userid vs. iterator of that user's linkedlist.

we create a maxheap(compare timestamp of tweet), and every round we poll one to add to returnlist, and offer the next node of the one just got polled.

Complexity:

Space: O(n) - n is the total number of tweets

Post: O(1)

follow/unfollow: O(1)

getNewsFeed(): O(nlogn) for each tweet we gather, we poll it from a heap, that takes O(logn) time.

Code:

public class Twitter {

    public class Tweet
    {
        public int userId, tweetId, timestamp;
        public Tweet(int uid, int tid)
        {
            userId = uid;
            tweetId = tid;
            timestamp = ts;
        }
    }

    Map<Integer, LinkedList<Tweet>> newsMap;
    Map<Integer, Set<Integer>> usersMap;
    int ts = 0;

    /** Initialize your data structure here. */
    public Twitter() {
        newsMap = new HashMap<Integer, LinkedList<Tweet>>();
        usersMap = new HashMap<Integer, Set<Integer>>();
    }

    /** Compose a new tweet. */
    public void postTweet(int userId, int tweetId) {
        if(userId < 0)
        {
            return;
        }
        if(!usersMap.containsKey(userId))
        {
            Set<Integer> temp = new HashSet<Integer>();
            temp.add(userId);
            usersMap.put(userId, temp);
        }

        if(newsMap.get(userId) == null)
        {
            newsMap.put(userId, new LinkedList<Tweet>());
        }
        newsMap.get(userId).addFirst(new Tweet(userId, tweetId));
        ts++;
    }

    /** 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) {
        if(!usersMap.containsKey(userId))
        {
            return new ArrayList<Integer>();
        }

        Set<Integer> followingUsers = usersMap.get(userId);
        Map<Integer, Iterator<Tweet>> tweetItrMap = new HashMap<Integer, Iterator<Tweet>>();

        for(Integer user : followingUsers)
        {
            if(newsMap.containsKey(user))
            {
                tweetItrMap.put(user, newsMap.get(user).iterator());
            }
        }

        PriorityQueue<Tweet> maxheap = new PriorityQueue<Tweet>(10, new Comparator<Tweet>(){
            @Override
            public int compare(Tweet a, Tweet b)
            {
                if(a.timestamp == b.timestamp)
                {
                    return 0;
                }
                return a.timestamp < b.timestamp ? 1 : -1;
            }
        });

        Set<Integer> userStillHasNews = new HashSet<Integer>(tweetItrMap.keySet());
        for(Integer user : tweetItrMap.keySet())
        {
            Iterator<Tweet> temp = tweetItrMap.get(user);
            maxheap.offer(temp.next());
            if(!temp.hasNext())
            {
                userStillHasNews.remove(user);
            }
        }

        List<Integer> newsFeed = new ArrayList<Integer>();
        while(newsFeed.size() < 10 && (userStillHasNews.size() != 0 || !maxheap.isEmpty()))
        {
            Tweet cur = maxheap.poll();
            newsFeed.add(cur.tweetId);
            Iterator<Tweet> temp = tweetItrMap.get(cur.userId);
            if(temp.hasNext())
            {
                maxheap.offer(temp.next());
                if(!temp.hasNext())
                {
                    userStillHasNews.remove(cur.userId);
                }
            }
        }
        return newsFeed;
    }

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

results matching ""

    No results matching ""