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:

**postTweet(userId, tweetId)**: Compose a new tweet.**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.**follow(followerId, followeeId)**: Follower follows a followee.**unfollow(followerId, followeeId)**: Follower unfollows a followee.

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

My implementation is simple and maybe not fast enough. I use a List of number array to store tweets. And I use a hashmap to store relationship of followers and followee.

In foMap, the key is users, value is a HashSet to store its followee. Method of follow and unfollow are easy too.

Then we traverse the list to generate news feed, check if a tweet from urself or from its followee. When we get ten tweets, we quit the loop.

Github：https://github.com/tinyfool/leetcode/tree/master/src/p0355

To see more hashtable related problems, see

Problems and Solutions of Hashmap.

Given two arrays, write a function to compute their intersection.

**Example 1:**

Input:nums1 = [1,2,2,1], nums2 = [2,2]Output:[2,2]

**Example 2:**

Input:nums1 = [4,9,5], nums2 = [9,4,9,8,4]Output:[4,9]

**Note:**

- Each element in the result should appear as many times as it shows in both arrays.
- The result can be in any order.

This problem is related to 349. intersection of Two Arrays, but it is more complex.

First, we use two hashmaps to separately count the elements in these two arrays. Then we but two keysets from two hashmaps together into a new keyset.

Then we traverse this new keyset, find the minimum value of the two hashmaps with the same key, it a key don’t exist in one hashmap, it means its value is 0. Then use the minimum to add corresponding amount numbers.

Github: https://github.com/tinyfool/leetcode/tree/master/src/p0350

To see more hashtable related problems, see

Problems and Solutions of Hashmap.

Given two arrays, write a function to compute their intersection.

**Example 1:**

Input:nums1 = [1,2,2,1], nums2 = [2,2]Output:[2]

**Example 2:**

Input:nums1 = [4,9,5], nums2 = [9,4,9,8,4]Output:[9,4]

**Note:**

- Each element in the result must be unique.
- The result can be in any order.

First, we use a hashmap to record numbers occur in the first array. Then we count the second array if a number is not in the first array, we don’t put it to the second hashmap either. In the end, all elements in the second hashmap are the results we need.

Github：https://github.com/tinyfool/leetcode/tree/master/src/p0349

To see more hashtable related problems, see

Problems and Solutions of Hashmap.

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

**Example 1:**

Input:nums = [1,1,1,2,2,3], k = 2Output:[1,2]

**Example 2:**

Input:nums = [1], k = 1Output:[1]

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

We use a hashmap to count every number. Then we transform this hashmap to a list, and sort it, output the first k elements.

Github: https://github.com/tinyfool/leetcode/tree/master/src/p0347

To see more hashtable related problems, see

Problems and Solutions of Hashmap.

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.

Write a function to return a hint according to the secret number and friend’s guess, use `A`

to indicate the bulls and `B`

to indicate the cows.

Please note that both secret number and friend’s guess may contain duplicate digits.

**Example 1:**

Input:secret = "1807", guess = "7810"Output:"1A3B"Explanation:`1`

bull and`3`

cows. The bull is`8`

, the cows are`0`

,`1`

and`7.`

**Example 2:**

Input:secret = "1123", guess = "0111"Output:"1A1B"Explanation:The 1st`1`

in friend's guess is a bull, the 2nd or 3rd`1`

is a cow.

**Note: **You may assume that the secret number and your friend’s guess only contain digits, and their lengths are always equal.

We look at the rules of bulls and cows separately. We need to compare the digits in string **secret** and string **guess**.

First, we look at how to calculate bulls. We can transform the two string into two character arrays. Then we compare the digits one by one. When we meet the same digits in the two arrays at the same position, we add bull by one. But note every time we find a match, we need to use ‘.’ to replace it in string **secret** and string **guess** to avoid to repeat count them in the cows’ calculating process.

Then we look at how to count cows. First, we put the remain digits in string **secret** into a HashSet. We use the remain digits in string **guess** to compare, find a match, we add one to cows. Code:

Compare function:

After we get bulls and cows, the output is easy:

Github：https://github.com/tinyfool/leetcode/tree/master/src/p0299

To see more hashtable related problems, see

Problems and Solutions of Hashmap.

Given a `pattern`

and a string `str`

, find if `str`

follows the same pattern.

Here **follow** means a full match, such that there is a bijection between a letter in `pattern`

and a **non-empty** word in `str`

.

**Example 1:**

Input:pattern =`"abba"`

, str =`"dog cat cat dog"`

Output:true

**Example 2:**

Input:pattern =`"abba"`

, str =`"dog cat cat fish"`

Output:false

**Example 3:**

Input:pattern =`"aaaa"`

, str =`"dog cat cat dog"`

Output:false

**Example 4:**

Input:pattern =`"abba"`

, str =`"dog dog dog dog"`

Output:false

**Notes:**

You may assume `pattern`

contains only lowercase letters, and `str`

contains lowercase letters that may be separated by a single space.

This problem is similar to 205. Isomorphic String. The difference is problem 205 we compare two strings but this problem we compare a pattern string with a string built with different words. This time we map pattern string to a new string and map str to a new string too.

First, we create a function to map string array to a new string.

Then we can split pattern string and words string to string arrays, then map then to two new string, compare them:

Github：https://github.com/tinyfool/leetcode/tree/master/src/p0290

To see more hashtable related problems, see

Problems and Solutions of Hashmap.

Given an array of integers and an integer *k*, find out whether there are two distinct indices *i* and *j* in the array such that **nums[i] = nums[j]**and the **absolute** difference between *i* and *j* is at most *k*.

**Example 1:**

Input:nums = [1,2,3,1], k = 3Output:true

**Example 2:**

Input:nums = [1,0,1,1], k = 1Output:true

**Example 3:**

Input:nums = [1,2,3,1,2,3], k = 2Output:false

This problem is similar to 217. Contains Duplicate, but a little harder. First we rule out some conditions (If k==0, must return false. if nums.length<2 must return false. And if k>nums.length we need let k=nums.length.) :

Then, we look at first k elements, if there is a duplicate, then return true. If k==nums.length, but we don’t find any duplicate return false.

Then we start from k+1, build a fixed-width sliding window. Every time we move one postion, we remove the oldest number from the window, add the new number in the window. In this process, if we find a duplicate return true. When all numbers are checked, we still can’t find a duplicate return false.

Github：https://github.com/tinyfool/leetcode/tree/master/src/p0219

Want to know details of the sliding window algorithm, check my post: The Sliding Window Algorithm for string and array.

To see more hashtable related problems, see

Problems and Solutions of Hashmap.

Given an array of integers, find if the array contains any duplicates.

Your function should return true if any value appears at least twice in the array, and it should return false if every element is distinct.

**Example 1:**

Input:[1,2,3,1]Output:true

**Example 2:**

Input:[1,2,3,4]Output:false

**Example 3:**

Input:[1,1,1,3,3,4,3,2,4,2]Output:true

This problem is super easy. we just traverse the array. And put every number to a HashSet. If we found any new number is in the HashSet already, we know we have duplicate, return true. If in the end we still can’t find a duplicate, we return false.

Github: https://github.com/tinyfool/leetcode/tree/master/src/p0217

To see more hashtable related problems, see

Problems and Solutions of Hashmap.

Two strings are isomorphic if the characters in ** s** can be replaced to get

All occurrences of a character must be replaced with another character while preserving the order of characters. No two characters may map to the same character but a character may map to itself.

**Example 1:**

Input:=s`"egg",`

t =`"add"`

Output:true

**Example 2:**

Input:=s`"foo",`

t =`"bar"`

Output:false

**Example 3:**

Input:=s`"paper",`

t =`"title"`

Output:true

**Note:**

You may assume both ** s **and

One way is to traverse the characters in string **s**, every time we meet a unique character, we use the character in the same position in string **t**. One by one, when we finish if the two strings are identical, then they are isomorphic. But I think this way is too complex.

So we use another way. We use a hashmap to restore the first time occurs of every unique character. Then we output the index to an array, so we get a pattern array of a string.

Like example 1, we can get the pattern array of “egg” as [0,1,1]. And the pattern array of “add” is [0,1,1] too. So “egg” and “add” are isomorphic.

“foo” from example 2, its pattern array is [0,1,1]. But bar’s pattern array is [0,1,2]. So they are not isomorphic.

The first part of the code is how to transform a string to a pattern array:

The second part compares the two pattern array is identical or not.

Github：https://github.com/tinyfool/leetcode/tree/master/src/p0205

To see more hashtable related problems, see

Problems and Solutions of Hashmap.

Write an algorithm to determine if a number is “happy”.

A happy number is a number defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1. Those numbers for which this process ends in 1 are happy numbers.

**Example: **

Input:19Output:trueExplanation:1^{2}+ 9^{2}= 82 8^{2}+ 2^{2}= 68 6^{2}+ 8^{2}= 100 1^{2}+ 0^{2}+ 0^{2}= 1

First, we define a function **split**, it can separate every digit from a number, and make a **List**.

Then we define a function **combine**，caculate the sum of the squares of all digits in the **List**.

Then, we keep calling split and combine until the number become 1, we return true. But sometimes we will get an infinite loop, so we put the number to a HashSet, if any number but 1 keep occurring, we quit the loop and return false.

Github：https://github.com/tinyfool/leetcode/tree/master/src/p0202

To see more hashtable related problems, see

Problems and Solutions of Hashmap.