Hash Map/Set is used for fast key-value pair storage and lookup. They are commonly implemented using arrays, combined with hashing.
| | Hash Set/Map | Trie | Sorted Set/Map: Binary Search Tree (BST) (If duplicates are not allowed) | Sorted Set/Map: Sorted Array (If duplicates are not allowed) | | --- | --- | --- | --- | --- | | In-Order Traversal | Not supported | Not supported | O(n) | O(n) | | Search | O(1) | O(m)
*m is the word length* | O(log n ~ n) | O(log n) (binary search) |
| Insertion | O(1) | O(m)
*m is the word length* | O(log n ~ n) | O(n) (binary search + shifting) |
| Deletion | O(1) | O(m)
*m is the word length* | O(log n ~ n) | O(n) (binary search + shifting) |
| Note | | 1. For large dataset, it is space efficient due to sharing memory.
2. It supports prefix search. | | |
The O(1) look up time is useful for:
The unique key is useful for:
<aside> 💡
We can use additional n length of array as Map, Set, or Bucket, using its index as key,
if the keys are integer value in the range of 0 to n-1(or to n).
n length of Permutation Array as key.n length of array as key, the Array Map length needs to be n+1.26 length of array as key.
</aside><aside> 💡
When we are collection a combination of characters of a string, we can not use its combined Unicode points as a key. Because different group of characters may have the same total Unicode points. Instead, we use string itself or [26]int (an array counts a strings characters, allowing anagrams to have the same array) as key.
</aside>
A hash function is responsible for converting a key (such as a string) into an integer, which is used as an index to store the key-value pair in the underlying array. This process is sometimes referred to as pre-hashing. The same key will always produce the same integer.
%) to map the sum to a valid index within the array, ensuring that no matter how large the hashValue is, the result will always be a valid index.func hash(key string, capacity int) int {
hashValue := 0
for _, char := range key {
hashValue += int(char)
}
return hashValue % capacity
}
Go's hash/fnv package offers the FNV-1a hash algorithm