Friday, October 23, 2026 New tutorials published every day
Home
Tutorials
Core PHP PHP Course JavaScript React & Next.js Python WordPress Artificial Intelligence
Free Tools
JSON Formatter Base64 Encoder / Decoder Password Generator Text to QR Code Generator Word Counter Case Converter Age Calculator Color Converter Number to Words All Free Tools
Projects
PHP Projects — all projects
Resources
Search tutorials About CodingCush Contact
More
Login
Data Structures

What Is a Hash Table (HashMap)? Explained with a Simple Example

A hash table stores data as key-value pairs and finds any value almost instantly. Learn how hashing works, what a collision is, and when to use a HashMap.

A hash table is a data structure that stores data as key–value pairs and can find any value almost instantly when you give it the key. Instead of searching through a long list one item at a time, it uses a small formula called a hash function to calculate exactly where the value is stored. In most programming languages you already use hash tables every day: a dictionary in Python, a Map or object in JavaScript, and a HashMap in Java are all hash tables. If you have ever written marks["Asha"] = 92 and later fetched it in a blink, you have used one.

A Simple Real-Life Example

Think of a big school with 1,000 students. If the office keeps one long register sorted by admission order, finding one student's record means flipping page after page. Now imagine a different system: every student has a roll number, and the office keeps one small drawer per class. To find a student, you do not search — you simply calculate which drawer to open from the roll number, and the record is right there.

A hash table works the same way. The roll number is the key, the record is the value, and the rule that tells you which drawer to open is the hash function. No scanning, no guessing — just one quick calculation and you are looking at the right spot. That is the whole magic, and honestly it feels a little unfair once you see how much time it saves.

How a Hash Table Works, Step by Step

Inside, a hash table is really just an array of empty slots, usually called buckets. Here is what happens when you store a value:

  1. You give the table a key and a value, for example the key "Asha" and the value 92.
  2. The hash function converts the key into a number. For the key "Asha" it might produce a long number like 2,417,903.
  3. The table divides that number by the number of buckets and uses the remainder as the slot index. With 10 buckets, 2,417,903 points to bucket 3.
  4. The value 92 is stored in bucket 3, together with its key.

When you later ask for "Asha", the table runs the same three steps again: hash the key, find bucket 3, and pick up the value. Because the same key always produces the same bucket, the lookup takes the same tiny amount of time whether the table holds ten items or ten million. Fetching data this way is the main reason hash tables are loved so much.

Hash Tables in Real Code

In Python, the dictionary is a hash table, and you use it like this:

marks = {}
marks["Asha"] = 92
marks["Ravi"] = 85

print(marks["Asha"])   # 92 — found instantly, no searching

The official Python tutorial explains dictionaries in its data structures chapter, and it is worth a slow read once you finish this post. In JavaScript, the built-in Map does the same job:

const marks = new Map();
marks.set("Asha", 92);
marks.set("Ravi", 85);

console.log(marks.get("Asha"));  // 92

MDN's guide to the JavaScript Map object shows more of its methods, like checking whether a key exists with has(). Different language, different name — dictionary, Map, HashMap — but the idea under the hood is always the same hash table.

Python documentation dictionary example showing key-value pairs in the interactive shell
A worked dictionary example from Python's official tutorial — the dictionary is Python's built-in hash table.

What Is a Collision?

There is one small problem, and it has a friendly name: a collision. A collision happens when two different keys produce the same bucket. With only 10 buckets and hundreds of students, sooner or later two roll numbers will point at the same drawer — it is like two people being given the same locker number.

The most common fix is called chaining: each bucket holds a small list instead of a single value. If two keys land in bucket 3, both pairs sit in that bucket's little list, and the table checks the keys one by one inside that short list only. Because a good hash function spreads keys out evenly, these lists stay very short, so lookups stay fast in practice. You do not have to build any of this yourself — the dictionary or HashMap in your language already handles collisions quietly in the background.

How Fast Is a Hash Table?

Here is the part interviewers love. On average, a hash table does its three main jobs in constant time, written as O(1) — the time does not grow when the table grows.

Operation Average case Worst case
Search by key O(1) O(n)
Insert a pair O(1) O(n)
Delete by key O(1) O(n)

The worst case happens only when almost every key collides into the same bucket, which turns the table into one long list. A well-built hash function makes that extremely unlikely with real data, so in daily work you can treat hash table lookups as instant. Compare this with a plain array, where finding a value by name can mean checking every single element.

Hash Table vs Array vs Linked List

So when should you pick a hash table over the simpler structures? An array is best when you access items by position and order matters. A linked list is handy when you insert and delete in the middle very often — we covered that comparison in detail in our guide on Array vs Linked List: what is the difference?. A hash table wins when your data naturally comes as pairs and you mostly ask questions like "give me the value for this key" — a username and their profile, a word and its meaning, a product code and its price. If your lookups are by name or ID rather than by position, the hash table is almost always the right tool.

When Should You Use a Hash Table?

  • Fast lookups by key: settings, user profiles, product prices, cached results.
  • Counting things: how many times each word appears in a paragraph, or each item in a cart.
  • Removing duplicates: storing items in a set (a close cousin of the hash table) keeps only one copy of each.
  • Pairing related data: a student's roll number with their marks, a country with its capital.

One honest warning: a basic hash table does not keep your items in sorted order, and it is not the best choice when you need range questions like "give me everyone between roll 50 and 80". For those jobs, sorted structures work better. Also note that in Python, keys must be of an unchangeable type like a string or a number — a list cannot be a key. If you are still deciding between a list and a dictionary for a task, our comparison of Python list vs dictionary walks through that exact choice.

Frequently Asked Questions

What is the difference between a hash table and a HashMap?

Almost nothing in daily use. "Hash table" is the name of the data structure idea, while "HashMap" is the name Java gives to its ready-made class that implements it. Python calls it a dictionary and JavaScript offers Map and plain objects — same idea, different labels.

Why is a hash table lookup O(1) on average?

Because the hash function calculates the bucket directly from the key, the table jumps straight to the right slot instead of checking items one by one. As long as collisions stay rare, the work stays the same no matter how big the table gets.

Can a hash table store duplicate keys?

No. Keys in a hash table are unique. If you store a value using a key that already exists, the old value is replaced by the new one. That is why dictionaries are perfect for settings: one key, one current value.

What makes a hash function "good"?

A good hash function spreads keys evenly across all buckets and always returns the same result for the same key. Even spreading means short bucket lists, and short lists mean fast lookups.

Is a hash table the same as an array?

No. An array finds items by their position number, while a hash table finds items by a meaningful key, like a name or an ID. Behind the scenes a hash table uses an array for storage, but you never deal with the positions yourself.

Conclusion

A hash table stores key–value pairs and uses a hash function to jump straight to the right bucket, which makes searching, inserting and deleting almost instant on average. You met its three moving parts — keys, the hash function and buckets — you saw how collisions are handled with chaining, and you now know the names it wears in real languages: dictionary in Python, Map in JavaScript and HashMap in Java. The next time you need to look something up by name instead of by position, reach for a hash table without a second thought. It is one of those rare ideas that is both simple and genuinely powerful.

Lavkush
Written by

Lavkush Super Admin

Lavkush Kumar is a software developer with over 6 years of experience turning ideas into websites and web applications. He holds a Master of Computer Applications (MCA) degree and enjoys building for the web, exploring new tools, and sharing what he learns along the way.

Through CodingCush, Lavkush creates easy-to-follow tutorials and practical guides to help students and beginners learn software development without feeling overwhelmed. His approach is simple: learn by doing, build real projects, and keep improving one step at a time.

Whether you’re just starting out or looking to sharpen your skills, CodingCush is all about making learning practical, beginner-friendly, and fun.

0 Comments

Leave a Comment