Hash Tables - potatoscript/dsa GitHub Wiki
π§© What is a Hash Table?
Imagine you have a super-fast address book π. You want to quickly look up someone's phone number, but you don't want to search through the whole book! Instead, you use a unique identifier (like a name) to instantly find the number, no matter how big the book is.
A hash table works in a similar way. It stores data using a hash function, which is like a magical formula that converts a key (like a person's name) into an address or location (like a phone number). The hash table then uses that address to store or retrieve the data super quickly.
πΌοΈ Visual Example:
Imagine you're organizing a group of friends by their names and assigning them a phone number.
Hash Table:
Key -> Value
"Alice" -> 123-456-7890
"Bob" -> 987-654-3210
"Charlie" -> 555-555-5555
Now, when you search for "Alice", you donβt have to go through all the names in the list. You can directly go to Alice's spot using her hash (like a special key).
π§ Why Use a Hash Table?
- Super Fast Lookups: You can find things almost instantly, even in huge data sets.
- Efficient Insertion and Deletion: You can add or remove data just as quickly.
- Key-Value Pairs: It stores data as pairs, where each key is mapped to a value.
In simple terms, hash tables are perfect when you need to access data quickly and don't want to waste time searching through long lists. πββοΈ
π§ Real-World Analogy
Situation | Hash Table Comparison |
---|---|
π House Directory | The house number is the key, and the address is the value. |
π School Locker | The locker number is the key, and the contents are the value. |
π’ Office Desk | The employee name is the key, and the desk location is the value. |
π» C# Code: Simple Hash Table (Dictionary)
In C#, we can use the Dictionary<TKey, TValue>
class to implement a hash table.
Define a Hash Table (Dictionary):
Dictionary<string, string> phoneBook = new Dictionary<string, string>();
Add Items (Insert Data):
phoneBook.Add("Alice", "123-456-7890");
phoneBook.Add("Bob", "987-654-3210");
phoneBook.Add("Charlie", "555-555-5555");
Retrieve Data (Look Up):
string phoneNumber = phoneBook["Alice"];
Console.WriteLine("Alice's Phone Number: " + phoneNumber);
Remove Items (Delete Data):
phoneBook.Remove("Bob");
Check if Key Exists:
if (phoneBook.ContainsKey("Charlie"))
{
Console.WriteLine("Charlie's Phone Number: " + phoneBook["Charlie"]);
}
π§© Operations in a Hash Table
Operation | Description | Time Complexity |
---|---|---|
Add |
Add a key-value pair to the hash table | O(1) |
Retrieve |
Retrieve a value based on its key | O(1) |
Remove |
Remove a key-value pair from the hash table | O(1) |
ContainsKey |
Check if a key exists in the hash table | O(1) |
In most cases, these operations are super fast because they are done in constant time, meaning no matter how big the hash table is, the time it takes to do these operations is the same.
π§ How Does a Hash Table Work?
-
Hash Function:
A hash function takes the key (like "Alice") and returns a hash code, which is a unique number. This number is then used to find a location in the hash table where the value (like "123-456-7890") is stored. -
Collision:
Sometimes, two different keys can produce the same hash code (this is called a collision). To handle this, hash tables use techniques like chaining (storing multiple values in the same location) or open addressing (finding a new location).
π§© Example with Hashing
Letβs say we have a hash function that gives us the following hash codes for names:
- "Alice" β 3
- "Bob" β 1
- "Charlie" β 5
Now we insert them into a hash table:
Hash Table:
Index 0 ->
Index 1 -> Bob -> "987-654-3210"
Index 2 ->
Index 3 -> Alice -> "123-456-7890"
Index 4 ->
Index 5 -> Charlie -> "555-555-5555"
π¨ Pitfalls to Avoid
- β Collisions: Two keys might end up with the same hash. Make sure to handle this properly to avoid overwriting data.
- β Resizing: If your hash table gets too full, you may need to resize it to keep operations fast. This is known as rehashing.
π§ Time Complexity (Big O)
- Insertion (Add): O(1) β Constant time to add a new item.
- Lookup (Retrieve): O(1) β Instant access to data.
- Deletion (Remove): O(1) β Fast removal.
- Search (ContainsKey): O(1) β Super fast search.
π Real-World Example: Grocery Store
Letβs say weβre creating a grocery store inventory system using a hash table. Each item (like "Apple") will be the key, and the quantity of the item (like 50) will be the value.
Dictionary<string, int> groceryInventory = new Dictionary<string, int>();
// Add items
groceryInventory.Add("Apple", 50);
groceryInventory.Add("Banana", 30);
groceryInventory.Add("Carrot", 100);
// Lookup the quantity of an item
int appleQuantity = groceryInventory["Apple"];
Console.WriteLine("Apple Quantity: " + appleQuantity);
// Remove an item
groceryInventory.Remove("Banana");
// Check if an item exists
if (groceryInventory.ContainsKey("Carrot"))
{
Console.WriteLine("Carrot Quantity: " + groceryInventory["Carrot"]);
}
π¨ Hash Table Challenges
π Challenge 1: Simple Phonebook
Create a phonebook system where you add people's names and phone numbers to a hash table. Then, search for someone's phone number by their name.
π§ Challenge 2: Grocery Inventory
Simulate a grocery store inventory. Add items like "Apple" and "Banana" to a hash table, then find out how many apples you have.
π§Ή Challenge 3: Employee Directory
Write a system to store employee names and IDs in a hash table. Check if a particular employee is in the directory by their name.
π§© Types of Hash Tables
- Open Addressing: If a spot in the hash table is taken, find another spot using a probing technique.
- Chaining: Use a linked list to store multiple values at the same index in the hash table.
π Summary Time!
β
Hash Tables store data in key-value pairs for fast access.
β
You can add, remove, and retrieve data super quickly with a hash table.
β
The hash function maps a key to an index where the value is stored.
β
Big O for hash table operations is O(1) β fast, fast, fast!