Algorithms
JeffErickson
0th edition (pre-publication draft) — December 29, 2018
0 1 2 3 4 5 6 7 8 9 — 27 26 25 24 23 22 21 20 19 18
© Copyright 2019 Jeff Erickson
c b
This work is available under a Creative Commons Attribution 4.0 International License.
For license details, see http://creativecommons.org/licenses/by/4.0/.
Download this book at http://jeffe.cs.illinois.edu/teaching/algorithms/
or http://algorithms.wtf
Please report errors at https://github.com/jeffgerickson/algorithms
Portions of our programming are mechanically reproduced,
and we now begin our broadcast day.
For Kim, Kate, and Hannah
with love and admiration
And for Erin
with thanks
for breaking her promise
Incipitprologusinlibroalghoarismidepracticaarismetrice.
—IoannisHispalensis[JohnofSeville?],
Liberalgorismidepraticaarismetrice(c.1135)
ShallItellyou,myfriend,howyouwillcometounderstandit?
Goandwriteabookuponit.
—HenryHome,LordKames(1696–1782),
inalettertotoSirGilbertElliot
Theindividualisalwaysmistaken. Hedesignedmanythings,anddrewinother
personsascoadjutors,quarrelledwithsomeorall,blunderedmuch,and
somethingisdone;allarealittleadvanced,buttheindividualisalwaysmistaken.
Itturnsoutsomewhatnewandveryunlikewhathepromisedhimself.
—RalphWaldoEmerson,“Experience”,Essays,SecondSeries(1844)
WhatIhaveoutlinedaboveisthecontentofabooktherealizationofwhosebasic
planandtheincorporationofwhosedetailswouldperhapsbeimpossible;whatI
havewrittenisasecondorthirddraftofapreliminaryversionofthisbook
—MichaelSpivak,prefaceofthersteditionof
DifferentialGeometry,VolumeI(1970)
Preface
AboutThisBook
This textbook grew out of a collection of lecture notes that I wrote for various
algorithms classes at the University of Illinois at Urbana-Champaign, which I
have been teaching about once a year since January 1999. Spurred by changes
of our undergraduate theory curriculum, I undertook a major revision of my
notes in 2016; this book consists of a subset of my revised notes on the most
fundamental course material, mostly reflecting the algorithmic content of our
new required junior-level theory course.
Prerequisites
The algorithms classes I teach at Illinois have two significant prerequisites:
a course on discrete mathematics and a course on fundamental data structures.
Consequently, this textbook is probably not suitable for most students as a first
i
P
ii
course in data structures and algorithms. In particular, I assume at least passing
familiarity with the following specific topics:
• Discrete mathematics: High-school algebra, logarithm identities, naive
set theory, Boolean algebra, first-order predicate logic, sets, functions,
equivalences, partial orders, modular arithmetic, recursive definitions, trees
(as abstract objects, not data structures), graphs (vertices and edges, not
function plots).
• Proof techniques: direct, indirect, contradiction, exhaustive case analysis,
and induction (especially “strong” and “structural” induction). Chapter 0
uses induction, and whenever Chapter n−1 uses induction, so does Chapter n.
• Iterative programming concepts: variables, conditionals, loops, records,
indirection (addresses/pointers/references), subroutines, recursion. I do not
assume fluency in any particular programming language, but I do assume
experience with at least one language that supports both indirection and
recursion.
• Fundamental abstract data types: scalars, sequences, vectors, sets, stacks,
queues, maps/dictionaries, ordered maps/dictionaries, priority queues.
• Fundamental data structures: arrays, linked lists (single and double,
linear and circular), binary search trees, at least one form of balanced binary
search tree (such as AVL trees, red-black trees, treaps, skip lists, or splay
trees), hash tables, binary heaps, and most importantly, the difference
between this list and the previous list.
• Fundamental computational problems: elementary arithmetic, sorting,
searching, enumeration, tree traversal (preorder, inorder, postorder, level-
order, and so on).
• Fundamental algorithms: elementary algorism, sequential search, binary
search, sorting (selection, insertion, merge, heap, quick, radix, and so
on), breadth- and depth-first search in (at least binary) trees, and most
importantly, the difference between this list and the previous list.
• Elementary algorithm analysis: Asymptotic notation (o, O, Θ, Ω, ω),
translating loops into sums and recursive calls into recurrences, evaluating
simple sums and recurrences.
• Mathematical maturity: facility with abstraction, formal (especially recur-
sive) definitions, and (especially inductive) proofs; writing and following
mathematical arguments; recognizing and avoiding syntactic, semantic,
and/or logical nonsense.
The book briefly covers some of this prerequisite material when it arises in
context, but more as a reminder than a good introduction. For a more thorough
overview, I strongly recommend the following freely available references:
AdditionalReferences
• Margaret M. Fleck. Building Blocks for Theoretical Computer Science, un-
published textbook, most recently revised January 2013. Available from
http://mfleck.cs.illinois.edu/building-blocks/.
• Eric Lehman, F. Thomson Leighton, and Albert R. Meyer. Mathematics for
Computer Science, unpublished lecture notes, most recent (public) revision
June 2018. Available from https://courses.csail.mit.edu/6.042/spring18/.
(I strongly recommend searching for the most recent revision.)
• Pat Morin. Open Data Structures, most recently revised January 2016 (edition
0.1Gβ). A free open-content textbook, which Pat maintains and regularly
updates. Available from http://opendatastructures.org/.
AdditionalReferences
Please do not restrict yourself to this or any other single reference. Authors and
readers bring their own perspectives to any intellectual material; no instructor
“clicks” with every student, or even with every very strong student. Finding the
author that most effectively gets their intuition into your head takes some effort,
but that effort pays off handsomely in the long run.
The following references have been particularly valuable sources of intuition,
examples, exercises, and inspiration; this is not meant to be a complete list.
• Alfred V. Aho, John E. Hopcroft, and Jeffrey D. Ullman. The Design and
Analysis of Computer Algorithms. Addison-Wesley, 1974. (I used this textbook
as an undergraduate at Rice and again as a masters student at UC Irvine.)
• Thomas Cormen, Charles Leiserson, Ron Rivest, and Cliff Stein. Introduction
to Algorithms, third edition. MIT Press/McGraw-Hill, 2009. (I used the first
edition as a teaching assistant at Berkeley.)
• Sanjoy Dasgupta, Christos H. Papadimitriou, and Umesh V. Vazirani. Algo-
rithms. McGraw-Hill, 2006. (Probably the closest in content to this book,
but considerably less verbose.)
• Jeff Edmonds. How to Think about Algorithms. Cambridge University Press,
2008.
• Michael R. Garey and David S. Johnson. Computers and Intractability:
A Guide to the Theory of NP-Completeness. W. H. Freeman, 1979.
• Michael T. Goodrich and Roberto Tamassia. Algorithm Design: Foundations,
Analysis, and Internet Examples. John Wiley & Sons, 2002.
• Jon Kleinberg and Éva Tardos. Algorithm Design. Addison-Wesley, 2005.
Borrow it from the library if you can.
• Donald Knuth. The Art of Computer Programming, volumes 1–4A. Addison-
Wesley, 1997 and 2011. (My parents gave me the first three volumes for
Christmas when I was 14. Alas, I didn’t actually read them until much later.)
iii
P
iv
• Udi Manber.
Introduction to Algorithms: A Creative Approach. Addison-
Wesley, 1989. (I used this textbook as a teaching assistant at Berkeley.)
• Ian Parberry. Problems on Algorithms. Prentice-Hall, 1995 (out of print).
Downloadable from https://larc.unt.edu/ian/books/free/license.html after
you agree to make a small charitable donation. Please honor your agreement.
• Robert Sedgewick and Kevin Wayne. Algorithms. Addison-Wesley, 2011.
• Robert Endre Tarjan. Data Structures and Network Algorithms. SIAM, 1983.
• Class notes from my own algorithms classes at Berkeley, especially those
taught by Dick Karp and Raimund Seidel.
• Lecture notes, slides, homeworks, exams, video lectures, research papers,
blog posts, and full-fledged MOOCs made freely available on the web by
innumerable colleagues around the world.
AbouttheExercises
Each chapter ends with several exercises, most of which I have used at least
once in a homework assignment, discussion/lab section, or exam. The exercises
are not ordered by increasing difficulty, but (generally) clustered by common
techniques or themes. Some problems are annotated with symbols as follows:
• nRed hearts indicate particularly challenging problems; many of these have
appeared on qualifying exams for PhD students at Illinois. A small number
of really hard problems are marked with nlarger hearts, and a few open
problems are marked with nenormous hearts.
• oBlue diamonds indicate problems that require familiarity with material
from later chapters, but thematically belong where they are. Problems that
require familiarity with earlier material are not marked, however; the book,
like life, is cumulative.
• pGreen clubs indicate problems that require familiarity with material out-
side the scope of this book, such as finite-state machines, linear algebra,
probability, or planar graphs. These are rare.
• mBlack spades indicate problems that require a significant amount of grunt
work and/or coding. These are rare.
• Orange stars indicate that you are eating Lucky Charms that were manu-
factured before 1998. Ew.
These exercises are designed as opportunities to practice, not as targets for their
own sake; the goal of these problems not to solve these particular problems,
but to practice exercising a particular skill, or solving a type of problem. Partly
for this reason, I don’t provide solutions to the exercises; the solutions are not
the point. In particular, there is no “instructor’s manual”; if you can’t solve a