</>
Skip to content
DSA lessons (15/55)

DSA — Hash Tables

What is a Hash Table?

A data structure that maps keys to values using a hash function.

class HashTable:
    def __init__(self, size=10):
        self.size = size
        self.table = [[] for _ in range(size)]
    
    def hash_function(self, key):
        return hash(key) % self.size
    
    def insert(self, key, value):
        index = self.hash_function(key)
        for pair in self.table[index]:
            if pair[0] == key:
                pair[1] = value
                return
        self.table[index].append([key, value])
    
    def get(self, key):
        index = self.hash_function(key)
        for pair in self.table[index]:
            if pair[0] == key:
                return pair[1]
        return None
    
    def delete(self, key):
        index = self.hash_function(key)
        for i, pair in enumerate(self.table[index]):
            if pair[0] == key:
                del self.table[index][i]
                return True
        return False

Operations

OperationAverageWorst Case
InsertO(1)O(n)
SearchO(1)O(n)
DeleteO(1)O(n)

Collision Handling

MethodDescription
ChainingLinked lists at each slot
Open AddressingFind next empty slot

Mini Practice

  1. Implement a hash table
  2. Handle collisions
  3. Use hash table for counting
  4. Implement a cache

Up Next

Continue with HashMap — HashMap implementation.

Related Topics

Frequently Asked Questions about Hash Tables

What is Hash Tables in DSA?

Hash Tables is a fundamental concept in DSA. This lesson explains it step by step with clear examples, making it easy for beginners to understand.

How do I learn Hash Tables?

Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Hash Tables.

Why is Hash Tables important in DSA?

Hash Tables is essential for DSA development. Understanding this concept will help you write better code and solve real-world problems more effectively.