edubun
English
1 / 20

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 questions

You 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.

keys
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 search
Output
15
4

3Problem

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 positionGet item iInsert or delete at front
Dynamic array1n
Linked listn1
Sorted array1n

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 keyFindInsertNext key
Array or listnnn
Sorted arraylog nnlog n
Hash table1 on average1 on averagen
Balanced BSTlog nlog nlog 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.

Expected output
8
null
Your code
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 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.

Expected output
true 1000
999
Your code
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();
// 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

Mistake
const prices = {};
console.log("toString" in prices);
Output
true
Fixed
const prices = new Map();
console.log(prices.has("toString"));
Output
false

A 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.

Back to the courseData structures
Full text · The whole lesson as one text

Start from the questions you will ask

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. A set keeps items by key, and you ask whether a key is there, or for the smallest key, or the next one after a given key. A set without the order questions is called a dictionary.

A few common situations and the usual answer:

  • Read items by position, add at the end: a dynamic array (a JavaScript array).
  • Undo history, matching brackets, depth-first search: a stack, which is an array used only at its end.
  • Jobs handled in arrival order, breadth-first search: a queue, with a head index or a ring buffer rather than shift on a long array.
  • Look things up by name or id: a hash table, which in JavaScript means Map or Set.
  • Keep keys sorted while inserting and deleting, ask for the next key: a balanced binary search tree.
  • Many inserts and deletes at a spot you already hold: a linked list.

The same lookup in five structures

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).

Comparisons needed to find one key in five structures holding the same keys. Bars show the chosen key; the dashed line is the average over every stored key. The table below the picture gives the average and the worst case.

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. That is why Map is the default choice for lookups, and why sorted structures are worth it only when you also need order.

By positionGet item iInsert or delete at front
Dynamic array1n
Linked listn1
Sorted array1n
By keyFindInsertNext key
Array or listnnn
Sorted arraylog nnlog n
Hash table1 on average1 on averagen
Balanced BSTlog nlog nlog n

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. The sorted array finds quickly but has to move values to make room for a new key.

Map or 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.

  • 1953: H. P. Luhn's IBM memorandum suggests hashing into buckets with chaining.
  • About 1956: Newell, Shaw and Simon's IPL brings linked lists.
  • 1957: Bauer and Samelson apply for a patent on the stack method; Fortran ships with arrays.
  • 1962: Adelson-Velsky and Landis publish the AVL tree, the first balanced search tree.
  • 2015: ECMAScript 2015 adds Map and Set to JavaScript.

Before choosing, name the question the program must answer. Finding a record by an exact id is different from asking for the next larger id. A Map can preserve insertion order without keeping keys numerically sorted. Likewise, a balanced tree and a chain-shaped tree share the BST rule but have very different heights, so their search costs can differ sharply.

Key points
  • 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.

Practice questions from Choosing a data structure on edubun

Embed this quiz

Free to embed. Please keep the credit line.

Sources for this course (11)
  • MIT OpenCourseWare 6.006 Introduction to Algorithms, Spring 2020 (Demaine, Ku, Solomon)
  • lecture notes 2 Data Structures (interface vs data structure, Sequence and Set interfaces, stack = insert_last/delete_last, queue = insert_last/delete_first, array, linked list, dynamic array, amortized Θ(1) append)
  • 4 Hashing (chaining, pigeonhole collisions, chain length n/m)
  • 6 Binary Trees Part 1 (height, traversal order, O(h) operations) and 7 Binary Trees Part 2: AVL (Adelson-Velsky and Landis, 1962) at ocw.mit.edu/courses/6-006-introduction-to-algorithms-spring-2020/pages/lecture-notes
  • MDN Web Docs, Array.prototype.shift (shifts all values left by 1)
  • Array.prototype.unshift, Map (insertion order, Map vs Object, spec requires sublinear average access) and Set (developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects)
  • ECMAScript 2025 Language Specification (tc39.es/ecma262)
  • 24.1 Map Objects and 24.2 Set Objects ("must be implemented using either hash tables or other mechanisms that, on average, provide access times that are sublinear on the number of elements")
  • Array.prototype.shift steps (Repeat, while k < len: move element k to k - 1)
  • D. E. Knuth, The Art of Computer Programming vol. 3 (2nd ed. 1998) section 6.4 History (H. P. Luhn, IBM internal memorandum January 1953, hashing with chaining; digit pairs added mod 10, 31415926 -> 4548) via gwern.net copy, and IEEE Spectrum, "Hans Peter Luhn and the Birth of the Hashing Algorithm" (2018)
  • "A brief history of the stack", SIGCIS (sigcis.org/files/A brief history.pdf: Bauer and Samelson applied for the patent in 1957, US 3,047,228 granted July 31, 1962; IPL list processing by Newell, Simon and Shaw at RAND 1956) and Wikipedia, Information Processing Language (Newell, Shaw, Simon, RAND and Carnegie Institute of Technology, about 1956).

Checked: 2026-10-18