Hashing in C
Searching a list takes O(n) steps; a balanced BST takes O(log n). Hashing aims for O(1) on average: you compute where an item belongs from the item itself, and jump straight there. That's how dictionaries, phone contacts, login systems and compilers' symbol tables find things instantly.
In this lesson you will learn what a hash function and a hash table are, why collisions happen, and the two main ways to handle them: separate chaining (linked lists) and linear probing (open addressing), with complete C programs.
What You Will Learn
- What hashing, a hash function and a hash table are.
- Properties of a good hash function.
- What a collision is and the load factor.
- Separate chaining: insert, search, delete.
- Linear probing (open addressing).
- Hashing strings and the time complexity of hashing.
Hashing in C Explained
Exam definition: Hashing is a technique that maps a key to a position (an index) in an array, called a hash table, using a hash function, e.g. h(key) = key % TABLE_SIZE. When two keys map to the same index, a collision occurs. Collisions are resolved by separate chaining (each slot holds a linked list of keys) or open addressing (search for another free slot, e.g. linear probing: try index+1, index+2, …). With a good hash function and a low load factor (keys ÷ slots), insert, search and delete take O(1) time on average.
Memory trick: A hash table is a school locker room. Your locker number is calculated from your roll number (the hash function), so you walk straight to it. If two students get the same locker (a collision), either they share it with a hanging chain of bags (separate chaining) or the second student takes the next empty locker (linear probing).
Table size 10, h(key) = key % 10
key 25 -> 25 % 10 = 5 index contents
key 42 -> 42 % 10 = 2 0 -
key 15 -> 15 % 10 = 5 (!) 1 -
2 42
3 -
collision at index 5 4 -
5 25 -> 15 (chaining)
Syntax: Hash Function and Chained Table
#define SIZE 10
int hash(int key)
{
return key % SIZE; /* division method */
}
struct entry /* one item in a chain */
{
int key;
struct entry *next;
};
struct entry *table[SIZE]; /* each slot is the head of a linked list */
A good hash function
- Is fast to compute.
- Spreads keys evenly over the table (few collisions).
- Always gives the same index for the same key.
- Uses a table size that is a prime number for the division method (e.g. 7, 11, 101) to spread keys better.
Example 1: Hash Table with Separate Chaining
#include <stdio.h>
#include <stdlib.h>
#define SIZE 7
struct entry
{
int key;
struct entry *next;
};
struct entry *table[SIZE];
int hash(int key)
{
return key % SIZE;
}
void insert(int key)
{
int i = hash(key);
struct entry *e = malloc(sizeof *e);
if (e == NULL)
exit(1);
e->key = key;
e->next = table[i]; /* add at the front of the chain */
table[i] = e;
}
int search(int key)
{
struct entry *e;
for (e = table[hash(key)]; e != NULL; e = e->next)
if (e->key == key)
return 1;
return 0;
}
int delete_key(int key)
{
int i = hash(key);
struct entry *e = table[i], *prev = NULL;
while (e != NULL && e->key != key)
{
prev = e;
e = e->next;
}
if (e == NULL)
return 0;
if (prev == NULL)
table[i] = e->next;
else
prev->next = e->next;
free(e);
return 1;
}
void display(void)
{
int i;
struct entry *e;
for (i = 0; i < SIZE; i++)
{
printf("[%d]", i);
for (e = table[i]; e != NULL; e = e->next)
printf(" -> %d", e->key);
printf("\n");
}
}
int main(void)
{
int keys[] = {15, 11, 27, 8, 12, 22, 33};
int i;
struct entry *e, *t;
for (i = 0; i < 7; i++)
insert(keys[i]);
display();
printf("Search 27: %s\n", search(27) ? "found" : "not found");
printf("Search 20: %s\n", search(20) ? "found" : "not found");
delete_key(8);
printf("After deleting 8:\n");
display();
for (i = 0; i < SIZE; i++)
for (e = table[i]; e != NULL; e = t)
{
t = e->next;
free(e);
}
return 0;
}
Output
[0] [1] -> 22 -> 8 -> 15 [2] [3] [4] -> 11 [5] -> 33 -> 12 [6] -> 27 Search 27: found Search 20: not found After deleting 8: [0] [1] -> 22 -> 15 [2] [3] [4] -> 11 [5] -> 33 -> 12 [6] -> 27
Code Explanation
hash(key) = key % 7: 15 → 1, 11 → 4, 27 → 6, 8 → 1, 12 → 5, 22 → 1, 33 → 5.- 15, 8 and 22 all hash to 1: a collision. With chaining, they simply share slot 1 in a linked list. New keys are added at the front, so the chain reads 22 → 8 → 15.
search(27)computes slot 6 and checks only that chain, not the whole table.delete_key(8)goes to slot 1 and removes 8 from the chain with the usual linked-list bypass.- The load factor is 7 keys ÷ 7 slots = 1. Chains stay short, so operations are close to O(1).
How Collisions Are Resolved
| Method | Idea | Pros / cons |
|---|---|---|
| Separate chaining | Each slot holds a linked list | Simple, never "full"; uses extra pointers |
| Linear probing | Try i, i+1, i+2, … (wrap around) | No pointers, cache-friendly; clusters form |
| Quadratic probing | Try i+1², i+2², i+3², … | Fewer clusters; may miss free slots |
| Double hashing | Step size from a second hash function | Best spread; slightly more work |
Load factor α = number of keys ÷ table size. For chaining, the average chain length is α. For open addressing, α must stay below 1 (the table can fill up); keeping it under about 0.7 keeps probing fast. When α grows too big, real hash tables resize (rehash into a bigger table).
Example 2: Linear Probing (Open Addressing)
#include <stdio.h>
#define SIZE 7
#define EMPTY -1
int table[SIZE];
int insert(int key)
{
int i = key % SIZE, tries;
for (tries = 0; tries < SIZE; tries++)
{
if (table[i] == EMPTY)
{
table[i] = key;
return i;
}
i = (i + 1) % SIZE; /* probe the next slot */
}
return -1; /* table full */
}
int search(int key, int *probes)
{
int i = key % SIZE;
*probes = 0;
while (*probes < SIZE && table[i] != EMPTY)
{
(*probes)++;
if (table[i] == key)
return i;
i = (i + 1) % SIZE;
}
return -1;
}
int main(void)
{
int keys[] = {50, 700, 76, 85, 92, 73, 101};
int i, pos, probes;
for (i = 0; i < SIZE; i++)
table[i] = EMPTY;
for (i = 0; i < 7; i++)
{
pos = insert(keys[i]);
printf("Insert %3d: home %d, stored at %d\n", keys[i], keys[i] % SIZE, pos);
}
printf("Table:");
for (i = 0; i < SIZE; i++)
printf(" %d", table[i]);
printf("\n");
pos = search(101, &probes);
printf("Search 101: index %d after %d probes\n", pos, probes);
printf("Insert 9 : %s\n", insert(9) == -1 ? "table full" : "stored");
return 0;
}
Output
Insert 50: home 1, stored at 1 Insert 700: home 0, stored at 0 Insert 76: home 6, stored at 6 Insert 85: home 1, stored at 2 Insert 92: home 1, stored at 3 Insert 73: home 3, stored at 4 Insert 101: home 3, stored at 5 Table: 700 50 85 92 73 101 76 Search 101: index 5 after 3 probes Insert 9 : table full
- 85 wants slot 1 (taken by 50), so it moves to 2. 92 also wants 1 and ends up at 3. 73 wants 3 (taken) and lands at 4.
- The keys pile up in a run of filled slots, called primary clustering: later keys like 101 need several probes.
- Searching follows the same probe sequence until it finds the key or an empty slot.
- With open addressing, the table can become full; chaining never does.
Important Points to Remember
- Hashing maps a key to an index with a hash function, e.g.
key % SIZE. - A collision happens when two keys get the same index; it can't be avoided completely.
- Separate chaining: a linked list per slot. Open addressing: probe for another slot (linear, quadratic, double hashing).
- Load factor = keys ÷ slots; keep it low (resize when needed).
- Average time: O(1); worst case (all keys collide): O(n).
- Choose a prime table size for the division method.
Common Mistakes Beginners Make
| Mistake | What happens | Fix |
|---|---|---|
Negative keys with key % SIZE | Negative index, out-of-bounds access | Use ((key % SIZE) + SIZE) % SIZE |
| Not wrapping around in linear probing | Probes past the end of the array | i = (i + 1) % SIZE |
| Simply emptying a slot when deleting with probing | Later keys in the cluster can't be found | Mark it as "deleted" (a tombstone) instead |
| Table size 10 with keys that end in 0 | All keys collide in slot 0 | Use a prime size like 11 |
| Letting the load factor reach 1 with probing | Insert fails, search becomes slow | Resize/rehash before it gets too full |
Hashing Practice Questions
- What is hashing? What is a hash function?
- What is a collision? Why can't it be avoided completely?
- Differentiate between separate chaining and linear probing.
- What is the load factor?
- Insert 10, 22, 31, 4, 15 into a table of size 7 using linear probing. Where does each key go?
Show answers
- A technique that stores and finds keys by computing their position in an array; a hash function converts a key into that array index.
- Two different keys mapping to the same index; there are usually far more possible keys than slots, so some keys must share an index.
- Chaining keeps colliding keys in a linked list at the same slot; linear probing stores the key in the next free slot (index + 1, + 2, …).
- Number of keys stored ÷ number of slots in the table.
- 10 → 3, 22 → 1, 31 → 3 is taken so 4, 4 → 4 is taken so 5, 15 → 1 is taken, 2 is free, so 2.
Coding Exercise
Write a hash function for strings: add the ASCII codes of all characters and take the remainder by 11. Store the names Amit, Riya, Sara, Dev and Neha in a chained hash table of size 11, print each name with its slot, and search for "Sara" and "Ravi".
Show solution
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define SIZE 11
struct entry
{
char name[20];
struct entry *next;
};
struct entry *table[SIZE];
int hash(const char *s)
{
int sum = 0;
for (; *s != '\0'; s++)
sum += (unsigned char)*s;
return sum % SIZE;
}
void insert(const char *name)
{
int i = hash(name);
struct entry *e = malloc(sizeof *e);
if (e == NULL)
exit(1);
strcpy(e->name, name);
e->next = table[i];
table[i] = e;
printf("%-5s -> slot %d\n", name, i);
}
int search(const char *name)
{
struct entry *e;
for (e = table[hash(name)]; e != NULL; e = e->next)
if (strcmp(e->name, name) == 0)
return 1;
return 0;
}
int main(void)
{
const char *names[] = {"Amit", "Riya", "Sara", "Dev", "Neha"};
struct entry *e, *t;
int i;
for (i = 0; i < 5; i++)
insert(names[i]);
printf("Search Sara: %s\n", search("Sara") ? "found" : "not found");
printf("Search Ravi: %s\n", search("Ravi") ? "found" : "not found");
for (i = 0; i < SIZE; i++)
for (e = table[i]; e != NULL; e = t) { t = e->next; free(e); }
return 0;
}
Amit -> slot 10 Riya -> slot 9 Sara -> slot 6 Dev -> slot 1 Neha -> slot 6 Search Sara: found Search Ravi: not found
Sara and Neha collide in slot 6 and share a chain (Sara = 83 + 97 + 114 + 97 = 391, and 391 % 11 = 6). Real programs use stronger string hashes (like djb2) that mix the character order, so "ab" and "ba" don't collide.
Quick Quiz: Hashing (MCQ)
-
With
h(k) = k % 10, key 47 goes to index:A) 4 B) 7 C) 47 D) 0
-
Two keys mapping to the same index is called a:
A) Overflow B) Collision C) Probe D) Leak
-
Separate chaining stores colliding keys in:
A) The next slot B) A linked list C) A stack D) A second array
-
Average time to search a good hash table:
A) O(1) B) O(log n) C) O(n) D) O(n log n)
-
Load factor is:
A) Keys × slots B) Keys ÷ slots C) Slots − keys D) Collisions ÷ keys
Show answers
- B: 7.
- B: a collision.
- B: a linked list.
- A: O(1).
- B: keys ÷ slots.
Quick Revision for Exams and Interviews
Read this before your exam. The highlighted words are the answer.
Must-remember facts
| Hashing | Key → index with a hash function |
|---|---|
| Division method | h(k) = k % SIZE, SIZE prime |
| Collision | Two keys, same index |
| Separate chaining | Linked list per slot |
| Linear probing | Try next slot: (i + 1) % SIZE |
| Load factor | Keys ÷ slots |
| Time | O(1) average, O(n) worst |
Frequently asked questions
- What is hashing in data structures?
- A technique that uses a hash function to compute the array index of a key, giving O(1) average insert and search.
- What are collision resolution techniques?
- Separate chaining and open addressing (linear probing, quadratic probing, double hashing).
- Why should the table size be prime?
- A prime size spreads keys more evenly with the division method, giving fewer collisions.
Remember
- Hash table = locker room: calculate the locker, walk straight there.
- Collision? Chain it or probe the next locker.
Next Topic
Next lesson: Sorting Algorithms in C. You will write insertion sort, merge sort and quick sort and compare their speed.