LeetCode - Design Twitter

Question Definition

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

LeetCode - Bulls and Cows

Question Definition

You are playing the following Bulls and Cows game with your friend: You write down a number and ask your friend to guess what the number is. Each time your friend makes a guess, you provide a hint that indicates how many digits in said guess match your secret number exactly in both digit and position (called “bulls”) and how many digits match the secret number but locate in the wrong position (called “cows”). Your friend will use successive guesses and hints to eventually derive the secret number.

More …

LeetCode - Top K Frequent Words

Question Definition

Given a non-empty list of words, return the k most frequent elements.

Your answer should be sorted by frequency from highest to lowest. If two words have the same frequency, then the word with the lower alphabetical order comes first.

More …

LeetCode - Top K Frequent Elements

Question Definition

Given a non-empty array of integers, return the k most frequent elements.

For example, Given [1,1,1,2,2,3] and k = 2, return [1,2].

Note:

  • You may assume k is always valid, 1 ≤ k ≤ number of unique elements.
  • Your algorithm’s time complexity must be better than O(n log n), where n is the array’s size.

    Java Solution

    public List<Integer> topKFrequent(int[] nums, int k) {
      Map<Integer, Integer> map = new HashMap<>();
    
      for(int c : nums){
          map.putIfAbsent(c, 0);
          map.put(c, map.get(c) + 1);
      }
    
      map = map.entrySet().stream().sorted((e1, e2) ->
      e2.getValue() - e1.getValue())
      .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
              (e1, e2) -> e1, LinkedHashMap::new));
    
      List<Integer> result = new LinkedList<>();
    
      for(Map.Entry<Integer, Integer> entry : map.entrySet()){
          if(result.size() < k)
              result.add(entry.getKey());
          else
              break;
      }
      return result;
    }