Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to initialize the hash table with empty chains.
DSA Typescript
class HashTable { table: Array<Array<number>>; constructor(size: number) { this.table = new Array(size).fill(null).map(() => [1]); } }
Attempts:
3 left
💡 Hint
Common Mistakes
Using null or {} instead of an empty array causes errors when pushing elements.
✗ Incorrect
We use an empty array [] to initialize each chain for collision handling by chaining.
2fill in blank
mediumComplete the code to compute the hash index for a given key.
DSA Typescript
hash(key: number): number {
return key [1] this.table.length;
}Attempts:
3 left
💡 Hint
Common Mistakes
Using + or * causes index out of range errors.
✗ Incorrect
The modulo operator % ensures the hash index fits within the table size.
3fill in blank
hardFix the error in the insert method to add the key to the correct chain.
DSA Typescript
insert(key: number): void {
const index = this.hash(key);
this.table[index].[1](key);
}Attempts:
3 left
💡 Hint
Common Mistakes
Using pop or shift removes elements instead of adding.
✗ Incorrect
push adds the key to the end of the chain array at the computed index.
4fill in blank
hardFill both blanks to complete the search method that checks if a key exists in the hash table.
DSA Typescript
search(key: number): boolean {
const index = this.hash(key);
return this.table[index].[1](k => k [2] key) !== undefined;
}Attempts:
3 left
💡 Hint
Common Mistakes
Using filter returns an array, not a single element.
Using == may cause unexpected matches.
✗ Incorrect
find returns the first element matching the condition; === checks exact equality.
5fill in blank
hardFill all three blanks to complete the remove method that deletes a key from the hash table.
DSA Typescript
remove(key: number): void {
const index = this.hash(key);
const chain = this.table[index];
const pos = chain.findIndex(k => k [1] key);
if (pos !== -1) {
chain.[2](pos, [3]);
}
}Attempts:
3 left
💡 Hint
Common Mistakes
Using slice instead of splice does not modify the original array.
Using == instead of === may cause wrong matches.
✗ Incorrect
findIndex uses === to find the key; splice removes 1 element at position pos.
