Hash Table Concept and Hash Functions in DSA C - Time & Space Complexity
We want to understand how fast a hash table can find or store data.
The question is: how does the time to do these actions change as the data grows?
Analyze the time complexity of the following code snippet.
// Simple hash function example
unsigned int hash(char *str, unsigned int table_size) {
unsigned int hash_value = 0;
for (int i = 0; str[i] != '\0'; i++) {
hash_value = (hash_value * 31 + (unsigned char)str[i]) % table_size;
}
return hash_value;
}
This code calculates a hash value for a string to find its place in a hash table.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Loop over each character in the input string.
- How many times: Once for every character in the string (length n).
As the string gets longer, the time to compute the hash grows in a straight line.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 steps |
| 100 | About 100 steps |
| 1000 | About 1000 steps |
Pattern observation: The work grows directly with the string length.
Time Complexity: O(n)
This means the time to compute the hash grows linearly with the input size.
[X] Wrong: "Hash functions always run in constant time no matter the input size."
[OK] Correct: The hash function must look at every character in the input, so time grows with input length.
Understanding how hash functions work and their time cost helps you explain why hash tables are fast and when they might slow down.
"What if the hash function only looked at the first few characters of the string? 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 data storage
This index tells where to store or find the data in the hash table.Final Answer:
To convert a key into an index for storing data -> Option BQuick Check:
Hash function = key to index [OK]
- Thinking hash function sorts data
- Confusing hash function with encryption
- Believing hash function counts elements
Solution
Step 1: Check function return type and parameters
The function should return an int and take an int parameter.Step 2: Verify syntax correctness
int hashFunction(int key); matches C syntax: return type first, then function name, then parameter list.Final Answer:
int hashFunction(int key); -> Option CQuick Check:
Correct C function declaration = int hashFunction(int key); [OK]
- Using void return type when int is needed
- Incorrect parameter type syntax
- Wrong order of function declaration parts
#include <stdio.h>
int hashFunction(int key) {
return key % 5;
}
int main() {
int hashTable[5] = {-1, -1, -1, -1, -1};
int keys[] = {12, 22, 32};
for (int i = 0; i < 3; i++) {
int index = hashFunction(keys[i]);
hashTable[index] = keys[i];
}
for (int i = 0; i < 5; i++) {
printf("%d ", hashTable[i]);
}
return 0;
}
What is the output of this program?Solution
Step 1: Calculate hash indices for each key
12 % 5 = 2, 22 % 5 = 2, 32 % 5 = 2.Step 2: Insert keys into hashTable at calculated indices
All keys map to index 2, so last key 32 overwrites previous ones. hashTable = {-1, -1, 32, -1, -1}.Final Answer:
-1 -1 32 -1 -1 -> Option AQuick Check:
Collision overwrites at index 2 = -1 -1 32 -1 -1 [OK]
- Assuming keys store at different indices
- Ignoring collisions overwrite
- Miscomputing modulo operation
int hashFunction(int key) {
return key % 10;
}
int main() {
int hashTable[10];
int keys[] = {5, 15, 25};
for (int i = 0; i < 3; i++) {
int index = hashFunction(keys[i]);
if (hashTable[index] == -1) {
hashTable[index] = keys[i];
}
}
return 0;
}
What is the bug in this code?Solution
Step 1: Check initialization of hashTable
hashTable is declared but not initialized, so values are garbage, not -1.Step 2: Understand impact on insertion condition
Condition 'hashTable[index] == -1' may never be true, so keys won't insert properly.Final Answer:
hashTable array is not initialized to -1 -> Option DQuick Check:
Uninitialized array causes insertion failure [OK]
- Assuming default zero initialization
- Changing loop bounds incorrectly
- Misunderstanding hash function correctness
Solution
Step 1: Evaluate simple sum method
Summing ASCII values (Sum ASCII values of all characters and take modulo 10) can cause many collisions for anagrams.Step 2: Consider position-weighted sum
Multiplying each character by its position (Multiply each character's ASCII by its position, sum all, then modulo 10) creates more unique values, reducing collisions.Step 3: Reject poor methods
Using only first character (Use only the ASCII value of the first character modulo 10) or fixed index (Return a fixed index like 0 for all strings) causes many collisions.Final Answer:
Multiply each character's ASCII by its position, sum all, then modulo 10 -> Option AQuick Check:
Position-weighted sum reduces collisions best [OK]
- Using only first character causes collisions
- Ignoring character positions
- Using fixed index for all keys
Ready to prove it?
Pass the test and this pattern moves unknown
