Hash Table Concept and Hash Functions in DSA Javascript - 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 actions change as we add more items?
Analyze the time complexity of the following code snippet.
function hash(key, size) {
let hashValue = 0;
for (let i = 0; i < key.length; i++) {
hashValue += key.charCodeAt(i);
}
return hashValue % size;
}
function insert(table, key, value) {
const index = hash(key, table.length);
table[index] = value;
}
This code creates a simple hash function and inserts a value into a hash table using the hash index.
- Primary operation: Loop over each character in the key string inside the hash function.
- How many times: Once per insert, the loop runs as many times as the key length.
The time to compute the hash grows with the length of the key, not the number of items in the table.
| Input Size (key length) | Approx. Operations |
|---|---|
| 10 | 10 additions |
| 100 | 100 additions |
| 1000 | 1000 additions |
Pattern observation: The work grows linearly with the key length, but inserting into the table is constant time.
Time Complexity: O(k)
This means the time depends on the key length (k), not the number of items stored.
[X] Wrong: "Hash table operations always take the same time no matter what."
[OK] Correct: The hash function time depends on the key length, so longer keys take more time to process.
Understanding how hash functions affect speed helps you explain why hash tables are fast and when they might slow down.
"What if the hash function used a fixed number of characters from the key instead of the whole key? 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 that can be used as an index in the hash table.Step 2: Identify the correct purpose
Sorting keys or encrypting data is not the job of a hash function; it only maps keys to indexes.Final Answer:
To convert a key into an index for storing data -> Option AQuick Check:
Hash function = key to index [OK]
- Thinking hash functions sort keys
- Confusing hash functions with encryption
- Believing hash functions count elements
Solution
Step 1: Recall JavaScript object syntax
In JavaScript, an empty object is created using curly braces {} which can act as a hash table.Step 2: Evaluate options
const table = []; creates an array, not a hash table. const table = new Map(); creates a Map, which is a different structure. const table = new HashTable(); is invalid as HashTable is not a built-in class.Final Answer:
const table = {}; -> Option BQuick Check:
Empty hash table = {} [OK]
- Using [] which creates an array, not a hash table
- Using Map() which is different from object
- Assuming HashTable is a built-in JavaScript class
const hashTable = {};
hashTable['apple'] = 5;
hashTable['banana'] = 3;
hashTable['apple'] = 10;
console.log(hashTable['apple']);Solution
Step 1: Understand key assignment in hash tables
Assigning a value to an existing key updates the value stored at that key.Step 2: Trace the code
Initially, 'apple' is set to 5, then updated to 10. So, hashTable['apple'] will be 10.Final Answer:
10 -> Option AQuick Check:
Last assignment to 'apple' = 10 [OK]
- Thinking the first assigned value remains
- Confusing keys and values
- Expecting undefined for existing keys
function hash(key) {
return key.length % 10;
}
const table = {};
table[hash('cat')] = 'animal';
table[hash('dog')] = 'animal';
console.log(table['cat']);Solution
Step 1: Understand how keys are stored and accessed
The hash function returns a number used as a key in the table object.Step 2: Check how the table is accessed
The code tries to access table['cat'], but the key stored is a number from hash('cat'), so it should access table[hash('cat')].Final Answer:
Accessing table['cat'] is incorrect; should use table[hash('cat')] -> Option CQuick Check:
Access key must match stored key type [OK]
- Accessing with original key instead of hashed key
- Thinking keys must be strings only
- Assuming hash function causes error due to key.length
function simpleHash(key) {
let sum = 0;
for (let char of key) {
sum += char.charCodeAt(0);
}
return sum % 5;
}Choose the best collision handling method.
Solution
Step 1: Understand collision in hash tables
When two keys produce the same hash index, a collision occurs and must be handled to store both values.Step 2: Evaluate collision handling methods
Overwriting loses data, ignoring new keys is incorrect, increasing hash size alone doesn't solve collisions. Chaining stores multiple values in a list at the same index, preserving all data.Final Answer:
Use chaining by storing multiple values in a list at the same index -> Option DQuick Check:
Chaining handles collisions by lists [OK]
- Overwriting values causing data loss
- Ignoring new keys on collision
- Thinking increasing hash size removes all collisions
Ready to prove it?
Pass the test and this pattern moves unknown
