1. Implement hash table 2. Cache With Time Limit 3. Valid Anagram
[Medium] Hash Table, Map, HashMap, Dictionary or Associative are all the names of the same data structure. It is a data structure that maps keys to values.
Implement hash table and its relevant methods:
put()Add a key-value pair to the hash tableget()Get the value of a keyremove()Remove a key-value pair to the hash table
and helper functions:
hash()Hash keyresize()Resize hash table and rehash
The data structure to implement a hash table is array. When you store a key-value pair, you first use a hash function to map the key to an index in the array and put the key, value to the index of the array.
Some interesting topics in hash table:
- key collision: It is possible that two different keys are hashed to same index. There are two ways to handle it: chaining and open addressing.
- hash function: A good hash function should distribute the keys uniformly across the hash table to minimise collisions.
- resizing: When the array is almost full (>=0.75 capacity) or empty(<=0.25 capacity), its capacity should be resized (doubling or halving). Since the array's capacity is changed, all the elements should be re-hashed and be put to the new array.
[Medium] Write a class that allows getting and setting key-value pairs, however a time until expiration is associated with each key.
The class has three public methods:
set(key, value, duration): accepts an integer key, an integer value, and a duration in milliseconds. Once the duration has elapsed, the key should be inaccessible. The method should return true if the same un-expired key already exists and false otherwise. Both the value and duration should be overwritten if the key already exists.
get(key): if an un-expired key exists, it should return the associated value. Otherwise it should return -1.
count(): returns the count of un-expired keys.
Use Hash Table to store key-value pairs. The value contains the actual value of the key and the time when the key expires.
[Easy] Given two strings s and t, return true if t is an anagram of s, and false otherwise. An anagram is a word or phrase formed by rearranging the letters of a different word or phrase, using all the original letters exactly once.
Example 1:
Input: s = "anagram", t = "nagaram"
Output: true
Example 2:
Input: s = "rat", t = "car"
Output: false
Use a hash table to count the occurrences of each character in s. Then iterate through t, decrementing the count for each character it contains. If a character in t is not found in the hash table (or its count drops below zero), the strings are not anagrams. Finally, all counts in the hash table must be zero for s and t to be anagrams of each other. Also, if s and t have different lengths, they cannot be anagrams.