Hash Maps Flashcards
1
Q
hash map
A
unordered associations between keys and values
2
Q
hashing
A
process of mapping a key to its location
3
Q
Hash Table
A
a storage that holds the records (the key and any value associated with the key)
-usually implemented internally using an array. Each slot in the array holds a key-value pair or is empty (null).
4
Q
Hash Function
A
maps keys to positions in the hash table
5
Q
standard hash function
A
class HashMap { constructor(initialCapacity=8) { this.length = 0; this._hashTable = []; this._capacity = initialCapacity; this._deleted = 0; }
static _hashString(string) { let hash = 5381; for (let i = 0; i < string.length; i++) { hash = (hash << 5) + hash + string.charCodeAt(i); hash = hash & hash; } return hash >>> 0; } }
6
Q
collisions
A
2 unique keys hash to the same slot in the array
7
Q
open addressing
A
when you have a collision, you hash the key to the empty slot nearest to where it should live
8
Q
separate chaining
A
when you have a collision, we use the next pointers to put the keys in a linked list.
9
Q
set() method
A
set(key, value){ const loadRatio = (this.length + this._deleted + 1) / this._capacity; if (loadRatio > HashMap.MAX_LOAD_RATIO) { this._resize(this._capacity * HashMap.SIZE_RATIO); } //Find the slot where this key should be in const index = this._findSlot(key);
if(!this._hashTable[index]){ this.length++; } this._hashTable[index] = { key, value, DELETED: false }; }
_findSlot(key) { const hash = HashMap._hashString(key); const start = hash % this._capacity;
for (let i=start; i
10
Q
resize()
A
_resize(size) { const oldSlots = this._hashTable; this._capacity = size; // Reset the length - it will get rebuilt as you add the items back this.length = 0; this._hashTable = [];
for (const slot of oldSlots) { if (slot !== undefined) { this.set(slot.key, slot.value); } } }