The problem: finding things fast
After this: Say what a key and a value are, why searching a list is slow, and what a hash map offers instead.
On this page · 8 sections · 3 checks
Open the contacts on your phone and type "Olive". Her number appears at once. You do not read every name from the top. You know one thing, the name, and you want the thing that goes with it, the number.
A paper dictionary is similar. You know a word, and you want its meaning.
Programs need to do this all the time. This lesson shows the tool that does the job, and why it matters.
Keys and values
In both examples you start from something you know, and you get back something that goes with it. The thing you know is called the . The thing you get back is called the . A key and its value together are called a pair.
| Example | Key | Value |
|---|---|---|
| Phone contacts | Olive | 555-0142 |
| Dictionary | apple | a round fruit |
| Class marks | Amir | 72 |
The smallest example
Python and Java both give you a ready-made tool for storing pairs. In Python it is called a dict, which is short for dictionary. In Java it is called a HashMap. You may have used one already, and if not, you will use one soon. Here are two contacts stored in one, and one of them found again by name.
phones = {}phones["Olive"] = "555-0142"phones["Bea"] = "555-0177"print(phones["Olive"])555-0142
Map<String, String> phones = new HashMap<>();phones.put("Olive", "555-0142");phones.put("Bea", "555-0177");System.out.println(phones.get("Olive"));555-0142
The two middle lines each store a pair. The last line gives the key "Olive" and gets back her number.
The general name for this kind of tool is a . This tutorial looks inside one. But first, why not store the pairs in a plain list?
Searching a list
Imagine a list of student records, in the order the students enrolled. A record holds a student's name and some details about them. Here are four: Amir, Bea, Olive and Kai. To find Olive, you start at the front.
- Look at Amir. This is not Olive.
- Look at Bea. This is not Olive.
- Look at Olive. You found her after three checks.
Now look for Zed, who is not in the list. You must check all four records before you can be sure.
Checking records one at a time like this is called a .
def find(records, name): checks = 0 for record in records: # one record at a time, front to back checks += 1 if record.name == name: return record, checks return None, checks # looked at every recordstatic Record find(List<Record> records, String name) { int checks = 0; for (Record record : records) { // one record at a time, front to back checks++; if (record.name.equals(name)) { return record; // found after 'checks' comparisons } } return null; // looked at every record}The loop takes one record at a time, from the front. checks counts how many records we have looked at. If a name matches, the function stops there and returns what it found. If the loop ends, the name is not in the list.
Four records is a small job. Now imagine many more.
A list holds 1,000 student records in no particular order. To find Olive, how many records might you have to check?
So the cost of a linear search grows with the list. A thousand records can mean a thousand checks, and a million can mean a million. Programmers write this as O(n), where n is the number of items. O(n) means that the work grows at the same rate as the list. Its opposite is O(1), which means that the work stays the same however long the list gets. The lesson Counting steps explains both.
A sorted list helps, but it has a cost
A paper dictionary is sorted, and that helps. Suppose the student records are sorted by name. Open the list in the middle, see whether Olive comes before or after that name, and ignore the half she cannot be in. Each check cuts the remaining records in half, so a million records take only about twenty checks.
But sorting has a price. A new record must go in its right place, so every record after that place has to move along by one. With a million records, that can mean a million moves. A sorted list is fast to search and slow to add to.
What we really want
We do not want to search at all. We want to jump straight to the record, as if the name told us where the record is stored.
You have seen a jump like this if you have read an array by its index. Reading index 1042 does not look at the 1,042 cells before it. The computer works out where that cell is and goes there, as the lesson How the computer finds a cell shows. So if every key were a small whole number, we could use the key as the index: student 1042 would go in cell 1042.
That stops working when the keys are names, because an array has no cell called "Olive". It also stops working for ids in the billions, because the array would need billions of cells.
A hash map is the answer to this problem. It turns any key into a cell number.
Scan versus jump
Here are twelve records, standing in for a thousand. First press the scan button and watch the checks counter. Then press the jump button.
- checks
- 0
- 0Amir
- 1Bea
- 2Chen
- 3Dara
- 4Eli
- 5Fay
- 6Gus
- 7Hana
- 8Ivo
- 9Olive
- 10Kai
- 11Lena
Two ways to find a record. Scan checks them one by one; jump goes straight to a position.
The scan took ten checks and the jump took one. That jump is what a hash map offers: you find an item by its key in about one step, however many items there are. The rest of the tutorial answers one question: how do we turn a key like "Olive" into a position, reliably, for any key?
Check yourself
What does a hash map offer that a plain list cannot?
A well-built hash map holds 1,000,000 records. Roughly how many checks does it take to find one record?
Connect
- Say what a key, a value and a pair are, with an everyday example.
- Say why searching a plain list is slow: the cost grows with the list.
- Say what sorting gives you and what it costs.
- Say what a hash map offers: you jump to an item by its key, whatever the size.