Find a course

Module 1: Analyzing AlgorithmsLesson 1 of 1312 min

Algorithms, Data Structures and Efficiency

See why the choice of algorithm can matter more than hardware, count operations instead of seconds, and compare best, average and worst cases.

Step 1 of 10Learn

A million names, two strategies

Imagine a printed phone book with one million names in alphabetical order, and you need to find Martinez, Sofia. One strategy: start on page one and check every name until you find her. If she's near the end, that's close to a million comparisons. Another strategy: open the book in the middle. If the names there come after Martinez, you know she's in the first half, so you discard the second half entirely. Repeat with the remaining half. Each check throws away half of what's left, so after about 20 checks you're down to a single name.

Both strategies are algorithms: precise, step-by-step procedures that solve a problem. Both are correct. But one does about 50,000 times less work, and the gap widens as the book grows. For a billion names, the first needs up to a billion checks; the second needs about 30.

Notice that the clever strategy only works because the book is sorted. The way data is organized decides which algorithms are possible. That's why algorithms and data structures, ways of organizing data in memory, are studied together. A data structure is chosen for the operations you need to make fast: looking things up, inserting, deleting, finding the smallest, visiting in order.

This course is about making those choices well. Faster computers help a little; better algorithms and structures can help by factors of thousands or millions.

Halving a sorted list of one million names1,000,000names500,000250,000…1 name~20 checks

Step 2 of 10Practice · Work it out

Using the halving strategy on a sorted list of 1,000,000 names, about how many checks are needed in the worst case? (Hint: 2 to the power of 20 is about 1.05 million.)

Step 3 of 10Learn

Counting operations, not seconds

How do you compare two algorithms? Timing them with a stopwatch seems natural, but the result depends on the computer, the programming language, what else is running and the specific input. A slow algorithm on a fast laptop can beat a fast algorithm on an old phone for small inputs.

Computer scientists instead count basic operations, such as comparisons, additions or array accesses, as a function of the input size, usually called n. This count describes the algorithm itself, independent of hardware.

Consider summing an array of n numbers:

let total = 0;
for (let i = 0; i < arr.length; i++) total += arr[i];

The loop body runs n times, so the work grows in proportion to n. Double the array, double the work.

Now consider checking whether any two elements in an array are equal by comparing every pair:

for (let i = 0; i < n; i++)
  for (let j = i + 1; j < n; j++)
    if (arr[i] === arr[j]) return true;

The number of pairs is n(n − 1)/2. For 1,000 elements that's 499,500 comparisons; for 10,000 it's almost 50 million. Ten times the data, about a hundred times the work.

What we really care about is this growth rate: how the work scales as n gets large. That's exactly what Big O notation, in the next lesson, captures.

Step 4 of 10Practice · Code challenge

Write linearSearch(arr, target) that checks each element in order and returns the index of the first element equal to target, or -1 if it isn't found. Don't use built-in search methods like indexOf.

Runs in a sandbox in your browser.
  • linearSearch([4, 8, 15, 16, 23, 42], 16)
  • linearSearch([4, 8, 15, 16, 23, 42], 4)
  • linearSearch([4, 8, 15, 16, 23, 42], 7)
  • linearSearch([], 1)
  • linearSearch([5, 3, 5], 5)

Step 5 of 10Learn

Thinking in operations

When choosing a data structure, start by asking which operations your program performs most often. An abstract data type describes the operations, like a set that supports add, remove and contains. A data structure is a concrete way to implement them, with specific costs.

Suppose a website must check whether a username is already taken every time someone signs up. With 10 million users stored in a plain array, each check might scan the whole array: up to 10 million comparisons per signup. Store the same names in a hash set instead, and each check takes, on average, a small constant number of steps regardless of how many users exist. Same data, same answer, radically different cost.

Common structures and what they're good at:

  • Array: instant access by position; slow to insert in the middle.
  • Linked list: cheap insertion and removal at known positions; slow to find things.
  • Stack: last in, first out; perfect for undo and for tracking nested calls.
  • Queue: first in, first out; for processing tasks in arrival order.
  • Hash table: fast lookup by key.
  • Binary search tree: fast lookup while keeping keys sorted.
  • Heap: always gives you the smallest or largest item quickly.
  • Graph: models connections such as roads, friendships and links.

There's rarely a best structure overall, only a best structure for a particular mix of operations.

One abstract data type, several data structures with different costsSet ADTPlain arraycontains O(n)Sorted arraycontains O(log n)Hash setcontains O(1) avg

Step 6 of 10Practice · Match the pairs

Match each problem to the data structure that fits it best.

Tap an answer, then tap the place where it belongs (or drag it there).

  1. An editor's undo history
  2. Print jobs handled in the order they arrive
  3. Looking up a product's price by its code
  4. An emergency room that always treats the most urgent patient next
  5. Flight routes between airports

Step 7 of 10Learn

Best, average and worst case

The same algorithm can do very different amounts of work on different inputs of the same size. Linear search on n elements:

  • Best case: the target is the first element. One comparison.
  • Worst case: the target is last, or missing. n comparisons.
  • Average case: if the target is present and equally likely to be anywhere, about (n + 1)/2 comparisons.

Which one matters? Usually the worst case, for three reasons. It's a guarantee: the algorithm will never do worse. It's often common in practice: searches for missing items always hit the worst case. And it's usually easier to analyze than the average, which requires assumptions about how inputs are distributed.

The best case is rarely useful on its own; almost any algorithm is fast on a lucky input. But some algorithms have very different typical and worst cases, and then both matter. Quicksort, which you'll meet later, is fast on average and slow in a rare worst case; engineers use tricks to make that worst case unlikely.

When someone says an algorithm is O(n), they usually mean its worst-case running time grows linearly, unless they say otherwise. Being clear about which case you're describing is a sign of careful analysis.

Comparisons for linear search on 1,000 elementsbest case1average case500.5worst case1,000Target first, anywhere at random, or last / missing

Step 8 of 10Note

Step 9 of 10Practice · Work it out

A list holds 1,000 items, and the target is equally likely to be at any position. On average, how many comparisons does a successful linear search make?

Step 10 of 10Practice · Choose one

Why do computer scientists usually describe algorithms by counting operations as a function of n rather than by timing them?