100% found this document useful (2 votes)
31 views

Algorithms For Competitive Programming 1st Edition David Esparza Alba - Instantly access the full ebook content in just a few seconds

The document promotes a collection of ebooks focused on competitive programming and algorithms, including titles by various authors. It provides links to download these ebooks in multiple formats for easy access on any device. Additionally, it outlines the contents of the book 'Algorithms for Competitive Programming' by David Esparza Alba and Juan Antonio Ruiz Leal, detailing various programming concepts and techniques.

Uploaded by

naikenkaleo
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (2 votes)
31 views

Algorithms For Competitive Programming 1st Edition David Esparza Alba - Instantly access the full ebook content in just a few seconds

The document promotes a collection of ebooks focused on competitive programming and algorithms, including titles by various authors. It provides links to download these ebooks in multiple formats for easy access on any device. Additionally, it outlines the contents of the book 'Algorithms for Competitive Programming' by David Esparza Alba and Juan Antonio Ruiz Leal, detailing various programming concepts and techniques.

Uploaded by

naikenkaleo
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 61

Explore the full ebook collection and download it now at textbookfull.

com

Algorithms For Competitive Programming 1st Edition


David Esparza Alba

https://textbookfull.com/product/algorithms-for-competitive-
programming-1st-edition-david-esparza-alba/

OR CLICK HERE

DOWLOAD EBOOK

Browse and Get More Ebook Downloads Instantly at https://textbookfull.com


Click here to visit textbookfull.com and download textbook now
Your digital treasures (PDF, ePub, MOBI) await
Download instantly and pick your perfect format...

Read anywhere, anytime, on any device!

Competitive Programming in Python: 128 Algorithms to


Develop your Coding Skills 1st Edition Christoph Dürr

https://textbookfull.com/product/competitive-programming-in-
python-128-algorithms-to-develop-your-coding-skills-1st-edition-
christoph-durr/
textbookfull.com

Basic Exercises for Competitive Programming Python 1st


Edition Jan Pol

https://textbookfull.com/product/basic-exercises-for-competitive-
programming-python-1st-edition-jan-pol/

textbookfull.com

Guide to Competitive Programming: Learning and Improving


Algorithms Through Contests (Undergraduate Topics in
Computer Science) Antti Laaksonen
https://textbookfull.com/product/guide-to-competitive-programming-
learning-and-improving-algorithms-through-contests-undergraduate-
topics-in-computer-science-antti-laaksonen/
textbookfull.com

Algorithms Illuminated Part 3 Greedy Algorithms and


Dynamic Programming 1st Edition Tim Roughgarden

https://textbookfull.com/product/algorithms-illuminated-part-3-greedy-
algorithms-and-dynamic-programming-1st-edition-tim-roughgarden/

textbookfull.com
Options and Derivatives Programming in C Algorithms and
Programming Techniques for the Financial Industry 1st
Edition Carlos Oliveira (Auth.)
https://textbookfull.com/product/options-and-derivatives-programming-
in-c-algorithms-and-programming-techniques-for-the-financial-
industry-1st-edition-carlos-oliveira-auth/
textbookfull.com

Strategic Management A Competitive Advantage Approach


Concepts Sixteenth Edition David

https://textbookfull.com/product/strategic-management-a-competitive-
advantage-approach-concepts-sixteenth-edition-david/

textbookfull.com

Algorithms Illuminated Part 3 Greedy Algorithms and


Dynamic Programming Tim Roughgarden

https://textbookfull.com/product/algorithms-illuminated-part-3-greedy-
algorithms-and-dynamic-programming-tim-roughgarden/

textbookfull.com

Options and Derivatives Programming in C++20: Algorithms


and Programming Techniques for the Financial Industry 2nd
Edition Carlos Oliveira
https://textbookfull.com/product/options-and-derivatives-programming-
in-c20-algorithms-and-programming-techniques-for-the-financial-
industry-2nd-edition-carlos-oliveira/
textbookfull.com

Forced Migration across Mexico 1st Edition Ximena Alba


Villalever

https://textbookfull.com/product/forced-migration-across-mexico-1st-
edition-ximena-alba-villalever/

textbookfull.com
Algorithms
for Competitive Programming

David Esparza Alba


Juan Antonio Ruiz Leal

January 26, 2021


ii
To Junue and Leonardo
– David Esparza Alba

To my parents Tito and Ma. del


Refugio
– Juan Antonio Ruiz Leal
iv
Contents

1 Introduction 7
1.1 Programming Contests . . . . . . . . . . . . . . . . . 7
1.2 Coding Interviews . . . . . . . . . . . . . . . . . . . 8
1.3 Online Judges . . . . . . . . . . . . . . . . . . . . . . 8
1.4 C and C++ . . . . . . . . . . . . . . . . . . . . . . . 10
1.5 Chapter Notes . . . . . . . . . . . . . . . . . . . . . 10

2 Fundamentals 13
2.1 Recursion . . . . . . . . . . . . . . . . . . . . . . . . 14
2.1.1 Memoization . . . . . . . . . . . . . . . . . . 15
2.2 Algorithm Analysis . . . . . . . . . . . . . . . . . . . 16
2.2.1 Asymptotic Notations . . . . . . . . . . . . . 17
2.2.2 Master Theorem . . . . . . . . . . . . . . . . 19
2.2.3 P and NP . . . . . . . . . . . . . . . . . . . . 21
2.3 Bitwise Operations . . . . . . . . . . . . . . . . . . . 22
2.3.1 AND (&) operator . . . . . . . . . . . . . . . 22
2.3.2 OR (|) operator . . . . . . . . . . . . . . . . . 23
2.3.3 XOR operator . . . . . . . . . . . . . . . . . 24
2.3.4 Two’s complement . . . . . . . . . . . . . . . 25
2.4 Chapter Notes . . . . . . . . . . . . . . . . . . . . . 26
2.5 Exercises . . . . . . . . . . . . . . . . . . . . . . . . 27

3 Data Structures 29
3.1 Linear Data Structures . . . . . . . . . . . . . . . . . 30
3.1.1 Stack . . . . . . . . . . . . . . . . . . . . . . 30
3.1.2 Queue . . . . . . . . . . . . . . . . . . . . . . 32
3.1.3 Linked List . . . . . . . . . . . . . . . . . . . 33
3.2 Trees . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
3.2.1 Tree Traversal . . . . . . . . . . . . . . . . . 41
3.2.2 Heap . . . . . . . . . . . . . . . . . . . . . . . 44

v
vi CONTENTS

3.2.3 Binary Search Tree (BST) . . . . . . . . . . . 46


3.2.4 AVL Tree . . . . . . . . . . . . . . . . . . . . 55
3.2.5 Segment Tree . . . . . . . . . . . . . . . . . . 64
3.2.6 Binary Indexed Tree (BIT) . . . . . . . . . . 68
3.2.7 Trie . . . . . . . . . . . . . . . . . . . . . . . 72
3.3 Standard Template Library (STL) C++ . . . . . . . 75
3.3.1 Unordered Set . . . . . . . . . . . . . . . . . 75
3.3.2 Ordered Set . . . . . . . . . . . . . . . . . . . 76
3.3.3 Unordered Map . . . . . . . . . . . . . . . . . 78
3.3.4 Ordered Map . . . . . . . . . . . . . . . . . . 80
3.3.5 Stack . . . . . . . . . . . . . . . . . . . . . . 82
3.3.6 Queue . . . . . . . . . . . . . . . . . . . . . . 83
3.3.7 Priority queue . . . . . . . . . . . . . . . . . 84
3.4 Chapter Notes . . . . . . . . . . . . . . . . . . . . . 85
3.5 Exercises . . . . . . . . . . . . . . . . . . . . . . . . 87

4 Sorting Algorithms 89
4.1 Bubble Sort . . . . . . . . . . . . . . . . . . . . . . . 90
4.2 Selection Sort . . . . . . . . . . . . . . . . . . . . . . 92
4.3 Insertion Sort . . . . . . . . . . . . . . . . . . . . . . 94
4.4 Quick Sort . . . . . . . . . . . . . . . . . . . . . . . . 95
4.5 Counting Sort . . . . . . . . . . . . . . . . . . . . . . 98
4.6 Merge Sort . . . . . . . . . . . . . . . . . . . . . . . 99
4.7 Heap Sort . . . . . . . . . . . . . . . . . . . . . . . . 103
4.8 Sorting With the algorithm Library . . . . . . . . . 108
4.8.1 Overloading operator < . . . . . . . . . . . . 109
4.8.2 Adding a function to sort . . . . . . . . . . . 111
4.9 Chapter Notes . . . . . . . . . . . . . . . . . . . . . 112
4.10 Exercises . . . . . . . . . . . . . . . . . . . . . . . . 114

5 Divide and Conquer 115


5.1 Binary Search . . . . . . . . . . . . . . . . . . . . . . 116
5.2 Binary Exponentiation . . . . . . . . . . . . . . . . . 117
5.3 Closest Pair of Points . . . . . . . . . . . . . . . . . 118
5.4 Polynomial Multiplication (FFT) . . . . . . . . . . . 121
5.5 Range Minimum Query (RMQ) . . . . . . . . . . . . 124
5.6 Chapter Notes . . . . . . . . . . . . . . . . . . . . . 127
5.7 Exercises . . . . . . . . . . . . . . . . . . . . . . . . 128
CONTENTS vii

6 Dynamic Programming 129


6.1 Longest Increasing Sub-sequence (LIS) . . . . . . . . 130
6.1.1 Longest Increasing Subsequence with Binary
Search . . . . . . . . . . . . . . . . . . . . . . 132
6.2 Longest Common Sub-sequence (LCS) . . . . . . . . 134
6.3 Levenshtein Distance (Edit Distance) . . . . . . . . . 137
6.4 Knapsack Problem . . . . . . . . . . . . . . . . . . . 140
6.5 Maximum Sum in a Sequence . . . . . . . . . . . . . 141
6.6 Rectangle of Maximum Sum . . . . . . . . . . . . . . 142
6.7 Optimal Matrix Multiplication . . . . . . . . . . . . 144
6.8 Coin Change Problem . . . . . . . . . . . . . . . . . 146
6.9 Chapter Notes . . . . . . . . . . . . . . . . . . . . . 148
6.10 Exercises . . . . . . . . . . . . . . . . . . . . . . . . 149

7 Graph Theory 151


7.1 Graph Representation . . . . . . . . . . . . . . . . . 153
7.1.1 Adjacency Matrix . . . . . . . . . . . . . . . 154
7.1.2 Adjacency List . . . . . . . . . . . . . . . . . 155
7.2 Graph Traversal . . . . . . . . . . . . . . . . . . . . 155
7.2.1 DFS . . . . . . . . . . . . . . . . . . . . . . . 156
7.2.2 BFS . . . . . . . . . . . . . . . . . . . . . . . 158
7.2.3 Topological Sort . . . . . . . . . . . . . . . . 159
7.3 Disjoint Sets . . . . . . . . . . . . . . . . . . . . . . 161
7.3.1 Union-Find . . . . . . . . . . . . . . . . . . . 161
7.4 Shortest Paths . . . . . . . . . . . . . . . . . . . . . 164
7.4.1 Dijkstra’s Algorithm . . . . . . . . . . . . . . 165
7.4.2 Bellman-Ford . . . . . . . . . . . . . . . . . . 168
7.4.3 Floyd-Warshall . . . . . . . . . . . . . . . . . 171
7.4.4 A* . . . . . . . . . . . . . . . . . . . . . . . . 173
7.5 Strongly Connected Components . . . . . . . . . . . 176
7.5.1 Tarjan’s Algorithm . . . . . . . . . . . . . . . 176
7.5.2 Kosaraju’s Algorithm . . . . . . . . . . . . . 181
7.6 Minimum Spanning Tree . . . . . . . . . . . . . . . . 185
7.6.1 Kruskal’s Algorithm . . . . . . . . . . . . . . 187
7.6.2 Prim’s Algorithm . . . . . . . . . . . . . . . . 189
7.7 Maximum Bipartite Matching . . . . . . . . . . . . . 191
7.8 Flow Network . . . . . . . . . . . . . . . . . . . . . . 193
7.8.1 Ford-Fulkerson Algorithm . . . . . . . . . . . 194
7.9 Chapter Notes . . . . . . . . . . . . . . . . . . . . . 196
7.10 Exercises . . . . . . . . . . . . . . . . . . . . . . . . 198
viii CONTENTS

8 Geometry 199
8.1 Point Inside a Polygon . . . . . . . . . . . . . . . . . 201
8.1.1 Point in Convex Polygon . . . . . . . . . . . 201
8.1.2 Point in Polygon . . . . . . . . . . . . . . . . 202
8.1.3 Point Inside a Triangle . . . . . . . . . . . . . 205
8.2 Area of a Polygon . . . . . . . . . . . . . . . . . . . 206
8.3 Line Intersection . . . . . . . . . . . . . . . . . . . . 207
8.4 Horner’s Rule . . . . . . . . . . . . . . . . . . . . . . 210
8.5 Centroid of a Convex Polygon . . . . . . . . . . . . . 210
8.6 Convex Hull . . . . . . . . . . . . . . . . . . . . . . . 210
8.6.1 Andrew’s Monotone Convex Hull Algorithm . 211
8.6.2 Graham’s Scan . . . . . . . . . . . . . . . . . 213
8.7 Chapter Notes . . . . . . . . . . . . . . . . . . . . . 218
8.8 Exercises . . . . . . . . . . . . . . . . . . . . . . . . 220

9 Number Theory and Combinatorics 221


9.1 Prime Numbers . . . . . . . . . . . . . . . . . . . . . 222
9.1.1 Sieve of Eratosthenes . . . . . . . . . . . . . 223
9.1.2 Prime Number Generator . . . . . . . . . . . 224
9.1.3 Euler’s Totient Function . . . . . . . . . . . . 225
9.1.4 Sum of Divisors . . . . . . . . . . . . . . . . . 227
9.1.5 Number of Divisors . . . . . . . . . . . . . . . 228
9.2 Modular Arithmetic . . . . . . . . . . . . . . . . . . 229
9.3 Euclidean Algorithm . . . . . . . . . . . . . . . . . . 231
9.3.1 Extended Euclidean Algorithm . . . . . . . . 232
9.4 Base Conversion . . . . . . . . . . . . . . . . . . . . 234
9.5 Sum of Number of Divisors . . . . . . . . . . . . . . 237
9.6 Combinations . . . . . . . . . . . . . . . . . . . . . . 238
9.6.1 Pascal’s Triangle . . . . . . . . . . . . . . . . 239
9.7 Catalan Numbers . . . . . . . . . . . . . . . . . . . . 240
9.8 Josephus . . . . . . . . . . . . . . . . . . . . . . . . . 243
9.9 Pigeon-Hole Principle . . . . . . . . . . . . . . . . . 245
9.10 Chapter Notes . . . . . . . . . . . . . . . . . . . . . 247
9.11 Exercises . . . . . . . . . . . . . . . . . . . . . . . . 249

10 String Manipulation 251


10.1 Next Permutation . . . . . . . . . . . . . . . . . . . 252
10.2 Knuth-Morris-Pratt Algorithm (KMP) . . . . . . . . 254
10.3 Manacher’s Algorithm . . . . . . . . . . . . . . . . . 256
10.4 Chapter Notes . . . . . . . . . . . . . . . . . . . . . 259
10.5 Exercises . . . . . . . . . . . . . . . . . . . . . . . . 261
CONTENTS ix

11 Solution to Exercises 263


11.1 Fundamentals . . . . . . . . . . . . . . . . . . . . . . 264
11.2 Data Structures . . . . . . . . . . . . . . . . . . . . . 268
11.3 Sorting Algorithms . . . . . . . . . . . . . . . . . . . 274
11.4 Divide and Conquer . . . . . . . . . . . . . . . . . . 276
11.5 Dynamic Programming . . . . . . . . . . . . . . . . 280
11.6 Graph Theory . . . . . . . . . . . . . . . . . . . . . . 284
11.7 Geometry . . . . . . . . . . . . . . . . . . . . . . . . 286
11.8 Number Theory and Combinatorics . . . . . . . . . . 290
11.9 String Manipulation . . . . . . . . . . . . . . . . . . 295

A Recursion and Bitwise 299


A.1 The 8-Queen problem . . . . . . . . . . . . . . . . . 299
A.2 Vacations . . . . . . . . . . . . . . . . . . . . . . . . 303

B Data Structures Problems 307


B.1 Find two numbers whose sum is k . . . . . . . . . . 307
B.2 Shunting-yard Algorithm . . . . . . . . . . . . . . . 309
B.3 Find the median . . . . . . . . . . . . . . . . . . . . 311

C Sorting Problems 315


C.1 Marching in the school . . . . . . . . . . . . . . . . . 315
C.2 How Many Swaps? . . . . . . . . . . . . . . . . . . . 317
C.3 Closest K Points to the Origin? . . . . . . . . . . . . 318

D Divide and Conquer Problems 321


D.1 Polynomial Product . . . . . . . . . . . . . . . . . . 321
D.2 Wi-Fi Connection . . . . . . . . . . . . . . . . . . . . 324

E Graph Theory Problems 327


E.1 Minmax and Maxmin . . . . . . . . . . . . . . . . . 327
E.1.1 Credit Card (minmax) . . . . . . . . . . . . . 327
E.1.2 LufeMart (maxmin) . . . . . . . . . . . . . . 330
E.2 Money Exchange Problem . . . . . . . . . . . . . . . 333

F Number Theory Problems 337


F.1 Sum of Consecutive Numbers . . . . . . . . . . . . . 337
F.2 Two Queens in Attacking Positions . . . . . . . . . . 339
F.3 Example. Sum of GCD’s . . . . . . . . . . . . . . . . 341
F.4 Find B if LCM(A,B) = C . . . . . . . . . . . . . . . 341
F.5 Last Non Zero Digit in n! . . . . . . . . . . . . . . . 344
x CONTENTS
List of Figures

2.1 Fibonacci Recursion Tree . . . . . . . . . . . . . . . 16


2.2 P and NP . . . . . . . . . . . . . . . . . . . . . . . . 21
2.3 AND operator . . . . . . . . . . . . . . . . . . . . . . 22
2.4 OR operator . . . . . . . . . . . . . . . . . . . . . . 23
2.5 XOR operator . . . . . . . . . . . . . . . . . . . . . . 24
2.6 XOR operator . . . . . . . . . . . . . . . . . . . . . . 25

3.1 Linked List . . . . . . . . . . . . . . . . . . . . . . . 34


3.2 Doubly Linked List . . . . . . . . . . . . . . . . . . . 37
3.3 Doubly Linked List . . . . . . . . . . . . . . . . . . . 40
3.4 Doubly Linked List . . . . . . . . . . . . . . . . . . . 40
3.5 Example of a binary tree . . . . . . . . . . . . . . . . 42
3.6 Example of a valid heap . . . . . . . . . . . . . . . . 44
3.7 example of BST . . . . . . . . . . . . . . . . . . . . . 46
3.8 BST after removal . . . . . . . . . . . . . . . . . . . 49
3.9 BST after removal . . . . . . . . . . . . . . . . . . . 49
3.10 BST after removal . . . . . . . . . . . . . . . . . . . 50
3.11 AVL right-right rotation . . . . . . . . . . . . . . . . 57
3.12 AVL left-left rotation . . . . . . . . . . . . . . . . . . 57
3.13 AVL left-right rotation . . . . . . . . . . . . . . . . . 58
3.14 AVL right-left rotation . . . . . . . . . . . . . . . . . 59
3.15 Segment Tree Example . . . . . . . . . . . . . . . . . 65
3.16 Bitwise operation to get rightmost bit . . . . . . . . 69
3.17 BIT Representation . . . . . . . . . . . . . . . . . . 70
3.18 Trie . . . . . . . . . . . . . . . . . . . . . . . . . . . 73

4.1 Merge Sort . . . . . . . . . . . . . . . . . . . . . . . 101


4.2 Heap Sort. Swap . . . . . . . . . . . . . . . . . . . . 103
4.3 Heap Sort. Building a heap . . . . . . . . . . . . . . 104
4.4 Heap Sort. Iterations . . . . . . . . . . . . . . . . . . 106

xi
xii LIST OF FIGURES

6.1 Longest Common Sub-sequence . . . . . . . . . . . . 135


6.2 Rectangle of Maximum Sum . . . . . . . . . . . . . . 143

7.1 Graph example . . . . . . . . . . . . . . . . . . . . . 152


7.2 Graph Traversal . . . . . . . . . . . . . . . . . . . . 154
7.3 Topological Sort . . . . . . . . . . . . . . . . . . . . 160
7.4 Disjoint Sets. Initialization . . . . . . . . . . . . . . 162
7.5 Disjoint Sets. Union-Find . . . . . . . . . . . . . . . 163
7.6 Weighted Graph . . . . . . . . . . . . . . . . . . . . 165
7.7 Dijkstra’s Algorithm . . . . . . . . . . . . . . . . . . 167
7.8 Bellman-Ford . . . . . . . . . . . . . . . . . . . . . . 169
7.9 Floyd-Warshall . . . . . . . . . . . . . . . . . . . . . 173
7.10 Strongly Connected Components . . . . . . . . . . . 176
7.11 Tarjan’s Algorithm . . . . . . . . . . . . . . . . . . . 181
7.12 Kosaraju’s Algorithm . . . . . . . . . . . . . . . . . . 182
7.13 Articulation Points . . . . . . . . . . . . . . . . . . . 184
7.14 Bridges . . . . . . . . . . . . . . . . . . . . . . . . . 185
7.15 Minimum Spanning Tree . . . . . . . . . . . . . . . . 186
7.16 Kruskal’s Algorithm . . . . . . . . . . . . . . . . . . 188
7.17 Bipartite Graphs . . . . . . . . . . . . . . . . . . . . 192

8.1 Geometry Rotation . . . . . . . . . . . . . . . . . . . 200


8.2 Point Inside a Polygon . . . . . . . . . . . . . . . . . 203
8.3 Point Inside a Triangle . . . . . . . . . . . . . . . . . 205
8.4 Line Intersection . . . . . . . . . . . . . . . . . . . . 209
8.5 Andrew’s Convex Hull . . . . . . . . . . . . . . . . . 211
8.6 Right Turn . . . . . . . . . . . . . . . . . . . . . . . 212
8.7 Graham’s Scan . . . . . . . . . . . . . . . . . . . . . 214

9.1 Pascal’s Triangle . . . . . . . . . . . . . . . . . . . . 240


9.2 Catalan Numbers. Balanced Parentheses . . . . . . . 241
9.3 Catalan Numbers. Mountains . . . . . . . . . . . . . 241
9.4 Catalan Numbers. Polygon Triangulation . . . . . . 242
9.5 Catalan Numbers. Shaking Hands . . . . . . . . . . 242
9.6 Catalan Numbers. rooted binary trees . . . . . . . . 243
9.7 Josephus . . . . . . . . . . . . . . . . . . . . . . . . . 244
9.8 Pigeon-Hole Principle . . . . . . . . . . . . . . . . . 245

11.1 Segment Tree . . . . . . . . . . . . . . . . . . . . . . 277


11.2 Domino Tiles . . . . . . . . . . . . . . . . . . . . . . 281
11.3 Dijkstra and Negative Weights . . . . . . . . . . . . 284
11.4 Maximum Matching to Maximum Flow . . . . . . . 285
LIST OF FIGURES xiii

11.5 Art Gallery Problem . . . . . . . . . . . . . . . . . . 290

A.1 8-Queen solution . . . . . . . . . . . . . . . . . . . . 300

E.1 Minmax . . . . . . . . . . . . . . . . . . . . . . . . . 328


xiv LIST OF FIGURES
Listings

2.1 Factorial by Recursion . . . . . . . . . . . . . . . . . 14


2.2 Fibonacci with Recursion . . . . . . . . . . . . . . . 15
2.3 Fibonacci with Memoization . . . . . . . . . . . . . . 16
3.1 Custom Implementation of a Stack . . . . . . . . . . 31
3.2 Custom Implementation of a Queue . . . . . . . . . 32
3.3 Simple Linked List . . . . . . . . . . . . . . . . . . . 35
3.4 Doubly Linked List . . . . . . . . . . . . . . . . . . . 37
3.5 A simple Node class . . . . . . . . . . . . . . . . . . 42
3.6 Pre-order Traversal . . . . . . . . . . . . . . . . . . . 42
3.7 In-order Traversal . . . . . . . . . . . . . . . . . . . 43
3.8 Post-order Traversal . . . . . . . . . . . . . . . . . . 43
3.9 Place element in a heap . . . . . . . . . . . . . . . . 44
3.10 BST . . . . . . . . . . . . . . . . . . . . . . . . . . . 47
3.11 BST: Insertion . . . . . . . . . . . . . . . . . . . . . 48
3.12 BST: Node Connection . . . . . . . . . . . . . . . . . 48
3.13 BST: Replace nodes . . . . . . . . . . . . . . . . . . 50
3.14 BST: Largest element from a node . . . . . . . . . . 50
3.15 BST: Smallest element from a node . . . . . . . . . . 51
3.16 BST: Node removal . . . . . . . . . . . . . . . . . . . 52
3.17 BST: Node disconnection . . . . . . . . . . . . . . . 53
3.18 BST Testing . . . . . . . . . . . . . . . . . . . . . . . 53
3.19 BST Print . . . . . . . . . . . . . . . . . . . . . . . . 54
3.20 AVL: Node class . . . . . . . . . . . . . . . . . . . . . 55
3.21 AVL: Insertion . . . . . . . . . . . . . . . . . . . . . 56
3.22 AVL: Update Height . . . . . . . . . . . . . . . . . . 56
3.23 AVL: Balance Node . . . . . . . . . . . . . . . . . . 60
3.24 AVL: Left Rotation . . . . . . . . . . . . . . . . . . . 60
3.25 AVL: Right Rotation . . . . . . . . . . . . . . . . . . 61
3.26 AVL: Node Removal . . . . . . . . . . . . . . . . . . 61
3.27 AVL: Get Smallest Node . . . . . . . . . . . . . . . . 62
3.28 AVL: Get Largest Node . . . . . . . . . . . . . . . . 62

xv
xvi LISTINGS

3.29 Segment Tree: Class Node . . . . . . . . . . . . . . . 66


3.30 Creation of a Segment Tree . . . . . . . . . . . . . . 66
3.31 Search in a Segment Tree . . . . . . . . . . . . . . . 67
3.32 Queries for a Segment Tree . . . . . . . . . . . . . . 68
3.33 BIT . . . . . . . . . . . . . . . . . . . . . . . . . . . 71
3.34 Trie Class . . . . . . . . . . . . . . . . . . . . . . . . 74
3.35 Insert Word in Trie . . . . . . . . . . . . . . . . . . . 74
3.36 Number of different words . . . . . . . . . . . . . . . 75
3.37 Number of 2D-points into a given rectangle . . . . . 77
3.38 Class Point for Unordered Map . . . . . . . . . . . . 79
3.39 Hash Function for Unordered Map . . . . . . . . . . 79
3.40 Unordered Map Example . . . . . . . . . . . . . . . 80
3.41 Class Point for Ordered Map . . . . . . . . . . . . . 81
3.42 STL: Stack Example . . . . . . . . . . . . . . . . . . 82
3.43 STL: Queue Example . . . . . . . . . . . . . . . . . 83
3.44 STL: Priority Queue Example . . . . . . . . . . . . . 85
4.1 Bubble Sort . . . . . . . . . . . . . . . . . . . . . . . 91
4.2 Selection Sort . . . . . . . . . . . . . . . . . . . . . . 93
4.3 Insertion Sort . . . . . . . . . . . . . . . . . . . . . . 95
4.4 Quick Sort . . . . . . . . . . . . . . . . . . . . . . . . 97
4.5 Counting Sort . . . . . . . . . . . . . . . . . . . . . . 99
4.6 Merge Sort . . . . . . . . . . . . . . . . . . . . . . . 101
4.7 Heap Sort . . . . . . . . . . . . . . . . . . . . . . . . 106
4.8 Simplest sort function . . . . . . . . . . . . . . . . . 108
4.9 Sorting in a non-increasing way . . . . . . . . . . . . 109
4.10 Sorting pairs in non-increasing form . . . . . . . . . 110
4.11 Sorting the letters first than the digits . . . . . . . . 111
5.1 Binary Search . . . . . . . . . . . . . . . . . . . . . . 116
5.2 Big Mod (AB mod M ) . . . . . . . . . . . . . . . . . 118
5.3 Closest Pair of Points . . . . . . . . . . . . . . . . . 119
5.4 RMQ (Fill the Table) . . . . . . . . . . . . . . . . . 126
5.5 RMQ (Answer a Query) . . . . . . . . . . . . . . . . 126
6.1 Longest Increasing Sub-sequence . . . . . . . . . . . 131
6.2 Longest Increasing Sub-sequence O(n log n) . . . . . 133
6.3 Longest Common Sub-sequence (LCS) . . . . . . . . 136
6.4 Printing of the LCS . . . . . . . . . . . . . . . . . . 136
6.5 Edit Distance . . . . . . . . . . . . . . . . . . . . . . 138
6.6 Knapsack Problem . . . . . . . . . . . . . . . . . . . 141
6.7 Maximum Sum . . . . . . . . . . . . . . . . . . . . . 142
6.8 Rectangle of Maximum Sum . . . . . . . . . . . . . . 143
6.9 Optimal Matrix Multiplication . . . . . . . . . . . . 145
6.10 Coing Change Problem . . . . . . . . . . . . . . . . . 147
LISTINGS xvii

7.1 DFS . . . . . . . . . . . . . . . . . . . . . . . . . . . 157


7.2 BFS . . . . . . . . . . . . . . . . . . . . . . . . . . . 158
7.3 Topological Sort . . . . . . . . . . . . . . . . . . . . 160
7.4 Union-Find . . . . . . . . . . . . . . . . . . . . . . . 163
7.5 Dijkstra . . . . . . . . . . . . . . . . . . . . . . . . . 167
7.6 Bellman-Ford . . . . . . . . . . . . . . . . . . . . . . 170
7.7 Floyd-Warshall . . . . . . . . . . . . . . . . . . . . . 172
7.8 A-star . . . . . . . . . . . . . . . . . . . . . . . . . . 174
7.9 Tarjan Algorithm . . . . . . . . . . . . . . . . . . . . 177
7.10 Kosaraju’s Algorithm . . . . . . . . . . . . . . . . . . 182
7.11 Articulation Points . . . . . . . . . . . . . . . . . . . 184
7.12 Bridge Detection . . . . . . . . . . . . . . . . . . . . 185
7.13 Kruskal’s Algorithm . . . . . . . . . . . . . . . . . . 188
7.14 Prim Algorithm . . . . . . . . . . . . . . . . . . . . . 190
7.15 Maximum Bipartite Matching . . . . . . . . . . . . . 193
7.16 Ford-Fulkerson Algorithm . . . . . . . . . . . . . . . 195
8.1 Point Inside a Convex Polygon . . . . . . . . . . . . 202
8.2 Point Inside a Polygon . . . . . . . . . . . . . . . . . 204
8.3 Point Inside a Triangle . . . . . . . . . . . . . . . . . 206
8.4 Area of a Polygon . . . . . . . . . . . . . . . . . . . 206
8.5 Line Intersection 1 . . . . . . . . . . . . . . . . . . . 207
8.6 Line Intersection 2 . . . . . . . . . . . . . . . . . . . 209
8.7 Andrew’s Convex Hull . . . . . . . . . . . . . . . . . 212
8.8 Graham’s Scan . . . . . . . . . . . . . . . . . . . . . 215
9.1 Sieve of Eratosthenes . . . . . . . . . . . . . . . . . . 223
9.2 Prime Number Generator . . . . . . . . . . . . . . . 225
9.3 Sum of Divisors . . . . . . . . . . . . . . . . . . . . . 228
9.4 Modular Arithmetic . . . . . . . . . . . . . . . . . . 230
9.5 Euclidean Algorithm . . . . . . . . . . . . . . . . . . 231
9.6 Extended Euclidean Algorithm . . . . . . . . . . . . 233
9.7 Base Conversion . . . . . . . . . . . . . . . . . . . . 235
9.8 Sum of Number of Divisors . . . . . . . . . . . . . . 237
9.9 Combinations . . . . . . . . . . . . . . . . . . . . . . 239
9.10 Josephus Problem . . . . . . . . . . . . . . . . . . . 244
9.11 Pigeon-Hole Principle . . . . . . . . . . . . . . . . . 246
10.1 Next Permutation . . . . . . . . . . . . . . . . . . . 253
10.2 KMP Algorithm . . . . . . . . . . . . . . . . . . . . 255
10.3 Manacher’s Algorithm . . . . . . . . . . . . . . . . . 257
11.1 Fundamentals. Exercise 1 . . . . . . . . . . . . . . . 265
11.2 Fundamentals. Exercise 2 . . . . . . . . . . . . . . . 267
11.3 Data Structures. Exercise 1 . . . . . . . . . . . . . . 268
11.4 Data Structures. Exercise 2 . . . . . . . . . . . . . . 268
xviii LISTINGS

11.5 Data Structures. Exercise 3 . . . . . . . . . . . . . . 272


11.6 Sorting Algorithms. Exercise 1 . . . . . . . . . . . . 274
11.7 Sorting Algorithms. Exercise 2 . . . . . . . . . . . . 275
11.8 Sorting Algorithms. Exercise 3 . . . . . . . . . . . . 275
11.9 Divide & Conquer. Exercise 3 . . . . . . . . . . . . . 279
11.10Dynamic Programming. Exercise 5 . . . . . . . . . . 283
11.11Geometry. Exercise 1 . . . . . . . . . . . . . . . . . . 287
11.12Geometry. Exercise 2 . . . . . . . . . . . . . . . . . . 288
11.13Number Theory and Combinatorics. Exercise 4 . . . 292
11.14Number Theory and Combinatorics. Exercise 6 . . . 294
11.15String Manipulation. Exercise 1 . . . . . . . . . . . . 295
11.16String Manipulation. Exercise 4 . . . . . . . . . . . . 297
11.17String Manipulation. Exercise 5 . . . . . . . . . . . . 297
A.1 8-Queen Problem Validation . . . . . . . . . . . . . . 301
A.2 Solution to 8-Queen Problem . . . . . . . . . . . . . 302
A.3 Vacations: Use case of bit masking . . . . . . . . . . 304
B.1 Find two numbers that sum k . . . . . . . . . . . . . 308
B.2 Shunting-yard Algorithm . . . . . . . . . . . . . . . 310
B.3 Find the median . . . . . . . . . . . . . . . . . . . . 312
C.1 Marching in the School . . . . . . . . . . . . . . . . . 316
C.2 How Many Swaps . . . . . . . . . . . . . . . . . . . . 318
C.3 Closest K Points to the Origin . . . . . . . . . . . . 320
D.1 Polynomial Multiplication (FFT) . . . . . . . . . . . 322
D.2 Wi-Fi Connection (Binary Search) . . . . . . . . . . 325
E.1 Minmax Algorithm . . . . . . . . . . . . . . . . . . . 329
E.2 Maxmin Algorithm . . . . . . . . . . . . . . . . . . . 331
E.3 Money Exchange Problem . . . . . . . . . . . . . . . 334
F.1 Sum of Consecutive Integers . . . . . . . . . . . . . . 338
F.2 Two Queens in Attacking Positions . . . . . . . . . . 340
F.3 Find B if LCM(A,B) = C . . . . . . . . . . . . . . . 342
F.4 Last non zero digit in n! . . . . . . . . . . . . . . . . 345
About the Authors

David Esparza Alba (Cheeto) got his bachelor degree in Elec-


tronic Engineering from Universidad Panamericana, and a master
degree in Computer Science and Mathematics from the Mathemat-
ics Research Center (CIMAT) where he focused his research in ar-
tificial intelligence, particularly in evolutionary algorithms. Inside
the industry he has more than 10 years of experience as a software
engineer, having worked at Oracle and Amazon. In the academy
he has done research stays at Ritsumeikan University and CIMAT,
focusing his investigations in the fields of Machine Learning and
Bayesian statistics. He frequently collaborates as a professor at
Universidad Panamericana, teaching mainly the courses of Com-
puter Programming, and Algorithm Design and Analysis.

Juan Antonio Ruiz Leal (Toño) got involved in competitive


programming during high school, he obtained silver and bronze
medals in the Mexican Informatics Olympiad (Olimpiada Mexicana
de Informática - OMI) in 2009 and 2010 respectively. Then, as a
Bachelor Student he continued in the field and was part of one of
the teams that represented Mexico in the ACM ICPC World Finals
in 2014 and 2015. He studied Computer Engineering at Universi-
dad Autónoma de Aguascalientes where he graduated with honors.
He has coached students for the Mexican Informatics Olympiad
and for the Mexican Mathematics Olympiad. In the industry he
has worked as a Software Engineer at Oracle, and currently he
is pursuing his master degree at Heidelberg University in the In-
terdisciplinary Center for Scientific Computing focusing on Deep
Learning algorithms.

1
2 LISTINGS
Preface

Computer Programming is something that has become part of our


daily lives in such a way that it results natural to us, it is present
in our smart phones, computers, TV, automobiles, etc. Some years
ago the only ones that needed to know how to program were soft-
ware engineers, but today, a vast of professions are linked to com-
puter programming, and in years to come that link will become
stronger, and those who know how to program will have more op-
portunities to develop their talent.

Nowadays more and more companies, and not only in the soft-
ware industry, need to develop mobile applications, or create ways
to improve their communications channels, or analyze great amount
of data in order to offer their customers a better service or a new
product. Well, in order to do that, computer programming plays
an indispensable role, and we are not talking about knowing just
the commands of a programming language, but being able to think
and analyze what is the best way to solve a problem, and in this
way transmit those ideas into a computer in order to create some-
thing that can help people.

The objective of this book is to show both sides of the coin, on


one side give a simple explanation of some of the most popular al-
gorithms in different topics, and on the other side show a computer
program containing the basic structure of each algorithm.

Who Should Read this Book?


The origin of this book started some years ago, when we used to
save files with algorithms used in programming competitions for

3
4 LISTINGS

problems that we considered interesting. After that, these same


algorithms that we learnt were useful to get jobs in the software
industry. Thus, based on our experience, this book is intended for
anyone looking to learn some of the algorithms used in program-
ming contests, coding interviews, and in the industry.

Competitive Programming is another tool for software engi-


neers, there are developers that excel in their jobs, but find diffi-
cult to answer algorithms questions. If you feel identified with this,
then this book can help you improve your problem solving skills.

Prerequisites
This book assumes previous knowledge on any programming lan-
guage. For each algorithm it is given a brief description of how it
works and a source code, this with the intention to put on practice
the theory behind the algorithms, it doesn’t contain any explana-
tion of the programming language used, with the exception of some
built-in functions.

Some sections contain college-level math (algebra, geometry


and combinatorics), a reasonable knowledge of math concepts can
help the reader to understand some of the algorithms in those sec-
tions.

Structure of the book


The book consists on 10 chapters, and with the exception of the
first chapter, the rest contains a section with exercises, and the so-
lutions for those exercises are located at the end of the book. Also
at the end of each chapter there is a section called ”Chapter Notes”,
where we mention some references and bibliography related to the
content of the corresponding chapter.

The first chapter is just a small description of some of the dif-


ferent programming contests and online judges that are available.
Some of those contests are directed to a specific audience and all
of them have different rules. On the other hand, online judges
are a place to improve your programming skills, some of them are
oriented to some specific area, there are some that focus more in
mathematics, others in logical thinking, etc. We encourage the
LISTINGS 5

reader to take a look to all of the online judges listed in the chap-
ter and try to solve at least one problem in each one of them.

Chapter 2 is an introduction of fundamental topics, such as


Computer Complexity, Recursion, and Bitwise operations, which
are frequently used in the rest of the book. If the reader is already
familiar with these topics, then this chapter can be skipped.

Chapter 3 covers different data structures, explaining their prop-


erties, advantages and how to implement them. Depending on the
problem definition some data structures fit better than others. The
content in this chapter is of great importance for the rest of the
chapters and we recommend to read this chapter first before mov-
ing to others.

Chapter 4 is about Sorting Algorithms, containing some of the


most popular algorithms, like Bubble Sort, Selection Sort, and oth-
ers that run faster, such as Heap Sort, and Merge Sort. We also
mention other methods like Counting Sort, which is an algorithm
to sort integer numbers in linear time.

Chapter 5 talks about an important technique called Divide


and Conquer, which allow us to divide a problem in easier sub-
problems. An useful tool when dealing with large amount of data.

In chapter 6 we review some of the most popular problems in


Dynamic Programming, which more than a tool, is an ability that
is developed by practice, and is closely related to recursion.

Chapter 7 is all about Graph Theory, which is one of the areas


with more applications, from social networks to robotics. Many
of the problems we face daily can be transformed to graphs. For
example, to identify the best route to go from home to the office.
We can apply the algorithms in this chapter to solve these kind of
problems and more.

Chapter 8 focuses on mathematical algorithms, specially on geo-


metric algorithms. Here we explain algorithms to solve some of the
most frequent problems, like finding the intersection of two lines, or
identifying if a point is inside a polygon, but also we describe more
complex algorithms like finding the convex hull of a cloud of points.
6 LISTINGS

The 9th chapter is about Number Theory and Combinatorics,


two of the most fascinating topics in mathematics and also in al-
gorithms. Number theory deals with properties of numbers, like
divisibility, prime numbers, sequences, etc. On the other hand,
combinatorics is more about counting in how many ways we can
obtain a result for a specific problem. Some applications of these
topics are password security and analysis of computational com-
plexity.

The last chapter is dedicated to String Processing, or String


Manipulation. Which consists on given a string or a set of strings,
manipulating the characters of those strings in order to solve a
problem. Some examples are: find a word in a text, check whether
a word is a palindrome or not, find the palindrome of maximum
length inside a string, etc.

Online Content
The source code of the exercises and appendices can be found in
the GitHub page:

https://github.com/Cheetos/afcp

The content of the repository will be updated periodically with


new algorithms and solutions to problems, but feel free to contact
us if you think that a specific algorithm should be added, or if you
have an interesting problem that you want to share.
1

Introduction

1.1 Programming Contests


Programming contests are great places to get involved in algorithms
and programming, and there is a contest for everyone. For people
from 12 to 18 years old, perhaps the most important contest is
the Olympiad of Informatics, which consists in solving different
problems using logic and computers. Each country organizes pre-
liminaries and a national contest, then they select four students to
participate in the International Olympiad of Informatics that takes
place every year. The following link contains the results, problems,
and solutions of all contests that have taken place since 1989.

http://www.ioinformatics.org/history.shtml

For college students there is the ACM-ICPC (ACM - Interna-


tional Collegiate Programming Contest). Here, each team consists
of three students and one coach. There is only one computer for
each team, and they have five hours to solve a set of problems. The
team that solves more problems is the winner, and in case of a tie,
the amount of time they needed to solve the problems is used to
break the tie. There is a penalty for each incorrect submission, so
be careful to check every detail before sending a solution.

As in the Olympiad of Informatics, in the ACM-ICPC there


are regional contests, and the best teams of each region participate
in the international contest. Results from previous contests and
problems sets can be consulted in the official website of the contest.

7
8 1. INTRODUCTION

https://icpc.baylor.edu/

For graduate students or professionals, there are other options


to continue participating in programming contests. Nowadays some
of the biggest companies in the software industry and other orga-
nizations do their own contests, each one with their own rules and
prizes. Some of these contests are the Facebook Hacker Cup,
and the Google Code Jam. Also Topcoder organizes some con-
tests that include monetary prizes.

1.2 Coding Interviews


Is well known that the most important companies in the software
industry have a well structured and high-selective hiring process,
which involves testing the candidate’s knowledge of algorithms.
This has caused an increase in the amount of material intended to
help future candidates to succeed in technical interviews. This book
differentiates in the aspect that its content is written by software
engineers with teaching experience that have been trough multiple
recruiting processes, not only as candidates, but also as interview-
ers.

Some advice that we can give to anyone planning to enter in an


interview process are:
• Prepare for your interview, each company has its own culture,
its own hiring processes, so try to learn about this before the
interview.
• If you are going to study for an interview, be confident on
your strengths and focus on your weaknesses.
• Moments before the interview try to relax. At the end you
should be able to enjoy the interview no matter the outcome.
• Independently from the verdict, the result from an interview
is always positive.

1.3 Online Judges


Online judges are websites where you can find problems from differ-
ent categories, and where you can submit your solution for any of
1.3. ONLINE JUDGES 9

those problems, which then is evaluated by comparing it with test


inputs and outputs, and finally a result is given back to you. Some
of these judges contain previous problems from ACM competitions,
from Olympiads of Informatics, and from other contests. Without
any doubt, online judges are one of the best places to practice and
improve your coding skills. Some of the most popular online judges
are:

• Leetcode. One of the most popular sites to train for job


interviews in top tech companies. Contains problems from
different categories.
• Project Euler. Focused on mathematics, there is no need
to send a source code, only the answer to the problem.
• Codeforces. One of the best online judges to practice, con-
tains problems from different categories, and they frequently
schedule competitions. There are also great tutorials and
discussions about solutions.
• UVA Online Judge. Here you can find problems of any
kind, and there are more than 4000 problems to choose from.
• HackerRank. A popular online judge to start coding, they
have a path so you can start with easy problems and then
move to more complicated ones.
• Timus. This page does not have as many problems as other
online judges, but the quality and complexity of the prob-
lems make it an excellent option to improve your math and
programming skills.
• CodeChef. This platform is useful to prepare students for
programming competitions, and for professionals to improve
their coding skills. It has a large community of developers
and supports more than 50 programming languages.
• Topcoder. Contains tutorials explaining with great detail
different algorithms. When solving a problem the points
gained from solving it decrease as the time goes by, so if you
want to improve your coding speed, this is the right place.
• OmegaUP. Excellent tool to teach computer programming.
It is very easy to create your own problems and there is also
a large data base of problems to solve.
10 1. INTRODUCTION

1.4 C and C++


The programming language chosen to write the source code of the
algorithms in this book is C++, along with some functions of C. Even
when there are other popular languages like Java and Python, we
chose C++ because it is still one of the more robust languages in
the market, and with the use of the Standard Template Library
(STL), we can implement more complex data structures, manipu-
late strings, use predefined algorithms, etc.

Another reason we chose C++ is because it runs faster than other


languages, for example, in some cases Java can be 10 times slower,
and Python is even more slow than that. In programming contests,
speed is something that matters. Nevertheless, the optimal solu-
tion should run inside the time limits of any problem independently
of the language used.

Something that the reader will notice is that in some occasions


we use C functions to read the input data and write the output
data. C++ has cin and cout to handle the input and output re-
spectively, but they are slow in comparison with C functions scanf,
and printf. Even so, C++ functions can be optimized by adding
the following lines at the beginning of the main function
cin.tie(0);
ios_base::sync_with_stdio(0);

Unfortunately we already have the ”bad” habit of using C func-


tions for read and write, but it is not only that, scanf and printf
provides great flexibility to handle the input and output of your
program.

1.5 Chapter Notes


Every programming language has its own advantages and disad-
vantages, and it is good to know or at least have a notion of those.
For this book we chose C/C++ as our main language, because of
its simplicity and all the libraries and capabilities it contains. One
of the things that makes C/C++ special is the way it handles the
input and output. It is just amazing how easy we can read and
write data using scanf and printf for C, and cin and cout for
C++. We personally find reading and writing in other programming
languages not as intuitive, at least at first.
1.5. CHAPTER NOTES 11

C++ also gives us all the advantages of Object Oriented Pro-


gramming (OOP), and the STL library, which contains algorithms,
data structures, string manipulation capability, etc.

Other programming languages have powerful tools for problem


solving. For example in the case of Java we have found very useful
the BigInteger class, which allows us to do operations with large
numbers. Another example is Python, with its simple syntax, it
allows to write solutions using few lines of code.
Discovering Diverse Content Through
Random Scribd Documents
The Project Gutenberg eBook of Hocus Pocus;
or The Whole Art of Legerdemain, in
Perfection.
This ebook is for the use of anyone anywhere in the United
States and most other parts of the world at no cost and with
almost no restrictions whatsoever. You may copy it, give it away
or re-use it under the terms of the Project Gutenberg License
included with this ebook or online at www.gutenberg.org. If you
are not located in the United States, you will have to check the
laws of the country where you are located before using this
eBook.

Title: Hocus Pocus; or The Whole Art of Legerdemain, in Perfection.

Author: Henry Dean

Release date: May 26, 2018 [eBook #57217]

Language: English

Credits: Produced by RichardW and the Online Distributed Proofreading


Team at http://www.pgdp.net (This file was produced from
images generously made available by the Library of Congress)

*** START OF THE PROJECT GUTENBERG EBOOK HOCUS POCUS;


OR THE WHOLE ART OF LEGERDEMAIN, IN PERFECTION. ***
H OCU S PO CU S; OR THE WHOL E ART OF
L EG ­E R ­D E­M AIN, IN P ER ­F EC­T ION. B Y
H EN­R Y DEAN .
Strange feats are herein taught by slight of hand,
With which you may amuse yourself and friend,
The like in print was never seen before,
And so you’ll say when once you’ve read it o’er.
HOCUS POCUS;
OR THE WHOLE ART OF

LEGERDEMAIN,
IN PERFECTION.

By which the meaneſt capacity may perform the


whole without the help of a teacher.
Together with the Uſe of all the Inſtruments
belonging thereto.
TO WHICH IS NOW ADDED,
Abundance of New and Rare Inventions.

B Y H ENRY D EAN .
The E LEVENTH E DITION , with large Additions and
Amendments.

PHILADELPHIA:
PRINTED FOR MATHEW CAREY, NO. 118,
MARKET-STREET.
1795.
THE

P R E FA C E
TO THE

R E A D E R.
K IND R EADER ,
Having in my former book of L EGERDEMAIN , promiſed
you farther im­prove­ments, ac­cord­ing­ly I have diſ­cov­‐
ered here­in to you the greateſt and moſt wonderful
ſecrets of this A RT , never written or publiſhed by any
man before: therefore I do not doubt but herein you
will find pleaſure to your full ſatisfaction; which is all
my deſire.
H ENRY D EAN .
The Whole ART of
LEGERDEMAIN;
OR,
HOCUS POCUS
I N PERFECTION, &c.
Leger­de­main is an oper­a­tion where­by one may seem to work won­‐
der­ful, im­pos­si­ble, and in­cred­ib
­ le things, by agil­ity, nim­ble­ness, and
slight of hand. The parts of this in­gen­io ­ us art, are prin­ci­pal­ly four.
First, In conveyance of balls.
Secondly, In conveyance of money.
Thirdly, In cards,
Fourthly, In con­fed­er­acy.

A Description of the Operation.


1. He must be one of a bold and undaunted resolution, so as to
set a good face upon the matter.
2. He must have strange terms, and emphatical words, to grace
and adorn his actions; and the more to amaze and astonish the
beholders.
3. And lastly, He must use such gestures of body, as may take off
the spectators eyes from a strict and diligent beholding his manner
of performance.

How to pass the Balls through the Cups.


You must place yourself at the farther end of the table, and then
you must provide yourself three cups, made of tin, and then you
must have your black sticks of magic to shew your wonders withal;
then you must provide four small cork balls to play with; but do not
let more than three of them be seen upon the table.
Note. Always conceal one ball in the right hand, between your
middle finger and ring finger: and be sure make yourself perfect to
hold it there, for, by this means, all the tricks of the cups are done.
Then say as followeth.

Gentlemen, three cups—’tis true


They are but tin, the reason why,
Silver is something dear.
I’ll turn them in gold, if I live, &c.
No equivocation at all:
But if your eyes are not as quick as my hands
I shall deceive you all.
View them within,
View them all round about,
Where there is nothing in,
There’s nothing can come out.
Then take your four balls privately between your fingers, and so
sling one of them upon the table, and say thus,
The first trick that e’er learn’d to do,
Was, out of one ball to make it into two:
Ah! since it cannot better be,
One of these two, I’ll divide them into three,
Which is call’d the first trick of dexterity.
So then you have three balls on the table to play with, and one
left between the fingers of your right hand.

The Operation of the Cups is thus.

Lay your three balls on the table, then say, Gentlemen, you see
here are three balls, and here are three cups, that is, a cup for each
ball, and a ball for each cup. Then, taking that ball that you had in
your right hand, (which you are always to keep private) and clapping
it under the first cup, then taking up one of the three balls, with
your right hand, seeming to put it into your left hand, but retain it
still in your right, shutting your left hand in due time, then say,
Presto, be gone.
Then taking the second cup up, say, Gentlemen, you see there is
nothing under my cup; so clap the ball that you have in your right
hand under it, and then take the second ball up with your right
hand, and seem to put it into your left, but retain it in your right
hand, shutting your left in due time, as before, saying, Verda, be
gone.

Then take the third cup, saying, Gentlemen, you see there is
nothing under my last cup; then clapping the ball you have in your
right hand under it, then take the third ball up with your right hand,
and seeming to put it into your left hand, but retain it in your right;
shutting your left hand in due time, as before, saying, Presto, make
haste; so you have your three balls come under your three cups, as
thus: and so lay your three cups down on the table.

Then with your right hand take up the first cup, and there clap
that ball under, that you have in your right hand; then saying,
Gentlemen, this being the first ball, I will put it into my pocket; but
that you must still keep in your hand to play withal.
So take up the second cup with your right hand, and clap that
ball you have concealed under it, and then take up the second ball
with your right hand, and say, this likewise, I take and put into my
pocket.

Likewise, take up the third cup, and clapping the cup down
again, convey that ball you have in your right hand under the cup,
then taking the third ball, say, Gentlemen, this being the last ball, I
take and put this into my pocket. Afterwards say to the company,
Gentlemen, by a little of my fine powder of experience, I will
command these balls under the cups again. As thus,

So lay them all along upon the table to the admiration of all the
beholders.
Then take up the first cup, and clap the ball you have in your
right hand under it, then taking the first ball up with your right hand,
seem to put the same into your left hand, but retain it still in your
right, then say, Vade, quick be gone when I bid you, and run under
the cup.

Then taking that cup up again, and flinging that you have in your
right hand under it, you must take up the second ball, and seem to
put it into your left hand, but retain it in your right hand, saying,
Gentlemen, see how the ball runs on the table.
So seemingly fling it away, and it will appear as thus.

So taking the same cup again, then clapping the ball under
again, as before, then taking the third ball in your right hand, and
seem to put it under your left, but still retain it in your right, then
with your left hand seem to fling it in the cup, and it will appear
thus; all the three balls to be under one cup.

And if you can perform these actions with the cups, you may
change the balls into apples pears, or plumbs, or to living birds, to
what your fancy leads you to. I would have given you more
examples, but I think these are sufficient for the ingenious, so that,
by these means, you may perform all manner of actions with the
cups.
Note. The artificial cups cannot well be described by words, but
you may have them of me, for they are accounted the greatest
secrets in this art: therefore, I advise you to keep them as such, for
this was never known to the world before.

How to shew the wonderful Magic Lanthorn.


This is the magic lanthorn that has made so much wonder in the
world, and that which Friar Bacon used to shew all his magical
wonders withal.
This lanthorn is called magic, with respect to the for­mid­able ap­‐
par­i­tions that by vir­tue of light it shews upon the white wall of a
dark room. The body of it is generally made of tin, and of a shape of
the lamp; towards the back part, is a concave looking glass of metal,
which may either be spherical or parabolical, and which, by a grove
made in the bottom of the lanthorn, may either be advanced nearer
or put farther back from the lamp, in which is oil or spirit of wine,
and the match ought to be a little thick, that when it is lighted, it
may cast a good light that may easily reflect from the glass to the
fore part of the lanthorn, where there is an aperture with the
perspective in it, composed of two glasses that make the rays
converge and magnify the object.
When you mean to make use of this admirable machine, light the
lamp, the light of which will be much augmented by the looking
glass at a reasonable distance. Between the fore-part of the
lanthorn, and the perspective glass, you have a trough, made on
purpose, in which you are to run a long, flat thin frame with different
figures, painted with transparent colours upon glass; then all these
little figures passing successively before the perspective glass, thro’
which passes the light of the lamp, will be painted, and represented
with the same colours upon the wall of a darkroom, in a gigantic and
monstrous manner.
By this Lanthorn you may shew what man, or woman, or birds,
or beasts, and all sorts of fish that are in the sea: so if any
gentleman has a desire to furnish themselves with one of these
lanthorns, I have the best that can be made.

The figure is as follows.

To seem to swallow a long pudding made of tin.


This pudding must be made of tin, consisting of twelve or
thirteen little hoops made as in the figure following, so as they may
almost seem to fall one through another, having little holes made at
the biggest end thereof, that it may not hurt your mouth, hold this
pudding (for so it is called) privately in your left hand, with the hole
end uppermost, and with your right hand take a ball out of your
pocket, and say, ‘If here is ever a maid, that has lost her
maidenhead or an old woman that is out of conceit with herself,
because her neighbours deem her not so young as she would be, let
them come to me, for this ball is a present remedy:’ then seem to
put the ball into your left hand, but let it slip into your lap, and clap
your pudding into your mouth, which will be thought to be the ball
that you shewed them; then decline your head, and open your
mouth, and the pudding will slip down at its full length, which with
your right hand you may strike it into your mouth again, doing this
three or four times, then you may discharge it into your hand, and
clap it into your pocket without any suspicion, by making three or
four wry faces after it, as tho’ it stuck in your throat, and if you
practise smiting easily upon your throat with your fist on each side,
the pudding will seem to chink; as if it were flying there; then say,
‘Thus they eat puddings in High Germany, they fling it down their
throats before their teeth can take possession of it.’
To seem to eat knives and forks.
Desire any one of the spectators to lend you a knife, which when
you get hold of, so that you may cover the whole with both hands,
the end of the haft excepted, and setting the point to your eye,
saying, “Some body strike it with your fist,” but nobody will, because
it is so dangerous a thing; then setting your hand on the side of the
table and looking about you, ask, “What will nobody strike it in?” in
which time let the knife slip into your lap, then make as if you chop
it hastily into your mouth, or to hold it with one hand, and to strike it
in with the other nimbly, making three or four wry faces, saying,
“Some drink, some drink,” or else, “Now let somebody put his finger
into my mouth, and pull it out again,” some will cry, “You will bite
me,” say, “I will assure you I will not:” then when he hath put his
finger in, he will pull it out and cry, There is nothing; this is time
sufficient to convey the knife into your pocket; then say, Why, you
have your finger again: so, by this means, you may swallow knives
and forks.
To put a lock upon a man’s mouth.
You must have a lock made for this purpose, according to the
figure; one side of its bow must be immovable, as that marked with
A, the other side is noted with B, and must be pinned to the body of
the lock, as appears at E, I say it must be pinned that it may play to
and fro with ease; this side of the bow must have a leg as at C, and
then turn it into the lock; this leg must have two notches filled in the
inner side, which must be so ordered, that one may lock or hold the
two sides of the bow as close together as may be, and the other
notch to hold the said part of the bow a proportionable distance
asunder, that, being locked upon the cheek, it may neither pinch too
hard, nor yet hold it so slight that it may be drawn off; let there be a
key fixed to it, to unlock it, as you see at D, and lastly, let the bow
have divers notches filled in it, so that the place of the partition,
when the lock is shut home, will the least of all be suspected in the
use of the lock; you must get one to hold a tester edge long
between his teeth, then take another tester, and with your left hand
proffer to set it edge-ways between a second man’s teeth,
pretending that your intent is to turn both into which of their mouths
they shall desire, by virtue of your words: which he shall no sooner
consent to do, but you, by holding your lock privately in your right
hand, with your fore-finger may flip it over his cheek, and lock it by
pressing your fore-finger a little down, after some store of words,
and the lock, having hung on a while, seem to pull the key out of his
nose.
You may have those locks neatly made, at my house, near the
watch-house, on little Tower-hill, Postern-row, a bookseller’s shop.
How to shew the magic bell and bushel.
This feat may well be called magical, for really it is very amazing,
if it be well handled. This device was never known to the public
before.
This bushel must be turned neatly like unto the egg-boxes, so
that they cannot find out where it opens, and you must have a false
lid to clap on and off; upon that false lid glue some bird-feed, and
then you must have a true lid made to clap neatly upon the false
one, now you must have your artificial bell to shew with your bushel.
You may make your bell with wood or brass, your bell must be
made to unscrew at the top, that it may hold as much seed as your
bushel will when it is filled, and you must have the handle of your
bell made with a spring, so as to let the seed fall down at your word
of command.
The manner how to use them is as followeth: Note, you must be
sure to fill the top of your bell with seed before you begin to shew;
then saying, Gentlemen, you see I have nothing in my bell (which
they cannot, if you hold it by the handle) nor have I any thing in my
bushel, therefore I will fill my bushel with seed, and, in filling it, clap
on the false lid, and no man can tell the contrary.
Then ask any body in the company to hold that seed in their
hands and you will command it all under the magical bell; so clap
the true lid on, and then ring your bell, and the seed will be gone
out of your bushel into your bell, to the admiration of all the
beholders.
If you cannot rightly conceive this by words, you may have them
of the newest fashions, ready made, at my house.
How to put a ring through one’s cheek.
You must have two rings made of silver, or brass, or what you
please, of one bigness, colour, and likeness, saving that one must
have a notch through, and the other must be whole, without a
notch; shew the whole ring, and conceal that which hath the notch,
and say, Now I will put this ring through my check, and privately slip
the notch over one side of your mouth; then take a small stick which
you must have in readiness, and slip the whole ring upon it, holding
your hand over it about the middle of the stick; then bid somebody
hold fast the stick at both ends; and say, see this ring in my cheek, it
turns round; then, while you perceive them fasten their eyes upon
that ring, on a sudden whip it out, and smite upon the stick
therewith, instantly concealing it, and whirling the other ring, you
hold your hand over round about the stick, and it will be thought
that you have brought that ring upon the stick which was upon your
cheek.
How to shew the Hen and Egg-bag, and out of an
empty bag to bring out above an hundred eggs, and
afterwards to bring out a living hen.

You must go and buy two or three yards of calico, or printed


linen, and make a double bag, and on the mouth of the bag, on that
side next to you, you must make four or five little purses, in which
you must put two or three eggs in a purse; and do so till you have
filled that side next to you; and have a hole made at one end of your
bag, that no more than two or three eggs come out at once; then
you must have another bag, like unto that exactly, that one must not
be known from the other; and then put a living hen into that bag,
and hang it on a hook on that side you stand. The manner of
performing it is thus: take the egg-bag, and put both your hands in
it, and turn it inside out, and say, Gentlemen, you see there is
nothing in my bag; and, in turning it again, you must slip some of
the eggs out of the purses, as many as you think fit, and then turn
your bag again and shew the company that it is empty; and, in
turning it again, you command more eggs to come out, and when all
is come out but one, you must take that egg and shew it to the
company; and then drop your egg-bag, and take up your hen-bag,
and so shake your hen, pidgeon, or any other fowl. This is a noble
fancy, if well handled.
Welcome to our website – the ideal destination for book lovers and
knowledge seekers. With a mission to inspire endlessly, we offer a
vast collection of books, ranging from classic literary works to
specialized publications, self-development books, and children's
literature. Each book is a new journey of discovery, expanding
knowledge and enriching the soul of the reade

Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.

Let us accompany you on the journey of exploring knowledge and


personal growth!

textbookfull.com

You might also like