About this book
Introduction to Algorithms was first published in 1990, jointly by the MIT Press and McGraw-Hill. Its authors were Thomas H. Cormen, Charles E. Leiserson and Ronald L. Rivest, all then at the Massachusetts Institute of Technology. A second edition in 2001 added Clifford Stein as a fourth author, and further editions followed in 2009 and 2022. Students often refer to it by the authors' initials, as CLR for the first edition and CLRS for the later ones. It became, within a few years of publication, the most widely used algorithms textbook in the world, assigned in university courses on every continent and kept on the desks of working engineers as a reference.
The book grew out of courses the authors taught at MIT. Its aim was to give a single, complete, rigorous introduction to the design and analysis of algorithms that could serve both as a course text and as a reference. It presents a very wide range of algorithms, each described in a uniform pseudocode, each accompanied by an argument that it is correct and an analysis of how much time it takes. The emphasis is on general methods rather than tricks, and on understanding why an algorithm works rather than merely how to code it.
The question the book sets out to answer is this: given a computational problem, how do you find a procedure that solves it correctly, how do you prove that it does, and how do you measure how efficiently it does so, in a way that does not depend on any particular machine or programming language? Behind that lies a further question, which the book answers only at its end: are there problems for which no efficient procedure is likely to exist at all, and how can you recognise them?
The intended reader is an undergraduate or graduate student in computer science, or a programmer with some mathematical maturity. The book assumes that the reader can program and has met proofs by induction. It supplies its own appendices on sums, sets, counting and probability for those whose background is thin. Its early chapters are gentle; its later chapters are demanding. It was designed so that a teacher could build many different courses from it by choosing chapters, and so that a reader could open it at almost any topic and find a self-contained treatment.
It is worth saying what the book is not. It is not a programming manual: its pseudocode is deliberately free of the details of any language. It is not a collection of ready-made code to copy, though many readers use it that way. It is not primarily a book about the theory of computation, which asks what can be computed at all; it is about how well things can be computed. And it is not a historical or philosophical book. It is a textbook in the strict sense, made of definitions, algorithms, theorems, proofs and exercises.
The authors
Thomas Cormen took his doctorate at MIT, working on parallel and input-output-efficient computation, and then joined the faculty of Dartmouth College, where he taught for many years and chaired the computer science department. Later he wrote a short, non-mathematical introduction to the subject, Algorithms Unlocked, for readers without the background the main textbook assumes.
Charles Leiserson took his doctorate at Carnegie Mellon University, where his work with H. T. Kung on systolic arrays, regular grids of simple processors that pass data rhythmically from neighbour to neighbour, became influential in hardware design. At MIT he worked on parallel computing for decades. He invented the fat tree, a network design used in parallel supercomputers, and led the development of Cilk, a language for writing parallel programs whose scheduling has provable performance guarantees. His interest in parallelism shows in the book, especially in the later editions, which include material on multithreaded algorithms.
Ronald Rivest is best known outside the field as the R in RSA, the public-key cryptosystem he devised in 1977 with Adi Shamir and Leonard Adleman. RSA made it practical for strangers to exchange secret messages without first sharing a key, and some form of public-key cryptography secures almost all communication on the internet today. Rivest, Shamir and Adleman received the Turing Award for this work in 2002. Rivest also designed widely used cryptographic functions and contributed to machine learning theory and to the study of voting systems. The book's chapter on number-theoretic algorithms, which builds up to the RSA system, carries the authority of one of its inventors.
Clifford Stein, who joined for the second edition, took his doctorate at MIT and became a professor at Columbia University, working on scheduling, network algorithms and approximation algorithms. His arrival brought additional material and helped manage the growing size of the book.
Together the authors shared a commitment to rigour combined with clarity. The book's tone is impersonal and even, and it rarely shows the personalities behind it. That is a deliberate choice. They wanted a reference whose every statement could be relied on, and they spent years correcting errors reported by readers, publishing lists of corrections and incorporating them into later printings.
The shape of the argument
The book is organised into several large parts, each of which develops a family of methods. It opens with foundations: what an algorithm is, how to analyse its running time, the notation for growth rates, and the mathematics of recurrences that arise when algorithms call themselves. It then treats sorting and the related problem of finding the median and other order statistics, which serve as a long case study in which every major analytical tool gets used. It then presents basic data structures, the organised ways of storing information that algorithms depend on.
The middle of the book turns from particular problems to general design techniques: dynamic programming, greedy algorithms and amortised analysis. These are methods that apply across many problems, and the book shows how to recognise when each applies. Advanced data structures follow, then a long sequence on graph algorithms: searching graphs, finding minimum spanning trees, computing shortest paths and maximum flows. The final part gathers selected topics, which vary between editions, including number theory and cryptography, string matching, computational geometry, polynomial and matrix computations, NP-completeness and approximation algorithms.
The movement of the book is from tools to techniques to applications to limits. First the reader learns how to measure. Then the reader learns standard building blocks. Then the reader learns strategies for designing new algorithms. Then those strategies are applied to rich problem domains. Finally the reader learns that some problems resist all known strategies, and learns how to prove that a problem belongs to this resistant class. The structure is cumulative: the analysis tools of the opening part are used everywhere, and the graph and data-structure chapters depend on one another closely.
Two features run through every chapter. The first is the pairing of an algorithm with a proof. Nothing is presented as obviously correct; correctness is argued, often by a loop invariant, a property that holds each time the algorithm passes a certain point. The second is the pairing of an algorithm with an analysis. Every procedure comes with a statement of how its running time grows with the size of its input, and a justification of that statement. A reader who absorbs these two habits has learned the most important thing the book teaches, whatever particular algorithms they forget.
The exercises and the longer problems at the end of each chapter are a large part of the book. Some check understanding; some extend the material; some introduce topics the text does not cover. Many instructors build their courses around them, and serious self-study requires doing a good share of them.
Idea one: an algorithm is something you can prove
The first idea is that an algorithm is a precise object whose correctness can be established by argument, not merely tested by running it. A program that passes every test you happen to try may still be wrong on an input you did not think of. A proof covers every input at once. The book insists on this from its first examples, and it teaches a particular technique for doing it with iterative procedures: the loop invariant.
A loop invariant is a statement about the state of the computation that is true before the loop begins, remains true after each pass through the loop, and, when the loop ends, tells you that the job is done. The book frames this as three steps, which it calls initialisation, maintenance and termination. Initialisation shows the statement holds at the start. Maintenance shows that if it holds before a pass, it holds after. Termination shows that when the loop stops, the statement together with the stopping condition gives the desired result. This is close to mathematical induction, and the analogy is intentional.
Consider an everyday example: sorting a hand of playing cards by picking them up one at a time and inserting each into its correct place among the cards already held. The invariant is that the cards in your hand are always in order. Before you pick up any card, your empty hand is trivially in order. Each time you insert a card in its correct place, the hand stays in order. When the table is empty, every card is in your hand, and the hand is in order, so the whole deck is sorted. This is the reasoning behind insertion sort, and the book uses exactly this kind of argument, in precise form, as its model.
The idea is often confused with formal verification, the use of software tools to check proofs about programs mechanically. The book's proofs are informal mathematical arguments of the kind found in any mathematics text. They are rigorous, but they are written for people. The skill they teach is the habit of asking, of any loop or recursion, what remains true as it runs. Programmers who acquire this habit write fewer bugs, because many bugs are simply violations of an invariant the programmer never stated.
Where the idea leads is to a different way of thinking about code. Instead of writing a procedure and then checking whether it works, one starts from the invariant and designs the procedure to maintain it. This is the approach advocated by Dijkstra and others in the structured programming tradition, represented in this bay by Structured Programming by Dahl, Dijkstra and Hoare. The book does not make a philosophy of it, but it practises it consistently.
Idea two: measuring growth, not seconds
The second idea is that the efficiency of an algorithm should be measured by how its resource needs grow as the input grows, in a way that ignores constant factors and the details of particular machines. To make this precise the book adopts a simple abstract model of a computer, the random-access machine, in which basic operations such as arithmetic, comparisons and memory accesses each take a constant amount of time. It then counts operations as a function of input size.
The resulting functions are compared using asymptotic notation. Big-O notation gives an upper bound: a running time is O of n squared if, for large enough inputs, it is at most some constant times n squared. Big-Omega gives a lower bound, and big-Theta gives both at once, a tight bound. These notations let one say that one algorithm takes time proportional to n log n and another time proportional to n squared, and conclude that for large inputs the first will win, whatever the constants and whatever the machine.
An analogy helps. Suppose two delivery services quote prices. One charges a high fixed fee plus a small amount per kilometre. The other charges no fixed fee but an amount per kilometre that rises with the square of the distance. For a short trip the second is cheaper. For a long trip the first is far cheaper, and the gap grows without limit. Asymptotic analysis is the habit of asking which service wins for long trips. It deliberately sets aside the fixed fee, because for large enough inputs the rate of growth decides everything.
A rough calculation shows why growth rates dominate. Suppose a machine performs a hundred million simple steps per second. An algorithm whose cost grows like n squared, given ten million items, needs about a hundred trillion steps, which takes more than eleven days. An algorithm whose cost grows like n log n, given the same input, needs roughly two hundred and thirty million steps, a little over two seconds. No realistic improvement in hardware closes a gap of that size. Buying a machine ten times faster turns eleven days into a day; changing the algorithm turns it into seconds. This is the practical reason the book spends so much effort on growth rates, and why programmers who skip this material often discover it later, when a system that worked well on test data stalls on real data.
The book distinguishes worst-case analysis, which bounds the running time over all inputs of a given size, from average-case analysis, which considers the expected running time over some distribution of inputs. It prefers worst-case bounds because they are guarantees: they hold no matter what input arrives. Average-case bounds are useful but depend on assumptions about inputs that may not hold in practice.
This idea is often misunderstood in two opposite ways. Some readers take asymptotic bounds as precise predictions of running time, which they are not; an algorithm with a better bound can be slower on realistic inputs if its constants are large or its memory access pattern is poor. Others dismiss asymptotic analysis as academic for the same reason. Both errors miss the point. Asymptotic analysis tells you how an algorithm will scale, which is usually the first and most important question. Once the right growth rate is secured, constants and machine details can be tuned. Choosing a quadratic method where a near-linear one exists is a mistake no tuning can fix.
Idea three: divide and conquer, and the recurrences it creates
Many of the best algorithms work by breaking a problem into smaller instances of the same problem, solving those recursively, and combining the results. This is divide and conquer. Merge sort is the book's first example: split the list in half, sort each half recursively, then merge the two sorted halves into one sorted list. Merging takes time proportional to the length of the list. Each level of recursion therefore does a linear amount of work in total, and there are about log n levels, so the whole sort takes time proportional to n log n.
The running time of a divide-and-conquer algorithm is naturally expressed as a recurrence: an equation that gives the time for an input of size n in terms of the time for smaller inputs. Merge sort's recurrence says that the time for n is twice the time for n over two, plus a linear term. The book teaches several methods for solving such recurrences: guessing the answer and proving it by induction, drawing a recursion tree and adding up the work at each level, and applying a general result called the master theorem, which gives the solution directly for a broad family of recurrences.
The recursion tree is the most illuminating of these. Draw the original problem at the root, its subproblems as children, their subproblems as grandchildren, and so on. Write the non-recursive work beside each node. Then add up each level. Three things can happen. The work can shrink geometrically as you go down the tree, so the root dominates. It can stay the same at every level, so the total is the work per level times the number of levels. Or it can grow geometrically, so the leaves dominate. The master theorem is essentially a formal statement of these three cases.
The book applies divide and conquer to multiplying matrices, where Strassen's method of 1969 shows that two matrices can be multiplied with fewer than the obvious number of multiplications, and to other problems such as finding the closest pair of points and computing the fast Fourier transform. Each example shows that a clever division of the problem can change its growth rate, not just its constant.
Divide and conquer is sometimes confused with recursion in general. Recursion is a programming technique; divide and conquer is a design strategy that uses it. Not every recursive algorithm divides its problem into independent parts of comparable size, and the efficiency of divide and conquer depends on doing exactly that. When subproblems overlap heavily, plain divide and conquer can become wildly inefficient, and a different technique, dynamic programming, is needed.
Idea four: randomness as a tool
The book makes a strong case that randomness, used deliberately inside an algorithm, can make it both simpler and more reliable. The leading example is quicksort. Quicksort picks one element, called the pivot, partitions the list into elements smaller and larger than the pivot, and sorts each part recursively. If the pivot happens to split the list evenly, quicksort is very fast. If the pivot is always the smallest or largest element, which happens with a naive choice on an already sorted list, quicksort degrades to quadratic time.
The remedy is to choose the pivot at random. Now no particular input is bad: every input has the same expected running time, proportional to n log n, and the chance of a very slow run is tiny. The randomness has moved from the input, which we do not control, into the algorithm, which we do. This is a subtle and important shift. An adversary who knows your algorithm cannot construct an input that defeats it, because the adversary does not know which random choices you will make.
The book develops the probability needed for such analysis carefully, using indicator random variables, which take the value one if an event happens and zero otherwise, and the linearity of expectation, which says that the expected value of a sum is the sum of the expected values even when the terms are not independent. These two tools make many analyses that look hard become short. Later editions introduce the method with a small puzzle about hiring: candidates are interviewed in random order and each is hired if better than everyone seen so far, and one asks how many hires to expect. The answer, which grows only like the logarithm of the number of candidates, falls out in a few lines once the right indicator variables are chosen.
Randomness also appears in hashing. A hash table stores items in an array, using a function that turns each key into an array position. A good hash function spreads keys evenly; a bad one sends many keys to the same place. Universal hashing, which the book presents, chooses the hash function at random from a carefully designed family, so that for any set of keys the expected number of collisions is small. As with quicksort, the guarantee no longer depends on the input being friendly.
The idea is often confused with average-case analysis. They are different. Average-case analysis assumes that inputs arrive at random from some distribution. Randomised analysis assumes nothing about inputs and puts the randomness in the algorithm. The first gives a guarantee only if the assumption about inputs holds. The second gives a guarantee for every input, in expectation over the algorithm's own coin flips. For practical engineering, the second is far more robust.
Idea five: what cannot be done faster
An upper bound tells you that some algorithm achieves a certain running time. A lower bound tells you that no algorithm can do better. Lower bounds are harder to prove, because they speak about all possible algorithms at once, but they are what lets you stop searching. The book's central example is the lower bound for sorting by comparisons.
Any sorting algorithm that learns about its input only by comparing pairs of elements can be pictured as a decision tree. Each internal node is a comparison; each branch is an outcome; each leaf is a final ordering. Since there are n factorial possible orderings of n distinct elements, the tree must have at least that many leaves. A binary tree with that many leaves must have height at least the logarithm of n factorial, which grows like n log n. So every comparison-based sort must, in the worst case, make on the order of n log n comparisons. Merge sort and heapsort achieve this bound, so they are optimal among comparison sorts.
The book then shows how to beat the bound by stepping outside its assumptions. Counting sort, which works when the keys are small integers, counts how many times each key appears and places the elements directly, without comparing them. Radix sort sorts numbers digit by digit using a stable sort at each step. Bucket sort distributes values into ranges and sorts each range. These algorithms can run in linear time, but only because they use information about the keys beyond comparisons. The lesson is not that the lower bound is wrong, but that every lower bound is relative to a model, and changing the model can change what is possible.
The same part of the book treats selection: finding the median, or more generally the element that would be at a given position if the list were sorted. Sorting first would take n log n time, but the book shows that selection can be done in linear time, first with a randomised algorithm in expectation, and then deterministically with a more intricate method that chooses a guaranteed good pivot by taking medians of small groups. This deterministic method, from a 1973 paper by Blum, Floyd, Pratt, Rivest and Tarjan, is one of the elegant surprises of the subject. One of its authors is one of this book's authors.
Lower bounds are often confused with statements about present ignorance. When we say that sorting by comparison needs n log n comparisons, we do not mean that nobody has found a faster method; we mean that a faster method is impossible. This kind of certainty is rare in engineering. It explains why algorithms texts care so much about lower bounds: they mark the places where the design is finished.
Idea six: data structures and the cost of a sequence
Algorithms need places to keep their data, and the choice of place often decides how fast they run. The book treats data structures as implementations of abstract operations. A dynamic set, for example, supports inserting an element, deleting one, searching for one, and finding the minimum or the successor of a given element. Different structures support these operations at different costs, and the right choice depends on which operations a program performs most often.
The book proceeds from simple structures to sophisticated ones. Stacks, queues and linked lists are the basics. Hash tables give expected constant-time search, insertion and deletion, but do not keep elements in order. Binary search trees keep elements in order, so that one can find successors and ranges, but an unlucky sequence of insertions can make them as slow as a list. Red-black trees, a form of balanced binary search tree, add a colouring rule and a set of rotations that keep the tree's height proportional to log n whatever the sequence of operations. Heaps maintain only enough order to find the minimum quickly, which makes them ideal for priority queues. Later parts treat B-trees, designed for data on disks where reading a block is expensive, and structures for disjoint sets, which support merging groups and asking which group an element belongs to.
Amortised analysis
Some data structures occasionally perform an expensive operation, but only after many cheap ones. A dynamic array, which doubles its capacity whenever it fills, is the standard example. Most insertions take constant time. Occasionally an insertion triggers a copy of the entire array, which takes time proportional to its size. Judging the structure by its worst single operation would be misleading. Amortised analysis instead bounds the total cost of any sequence of operations and divides by the number of operations.
The book presents three methods. The aggregate method simply adds up the total cost of a sequence. The accounting method charges each cheap operation a little extra and stores the surplus as credit to pay for later expensive ones. The potential method defines a function of the data structure's state, like stored energy, which rises with cheap operations and falls when expensive ones release it. For the doubling array, each insertion can be charged a small constant, which covers its own cost and saves enough to pay for copying it and one older element at the next doubling. The analysis shows that the average cost per insertion over any sequence is constant.
An analogy from household budgeting fits closely. A family sets aside a small amount each month for an annual insurance bill. No single month bears the full cost, but the savings always cover the bill when it arrives. Amortised analysis proves that such a scheme always balances for the data structure, whatever sequence of operations is performed. It is often confused with average-case analysis, but it involves no probability: the bound holds for every sequence, deterministically.
The disjoint-set structure is the book's most striking amortised result. With two simple heuristics, union by rank and path compression, a sequence of operations runs in time that is almost linear: the extra factor grows so slowly, as an inverse of the very fast-growing Ackermann function, that it is at most a small constant for any input that could ever be stored. The analysis, due to Robert Tarjan and others, is one of the most intricate in the book and a good test of a reader's grasp of amortisation.
Idea seven: dynamic programming
Dynamic programming is the design technique most students find hardest and most rewarding. It applies when a problem can be solved by combining solutions to smaller subproblems, as in divide and conquer, but the subproblems overlap: the same smaller problem appears again and again inside different larger ones. Solving each occurrence separately wastes enormous effort. Dynamic programming solves each distinct subproblem once, stores the answer in a table, and looks it up whenever it is needed again.
The book identifies two conditions that make the technique work. The first is optimal substructure: an optimal solution to the whole problem contains optimal solutions to its subproblems. The second is overlapping subproblems: the number of distinct subproblems is small, perhaps polynomial in the input size, even though a naive recursion would visit them exponentially many times. When both hold, a table of subproblem answers, filled in a suitable order, solves the problem efficiently.
Across its editions, the book's examples include finding the cheapest order in which to multiply a chain of matrices, finding the longest common subsequence of two strings, and building an optimal binary search tree when some keys are searched more often than others; later editions add problems such as cutting a rod into pieces to maximise their total price. In each case the work lies in defining the subproblems well. Once they are defined, the recurrence connecting them is often short, and the algorithm follows mechanically.
A small everyday example shows the idea. Suppose you want to climb a staircase of twenty steps, taking one or two steps at a time, and you want to know how many different ways there are. The number of ways to reach step twenty is the number of ways to reach step nineteen plus the number of ways to reach step eighteen, since your last move was either one step or two. A naive recursion recomputes the counts for lower steps millions of times. A table filled from the bottom up computes each count once and finishes in twenty additions. The difference between the two approaches grows exponentially with the height of the staircase.
The longest common subsequence problem shows why the technique matters in practice. Given two strings, find the longest sequence of characters that appears in both in the same order, not necessarily contiguously. This is the core of tools that compare versions of a document and report what changed, and of methods for comparing genetic sequences. The dynamic programming solution fills a table whose rows correspond to prefixes of one string and whose columns correspond to prefixes of the other, and reads off the answer from the bottom corner.
Dynamic programming is often confused with memoisation, which is one way of implementing it: write the natural recursive solution and add a cache so that each subproblem is computed only once. The book presents both this top-down approach and the bottom-up approach of filling the table in order. They give the same answers. The idea is also sometimes confused with greedy algorithms, which make one choice and never reconsider it. Dynamic programming considers all choices at each step, relying on the table to make that affordable. The name itself, chosen by Richard Bellman in the 1950s, is historical and somewhat misleading; programming here means planning with a table, not writing code.
Idea eight: greedy choices and when they work
A greedy algorithm builds a solution step by step, at each step taking the choice that looks best at the moment and never revisiting it. Greedy algorithms are simple and fast, but they are correct only for certain problems. The book's contribution is to show how to recognise those problems and how to prove that a greedy choice is safe.
The standard example is activity selection. Given a set of activities with start and finish times, choose as many as possible that do not overlap. The greedy rule is to choose the activity that finishes first, discard those that conflict with it, and repeat. The proof that this works uses an exchange argument: take any optimal solution, and show that replacing its first activity with the earliest-finishing one keeps it valid and optimal. Repeating the argument shows that the greedy solution is as good as any.
Huffman coding is a deeper example. To compress a text, give short binary codes to frequent characters and long codes to rare ones, in such a way that no code is a prefix of another so the compressed text can be decoded unambiguously. Huffman's greedy algorithm repeatedly merges the two least frequent symbols into a combined node, building a tree from the bottom up. The book proves that this produces an optimal prefix code. Huffman coding, in one form or another, appears inside many file and image compression formats.
Greedy methods fail when an early choice that looks good blocks a better solution later. Making change with coins is the familiar illustration. With the usual denominations of many currencies, always taking the largest coin that fits gives the fewest coins. With some unusual sets of denominations it does not, and a dynamic programming solution is needed instead. The book discusses a general structure, the matroid, under which greedy algorithms are guaranteed to work, giving a theoretical account of when greed is safe. A reader should come away with a healthy suspicion: a greedy algorithm without a proof is a guess.
The minimum spanning tree algorithms of the graph chapters, due to Kruskal and Prim, are greedy, and Dijkstra's shortest-path algorithm is greedy as well. Each comes with its own proof that the locally best choice is globally safe. Seeing the same pattern of proof recur across these algorithms is one of the ways the book teaches technique rather than mere facts.
Idea nine: graphs as a universal language
A graph is a set of points, called vertices, joined by lines, called edges. Graphs model road networks, social connections, dependencies among tasks, links between web pages, circuits, molecules and the states of a game. The book's long part on graph algorithms is, for many readers, the most practically useful in the whole volume, because so many real problems become graph problems once they are seen the right way.
The foundation is graph search. Breadth-first search explores a graph in rings, visiting all vertices one edge away from the start, then all those two edges away, and so on; it finds shortest paths when all edges count equally. Depth-first search follows each path as far as it can before backing up; the times at which it enters and leaves each vertex reveal a great deal of structure. The book uses depth-first search to sort tasks so that each comes after the tasks it depends on, a process called topological sorting, and to find strongly connected components, the maximal groups of vertices that can all reach one another.
Minimum spanning trees answer the question of how to connect all the vertices at the least total cost, as when laying cable between towns. Shortest-path algorithms answer how to get from one vertex to another, or from one to all, at least cost. Dijkstra's algorithm handles graphs with non-negative edge weights efficiently. The Bellman-Ford algorithm handles negative weights and detects negative cycles, which in a currency exchange graph would represent an opportunity for risk-free profit. The Floyd-Warshall algorithm computes shortest paths between all pairs of vertices using dynamic programming. Maximum flow algorithms, starting from the Ford-Fulkerson method, answer how much can be sent through a network of pipes or links with limited capacities, and the same machinery solves matching problems, such as assigning workers to jobs.
An example shows the power of seeing a problem as a graph. Suppose a set of university courses has prerequisites, and a student wants to know an order in which to take them. Draw each course as a vertex and each prerequisite as an edge from the earlier course to the later one. A topological sort gives a valid order, or proves that none exists because the prerequisites form a cycle. A problem that looked like a matter of administration becomes a few lines of a standard algorithm.
Graph algorithms are often confused with their implementations in particular libraries, and readers sometimes learn them as recipes to call. The book's aim is different. It explains why each algorithm works, and the proofs reveal shared ideas: the relaxation step common to all shortest-path methods, the cut property that underlies minimum spanning trees, and the duality between maximum flows and minimum cuts. Understanding those ideas makes it possible to adapt the algorithms to problems that no library anticipates.
Idea ten: hard problems and NP-completeness
The last major idea is that some problems appear to have no efficient solution at all, and that these problems are tied together so closely that an efficient solution to any one would give efficient solutions to all. The book introduces the classes P, problems solvable in polynomial time, and NP, problems whose proposed solutions can be checked in polynomial time. Every problem in P is in NP, since solving a problem is one way to check a solution. Whether the reverse holds, whether every problem whose solutions can be checked quickly can also be solved quickly, is the famous P versus NP question, still unanswered.
A problem is NP-complete if it is in NP and every problem in NP can be transformed into it efficiently. Stephen Cook showed in 1971 that the satisfiability problem for Boolean formulas is NP-complete, and Richard Karp showed in 1972 that many natural problems, including finding a large clique in a graph, covering the edges of a graph with few vertices, and finding a route through every vertex, are NP-complete too. The book teaches the technique of reduction, by which one shows a new problem is NP-complete by transforming a known NP-complete problem into it.
The practical meaning is important. If you are asked to solve a problem and you can show that it is NP-complete, you have strong evidence that no efficient exact algorithm exists, and you should stop looking for one. Instead you can look for approximation algorithms, which find solutions provably close to optimal, or exploit special structure in your inputs, or use heuristics that work well in practice without guarantees. The book presents several approximation algorithms, such as one for vertex cover that always finds a cover at most twice the optimal size, and one for the travelling salesman problem when distances obey the triangle inequality.
This idea is often confused with the claim that NP-complete problems cannot be solved. They can; the question is only how long it takes as inputs grow. Small instances are often easy, and practical solvers handle many large instances well. NP-completeness is a statement about worst-case growth, and it tells you what kind of guarantee to give up. It is also often confused with undecidability, a much stronger notion: undecidable problems cannot be solved by any algorithm at all, however slow. Garey and Johnson's book in this bay is the classic guide to NP-completeness; the theory of undecidability is collected in The Undecidable.
Idea eleven: the same tools in other territories
The final part of the book gathers topics from areas that might seem far apart: number theory, string matching, computational geometry, and computations with polynomials and matrices. Their common purpose is to show that the techniques of the earlier parts, careful analysis, divide and conquer, randomisation and clever data organisation, carry over to whole new territories. A reader who has learned the method can enter a new field and recognise the shape of its problems.
Numbers and secrets
The number-theoretic material begins with the oldest algorithm still in everyday use: Euclid's method for finding the greatest common divisor of two numbers by repeatedly replacing the larger with its remainder on division by the smaller. The book analyses how many steps it takes and connects the worst case to the Fibonacci numbers. It then develops modular arithmetic, the arithmetic of remainders, and shows how to compute large powers quickly by repeated squaring, so that raising a number to a power with hundreds of digits takes only a few hundred multiplications.
These pieces assemble into the RSA public-key cryptosystem. Each user publishes a key built from the product of two large primes and keeps the primes secret. Anyone can encrypt a message with the public key; only the holder of the primes can decrypt it efficiently. The security rests on the belief that factoring the product of two large primes is hard, a belief no one has proved. The book also presents a randomised test for whether a number is prime, which is needed to find the large primes in the first place. Seeing how a few modest algorithms combine into a system that secures global communication is one of the most satisfying moments in the book.
Strings and patterns
String matching asks where a given pattern occurs in a longer text. The naive method checks every starting position and can be slow when the pattern partly matches in many places. The book presents faster methods. The Rabin-Karp algorithm compares a numerical fingerprint of the pattern with fingerprints of each window of the text, updating the fingerprint cheaply as the window slides. The Knuth-Morris-Pratt algorithm preprocesses the pattern so that after a mismatch it knows exactly how far it can shift without missing a match, and so never re-examines a character of the text. A finite-automaton method does the same through a table of states. These ideas connect to the lexical analysers described in the compilers book on this shelf, which also use finite automata to recognise patterns in text.
Shapes and transforms
Computational geometry deals with points, lines and polygons. The book shows how to decide whether two line segments cross using only multiplications and comparisons, avoiding division and the errors it brings, and how to find the convex hull of a set of points, the smallest convex shape that contains them all, much as a rubber band stretched around nails in a board. The polynomial material presents the fast Fourier transform, which multiplies two polynomials in n log n time instead of quadratic time by evaluating them at cleverly chosen complex points, multiplying the values and converting back. The same transform underlies digital signal processing, image compression and much of scientific computing. Its appearance here shows that divide and conquer, applied to the right representation, can transform a whole field.
The tradition around it
The study of algorithms as a mathematical subject took shape in the 1960s and 1970s. Donald Knuth's The Art of Computer Programming, whose first volume appeared in 1968 and sits in this bay, established the practice of analysing algorithms precisely, often down to exact constants, and gave the field much of its vocabulary. In 1974 Aho, Hopcroft and Ullman published The Design and Analysis of Computer Algorithms, which organised the subject around design techniques and asymptotic analysis and became the standard graduate text of its time. Robert Sedgewick's Algorithms, first published in 1983, offered a more implementation-oriented approach. Robert Tarjan's work on data structures and graph algorithms set new standards for elegant, efficient methods and for amortised analysis.
Introduction to Algorithms synthesised this body of work at the moment when it had become large enough to need a comprehensive introduction. It was more complete than its predecessors, more uniform in presentation, and more careful about proofs at an introductory level. It combined the analytical seriousness of Knuth with the organisation by technique of Aho, Hopcroft and Ullman, and it covered newer material such as amortised analysis and randomised algorithms more fully than earlier texts. Its success was partly a matter of timing: computer science departments were growing quickly, and they needed a standard book.
Later textbooks responded to it in different ways. Algorithm Design by Jon Kleinberg and Eva Tardos, published in 2005, emphasised the process of modelling real problems and designing algorithms for them, with less encyclopedic coverage. Algorithms by Dasgupta, Papadimitriou and Vazirani offered a shorter, more conversational path. Steven Skiena's The Algorithm Design Manual focused on practical problem-solving and a catalogue of problems. Each of these was written partly in the knowledge that CLRS existed as the comprehensive reference, and each tried to do something it did less well.
Within this bay, the book has many neighbours. The Art of Computer Programming by Knuth is its great predecessor, deeper and more exact on the topics it covers, though far less broad in its finished volumes. Computers and Intractability by Garey and Johnson is the classic guide to NP-completeness and extends the book's final part into a full subject. Introduction to the Theory of Computation by Sipser and Introduction to Automata Theory, Languages, and Computation by Hopcroft and Ullman treat the theory of what can be computed at all, which sits beneath the question of how efficiently. Structured Programming by Dahl, Dijkstra and Hoare is the source of the discipline of reasoning about programs that the book's loop invariants practise. Compilers: Principles, Techniques, and Tools by Aho, Sethi and Ullman applies graph algorithms and dynamic programming to the translation of programs. Computer Architecture: A Quantitative Approach by Hennessy and Patterson explains the real machines whose caches and pipelines make the gap between asymptotic analysis and actual speed. Quantum Computation and Quantum Information by Nielsen and Chuang shows how a different model of computation changes which problems are efficiently solvable, as with factoring, on which the RSA system in this book depends. Deep Learning by Goodfellow, Bengio and Courville describes methods built on optimisation and linear algebra that complement, rather than replace, the combinatorial algorithms here.
Questions and criticisms
The most frequent complaint is size. Each edition has grown, and the book now runs well beyond a thousand pages. No single course covers it, and a self-taught reader can be overwhelmed. The authors intended it to be read selectively, and say so, but its bulk can still discourage. Some readers find that a shorter book serves better for a first encounter, with this one kept as a reference.
A second criticism concerns style. The book's uniform, impersonal tone and its pseudocode make it reliable but sometimes dry. It rarely explains how an algorithm was discovered, or how one might come up with it oneself. Kleinberg and Tardos, among others, deliberately chose a style that shows the design process more fully. Readers who want to learn to invent algorithms, not just understand them, may need to supplement this book with others or with practice on fresh problems.
A third criticism concerns the model of computation. The random-access machine treats every memory access as costing the same, but real computers have deep memory hierarchies in which an access to a nearby cached value is hundreds of times faster than an access to main memory. Algorithms that are optimal in the book's model can be slow in practice because of poor locality. Later research developed external-memory and cache-oblivious models to address this, and later editions mention them, but the book's core analyses remain in the classical model. A reader should treat its running-time bounds as statements about scaling, not about wall-clock time.
Some topics in the first edition have aged. It included material on sorting networks, arithmetic circuits and parallel algorithms for idealised parallel machines, much of which was removed in later editions as practice moved toward different models of parallelism. Conversely, topics that later became central, such as online algorithms and algorithms for very large data, receive limited treatment in the earlier editions.
What has held up is the core: asymptotic analysis, loop invariants, recurrences, sorting and selection, hash tables and balanced trees, dynamic programming, greedy algorithms, graph search, shortest paths, spanning trees, network flow and NP-completeness. These are the ideas that technical interviews test, that working engineers use, and that later research builds on. The book's insistence on proof and analysis has held up best of all. In a profession that often tests code by running it and hoping, it teaches a habit of certainty that remains rare and valuable.
Why it is on this shelf
This shelf keeps books that teach a way of thinking, not only a body of facts. Introduction to Algorithms teaches the habit of asking, of any procedure, whether it is correct and how its cost grows. That habit applies far beyond computer science. It is the habit of a careful mind confronting any method of getting something done.
For a reader of Vedanta, the book offers a clear example of the difference between knowing that and knowing why. A procedure that works but is not understood can fail without warning on an unforeseen case; a procedure whose invariant is known can be trusted in every case it covers. That is a working lesson in the value of understanding over rote performance. For a reader of Jyotish, the book's methods are directly useful: astronomical computation, search over many combinations of positions, and the efficient tabulation of results all draw on the techniques it teaches. For a reader of economics, the chapters on greedy algorithms, dynamic programming, network flows and approximation describe the mathematics of allocation and optimisation, and NP-completeness explains why some planning problems cannot be solved exactly at scale. For a reader of technology, the reasons are plain: this is the shared vocabulary of the field.
We keep it because it is the reference to which we return. Many books on this shelf are read once and remembered. This one is consulted repeatedly, opened to a single chapter when a problem calls for it, and found to have the answer stated precisely, with a proof.
How to read it
Do not try to read the book from cover to cover on a first pass. Begin with the opening chapters on the role of algorithms, insertion sort, the analysis of algorithms and the growth of functions. Read the material on loop invariants slowly and prove the correctness of insertion sort for yourself. Then read the chapter on divide and conquer and recurrences, drawing recursion trees by hand until the master theorem seems obvious.
Next read the chapters on heapsort, quicksort and the lower bound for sorting, and the chapter on linear-time sorting. Implement merge sort, heapsort and randomised quicksort in a language you know, and time them on inputs of increasing size to see asymptotic growth with your own eyes. Then read the basic data structures, hash tables and binary search trees. Read red-black trees for the idea of balancing, but do not worry on a first pass about memorising every case of insertion and deletion.
Then read dynamic programming and greedy algorithms, which are the heart of algorithm design. Work several exercises from each, because these techniques are learned only by practice. Read amortised analysis next. Then read the graph chapters in order: elementary graph algorithms, minimum spanning trees, single-source shortest paths, all-pairs shortest paths and maximum flow. Finally read NP-completeness and, if time allows, approximation algorithms.
On a first pass, skip the advanced data structures such as Fibonacci heaps and van Emde Boas trees where they appear, and most of the selected topics, returning to them when a problem calls for them. The appendices on mathematical background should be read as needed, not in advance. Work with a pencil on every proof you read, and do at least two or three exercises per section. A pace of one chapter a week is steady and realistic; the core path described here takes about four to six months.
From this shelf, read Computers and Intractability by Garey and Johnson after the NP-completeness chapter. Read Knuth's The Art of Computer Programming, Volume 1 for a deeper and more exact treatment of fundamental algorithms and their analysis. Read Sipser's Introduction to the Theory of Computation to understand the limits of computation beyond efficiency. Read Structured Programming for the discipline of program reasoning that the loop invariants practise.
Questions to carry
- What does a loop invariant capture that testing a program on many inputs cannot?
- When can an algorithm with a better asymptotic bound be slower in practice, and why does the bound still matter?
- Why does choosing a pivot at random protect quicksort against every possible input?
- What exactly does the comparison lower bound for sorting rule out, and what does it leave open?
- How does amortised analysis differ from average-case analysis, and why does the difference matter?
- How do you recognise that a problem has optimal substructure and overlapping subproblems?
- What would it take to convince you that a greedy algorithm is correct?
- Which everyday problems that you deal with are really graph problems in disguise?
- Why does Dijkstra's algorithm fail when edge weights can be negative?
- What changes in practice when you learn that a problem you need to solve is NP-complete?
- How does the random-access machine model differ from a real computer with caches, and when does the difference matter?
- Why is a reduction from a known hard problem evidence of hardness, rather than evidence of ease?
- Which of the book's design techniques have you used without naming it?
Words to know
- Algorithm: A well-defined computational procedure that takes an input and produces an output, solving a specified problem.
- Loop invariant: A property that holds before a loop starts, is preserved by each iteration, and yields correctness when the loop ends.
- Random-access machine: The abstract model of a computer in which each basic operation takes constant time, used for analysis.
- Asymptotic notation: Big-O, big-Omega and big-Theta, which describe upper, lower and tight bounds on growth rates.
- Worst-case running time: The maximum running time over all inputs of a given size.
- Recurrence: An equation that expresses a function's value in terms of its values on smaller inputs.
- Master theorem: A general result giving the solution of a broad class of divide-and-conquer recurrences.
- Divide and conquer: Splitting a problem into smaller independent instances, solving them recursively and combining the results.
- Randomised algorithm: An algorithm that makes random choices, so that its performance guarantee holds in expectation for every input.
- Indicator random variable: A variable equal to one if an event occurs and zero otherwise, used to compute expected values.
- Comparison sort: A sorting algorithm that learns about its input only by comparing pairs of elements.
- Decision tree: A tree representing the comparisons a comparison sort makes; used to prove the n log n lower bound.
- Hash table: A structure that stores items in an array at positions computed from their keys, giving fast expected lookup.
- Red-black tree: A binary search tree with colouring rules that keep its height logarithmic in the number of items.
- Heap: A tree-shaped structure that keeps the smallest or largest item at the top, used for priority queues and heapsort.
- Amortised analysis: Bounding the total cost of a sequence of operations, so that occasional expensive steps are averaged over many cheap ones.
- Dynamic programming: Solving overlapping subproblems once each and storing the answers in a table.
- Optimal substructure: The property that an optimal solution contains optimal solutions to its subproblems.
- Greedy algorithm: An algorithm that makes the locally best choice at each step and never reconsiders it.
- Topological sort: A linear ordering of the vertices of a directed acyclic graph so that every edge points forward.
- Minimum spanning tree: A set of edges connecting all vertices of a weighted graph at the least total weight.
- Maximum flow: The greatest rate at which material can be sent from a source to a sink through a network with capacity limits.
- P and NP: The classes of problems solvable in polynomial time, and of problems whose solutions can be checked in polynomial time.
- NP-complete: A problem in NP to which every problem in NP can be efficiently reduced; the hardest problems in NP.
- Approximation algorithm: An efficient algorithm that finds a solution provably within a fixed factor of the optimum.
A note on this edition
This is a study edition written for the shelf in our own words. It describes and comments on Introduction to Algorithms; it does not reproduce its algorithms, proofs or exercises, and it cannot stand in for working through them. The book itself is in copyright and is worth getting from a library or a bookshop, in any of its editions; the later ones are larger and include material the first did not. Any errors in this companion are ours, not the authors'.