Simple Algorithm
Algorithms & Data Structures · Brute Force · 16 min

What Is an Algorithm?

Precise recipes, judged by whether they are right and how they scale.

Sort a million numbers the way most people first think of, by repeatedly picking out the smallest one left, and you make about 500 billion comparisons. Merge sort makes fewer than 19 million. At a rule-of-thumb 10810^8 simple steps per second, that is more than an hour against a fifth of a second: the algorithm matters more than the machine.

What you’ll learn

  • Say what makes a procedure an algorithm, and what a data structure is for.
  • Compare linear and binary search by counting their steps, and explain why binary search needs sorted data.
  • Compare growth rates with big-O intuition, and find the largest input a growth rate handles in a second.
  • Explain how a loop invariant shows that an algorithm is correct, and why tests alone cannot.
  • Read a problem's constraints to rule out algorithms that are too slow.

Precise enough for a machine

An algorithm is a finite list of precise steps that, for every valid input, stops and produces the right output. Every word in that sentence does work. Finite: you can write it down. Precise: a machine with no judgment can follow it. Stops and right: on every valid input, not just on the ones you tried.

The oldest algorithm still in daily use finds the greatest common divisor (gcd) of two whole numbers, the largest number that divides both: the gcd of 48 and 18 is 6. The obvious method tries every candidate. Euclid's algorithm, written down around 300 BC, uses one fact instead. Write a mod ba \bmod b for the remainder when aa is divided by bb. The pairs (a,b)(a, b) and (b,a mod b)(b, a \bmod b) have exactly the same common divisors, so the bigger pair can be swapped for the smaller one without changing the gcd.

python
def gcd_brute(a, b):          # a, b >= 1
    d = min(a, b)
    while a % d != 0 or b % d != 0:
        d -= 1                # not a common divisor: try the next one down
    return d

def gcd_euclid(a, b):         # a, b >= 0, not both 0
    while b != 0:
        a, b = b, a % b       # same common divisors, smaller numbers
    return a

In Python, a % b is a mod ba \bmod b. gcd_brute(48, 18) tries 18, 17, 16, …, 6: thirteen candidates. gcd_euclid(48, 18) needs three rounds, traced below.

Roundaabba mod ba \bmod b
1481812
218126
31260
stop60b=0b = 0, so the answer is a=6a = 6
Each round replaces (a,b)(a, b) by (b,a mod b)(b, a \bmod b). The numbers shrink fast, and the gcd never changes.
Think first How many candidates does gcd_brute try for 1,000,000 and 999,999? How many rounds does gcd_euclid need?

Any common divisor of two consecutive numbers also divides their difference, 1, so the gcd is 1, and the brute force tries all 999,999 candidates down to 1. Euclid needs two rounds: 1,000,000 mod 999,999=11{,}000{,}000 \bmod 999{,}999 = 1, then 999,999 mod 1=0999{,}999 \bmod 1 = 0. Both functions are correct. Their costs are worlds apart.

Every algorithm therefore faces two questions, and this whole course is about answering them. Is it correct on every valid input? And how does its cost grow as the input gets bigger? Donald Knuth called Euclid's method "the granddaddy of all algorithms, because it is the oldest nontrivial algorithm that has survived to the present day." It is correct, and its cost barely grows. The next steps show how to measure that.

Searching: one by one, or by halves

You have 16 numbers in sorted order and want to know where 37 is. Linear search checks the cells one by one from the left: up to 16 comparisons. Binary search looks at the middle cell first. Because the numbers are sorted, that one comparison tells it which half could hold 37, and the other half is never looked at again.

Each probe halves the range that is still possible. Try it: you play the algorithm.

Predict before you look

Binary search runs on a sorted list of 1,000,000 numbers. At most how many probes can it need?

Show the answer

20 probes

Each probe that misses halves what is left: 1,000,000, then 500,000, then 250,000, and after 19 probes at most one cell remains, because 219=524,288≤106<2202^{19} = 524{,}288 \le 10^6 < 2^{20}. One more probe checks it: at most ⌊log⁡2106⌋+1=20\lfloor \log_2 10^6 \rfloor + 1 = 20 probes. A linear scan may need all 1,000,000, and doubling the list adds just one probe to binary search.

The number of times you can halve nn before reaching 1 is the logarithm log⁡2n\log_2 n, and it grows very slowly: about 10 for a thousand, 20 for a million, 30 for a billion.

But binary search works only because the numbers are kept sorted. Arranging data so that the operations you need are fast is the job of a data structure, and every arrangement has a price: a sorted array is fast to search, but inserting a new number means shifting every larger one to make room.

Count steps, not seconds

How fast is binary search? A stopwatch measures the computer, the language and the input as much as the algorithm. Instead, count the simple steps as a function of the input size nn. Linear search makes up to nn comparisons, binary search about log⁡2n\log_2 n, and what matters is how those counts grow with nn.

Two habits make counts easy to compare. Keep only the fastest-growing term, and drop constant factors, which depend on the machine anyway. An algorithm that takes 3n2+5n+73n^2 + 5n + 7 steps is "of order n2n^2", written O(n2)O(n^2) in big-O notation: at n=1000n = 1000 the 3n23n^2 term is 3,000,000 steps and the rest only 5,007. Unless we say otherwise, we count the worst case, the most steps on any input of size nn, because that is a guarantee.

GrowthNameTypical example
O(1)O(1)constantread the item at a given position
O(log⁡n)O(\log n)logarithmicbinary search
O(n)O(n)linearlinear search; the largest item of a list
O(nlog⁡n)O(n \log n)linearithmicmerge sort
O(n2)O(n^2)quadraticcompare every pair of items
O(2n)O(2^n)exponentialtry every subset of the items
O(n!)O(n!)factorialtry every ordering of the items
Predict before you look

A program whose running time grows like n2n^2 takes 1 second when n=10,000n = 10{,}000. About how many seconds will it take when n=100,000n = 100{,}000?

Show the answer

100 seconds

Ten times the input means 102=10010^2 = 100 times the steps, so about 100 seconds. On the same tenfold input, an O(n)O(n) program would take 10 times longer, and an O(nlog⁡n)O(n \log n) one about 12.5 times, because log⁡2n\log_2 n grows too, from about 13.3 to 16.6.

Is it right?

A fast wrong answer is worthless. Tests help, but they only sample the inputs. As Edsger Dijkstra wrote in 1970, "program testing can be used to show the presence of bugs, but never to show their absence!" A list of 20 numbers can arrive in 20!≈2.4×101820! \approx 2.4 \times 10^{18} different orders, and no test suite tries them all.

So algorithms are proved correct, and the workhorse is the loop invariant: a statement that is true before a loop starts and stays true after every round. When the loop stops, the invariant says that the job is done.

Insertion sort sorts the way many people sort a hand of cards. Its invariant: the left part of the array is sorted. Each round picks up the next key, slides it left past every larger key, and the sorted part grows by one. When the sorted part is the whole array, the array is sorted.

The Optimized lesson Correctness: Invariants & Proofs turns this into a method: how to find an invariant, how to prove it, and how to prove that a loop stops at all.

Algorithms that call themselves

Some algorithms are easiest to state in terms of themselves. The Fibonacci numbers 0, 1, 1, 2, 3, 5, 8, 13, … each add the two before them, so the recursive function writes itself: fib(n) = fib(n - 1) + fib(n - 2), with fib(0) = 0 and fib(1) = 1 as base cases that stop the calls.

It is obviously correct. Is it fast?

Without memory, fib(6) makes 25 calls, and the count grows by a factor of about 1.6 each time nn goes up by one: fib(40) makes 331,160,281 calls. With memoization, storing each answer the first time it is computed, the same recursion makes n+1n + 1 calls. The Optimized lesson Recursion & Recurrences shows how to count calls like these with an equation, a recurrence, and how to solve it.

Reading the constraints

In a contest or an interview, the problem statement tells you how fast your algorithm must be. Read the limit on nn and do the arithmetic: at about 10810^8 simple steps per second (a rule of thumb for compiled code) and a time limit of 1–2 seconds, n≤105n \le 10^5 allows nlog⁡2n≈1.7×106n \log_2 n \approx 1.7 \times 10^6 steps easily, but rules out n2=1010n^2 = 10^{10}, which would take about 100 seconds.

So the constraints are a hint. Read backward, they give a complexity budget:

nn up to aboutFits in about a secondTypical idea
10–11O(n!)O(n!)try every ordering
20–25O(2n⋅n)O(2^n \cdot n)try every subset
500O(n3)O(n^3)three nested loops
5,000O(n2)O(n^2)look at every pair
10610^6O(nlog⁡n)O(n \log n)sort, then scan; a binary search per item
10810^8O(n)O(n)one pass
moreO(log⁡n)O(\log n) or O(1)O(1)a formula, or binary search on the answer
A rule of thumb, not a law: constant factors, memory access and the language move these limits by a few times either way, and Python is often 10–100 times slower per step.
Check your understanding

A sorted list of n≤105n \le 10^5 numbers comes with 10510^5 questions, each asking whether some number xx is in the list. Which approach fits in about a second?

  1. Scan the whole list for every question
  2. Sort the list again before every question
  3. Precompute something for every pair of numbers, then answer each question instantly
  4. Binary search for each question
Show the answer

D. Binary search for each question

Binary search needs at most ⌊log⁡2105⌋+1=17\lfloor \log_2 10^5 \rfloor + 1 = 17 probes per question, 1.7×1061.7 \times 10^6 steps for all of them. The list is already sorted, and that is the signal: sorted data and many lookups → binary search.

The four Optimized lessons of this topic turn each idea of this lesson into a working tool:

Optimized lessonWhat you will do there
Big-O Notation & Running TimeDefine OO, Ω\Omega and Θ\Theta exactly, count the steps of nested and halving loops, and estimate what fits in a time limit.
Correctness: Invariants & ProofsProve loops correct with invariants, prove that they stop, and prove recursive algorithms correct by induction.
Recursion & RecurrencesTurn recursive code into an equation that counts its work, and solve it with recursion trees and the master theorem.
Amortized AnalysisProve that rare expensive steps average out, with the aggregate, accounting and potential methods.

Key takeaways

  • An algorithm is a finite, precise procedure that stops with the right output on every valid input; a data structure arranges data so that the operations you need are fast.
  • Every algorithm faces two questions: is it correct, and how does its cost grow with the input size nn? Euclid's algorithm and a brute-force search find the same gcd at wildly different costs.
  • Count steps, not seconds: keep the fastest-growing term and drop constant factors, so 3n2+5n+73n^2 + 5n + 7 steps is O(n2)O(n^2), and quote the worst case as a guarantee.
  • Binary search on sorted data needs at most ⌊log⁡2n⌋+1\lfloor \log_2 n \rfloor + 1 probes, 20 for a million items, where a linear scan may need all of them.
  • Correctness comes from invariants, not from tests: a statement that holds before a loop and after every round says, when the loop ends, that the job is done.
  • At about 10810^8 simple steps per second, n≤105n \le 10^5 rules out O(n2)O(n^2) but allows O(nlog⁡n)O(n \log n), and exponential algorithms stop near n=25n = 25.

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

A procedure returns the right answer on every input you have tested, but on some valid inputs it never stops. Is it an algorithm for the problem?

  1. Yes: every answer it gives is right
  2. Yes, as long as those inputs are rare
  3. No: an algorithm must stop with the right output on every valid input
  4. It depends on how fast the computer is
Show the answer

C. No: an algorithm must stop with the right output on every valid input

Stopping is part of the definition. On an input where the procedure runs forever it gives no answer at all, so it does not solve the problem, however rare such inputs are. Proving that a loop stops is a separate part of every correctness proof.

Question 2

Algorithm A takes 100n100n steps on inputs of size nn, and algorithm B takes n2n^2 steps. Which is faster?

  1. A, for every nn
  2. B for n<100n < 100, and A for n>100n > 100
  3. B, for every nn, because 100 is a large constant
  4. Neither: constants do not matter, so they are equally fast
Show the answer

B. B for n<100n < 100, and A for n>100n > 100

n2<100nn^2 < 100n exactly when n<100n < 100. Below that, B is faster; above it, A wins by more and more: at n=106n = 10^6, A takes 10810^8 steps and B takes 101210^{12}. Big-O ignores the constant 100 because for large inputs the growth rate decides.

Question 3

Insertion sort has just finished placing the fifth key of a list. What is guaranteed at this moment?

  1. The first five places hold the first five keys of the list, in sorted order
  2. The five smallest keys of the whole list are in the first five places
  3. The whole list is sorted
  4. The fifth key is now in its final place
Show the answer

A. The first five places hold the first five keys of the list, in sorted order

Insertion sort's invariant is that the left part of the array is sorted. It rearranges only the keys it has already picked up, so the first five places hold exactly the original first five keys, sorted among themselves. Later keys can still slide in between them.

Question 4

A problem has n≤2000n \le 2000 and a time limit of 1 second. Which is the fastest-growing running time you can safely afford?

  1. O(n3)O(n^3)
  2. O(2n)O(2^n)
  3. O(n!)O(n!)
  4. O(n2)O(n^2)
Show the answer

D. O(n2)O(n^2)

n2=4×106n^2 = 4 \times 10^6 steps, a few hundredths of a second at 10810^8 steps per second. n3=8×109n^3 = 8 \times 10^9 steps would take about 80 seconds, and 220002^{2000} and 2000!2000! are beyond any time limit.

Question 5

Why is the plain recursive fib(n), which returns fib(n - 1) + fib(n - 2), so slow?

  1. Recursion is always slower than a loop
  2. It recomputes the same smaller values again and again
  3. The numbers it adds become very large
  4. Its call stack grows to 2n2^n frames
Show the answer

B. It recomputes the same smaller values again and again

fib(6) computes fib(2) five separate times, and the repetition compounds as nn grows. With memoization each value is computed once, and the same recursion makes only n+1n + 1 calls.

Go deeper

Further reading

  • D. E. Knuth, The Art of Computer Programming, Vol. 1: Fundamental Algorithms, 3rd ed. (Addison-Wesley, 1997), §1.1, "Algorithms".
  • T. H. Cormen, C. E. Leiserson, R. L. Rivest & C. Stein, Introduction to Algorithms, 4th ed. (MIT Press, 2022), chapters 1–3.