7 / 7 · Intermediate
Choosing a data structure
Among 1,023 keys, a linear search for a missing key makes 1,023 comparisons, binary search makes 10, and a hash table with 1,023 buckets made at most 6 in the lab.
Jump to the 10 practice questionsYou will learn
- List the operations a program needs most
- Compare structures by the cost of those operations
- Pick Map, Set, a stack or a queue in JavaScript
Before this: Binary search trees
1Explain
No structure is best at everything
No structure is best at everything. Each one makes some operations cheap by making others expensive, so the way to choose is to list what your program will do most often. MIT's 6.006 splits the possibilities into two interfaces. A sequence keeps items in an order you decide (first, second, third), and you ask for items by position.
2Explore
Counting comparisons for one lookup
The lab below stores the same keys in five ways and counts the comparisons needed to find one of them. The keys are 15, 127 or 1,023 random whole numbers. The unsorted array uses linear search. The sorted array uses binary search. The balanced tree was built by inserting middle keys first, so it is as short as possible. The other tree was built from the keys in sorted order, so it is a chain. The hash table has as many buckets as keys and counts 1 for computing h(k).
A missing key is the worst case for both: linear search checks every key, binary search about log₂ n of them.
const n = 15;
const keys = Array.from({ length: n }, (_, i) => i * 2);
const target = -1; // missing: the worst case
let linear = 0;
for (const k of keys) { linear++; if (k === target) break; }
let binary = 0, lo = 0, hi = n - 1;
while (lo <= hi) {
const mid = Math.floor((lo + hi) / 2); binary++;
if (keys[mid] === target) break;
if (keys[mid] < target) lo = mid + 1; else hi = mid - 1;
}
console.log(linear); // unsorted array, linear search
console.log(binary); // sorted array, binary search15
43Problem
Linear, 1,023 keys
Linear search for a missing key among 1,023 keys makes how many comparisons?
Hint
A missing key: every key is checked.
Solution
Answer: 1023
Every key has to be checked before you can say it is missing.
4Problem
Binary, 1,023 keys
Binary search among 1,023 sorted keys makes at most how many comparisons?
Hint
⌊log₂ 1023⌋ + 1.
Solution
Answer: 10
Each comparison halves the remaining sorted search range. The maximum path has floor(log₂ 1023) + 1 = 9 + 1 = 10 comparisons, not a scan of every key.
5Problem
The average over 15 keys
Linear search over 15 keys: what is the average number of comparisons over all 15 keys?
Hint
(1 + 2 + … + 15) / 15.
Solution
Answer: 8
A present key in position 1 needs 1 comparison, position 2 needs 2, and so on. Averaging equally over all 15 present keys gives (1 + 2 + ... + 15) / 15 = 120 / 15 = 8.
6Problem
A chain of 127
A BST built from 127 keys inserted in sorted order: how many comparisons for the largest key?
Hint
Sorted insertion makes the tree a chain.
Solution
Answer: 127
The tree is a chain and the largest key is at the bottom: 127 comparisons.
7Explain
By position
With 15 keys the differences are small: linear search needs 8 comparisons on average and binary search about 3.3. With 1,023 keys they are not. Linear search averages 512 and needs 1,023 for a missing key, while binary search and the balanced tree never need more than 10. The chain tree is as bad as linear search. The hash table stays between 2.3 and 2.5 on average at every size because its chains stay short, and in this lab its worst case for 1,023 keys was 6.
| By position | Get item i | Insert or delete at front |
|---|---|---|
| Dynamic array | 1 | n |
| Linked list | n | 1 |
| Sorted array | 1 | n |
8Explain
By key
Each cell in these two tables is the growth rate of the cost for n items, following the tables in MIT's lecture notes 2, 4 and 7. Hash tables and search trees appear only in the second table because they work by key, not by position. In an unsorted array or a list, inserting a key costs n because you must first check that it is not already there.
| By key | Find | Insert | Next key |
|---|---|---|---|
| Array or list | n | n | n |
| Sorted array | log n | n | log n |
| Hash table | 1 on average | 1 on average | n |
| Balanced BST | log n | log n | log n |
9Explore
Same keys, two tools
Top: an undo history as a stack, the last edit comes back first. Bottom: a print queue, the first job is printed first.
Press a button: each one runs one operation and shows what it cost.
[]Total steps 0
Press a button: each one runs one operation and shows what it cost.
[]Total steps 0
10Problem
Undo
A text editor needs Undo. Which structure fits?
Hint
The most recent change is undone first.
Solution
Answer: Stack
Undo reverses the most recent change first: last in, first out.
11Problem
A print server
A print server must handle jobs in the order they arrive. Which structure fits?
Hint
Jobs in the order they arrive.
Solution
Answer: Queue
First in, first out is the queue rule.
12Problem
Records by id
You must look up a user record by its id many times per second. Which is the usual choice in JavaScript?
Hint
Many exact lookups per second.
Solution
Answer: A Map keyed by id
Map lookups are required to be faster than linear on average; a loop is linear.
13Problem
The next larger key
You need keys kept in sorted order while inserting and deleting, and you often ask for the next larger key. Which fits best?
Hint
Sorted order while inserting and deleting.
Solution
Answer: Balanced BST
A balanced BST keeps its height small, so the ordered operations cost O(log n). Hash lookup does not maintain sorted-key order; a Map’s insertion order does not guarantee the order needed for the next larger key.
14Explain
Map or plain object
JavaScript programs often use a plain object as a dictionary, writing prices["apple"]. MDN lists reasons to prefer Map when the keys come from data. An object has a prototype, so it contains default keys that could collide with yours. A Map can use any value as a key, not only strings and symbols. Its size is one property, map.size, and it is iterated in insertion order. Objects remain the natural choice for records with a fixed set of named fields.
15Problem
A risky dictionary
According to MDN, why can a plain object be risky as a dictionary for keys that come from data?
Hint
Think of the keys an object already has.
Solution
Answer: Its prototype brings default keys that may collide with yours
A Map contains only what you put into it; an object inherits keys from its prototype.
16Problem
A set without order
In MIT 6.006 terms, a set without the order operations is called
Hint
MIT lecture 2.
Solution
Answer: a dictionary
Lecture 2 lists "dictionary: set without the Order operations".
17Practice
The first repeat
Use a Set to find the first value that appears a second time. It should print 8 and then null.
8
nullconst ids = [4, 8, 15, 16, 23, 42, 8, 15, 4, 99];
function firstRepeat(list) {
const seen = new Set();
for (const x of list) {
// If seen already has x, return x. Otherwise add x to seen.
}
return null;
}
console.log(firstRepeat(ids));
console.log(firstRepeat([1, 2, 3]));
Hint
Check before you add, or every value looks like a repeat.
A solution
const ids = [4, 8, 15, 16, 23, 42, 8, 15, 4, 99];
function firstRepeat(list) {
const seen = new Set();
for (const x of list) {
if (seen.has(x)) return x;
seen.add(x);
}
return null;
}
console.log(firstRepeat(ids));
console.log(firstRepeat([1, 2, 3]));18Practice
An index with a Map
Linear search for 2997 checks all 1,000 values. Build a Map from value to position so the last line prints 999 straight away. Output: true 1000, then 999.
true 1000
999const n = 1000;
const list = Array.from({ length: n }, (_, i) => i * 3);
let checks = 0;
function linearHas(list, x) {
for (const v of list) { checks++; if (v === x) return true; }
return false;
}
const index = new Map();
// Fill index so that index.get(v) is the position of v in list.
console.log(linearHas(list, 2997), checks);
console.log(index.get(2997));
Hint
The key is the value v; what you store is its position i.
A solution
const n = 1000;
const list = Array.from({ length: n }, (_, i) => i * 3);
let checks = 0;
function linearHas(list, x) {
for (const v of list) { checks++; if (v === x) return true; }
return false;
}
const index = new Map();
list.forEach((v, i) => index.set(v, i));
console.log(linearHas(list, 2997), checks);
console.log(index.get(2997));19Explain
Common mistakes
const prices = {};
console.log("toString" in prices);trueconst prices = new Map();
console.log(prices.has("toString"));falseA plain object already has keys from its prototype, so "toString" looks present in an empty object. A Map holds only what you put in.
20
Summary
- Choose by the operations you will do most often.
- Sequence: array, linked list, stack, queue. Set: hash table, BST.
- For 1,023 keys: linear search up to 1,023 comparisons, binary search and a balanced tree up to 10.
- Map is the usual dictionary in JavaScript; use a balanced tree when you also need order.