Algorithmic Thinking. Learn Algorithms...Your Coding Skills 2ed 2024 Zingaro D. download
Algorithmic Thinking. Learn Algorithms...Your Coding Skills 2ed 2024 Zingaro D. download
Your
Coding Skills 2ed 2024 Zingaro D. download
https://textbookfull.com/product/algorithmic-thinking-learn-
algorithms-your-coding-skills-2ed-2024-zingaro-d/
https://textbookfull.com/product/algorithmic-thinking-2nd-
edition-a-problem-based-introduction-daniel-zingaro/
https://textbookfull.com/product/competitive-programming-in-
python-128-algorithms-to-develop-your-coding-skills-1st-edition-
christoph-durr/
https://textbookfull.com/product/php-and-algorithmic-thinking-
for-the-complete-beginner-2nd-edition-learn-to-think-like-a-
programmer-bouras/
https://textbookfull.com/product/learn-javascript-with-p5-js-
coding-for-visual-learners-arslan/
https://textbookfull.com/product/algorithmic-governance-and-
governance-of-algorithms-legal-and-ethical-challenges-martin-
ebers/
https://textbookfull.com/product/learn-python-visually-creative-
coding-with-processing-py-1st-edition-tristan-bunn/
PRAISE FOR
ALGORITHMIC THINKING, 2ND EDITION
“This book . . . is by far the quickest way to get hands-on experience with
algorithms, and is also a great supplement to more theoretical expositions.”
—r ichard peng, associate professor
at the university of waterloo’s
cheriton school of computer
science
by Daniel Zingaro
San Francisco
ALGORITHMIC THINKING, 2ND EDITION. Copyright © 2024 by Daniel Zingaro.
All rights reserved. No part of this work may be reproduced or transmitted in any form or by any means, electronic
or mechanical, including photocopying, recording, or by any information storage or retrieval system, without the
prior written permission of the copyright owner and the publisher.
First printing
27 26 25 24 23 12345
For customer service inquiries, please contact [email protected]. For information on distribution, bulk sales,
corporate sales, or translations: [email protected]. For permission to translate this work: [email protected].
To report counterfeit copies or piracy: [email protected].
No Starch Press and the No Starch Press logo are registered trademarks of No Starch Press, Inc. Other product and
company names mentioned herein may be the trademarks of their respective owners. Rather than use a trademark
symbol with every occurrence of a trademarked name, we are using the names only in an editorial fashion and to the
benefit of the trademark owner, with no intention of infringement of the trademark.
The information in this book is distributed on an “As Is” basis, without warranty. While every precaution has been
taken in the preparation of this work, neither the author nor No Starch Press, Inc. shall have any liability to any
person or entity with respect to any loss or damage caused or alleged to be caused directly or indirectly by the
information contained in it.
To Doyali
About the Author
Dr. Daniel Zingaro is an associate teaching professor of computer science
and award-winning teacher at the University of Toronto. His main area of
research is computer science education, where he studies how students learn
computer science material.
Foreword . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xix
Acknowledgments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xxi
Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xxiii
Afterword. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 403
Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 431
CONTENTS IN DETAIL
FOREWORD xix
ACKNOWLEDGMENTS xxi
INTRODUCTION xxiii
What We’ll Do . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xxiii
New to the Second Edition . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xxiv
Who This Book Is For . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xxv
Our Programming Language . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xxvi
Why Use C? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xxvi
Static Keyword . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xxvi
Include Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xxvii
Freeing Memory . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xxvii
Topic Selection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xxvii
Programming Judges . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xxviii
Anatomy of a Problem Description . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xxx
Starter Problem: Food Lines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xxxi
The Problem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xxxi
Solving the Problem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xxxii
Online Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xxxiv
Notes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xxxiv
1
HASH TABLES 1
Problem 1: Unique Snowflakes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
The Problem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
Simplifying the Problem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
Solving the Core Problem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
Solution 1: Pairwise Comparisons . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
Solution 2: Doing Less Work . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
Hash Tables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
Hash Table Design . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
Why Use Hash Tables? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
Problem 2: Login Mayhem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
The Problem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
Solution 1: Looking at All Passwords . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
Solution 2: Using a Hash Table . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
Problem 3: Spelling Check . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
The Problem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
Thinking About Hash Tables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
An Ad Hoc Solution . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
Notes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
2
TREES AND RECURSION 37
Problem 1: Halloween Haul . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
The Problem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38
Binary Trees . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
Solving the Sample Instance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
Representing Binary Trees . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
Collecting All the Candy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46
A Completely Different Solution . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
Walking the Minimum Number of Streets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56
Reading the Input . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59
Why Use Recursion? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65
Problem 2: Descendant Distance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66
The Problem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66
Reading the Input . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68
Number of Descendants from One Node . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72
Number of Descendants from All Nodes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73
Sorting Nodes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74
Outputting the Information . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75
The main Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76
Notes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76
3
MEMOIZATION AND DYNAMIC PROGRAMMING 77
Problem 1: Burger Fervor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78
The Problem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78
Forming a Plan . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78
Characterizing Optimal Solutions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80
Solution 1: Recursion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81
Solution 2: Memoization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86
Solution 3: Dynamic Programming . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91
Memoization and Dynamic Programming . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 94
Step 1: Structure of Optimal Solutions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95
Step 2: Recursive Solution . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 96
Step 3: Memoization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 96
Step 4: Dynamic Programming . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97
4
ADVANCED MEMOIZATION AND DYNAMIC PROGRAMMING 125
Problem 1: The Jumper . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 125
The Problem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 126
Working Through an Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 127
Solution 1: Backward Formulation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 128
Solution 2: Forward Formulation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 133
Problem 2: Ways to Build . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 137
The Problem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 138
Working Through an Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 139
Solution 1: Using “Exactly” Subproblems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 140
Solution 2: Adding More Subproblems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 144
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 149
Notes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 149
5
GRAPHS AND BREADTH-FIRST SEARCH 151
Problem 1: Knight Chase . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 151
The Problem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 152
Moving Optimally . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 153
Best Knight Outcome . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 163
The Knight Flip-Flop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 165
A Time Optimization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 168
Graphs and BFS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 169
What Are Graphs? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 169
Graphs vs. Trees . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 170
BFS on Graphs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 172
Graphs vs. Dynamic Programming . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 173
6
SHORTEST PATHS IN WEIGHTED GRAPHS 197
Problem 1: Mice Maze . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 198
The Problem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 198
Moving On from BFS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 199
Finding Shortest Paths in Weighted Graphs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 200
Building the Graph . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 203
Implementing Dijkstra’s Algorithm . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 205
Two Optimizations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 207
Dijkstra’s Algorithm . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 210
Runtime of Dijkstra’s Algorithm . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 210
Negative-Weight Edges . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 211
Problem 2: Grandma Planner . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 213
The Problem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 213
Adjacency Matrix . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 214
Building the Graph . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 215
Working Through a Weird Test Case . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 217
Task 1: Shortest Paths . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 219
Task 2: Number of Shortest Paths . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 222
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 228
Notes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 229
7
BINARY SEARCH 231
Problem 1: Feeding Ants . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 231
The Problem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 232
A New Flavor of Tree Problem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 233
Reading the Input . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 235
Testing Feasibility . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 237
Searching for a Solution . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 239
8
HEAPS AND SEGMENT TREES 277
Problem 1: Supermarket Promotion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 277
The Problem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 277
Solution 1: Maximum and Minimum in an Array . . . . . . . . . . . . . . . . . . . . . . . . . . . 278
Max-Heaps . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 282
Min-Heaps . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 293
Solution 2: Heaps . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 295
Heaps . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 298
Two More Applications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 298
Choosing a Data Structure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 300
Problem 2: Building Treaps . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 300
The Problem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 300
Recursively Outputting Treaps . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 302
Sorting by Label . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 303
Solution 1: Recursion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 303
Range Maximum Queries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 307
Segment Trees . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 308
Solution 2: Segment Trees . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 316
Segment Trees . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 317
Contents in Detail xv
Problem 3: Two Sum . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 318
The Problem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 318
Filling the Segment Tree . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 319
Querying the Segment Tree . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 323
Updating the Segment Tree . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 324
The main Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 328
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 329
Notes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 329
9
UNION-FIND 331
Problem 1: Social Network . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 332
The Problem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 332
Modeling as a Graph . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 333
Solution 1: BFS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 336
Union-Find . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 340
Solution 2: Union-Find . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 343
Optimization 1: Union by Size . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 346
Optimization 2: Path Compression . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 350
Union-Find . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 352
Relationships: Three Requirements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 353
Choosing Union-Find . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 353
Optimizations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 353
Problem 2: Friends and Enemies . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 354
The Problem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 354
Augmenting Union-Find . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 355
The main Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 359
Find and Union . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 360
SetFriends and SetEnemies . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 361
AreFriends and AreEnemies . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 363
Problem 3: Drawer Chore . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 364
The Problem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 364
Equivalent Drawers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 365
The main Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 370
Find and Union . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 372
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 373
Notes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 373
10
RANDOMIZATION 375
Problem 1: Yokan . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 376
The Problem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 376
Randomly Choosing a Piece . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 376
AFTERWORD 403
A
ALGORITHM RUNTIME 405
The Case for Timing . . . and Something Else . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 405
Big O Notation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 407
Linear Time . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 407
Constant Time . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 408
Another Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 409
Quadratic Time . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 409
Big O in This Book . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 410
B
BECAUSE I CAN’T RESIST 411
Unique Snowflakes: Implicit Linked Lists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 411
Burger Fervor: Reconstructing a Solution . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 414
Knight Chase: Encoding Moves . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 416
Dijkstra’s Algorithm: Using a Heap . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 418
Mice Maze: Tracing with Heaps . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 418
Mice Maze: Implementation with Heaps . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 421
C
PROBLEM CREDITS 427
INDEX 431
For the novice tennis player, keeping the ball in the court is hard enough
(especially from the backhand side). Only after months of practice, once
the basic rallying skills have been mastered, does the sport and its addic-
tive nature begin to reveal itself. You add to your repertoire more advanced
tools—a slice backhand, a kick serve, a drop volley. You strategize at a higher
level of abstraction—serve and volley, chip and charge, hug the baseline. You
develop intuition for which tools and strategies will be most effective against
different types of opponents—there’s no silver-bullet approach that works
well against everyone.
Programming is like tennis. For the beginning coder, coaxing the com-
puter to understand what you want it to do—to execute your solution to a
problem—is hard enough. Graduate from this white-belt level and the true
problem-solving fun begins: How do you come up with the solution in the
first place? While there’s no silver-bullet approach that solves every com-
putational problem efficiently, there are enduringly useful, advanced tools
and strategies: hash tables, search trees, recursion, memoization, dynamic
programming, graph search, and more. And to the trained eye, many prob-
lems and algorithms offer dead giveaways as to which tools are the right
ones. Does your algorithm perform repeated lookups or minimum com-
putations? Speed it up with a hash table or min-heap, respectively! Can you
build a solution to your problem from solutions to smaller subproblems?
Use recursion! Do the subproblems overlap? Speed up your algorithm with
memoization!
Be it tennis or programming, you can’t up your game to the next level
without two things: practice and a good coach. To this end, I give you
Algorithmic Thinking: Learn Algorithms to Level up Your Coding Skills and
Daniel Zingaro. This book teaches all the concepts that I’ve mentioned, but
it is no mere laundry list. With Zingaro as a tutor by your side, you’ll learn,
through practice on challenging competition problems, a repeatable process
for figuring out and deftly applying the right algorithmic tools for the job.
And you’ll learn it all from a book that exudes clarity, humor, and just the
right dose of Canadian pride. Happy problem-solving!
Tim Roughgarden
New York, NY
May 2020
xx Foreword
ACKNOWLEDGMENTS
What an idyllic experience it was to work with the folks at No Starch Press.
They’re all laser-focused on writing books to help readers learn. I’ve found
my people! Liz Chadwick supported my book from the start (and unsup-
ported another one—I’m grateful for that!). It is a gift to have worked with
Alex Freed, my developmental editor. She’s patient, kind, and always eager
to help me improve how I write instead of just fixing my mistakes. I thank all
those involved in the production of the second edition of this book, includ-
ing my copyeditor, George Hale; production editor, Sydney Cromwell; and
cover designer, Rob Gale.
I thank the University of Toronto for offering me the time and space to
write. I thank Naaz Sibia, my technical reviewer, for her careful review of the
manuscript and for finding the time to help me.
I thank Tim Roughgarden for authoring the book’s foreword. Tim’s
books and videos are examples of the kind of clarity that we need to strive
for when teaching algorithms.
I thank my colleagues Larry Zhang, Jan Vahrenhold, and Mahika
Phutane for their review of draft chapters.
I thank everyone who contributed to the problems that I used in this
book and to competitive programming in general. I thank the DMOJ ad-
ministrators for their support of my work. Special thanks to Tudor Brindus,
Radu Pogonariu, and Maxwell Cruickshanks for their help in improving and
adding problems.
I thank my parents for handling everything—everything. All they asked
me to do was learn. I thank Doyali, my partner, for giving some of our time
to this book and for modeling the care it takes to write.
Finally, I thank all of you for reading this book and wanting to learn.
INTRODUCTION
What We’ll Do
I could start by teaching you some fancy new techniques, telling you why
they’re useful, and comparing them to other fancy techniques, but I won’t.
That material would lay inert, holding on for a little, waiting for the opportu-
nity to spring into action—if in fact some opportunity ever did present itself.
Instead, what I do throughout this book is pose problems: hard prob-
lems. These are problems that I hope you cannot solve, problems that I
hope stymie your current approaches. You’re a programmer. You want
to solve problems. Now it’s time for learning those fancy techniques. This
book is all about posing hard problems and then solving them by bridging
between what you know and what you need.
You won’t see traditional textbook problems here. You won’t find an op-
timal way to multiply a chain of matrices or compute Fibonacci numbers. I
promise: you won’t solve the Towers of Hanoi puzzle. There are many excel-
lent textbooks out there that do these things, but I suspect that many people
are not motivated by those kinds of puzzles.
My approach is to use new problems that you haven’t seen before. Each
year, thousands of people participate in programming competitions, and
these competitions require new problems to measure what participants can
come up with on their own rather than who can google the fastest. These
problems are fascinating, riffing on the classics while adding twists and con-
text to challenge people to find new solutions. There is a seemingly endless
stream of programming and computing knowledge encompassed by these
problems. We can learn as much as we like by choosing the right problems.
Let’s start with some basics. A data structure is a way to organize data so
that desirable operations are fast. An algorithm is a sequence of steps that
solves a problem. Sometimes we can make fast algorithms without using
sophisticated data structures; other times, the right data structure can
offer a significant speed boost. My goal is not to turn you into a competi-
tive programmer, though I’d take that as a happy side benefit. Rather, my
goal is to teach you data structures and algorithms using problems from the
competitive programming world—and to have fun while doing so. You can
reach me at [email protected]. Email me if you have learned. Email
me if you have laughed.
xxiv Introduction
Chapter 5, previously Chapter 4 I added guidance on how to choose
between using dynamic programming and using a graph.
Chapter 8, previously Chapter 7 I added further discussion of why we
implement heaps as arrays rather than as explicit trees.
Chapter 10 This chapter is completely new and teaches you how to use
randomization, a topic not often covered in books. Randomization is a
technique that can help you design algorithms that are simple and fast.
You’ll use two types of randomization algorithms to solve problems that
would otherwise be very difficult. You’ll also learn what to look for in
a problem when trying to decide whether to use randomization in the
first place.
Introduction xxv
Our Programming Language
I’ve chosen to use C as the programming language for this book, rather than
some higher-level language such as C++, Java, or Python. I’ll discuss why and
also justify a couple of other C-related decisions I’ve made.
Why Use C?
The primary reason for using C is that I want to teach you data structures
and algorithms from the ground up. When we want a hash table, we’ll build
it ourselves. There will be no reliance on dictionaries or hashmaps or simi-
lar data structures of other languages. When we don’t know the maximum
length of a string, we’ll build an extensible array: we won’t let the language
handle memory allocation for us. I want you to know exactly what’s going
on, with no tricks up my sleeve. Using C helps me toward this goal.
Solving programming problems in C, as we do in this book, is a use-
ful primer should you decide to continue with C++. If you become serious
about competitive programming, then you’ll be happy to know that C++ is
the most popular language used by competitive programmers, thanks to its
rich standard library and ability to generate code that favors speed.
Static Keyword
Regular local variables are stored on what’s called the call stack. On each call
of a function, some of the call stack memory is used to store local variables.
Then, when the function returns, that memory is freed up for other local
variables to use later. The call stack is small, though, and isn’t appropriate
for some of the massive arrays that we’ll meet in this book. Enter the static
keyword. When used on a local variable, it changes the storage duration
from automatic to static, which means that the variable maintains its value
between function calls. As a side effect, these variables are not stored in the
same memory area along with regular local variables, since then their values
would be lost when a function is terminated. Instead, they’re stored in their
own separate segment of memory, where they don’t have to compete with
whatever else might be on the call stack.
One thing to watch out for with this static keyword is that such local
variables are only initialized once! For a quick example, see Listing 1.
int f(void) {
¶ static int x = 5;
printf("%d\n", x);
x++;
}
int main(void) {
f();
f();
f();
xxvi Introduction
return 0;
}
5
6
7
Include Files
To save space, I don’t include the #include lines that should be added to the
start of C programs. You’ll be safe if you include the following:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
Freeing Memory
Unlike Java or Python, C requires the programmer to free all memory that is
manually allocated. The pattern is to allocate memory using malloc, use that
memory, and then free the memory using free.
For two reasons, though, I do not free memory here. First, freeing mem-
ory adds clutter, distracting from the primary teaching purpose of the code.
Second, these programs are not long-lived: your program will run on a few
test cases, and that’s it. The operating system reclaims all of the unfreed
memory on program termination, so there’s nothing to worry about even
if you run a program many times. Of course, not freeing memory is quite ir-
responsible in practice: no one is happy with a program that consumes more
and more memory as it runs. If you’d like to practice freeing memory, you
can add calls of free to the programs presented in this book.
Topic Selection
The fields of data structures and algorithms are too large to be corralled by
one book (or by this one author!). I used three criteria to help me decide
what topics made the cut.
First, I chose topics of broad applicability: each can be used to solve not
only the corresponding problems in the book but many other problems as
well. In each chapter, I focus on at least two problems. I generally use the
first problem to introduce the data structure or algorithm and one of its pro-
totypical uses. The other problems are meant to give a sense of what else
Introduction xxvii
Random documents with unrelated
content Scribd suggests to you:
military service as a make-shift; but, to a great extent, a guild,
following the profession of arms by hereditary custom from the
cradle to the grave.
"Eyes front, there; forward!" came the order from behind, and he
pulled himself together by instinct and went on.
"Only three weeks longer, brother!" said that voice beside him
meaningly; and a dull rage rose in Soma's heart. So it had been
seen. It might be said of him, Soma, that he had tamely submitted
to a defiling touch. He did not look round at his officers this time.
They might hear if they chose, the future might hold what it chose.
Mayhap they had seen the insult and were laughing at it. They were
not his Huzoors; they belonged to the man at his side, who had the
right to taunt him. As a matter of fact, they were discussing the
chances of their ponies in next week's races; but Soma, lost in a
great wrath, a great fear, made it, inevitably, the topic of the whole
world.
Hark! The bugle for the Rifles to form; they were to come to the
parade loaded with ball cartridge. And that rumble was the Artillery,
loaded also, going to take up their position. By and by the
Carabineers would sweep with a clatter and a dash to form the third
side of the hollow square, whereof the fourth was to be a mass of
helpless dark faces, with the eighty-five martyrs and tumbrils in the
middle. Soma had seen it all in general orders, talked it over with his
dearest friend, and called it tyranny. And now the tumbrils clanked
past a little heap of smoldering ashes, that but the day before had
been a guard-house. The lingering smoke from this last work of the
incendiary drifted northward, after the fetters, making one of the
officers cough. But he went on talking of his ponies. True type of the
race which lives to make mistakes, dies to retrieve them. Quick
march!
But the hammers went on as the sun climbed out of the dust-
haze to gleam on the sloped sabers, glint on the loaded guns, and
send glittering streaks of light along the rifles.
"I don't care who hears me," retorted Jim Douglas recklessly as
he steered through the crowd, followed by his friend, "I say it is d----
d inconceivable folly and tyranny. Come on, and let's have a gallop,
for God's sake, and get rid of that devilish sound."
"It is nothing to them; that's one comfort," he said. "But they will
have to suffer for it in the end, I expect. Who will believe when the
time comes that this"--he gave a backward wave of his hand--"went
on unwittingly of that?"
"Unjustly?"
"Yes. To their minds unjustly. And you know what forcible injustice
means to children--and these are really children--simple, ignorant,
obstinate."
"Well," said the civilian dryly, "I would give a great deal to know
what those simple babes really thought of us."
"Hate us stock and block for the time. I should," replied Jim
Douglas. They were passing the tumbrils at the moment, and one of
the guard, in sergeant's uniform, looked up in joyful recognition.
"Huzoor It is I, Soma."
The civilian looked at his companion oddly when, after a minute
or two spent in answering Soma's inquiries as to where and how the
master was to be found, Jim Douglas rode alongside once more.
"Very much out; but they are a queer lot. Do you remember the
story of the self-made American who was told his boast relieved the
Almighty of a great responsibility? Well, he is only responsible for
one-half of the twice-born. The other is due to humanity, to heredity,
what you will! That is what makes these high-caste men so difficult
to deal with. They are twice born. Yes! they are a queer lot."
"What's the odds? He can sleep all day. I'm sure his buggy
charger needs a rest."
"I don't care. It's Scriptural. Thou and thy ox and thy ass----"
The last words came nearer, softer. Mr. Fitzgerald was evidently
riding home beside someone's carriage.
No! truly there could be no fear. It was all talk! He set spurs to his
horse and went on through the silent night at a hand-gallop, for he
had another beast awaiting him halfway, and he wished to be in
Delhi by dawn. There was a row of tall trees bordering the road on
either side, making it dark, and through their swiftly passing boles
the level country stretched to the paler horizon like a sea. And as he
rode, he sat in judgment in his thoughts on those dead levels and
the people who lived in them.
"The Huzoor has mistaken the road," came Tiddu's familiar creak.
"Meerut lies to the north."
The old man laughed. "The Huzoor is mighty clever. He knows old
Tiddu has eyes. They saw the Huzoor's horse--a bay Wazeerie with a
white star none too small, and all the luck-marks--waiting at the
fifteenth milestone, by Begum-a-bad. But the Huzoor, being so
clever, is not going to ride the Wazeerie to-night. He is going to ride
the Belooch he is on back to Meerut, though the star on her
forehead is too small for safety; my thumb could cover it."
"It's a bit too late to teach me the luck-marks, Tiddu," said Jim
Douglas coolly. "You want money, you ruffian; so I suppose you have
something to sell. What is it? If it is worth anything, you can trust
me to pay, surely."
"The yellow fakir!" echoed his hearer; "who the devil is he? And
why shouldn't he come, if he likes?"
Tiddu paused, as if in sheer amaze, for a second. "The Huzoor
has not heard of the yellow fakir? The dumb fakir who brings the
speech that brings more than speech. Wâh!"
Tiddu's hand went out to the Belooch's rein; his voice lost its
creak and took a soft sing-song to which the mare seemed to come
round of her own accord.
He slipped from his horse without a word, and was about to pull
the reins over her head so as to lead her, when Tiddu stopped short.
"Leave her so, Huzoor! She is safe," said Tiddu; and Jim Douglas,
as he obeyed, heard the mare whinny softly, as if to a foal, as a
shadow came out of the bushes. Junghi or Bhungi, no doubt.
They were close on the city of Meerut. The road, dipping down to
cross a depression, left a bank of yellow dust on either side. And on
the eastern one, outlined against the yellow sunrise, sat a
motionless figure. It was naked, and painted from head to foot a
bright yellow color. The closed eyes were daubed over so as to hide
them utterly, and on the forehead, as it is in the image of Siva, was
painted perpendicularly a gigantic eye, wide, set, stony. Before it in
the dust lay the beggar's bowl for alms.
"The roads part here, Huzoor," said Tiddu. "This to the city; that
to the cantonments."
"I meant the trooper, Huzoor. The fakir wanted him. To give the
word, mayhap. Someone must always give it."
But what a strange knack the old man had of stirring the
imagination with ridiculous mystery! He felt vexed with himself for
his own thrill, his own thoughts. "He is a very ordinary yogi, I should
say," he remarked, looking toward the yellow sunrise, but the figure
was gone. He turned to Tiddu again, with real annoyance. "Well!
Whoever he is, he cannot want me. And I certainly saw him."
"I willed the Huzoor to see!" replied Tiddu with calm effrontery.
Mayhap it was but the inevitable reaction after the stun and
stupefaction of Saturday, the sudden awakening to the result--
namely, that eighty-five of the best, smartest soldiers in Meerut had
been set to toil for ten years in shackles because they refused to be
defiled, to become apostate. On the other hand, the old Baharupa
may have been right about the yellow fakir: the silent, motionless
figure might have set folk listening and waiting for the word. It was
to be seen by all now sitting outside the city; at least Jim Douglas
saw it several times. Saw, also, that the beggar's bowl was fuller and
fuller; but the impossibility of asserting that all the passers-by saw it,
as he did, haunted him, once the idea presented itself to his mind. It
was always so with Tiddu's mysteries; they were no more
susceptible to disproof than they were to proof. You could waste
time, of course, in this case by waiting and watching, but in the
natural course of events half the passers-by would go on as if they
saw nothing, and only one in a hundred or so would give an alms.
So what would be the good?
It was not the heat, however, which prevented Major Erlton from
taking his usual siesta. It was thought. He had come over from Delhi
on inspection duty a few days before and had intended returning
that evening; but the morning's post had brought him a letter which
upset all his plans. Alice Gissing's husband had come out a fortnight
earlier than they had expected, and was already on his way up-
country. The crisis had come, the decision must be made. It was not
any hesitation, however, which sent the heavy handsome face to rest
in the big strong hands as he rested his elbows on a sheet of blank
paper. He had made up his mind on the very day when Alice Gissing
had first told him why she could not go back to her husband. The
letter forwarding his papers for resignation was already sealed on
the table beside him; and the surprise was rather a gain than
otherwise. Alice could join him at Meerut now, and they could slip
away together to Cashmere or any out of the way place where there
was shooting. That would save a lot of fuss; and the fear of fuss was
the only one which troubled the Major, personally. He hated to know
that even his friends would wonder--for the matter of that those who
knew him best would wonder most--why he was chucking everything
for a woman he had been mixed up with for years. Yet he had found
no difficulty in writing that official request; none in telling little Allie
to join him as soon as she could. It was this third letter which could
not be written. He took up the pen more than once, only to lay it
down again. He began, "My dear Kate," once, only to tear the sheet
to pieces. How could he call her his when he was going to tell her
that she was his no longer; that the best thing she could do was to
divorce him and marry some other chap to be a father to the boy.
The thought sent the head into the hands again; for Herbert
Erlton was a healthy animal and loved his offspring by instinct. He
had, in truth, a queer upside-down notion of his responsibilities
toward them. If the fates had permitted it he would have done his
best by Freddy. Shown him the ropes, given him useful tips, stood
by his inexperience, paid his reasonable debts--always supposing he
had the wherewithal.
Then how was he to tell Kate all the ugly story. He had left her in
his thoughts so completely, she had been so far apart from him for
so many years now, that he hesitated over telling her the bare facts,
just as--being conventionally a perfectly well-bred man--he would
have hesitated how to tell them to any innocent woman of his
acquaintance. Rather more so, for Kate--though she was sentimental
enough, he told himself, for two--had never been sensible and
looked things in the face. If she had, it might all have been different.
Then with a rush came the remembrance that Allie did--that she
knew him every inch and was yet willing to come with him. While
he? He would stick through thick and thin to little Allie, who never
made a man feel a fool or a beast. Something in the last assertion
seemed to harden his heart; he took up his pen and began to write:
"My Dear Kate: I call you that because I can't think of any
other beginning that doesn't seem foolish; but it means nothing, and
I only want to tell you that circumstances over which we had no
control (he felt rather proud of this circumlocution for a circumstance
due entirely to his volition) make it necessary for me to leave you. It
is the only course open to me as a gentleman. Besides I want to, for
I love Alice Gissing dearly. I am going to marry her, D. V., as soon as
I can. Mr. Gissing may make a fuss--it is a criminal offense, you see,
in India--but we shall tide over that. Of course you could prevent me
too, but you are not that sort. So I have sent in my papers. It is a
pity, in a way, because I liked this work. But it is only a two-year
appointment, and I should hate the regiment after it. For the rest, I
am not such a fool as to think you will mind; except for the boy. It is
a pity for him too, but it isn't as if he were a girl, and the other may
be. It will do no good to say I'm sorry. Besides, I don't think it is all
my fault, and I know you will be happier without me.
"Yours sincerely,
"Herbert Erlton.
"P. S.--It's no use crying over spilled milk. I believe you used to
think I would get the regiment some day, but they would never have
given it to me. I made a bit of a spurt lately, but it couldn't have
lasted to the finish, and after all, that is the win or the lose in a race.
"H. E."
But in the southern half, humanity was still swarming in and out,
waiting, listening. In one of the mud-huts, however, a company of
men gathered within closed doors had been listening to some
purpose. Listening to an eloquent speaker, the accredited agent of a
down-country organization. He had arrived in Meerut a day or two
before, and had held one meeting after another in the lines, doing
his utmost to prevent any premature action; for the fiat of the
leaders was that there should be patience till the 31st of May. Then,
not until then, a combined blow for India, for God, for themselves,
might be struck with chance of success.
"Ameen!" assented one old man who had come with him. An old
man in a huge faded green turban with dyed red hair and beard,
and with a huge green waistband holding a curved scimitar. Briefly, a
Ghâzee or Mohammedan fanatic. "Patience, all ye faithful, till
Sunday, the 31st of May. Then, while the hell-doomed infidels are at
their evening prayer, defenseless, fall on them and slay. God will
show the right! This is the Moulvie's word, sent by me his servant.
Give the Great Cry, brothers, in the House of the Thief! Smite ye of
Meerut, and we of Lucknow will smite also." His wild uncontrolled
voice rolled on in broad Arabic vowels from one text to another.
"Then our comrades are to rot in jail till the 31st? That suits not
the men of the 3d Cavalry."
"Then let the 3d Cavalry suit itself," retorted the agent fearlessly.
"We can stand without them. Can they stand without us? Answer
me, men of the 20th; men of the 11th."
"The 31st! Then slay and spare not! It is jehad! Deen! Deen!
Futteh Mohammed!" said the Ghâzee.
"I'll hold mine, Khân sahib, without thine aid," retorted a very
young smart-looking native officer angrily. "That is if the women will
hold their tongues. But, look you, my troop held the hardest hitters
in the 3d. And Nargeeza's fancy is of those in jail. Now Nargeeza
leads all the other town-women by the nose; and that means much
to men who be not all saints like Ghâzee-jee yonder, who ties the
two ends of life with a ragged green turban and a bloody banner!"
"And I see not why our comrades should stay yonder for three
weeks, when there is but a native guard to hold them, and I and
mine have made the Sirkar what it is," put in a man with arrogance
and insolence written on him from top to toe; a true type of the
pampered Brahmin sepoy.
"For our officers lives, baboo-jee," came the voice again, bold as
the agent's. "We of the 11th kill not men who have led us to victory.
And if this be not understood I, Soma, Yadubansi, go straight to the
Colonel and tell him. We are not butchers in the 11th: Oh, priest of
Kâli!"
The agent turned a little pale. He did not care to have his calling
known, and he saw at a glance that his challenger had the reckless
fire of hemp in his eyes. He had indeed been drinking as a refuge
from the memory of the sweeper's broom and from the taunts and
threats which had been used to force him to join the malcontents.
Such a man was not safe to quarrel with, nor was the audience fit
for a discussion of that topic; there was already a stir in it, and
mutterings that butchery was one thing, fighting another.
"He will, brother, he will. The Cry shall yet be heard in the House
of the Thief," said the Ghâzee fiercely, his eyes growing dreamy with
hope. He was thinking of a sunset near the Goomtee more than a
year ago, when he had bid every penny he possessed for his own, in
vain.
The Moghul ducked hastily from a wild swing of the curved sword,
and moved off swearing such firebrands should be locked up; they
might set light to the train ere wise men had it ready.
"No fear!" said the smart young troop-sergeant of the 3d. "Who
listens to such as he save those whose blood has cooled, and those
whose blood was never hot? The fighters listen to women who can
make their flame."
Soma, who was drifting with them toward the drug-shops of the
city, scowled fiercely. "That may suit thee, Mussulman-jee, who art
casteless, and can sup shares with sweeper women in the bazaar;
but the Rajpoot needs no harlot to teach him courage. The mothers
of his race have enough and to spare."
"Loh! hark to him!" jibed the corporal of the 20th, who was
sticking to his prey like a leech. "Ask him, Havildar-jee, if he prefers
a sweeper's broom to a sweeper's lips."
"Thou didst not tell me, Nasiban, what Gulâbi said. Is she of us?"
The voice tailed off into sleep again, and Nargeeza lay back with a
smile of content to wait also. So, after a time, folk began to stir in
the bungalows. First in the rest-house, where, oddly enough, Jim
Douglas occupied one end of the long low barrack of a place, and
Herbert Erlton the other. The former having come back from the city
in an evil temper to get something to eat before starting for Delhi,
had found his horse, the Belooch, unaccountably indisposed; Jhungi,
who had brought her there safely, professing entire ignorance of the
cause, or, on pressure, suggesting the nefarious Bhungi. Tiddu
asserting--with a calm assumption of superior knowledge, for which
Jim Douglas could have kicked him--that the mare had been
drugged. As if anybody could not tell that? And that the drug had
been opium. To which the old scoundrel had replied affably that in
that case the effects would pass off during the night, and the mare
be none the worse; no one be any the worse, since the Huzoor was
quite comfortable in Meerut, and could easily stay another day. It
was a nicer place than Delhi; there were more sahibs in it, and the
presence of the "ghora logue" (i. e., English soldiers) kept everyone
virtuous.
His hearer looked at him sharply. Here was some other trick, no
doubt, to cozen him out of another five rupees; for something,
maybe, as useless as the yellow fakir. And there was really no reason
for delay; it was only a case of walking the mare quietly. For the
matter of that, the exercise would do her good, and help her to work
off the effects of the drug. So he would start sooner, that was all.
Nevertheless he gave an envious look at the Major's little Arab in the
next stall. It would most likely be marching back to Delhi that night,
and he would have given something to ride it again. But as he was
returning from the stables, he learned by chance that the Major's
plans had been altered. An orderly was coming from his room with
letters and a telegram, and knowing the man, Jim Douglas asked
him to take one for him also, and so save trouble. It did not take
long to write, for it only contained one word, "No." It was in reply to
one he had received a few hours before from the military magnate,
asking him to do some more work. And as the orderly stowed away
the accompanying rupee carefully, Jim Douglas--waiting to make
over the paper--saw quite involuntarily that the Major's telegram
also consisted of one word, "Come." And he saw the name also; big,
black, bold, in the Major's handwriting. "Gissing, Delhi."
"The Cavalry," it ran, "have risen, setting fire to their own houses
besides having killed and wounded all European officers and soldiers
they could find near the lines. If Aunt intends starting to-morrow,
please detain her, as the van has been prevented from leaving the
station."
For, as Jim Douglas paced slowly down the Mall toward Delhi, and
Soma, his buckles gleaming, his belts pipe-clayed to dazzling
whiteness, was swaggering through the bazaar on his way to the
rest-house with his word of warning--the word which would have
given Jim Douglas the power for which he had longed--another word
was being spoken in that lane of lust, where the time had come for
which Nargeeza had waited all day. But she did not say it. It was
only a big trollop of a girl hung with jasmine garlands, painted,
giggling.
The word had been spoken. The speech which brings more than
speech, had come from the painted lips of a harlot.
"To horse! To horse! Let the comrades be rescued first; and then--
--"
The word had been spoken. Nothing so very soul-stirring after all.
No consideration of caste or religion, patriotism or ambition. Only a
taunt from a pair of painted lips.
BOOK III.
FROM DUSK TO DAWN.
CHAPTER I.
NIGHT.
The cry was no more than that at first. To the rescue of the
eighty-five martyrs, the blows upon whose shackles still seemed to
echo in their comrades' ears. Even so, the cry heard by Soma as he
passed through the bazaar meant insubordination--the greatest
crime he knew--and sent him flying to his own lines to give the
alarm. Sent him thence by instinct, oblivious of that promise for the
31st--or perhaps mindful of it and seeing in this outburst a mere
riot--to his Colonel's house with twenty or thirty comrades clamoring
for their arms, protesting that with them they would soon settle
matters for the Huzoors. But suspicion was in the air, and even the
Colonel of the 11th could not trust all his regiment. Ready for
church, he flung himself on his horse and raced back with the
clamoring men to the lines.
And by this time there was another race going on. Captain
Craigie's faithful troop of the 3d Cavalry were racing after his shout
of "Dau-ro! bhai-yan, Dau-ro!" (Ride, brothers, ride!) toward the jail
in the hopes of averting the rescue of their comrades. For, as the
records are careful to say, he and his troop "were dressed as for
parade"--not a buckle or a belt awry--ready to combat the danger
before others had grasped it, and swiftly, without a thought, went
for the first offenders. Too late! the doors were open, the birds
flown.
What next was to be done? What but to bring the troop back
without a defaulter--despite the taunts of escaping convicts, the
temptations of comrades flushed by success--to the parade ground
for orders. But there was no one to give them, for when the 3d
Cavalry led the van of mutiny at Meerut their Colonel was in the
European cantonment as field officer of the week, and there he
"conceived it his duty to remain." Perhaps rightly. And it is also
conceivable that his absence made no difference, since it is,
palpably, an easier task to make a regiment mutiny than to bring it
back to its allegiance.
Meanwhile the officers of the other regiments, the 11th and the
20th, were facing their men boldly; facing the problem how to keep
them steady till that squadron of the Carabineers should sweep
down, followed by a company or two of the Rifles at the double, and
turn the balance in favor of loyalty. It could not be long now. Nearly
an hour had passed since the first wild stampede to the jail. The
refuse and rabble of the town were by this time swarming out of it,
armed with sticks and staves; the two thousand and odd felons
released from the jails were swarming in, seeking weapons. The
danger grew every second, and the officers of the 11th, though their
men stood steady as rocks behind them, counted the moments as
they sped. For on the other side of the road, on the parade ground
of the 20th regiment, the sepoys, ordered, as the 11th had been, to
turn out unarmed, were barely restrained from rushing the bells by
the entreaties of their native officers; the European ones being
powerless.
"Keep the men steady for me," said Colonel Finnis to his second in
command; "I'll go over and see what I can do."
"Quick! brothers. Quick! Kill! Kill! Down with the officers! Shoot
ere the white faces come!"
That call, in the alien voice, echoed above the whistling of the
bullets as they found a billet here and there among the ranks; for
the men of the 20th, maddened by that fresh murder, now shot
wildly at their officers.
The entreaty was not in vain; they were steady still. Ay, steady,
but unarmed! Steady as a rock still, but helpless!
Helpless, unarmed! By all the gods all men worshiped, men could
not suffer that for long, when bullets were whistling into their ranks.
So there was a waver at last in the long line. A faint tremble, like
the tremble of a curving wave ere it falls. Then, with a confused
roar, an aimless sweeping away of all things in its path, it broke as a
wave breaks upon a pebbly shore.
Upon whom?[2] God knows! Not on their officers, for these were
already being hustled to the rear, hustled into safety.
The cry rose on all sides now, as the wave of revolt surged on.
But there was none left to kill; for the work was done in the 20th
lines, and no new white faces came to stem the tide. Two thousand
and odd Englishmen who might have stemmed it being still on the
parade-ground by the church, waiting for orders, for ammunition, for
a General, for everything save--thank Heaven!--for courage.
"Whose fault but their own?" muttered an old man fiercely; an old
man whose son served beside him in the regiment, whose grandson
was on the roster for future enlistment. "Why were we left helpless
as new-born babes?"
The words caught the old man's ear and sent a quick decision to
his dazed face. The baba logue! Yes; they must be safeguarded; for
ominous smoke began to rise from neighboring roof-trees, and a
strange note of sheer wild-beast ferocity grew to the confused roar
of the drifting, shifting, still aimless crowd.
"Quick, brothers, quick! Kill, root and branch! Why dost linger? Art
afraid? Afraid of cowards? Quick--kill everyone!"
"What! art cowards too?" he went on. "Then follow me. For I
began it--I fired the first shot--I killed the first infidel. I----"
The boast never ended, for above it came a quicker cry: "Kill, kill,
kill the traitor! Kill the man who betrayed us."
There was a rush onward toward the boastful, arrogant voice, the
report of half a dozen muskets, and the crowd surged on to revolt
over the body of the man who had fired the first shot of the mutiny.
But there were more like Soma, who, as the darkness deepened
and the glare and the dire confusion and dismay grew, stood aloof
from it voluntarily, waiting, with a certain callousness, to see if the
master would come, or if folk said true when they declared his time
was past, his day done.
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.
textbookfull.com