class HashMap { private buckets: Array<Array<[string, number]>>; private size: number; constructor(size: number = 5) { this.size = size; this.buckets = Array.from({ length: size }, () => []); } private hash(key: string): number { let hash = 0; for (let char of key) { hash += char.charCodeAt(0); } return hash % this.size; } put(key: string, value: number): void { const index = this.hash(key); const bucket = this.buckets[index]; for (let i = 0; i < bucket.length; i++) { if (bucket[i][0] === key) { bucket[i][1] = value; return; } } bucket.push([key, value]); } get(key: string): number | undefined { const index = this.hash(key); const bucket = this.buckets[index]; for (let [k, v] of bucket) { if (k === key) return v; } return undefined; } } const map = new HashMap(); map.put("apple", 10); map.put("banana", 20); map.put("grape", 30); console.log(map.get("banana")); console.log(map.get("apple")); console.log(map.get("orange"));
The keys "banana" and "apple" are stored with values 20 and 10 respectively. The get method returns the value for the key if found, otherwise undefined. "orange" was never added, so it returns undefined.
Separate chaining stores all key-value pairs that hash to the same bucket in a list (or chain) at that bucket. This allows multiple entries to coexist without overwriting.
put(key: string, value: number): void {
const index = this.hash(key);
const bucket = this.buckets[index];
for (let pair of bucket) {
if (pair[0] === key) {
pair[1] = value;
return;
}
}
bucket.push([key, value]);
}The method updates the value if the key exists but does not stop the loop or return, so it still adds a new pair at the end, causing duplicates.
get(key: string): number | undefined {
const index = this.hash(key);
const bucket = this.buckets[index];
for (let [k, v] of bucket) {
if (k === key) return v;
}
return undefined;
}Adding semicolons after statements fixes the syntax error. The other options either introduce errors or change behavior.
class HashMap { buckets: Array<Array<[string, number]>>; size: number; constructor(size: number = 3) { this.size = size; this.buckets = Array.from({ length: size }, () => []); } hash(key: string): number { let sum = 0; for (let c of key) { sum += c.charCodeAt(0); } return sum % this.size; } put(key: string, value: number): void { const index = this.hash(key); const bucket = this.buckets[index]; for (let i = 0; i < bucket.length; i++) { if (bucket[i][0] === key) { bucket[i][1] = value; return; } } bucket.push([key, value]); } } const map = new HashMap(3); map.put("cat", 1); map.put("dog", 2); map.put("bird", 3); map.put("cow", 4); // What is map.buckets now?
Calculate sum of char codes mod 3 for each key:
"cat": 99+97+116=312 %3=0
"dog": 100+111+103=314 %3=2
"bird": 98+105+114+100=417 %3=0
"cow": 99+111+119=329 %3=2
Then group keys by bucket index.
