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 using a hash function.
How does the time to do these operations change as we add more items?
Analyze the time complexity of the following code snippet.
public class SimpleHashTable
{
private readonly int size = 10;
private readonly LinkedList<KeyValuePair<int, string>>[] buckets;
public SimpleHashTable()
{
buckets = new LinkedList<KeyValuePair<int, string>>[size];
}
private int HashFunction(int key) => key % size;
public void Add(int key, string value)
{
int index = HashFunction(key);
if (buckets[index] == null)
buckets[index] = new LinkedList<KeyValuePair<int, string>>();
buckets[index].AddLast(new KeyValuePair<int, string>(key, value));
}
public string Get(int key)
{
int index = HashFunction(key);
var bucket = buckets[index];
if (bucket != null)
{
foreach (var pair in bucket)
{
if (pair.Key == key)
return pair.Value;
}
}
return null;
}
}
This code creates a simple hash table that stores and retrieves key-value pairs in buckets using a hash function.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Traversing a bucket list (foreach loop in Get) after computing the hash index.
- How many times: The hash function runs once per operation; traversal length grows with collisions in the bucket.
As we add more items, the number of collisions may increase, making linked lists longer.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 1 operation per lookup (few collisions) |
| 100 | Operations grow as some buckets get longer lists |
| 1000 | More collisions cause longer lists, more operations per lookup |
Pattern observation: Operations grow roughly linearly with input if collisions increase; otherwise, they stay close to constant.
Time Complexity: O(1) on average, O(n) in worst case
This means usually adding or finding an item is very fast, but if many keys collide, it can slow down to checking many items.
[X] Wrong: "Hash tables always work in constant time no matter what."
[OK] Correct: If many keys hash to the same bucket, operations slow down because we must check many items in that bucket.
Understanding hash tables and their time complexity shows you know how data can be stored and found quickly in many real programs.
"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 CQuick 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 correct class name in C#
The correct class name is 'Hashtable' with capital H and T.Step 2: Check syntax for creating instance
Using 'new Hashtable()' with correct casing creates a hash table object.Final Answer:
var table = new Hashtable(); -> Option AQuick Check:
Correct class name and syntax [OK]
- Using wrong capitalization
- Adding underscores in class name
- Using lowercase letters incorrectly
var table = new Hashtable(); table["apple"] = 5; table["banana"] = 3; table["apple"] = 7; Console.WriteLine(table["apple"]);
Solution
Step 1: Understand key-value assignment in Hashtable
Assigning table["apple"] = 5 stores 5 at key "apple".Step 2: Overwriting value for the same key
Later, table["apple"] = 7 replaces the old value 5 with 7.Step 3: Print the current value for key "apple"
Console.WriteLine outputs the latest value 7.Final Answer:
7 -> Option AQuick Check:
Last assigned value for key = output [OK]
- Thinking values add up
- Expecting first value to print
- Assuming error on duplicate key
var table = new Hashtable();
table.Add("key1", 10);
table.Add("key1", 20);
Console.WriteLine(table["key1"]);Solution
Step 1: Understand Add method behavior
Add throws an error if the key already exists in the Hashtable.Step 2: Check duplicate key usage
Adding "key1" twice causes a runtime exception on second Add.Final Answer:
Runtime error due to duplicate key -> Option BQuick Check:
Add fails on duplicate keys [OK]
- Assuming Add overwrites existing keys
- Expecting compile-time error
- Thinking output prints without error
hash(key) = key % 5, which of the following keys will cause a collision if inserted in order: 12, 8, 9, 22?Solution
Step 1: Calculate hash for each key
12 % 5 = 2, 8 % 5 = 3, 9 % 5 = 4, 22 % 5 = 2.Step 2: Identify keys with same hash index
12 and 22 both hash to index 2. Others have unique indices.Step 3: Check insertion order
Insert 12 (index 2), 8 (3) no collision, 9 (4) no collision, 22 (2) causes collision with 12.Final Answer:
12 and 22 -> Option DQuick Check:
Keys with same hash cause collision [OK]
- Calculating wrong modulo
- Ignoring insertion order
- Assuming different hashes for close numbers
Ready to prove it?
Pass the test and this pattern moves unknown
