Hash Table Concept and Hash Functions in DSA Typescript - Time & Space Complexity
We want to understand how fast a hash table can find or store data using a hash function.
How does the time to do these operations change as we add more items?
Analyze the time complexity of inserting and searching in a hash table using a hash function.
class HashTable {
private buckets: Array> = [];
private size: number;
constructor(size: number) {
this.size = size;
this.buckets = Array(size).fill(null).map(() => []);
}
private hash(key: string): number {
let hashValue = 0;
for (const char of key) {
hashValue += char.charCodeAt(0);
}
return hashValue % this.size;
}
set(key: string, value: number): void {
const index = this.hash(key);
// Check if key already exists and update
for (let i = 0; i < this.buckets[index].length; i++) {
if (this.buckets[index][i][0] === key) {
this.buckets[index][i][1] = value;
return;
}
}
this.buckets[index].push([key, value]);
}
get(key: string): number | undefined {
const index = this.hash(key);
for (const [k, v] of this.buckets[index]) {
if (k === key) return v;
}
return undefined;
}
}
This code creates a hash table that stores key-value pairs using a simple hash function and handles collisions by storing multiple pairs in the same bucket.
Look at what repeats when we insert or search:
- Primary operation: Loop over characters in the key to compute the hash.
- How many times: Once per operation, proportional to key length.
- Secondary operation: Loop over items in a bucket when searching for a key.
- How many times: Depends on number of items in that bucket (collision count).
As we add more items, the time to compute the hash stays about the same (depends on key length, not number of items).
But searching inside a bucket can get slower if many items land in the same bucket.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | Hash calculation + few items in bucket |
| 100 | Hash calculation + more items in bucket if collisions occur |
| 1000 | Hash calculation + possibly many items in bucket if hash is poor |
Pattern observation: Hash calculation cost stays steady; bucket search cost grows with collisions.
Time Complexity: O(k + m)
This means time grows with key length k plus the number of items m in the bucket due to collisions.
[X] Wrong: "Hash table operations always take constant time no matter what."
[OK] Correct: If many keys collide, searching a bucket can take longer, so time depends on how well the hash function spreads keys.
Understanding how hash functions affect speed helps you explain why hash tables are fast and when they might slow down.
"What if we used a better hash function that spreads keys evenly? How would the time complexity change?"
Practice
Solution
Step 1: Understand the role of a hash function
A hash function takes a key and converts it into a number called an index.Step 2: Connect index to storage in hash table
This index tells where to store or find the value in the hash table.Final Answer:
To convert a key into an index for storing values -> Option DQuick Check:
Hash function = key to index [OK]
- Thinking hash function sorts keys
- Confusing hash function with encryption
- Believing hash function counts elements
Solution
Step 1: Recall TypeScript Map syntax
In TypeScript, a Map is created with new Map().Step 2: Check each option's syntax
const map = new Map(); uses correct syntax: new Map(). Others have syntax errors or wrong usage.Final Answer:
const map = new Map(); -> Option CQuick Check:
Map declaration = new Map<Key, Value>() [OK]
- Omitting 'new' keyword
- Using lowercase 'map' instead of 'Map'
- Incorrect generic syntax
const map = new Map();
map.set('apple', 5);
map.set('banana', 3);
map.set('apple', 10);
console.log(map.get('apple'));Solution
Step 1: Understand Map set behavior
Setting a key that already exists updates its value.Step 2: Trace the code
First 'apple' is set to 5, then updated to 10. So map.get('apple') returns 10.Final Answer:
10 -> Option AQuick Check:
Updated value = 10 [OK]
- Assuming first value stays
- Thinking get returns undefined if key repeated
- Confusing Map with object property behavior
const map = new Map();
map.set(1, 'one');
map.set(2, 'two');
console.log(map.get('1'));Solution
Step 1: Check Map key type
Map is declared with number keys, so keys must be numbers.Step 2: Analyze map.get argument
map.get('1') uses string '1', which does not match number 1 key, so returns undefined.Final Answer:
Using string '1' instead of number 1 as key -> Option BQuick Check:
Key type mismatch causes undefined [OK]
- Assuming '1' and 1 are same keys
- Thinking Map keys must be strings
- Ignoring type mismatch errors
Solution
Step 1: Understand collision minimization
Good hash functions spread keys evenly to reduce collisions.Step 2: Evaluate each approach
Sum the ASCII codes of all characters and take modulo table size sums codes but can cause many collisions (e.g., 'abc' and 'cab'). Use the length of the string as the hash value uses length only, very poor. Use the first character's ASCII code only uses first char only, also poor. Multiply each character code by a prime number and sum, then modulo table size uses weighted sum with primes, better distribution.Final Answer:
Multiply each character code by a prime number and sum, then modulo table size -> Option AQuick Check:
Weighted sum with primes = better hash [OK]
- Using simple sums causing collisions
- Ignoring character positions
- Using string length as hash
Ready to prove it?
Pass the test and this pattern moves unknown
