100% found this document useful (2 votes)
26 views69 pages

Algorithmic Thinking. Learn Algorithms...Your Coding Skills 2ed 2024 Zingaro D. download

The document promotes the second edition of 'Algorithmic Thinking' by Daniel Zingaro, which focuses on problem-based learning of algorithms to enhance coding skills. It includes praise from various professionals highlighting its practical approach and effectiveness in teaching algorithms. Additionally, it provides links to other related resources and books for further learning in programming and algorithmic concepts.

Uploaded by

soskoxtamkego
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)
26 views69 pages

Algorithmic Thinking. Learn Algorithms...Your Coding Skills 2ed 2024 Zingaro D. download

The document promotes the second edition of 'Algorithmic Thinking' by Daniel Zingaro, which focuses on problem-based learning of algorithms to enhance coding skills. It includes praise from various professionals highlighting its practical approach and effectiveness in teaching algorithms. Additionally, it provides links to other related resources and books for further learning in programming and algorithmic concepts.

Uploaded by

soskoxtamkego
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/ 69

Algorithmic Thinking. Learn Algorithms...

Your
Coding Skills 2ed 2024 Zingaro D. download

https://textbookfull.com/product/algorithmic-thinking-learn-
algorithms-your-coding-skills-2ed-2024-zingaro-d/

Download more ebook from https://textbookfull.com


We believe these products will be a great fit for you. Click
the link to download now, or visit textbookfull.com
to discover even more!

Algorithmic Thinking 2nd Edition A Problem Based


Introduction Daniel Zingaro

https://textbookfull.com/product/algorithmic-thinking-2nd-
edition-a-problem-based-introduction-daniel-zingaro/

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/

PHP and Algorithmic Thinking for the Complete Beginner


2nd Edition Learn to Think Like a Programmer Bouras

https://textbookfull.com/product/php-and-algorithmic-thinking-
for-the-complete-beginner-2nd-edition-learn-to-think-like-a-
programmer-bouras/

Learning functional data structures and algorithms


learn functional data structures and algorithms for
your applications and bring their benefits to your work
now Khot
https://textbookfull.com/product/learning-functional-data-
structures-and-algorithms-learn-functional-data-structures-and-
algorithms-for-your-applications-and-bring-their-benefits-to-
Generative Art with JavaScript and SVG: Utilizing
Scalable Vector Graphics and Algorithms for Creative
Coding and Design (Design Thinking) 1st Edition David
Matthew
https://textbookfull.com/product/generative-art-with-javascript-
and-svg-utilizing-scalable-vector-graphics-and-algorithms-for-
creative-coding-and-design-design-thinking-1st-edition-david-
matthew/

Learn JavaScript with p5.js: Coding for Visual Learners


Arslan

https://textbookfull.com/product/learn-javascript-with-p5-js-
coding-for-visual-learners-arslan/

Learning Functional Data Structures and Algorithms


Learn functional data structures and algorithms for
your applications and bring their benefits to your work
now 1st Edition Atul S. Khot
https://textbookfull.com/product/learning-functional-data-
structures-and-algorithms-learn-functional-data-structures-and-
algorithms-for-your-applications-and-bring-their-benefits-to-
your-work-now-1st-edition-atul-s-khot/

Algorithmic Governance And Governance Of Algorithms:


Legal And Ethical Challenges Martin Ebers

https://textbookfull.com/product/algorithmic-governance-and-
governance-of-algorithms-legal-and-ethical-challenges-martin-
ebers/

Learn Python Visually Creative Coding with Processing


py 1st Edition Tristan Bunn

https://textbookfull.com/product/learn-python-visually-creative-
coding-with-processing-py-1st-edition-tristan-bunn/
PRAISE FOR
ALGORITHMIC THINKING, 2ND EDITION

“Algorithmic Thinking will empower you–whether you’re looking to get a leg up


on technical interviews, enter the world of competitive programming, or just
want to sharpen your skills.”
—josh lospinoso, phd, author of
c++ crash course

“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

“Algorithmic Thinking provides the theoretical background and detailed


problem explanations required to stay ahead of our human and robotic
competitors.”
—duncan smith, senior software
engineer at microsoft

“Not only does Algorithmic Thinking guide readers on how to approach


tackling problems, but Zingaro also helps them understand why these
approaches work.”
—sushant sachdeva, phd,
algorithms professor at
the university of toronto

“The step-by-step solution explanations are so detailed, it feels like Zingaro


is directly teaching us, his readers. This second edition is a worthy update to
an already excellent text.”
—dr steven halim, senior
lecturer at national
university of singapore

“Algorithmic Thinking discusses many interesting problems from programming


contests and presents useful techniques that are not often included in
algorithm textbooks.”
—a ntti laaksonen,
university of helsinki
ALGORITHMIC
THINKING
2ND EDITION

Learn Algorithms to Level up


Your Coding Skills

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

ISBN-13: 978-1-7185-0322-9 (print)


ISBN-13: 978-1-7185-0323-6 (ebook)

® Published by No Starch Press®, Inc.


245 8th Street, San Francisco, CA 94103
phone: +1.415.863.9900
www.nostarch.com; [email protected]

Publisher: William Pollock


Managing Editor: Jill Franklin
Production Manager: Sabrina Plomitallo-González
Production Editor: Sydney Cromwell
Developmental Editor: Alex Freed
Cover Illustrator: Rob Gale
Interior Design: Octopod Studios
Technical Reviewers: Naaz Sibia and Larry Yueli Zhang
Copyeditor: George Hale
Proofreader: Elizabeth Littrell

The Library of Congress has catalogued the first edition as follows:

Name: Zingaro, Daniel, author.


Title: Algorithmic thinking : a problem-based introduction / by Daniel Zingaro.
Includes bibliographical references and index.
Identifiers: LCCN 2020031510 (print) | LCCN 2020031511 (ebook) | ISBN 9781718500808 (paperback) |
ISBN 1718500807 (paperback) | ISBN 9781718500815 (ebook)
Subjects: LCSH: Computer algorithms--Problems, exercises, etc. | Computer programming--Problems, exercises, etc.
Classification: LCC QA76.9.A43 Z56 2020 (print) | LCC QA76.9.A43 (ebook) | DDC 005.13--dc23
LC record available at https://lccn.loc.gov/2020031510
LC ebook record available at https://lccn.loc.gov/2020031511

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.

About the Technical Reviewer


Naaz Sibia is an MSc student of computer science at the University of Toronto
with an interest in computer science education research and human com-
puter interaction (HCI). Her research focuses on identifying challenges
faced by students in computing and utilizing HCI principles to design in-
terventions that improve their learning experience.

About the First Edition Technical Reviewer


Larry Yueli Zhang is an assistant professor of computer science in the De-
partment of Electrical Engineering and Computer Science at York Univer-
sity’s Lassonde School of Engineering. His teaching and research span a
wide range of topics, including introductory programming, algorithms, data
structures, operating systems, computer networks, and social network anal-
ysis, all underscored by a passion for computing education. Larry holds a
PhD in computer science from the University of Toronto.
BRIEF CONTENTS

Foreword . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xix
Acknowledgments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xxi
Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xxiii

Chapter 1: Hash Tables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1


Chapter 2: Trees and Recursion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
Chapter 3: Memoization and Dynamic Programming . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77
Chapter 4: Advanced Memoization and Dynamic Programming . . . . . . . . . . . . . . . . . . . . . . . . . 125
Chapter 5: Graphs and Breadth-First Search . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 151
Chapter 6: Shortest Paths in Weighted Graphs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 197
Chapter 7: Binary Search . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 231
Chapter 8: Heaps and Segment Trees . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 277
Chapter 9: Union-Find . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 331
Chapter 10: Randomization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 375

Afterword. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 403

Appendix A: Algorithm Runtime . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 405


Appendix B: Because I Can’t Resist . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 411
Appendix C: Problem Credits . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 427

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

xii Contents in Detail


Problem 2: Moneygrubbers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 98
The Problem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 98
Characterizing Optimal Solutions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99
Solution 1: Recursion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101
The main Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 105
Solution 2: Memoization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 106
Problem 3: Hockey Rivalry . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 108
The Problem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109
About Rivalries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 110
Characterizing Optimal Solutions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111
Solution 1: Recursion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 114
Solution 2: Memoization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 117
Solution 3: Dynamic Programming . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 119
A Space Optimization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 122
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 123
Notes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 123

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

Contents in Detail xiii


Problem 2: Rope Climb . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 173
The Problem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 173
Solution 1: Finding the Moves . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 174
Solution 2: A Remodel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 179
Problem 3: Book Translation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 187
The Problem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 187
Reading the Language Names . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 188
Building the Graph . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 189
The BFS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 192
The Total Cost . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 194
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 195
Notes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 195

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

xiv Contents in Detail


Binary Search . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 240
Runtime of Binary Search . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 241
Determining Feasibility . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 242
Searching a Sorted Array . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 242
Problem 2: River Jump . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 243
The Problem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 243
A Greedy Idea . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 244
Testing Feasibility . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 246
Searching for a Solution . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 250
Reading the Input . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 253
Problem 3: Living Quality . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 254
The Problem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 254
Sorting Every Rectangle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 256
Using Binary Search . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 259
Testing Feasibility . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 260
A Quicker Way to Test Feasibility . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 261
Problem 4: Cave Doors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 267
The Problem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 267
Solving a Subtask . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 268
Using Linear Search . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 270
Using Binary Search . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 272
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 274
Notes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 275

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

xvi Contents in Detail


Generating Random Numbers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 378
Determining Number of Pieces . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 379
Guessing Flavors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 381
How Many Attempts Do We Need? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 384
Filling the Flavor Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 385
The main Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 386
Randomization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 387
Monte Carlo Algorithms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 387
Las Vegas Algorithms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 388
Deterministic vs. Randomized Algorithms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 389
Problem 2: Caps and Bottles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 390
The Problem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 390
Solving a Subtask . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 391
Solution 1: Recursion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 393
Solution 2: Adding Randomization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 396
Quicksort . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 398
Implementing Quicksort . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 398
Worst-Case and Expected Runtime . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 400
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 402
Notes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 402

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

Contents in Detail xvii


Compressing Path Compression . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 422
Step 1: No More Ternary If . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 423
Step 2: Cleaner Assignment Operator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 423
Step 3: Understand the Recursion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 424
Caps and Bottles: In-Place Sorting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 424

C
PROBLEM CREDITS 427

INDEX 431

xviii Contents in Detail


FOREWORD

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

I’m assuming that you’ve learned to use


a programming language such as C, C++,
Java, or Python . . . and I’m hoping that
you’re hooked. It’s hard to explain to nonpro-
grammers why solving problems through program-
ming is so rewarding and fun.
I’m also hoping that you’re ready to take your programming skill to the
next level. I have the privilege of helping you do that.

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.

New to the Second Edition


I’ve thoroughly enjoyed the opportunity to discuss the first edition of this
book with readers. Their feedback has led to many of the changes and im-
provements in this new edition.
I’ve made small improvements and additions throughout, but here are
the major highlights of what’s new:
Chapter 1 I removed the Compound Words problem, as it can be
solved in ways that did not require a hash table. Instead, now we have
a problem about passwords on a social networking website. I’ve also
streamlined the code in this chapter to help those without a C/C++ pro-
gramming background, and I added more information about the effi-
ciency of hash tables.
Chapter 3 I added more guidance for how to discover the needed sub-
problems when solving a problem with dynamic programming.
Chapter 4 This chapter is completely new, and it focuses on more ad-
vanced uses of memoization and dynamic programming. This was a fre-
quent request of readers, and I’m excited to have been able to add this.
You’ll learn how to look at dynamic programming problems in reverse
(and why you’d want to), how to work with more dimensions in your
subproblem arrays, and how to further optimize your dynamic program-
ming code when it’s just not fast enough.

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.

Who This Book Is For


This book is for any programmer who wants to learn how to solve tough
problems. You’ll learn many data structures and algorithms, their benefits,
the types of problems they can help you solve, and how to implement them.
You’ll be a better programmer after this!
Are you taking a course on data structures and algorithms and getting
your butt kicked by a wall of theorems and proofs? It doesn’t have to be that
way. This book can serve as a companion text for you, helping you get to the
core of what’s going on so that you can write code and solve problems.
Are you looking for an edge in your next coding interview? You need
to be able to compare and contrast different approaches for solving a prob-
lem, choose the best data structure or algorithm, and explain and imple-
ment your solution. You’ll practice all of these skills over and over as you
read this book. Never fear hash tables, recursion, dynamic programming,
trees, graphs, or heaps again!
Are you an independent learner working toward expertise in data struc-
tures and algorithms? Piecing together stuff from all over the internet can
be tiring and lead to knowledge gaps if the right resources are not found.
This book will provide you the solid foundation and consistent presentation
that you need to become an expert.
As explored further in the next section, all code in this book is written
in the C programming language. However, this isn’t a book on learning C.
If your prior programming experience is in C or C++, then jump right in. If
instead you’ve programmed in a language such as Java or Python, I suspect
that you’ll pick up most of what you need by reading, but you may wish to
review some C concepts now or on first encounter. In particular, I’ll use
pointers and dynamic memory allocation, so, no matter what your prior
experience, you might like to brush up on those topics. The best C book I
can recommend is C Programming: A Modern Approach, 2nd edition, by K. N.
King. Even if you’re okay with C, read it anyway. It’s that good and a won-
derful companion any time you get tripped up by C stuff.

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;
}

Listing 1: A local variable with a static keyword


I’ve used static on local variable x ¶. Without that, you’d expect 5 to
be printed three times. However, since static is there, you should see this
output instead:

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.

Quick march! A woman, early astir, peered at the little procession


through the chink of a door, and whispered to an unseen companion
behind. What was she saying? What, by implication, would other
women, who peeped virtuously--women he knew--say of his present
occupation? That he was a coward to be guarding his comrades'
fetters? No doubt; since others with less right would say it too. All
the miserable, disreputable riff-raff, for instance, which had drifted in
from the neighborhood to see the show. The bazaar had been full of
it these three days past. Even the sweepers, pariahs, out-castes,
would snigger over the misfortunes of their betters--as those two
ahead were doubtless sniggering already as they drew aside from
their slave's work of sweeping the roadway, to let the tumbrils pass.
Drew aside with mock deference, leaving scantiest room for the
twice-born following them. So scant, indeed, that the outermost tip
of a reed broom, flourished in insolent salaam, touched the Rajput's
sleeve. It was the veriest brush, no more than a fly's wing could
have given; but the half-stifled cry from Soma's lips meant murder--
nothing less. His disciplined feet wavered, he gave a furtive glance
at his companions. Had they seen the insult? Could they use it
against him?

"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!

Streams of spectators bound for the show began to overtake


them, ready with comments on what Soma guarded. And on the
broad white Mall, dividing the native half of the cantonments and
the town of Meerut from the European portion, more than one
carriage with a listless, white-faced woman in it dashed by, on its
way to see the show. The show!

Quick march! Whatever else might be possible in the futures that


was all now, midway between the barracks of the Rifles and the
Carabineers, with the church--mute symbol of the horror which, day
by day, month by month, had been closing in round the people--
blocking the way in front. So they passed on to the wide northern
parade ground, with that hollow square ready; three sides of it
threatening weapons, the fourth of unarmed men, and in the center
the eighty-five picked men of a picked regiment.
The knot of European spectators round the flag listened with
yawns to the stout General's exordium. The eighty-five being
hopelessly, helplessly in the wrong by military law, there seemed to
be no need to insist on the fact. And the mass of dark faces standing
within range of loaded guns and rifles, within reach of glistening
sabers, did not listen at all. Not that it mattered, since the units in
that crowd had lost the power of accepting facts. Even Soma,
standing to attention beside the tumbrils, only felt a great sense of
outrage, of wrong, of injustice somewhere. And there was one
Englishman, at least, rigid to attention also before his disarmed,
dismounted, yet loyal troop, who must have felt it also, unless he
was more than human. And this was Captain Craigie, who, when his
men appealed to him to save them, to delay this unnecessary
musketry parade, had written in his haste to the Adjutant, "Go to
Smyth at once! Go to Smyth!" and Smyth was his Colonel! Incredible
lack of official etiquette. Repeated hardily, moreover. "Pray don't lose
a moment, but go to Smyth and tell him." What? Only "that this is a
most serious matter, and we may have the whole regiment in open
mutiny in half an hour if it is not attended to." Only that! So it is to
be hoped that Captain Craigie had the official wigging for his
unconventional appeal in his pocket as he shared his regiment's
disgrace, to serve him as a warning--or a consolation.

And now the pompous monotone being ended, the silence,


coming after the clankings, and buglings, and trampings which had
been going on since dawn, was almost oppressive. The three sides
of steel, even the fourth of faces, however, showed no sign. They
stood as stone while the eighty-five were stripped of their uniforms.
But there was more to come. By the General's orders the leg-irons
were to be riveted on one by one; and so, once more, the sound of
iron upon iron recurred monotonously, making the silence of the
intervals still more oppressive. For the prisoners at first seemed
stunned by the isolation from even their as yet unfettered comrades.
But suddenly from a single throat came that cry for justice, which
has a claim to a hearing, at least, in the estimation of the people of
India.
"Dohai! Dohai! Dohai!"

Soma gave a sort of sigh, and a faint quiver of expectation passed


over the sea of dark faces.

Clang! Clang! The hammers, going on unchecked, were the only


answer. Those three sides of stone had come to see a thing done,
and it must be done; the sooner the better. But the riveting of
eighty-five pairs of leg-irons is not to be done in a moment; so the
cry grew clamorous. Dohai! Dohai! Had they not fought faithfully in
the past? Had they not been deceived? Had they had a fair chance?

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.

So the cry changed. Were their comrades cowards to stand by


and see this tyranny and raise no finger of help? Oh! curses on
them! 'Tis they who were degraded, dishonored. Curses on the
Colonel who had forced them to this! Curses on every white face!--
curses on every face which stood by!

One, close to the General's flag, broke suddenly into passionate


resentment. Jim Douglas drew out his watch, looked at it, and
gathered his reins together. "An hour and forty-five minutes already.
I'm off, Ridgeway. I can't stand this d----d folly any more."

"My dear fellow, speak lower! If the General----"

"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."

The echo of their horses' resounding hoofs covered, obliterated it.


The wind of their own swiftness seemed to blow the tension away.
So after a spin due north for a mile or two they paused at the edge
of a field where the oxen were circling placidly round on the
threshing-floors and a group of women were taking advantage of
the gustiness to winnow. Their bare, brown arms glistened above
the falling showers of golden grain, their unabashed smiling faces
showed against the clouds of golden chaff drifting behind them.

Jim Douglas looked at them for a moment, returned the salaam of


the men driving the oxen and forking the straw, then turned his
horse toward the cantonment again.

"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?"

His companion, following his look ahead, to where, in the far


distance, a faint cloud of dust, telling of many feet, hung on the
horizon, said suddenly, as if the sight brought remembrance: "By
George! Douglas, how steady the sepoys stood! I half expected a
row."

"Steadier than I should," remarked the other grimly. "Well, I hope


Smyth is satisfied. To return from leave and drive your regiment into
mutiny in twelve hours is a record performance."

His hearer, who was a civilian, gave a deprecating cough. "That's


a bit hard, surely. I happen to know that he heard while on leave
some story about a concerted rising later on. He may have done it
purposely, to force their hands."

Jim Douglas shrugged his shoulders. "Did he warn you what he


was about to do? Did he allow time to prepare others for his private
mutiny? My dear Ridgeway, it was put on official record two months
ago that an organized scheme for resistance existed in every
regiment between Calcutta and Peshawur; so Smyth might at least
have consulted the colonels of the other two regiments at Meerut.
As it is, the business has strained the loyalty of the most loyal to the
uttermost; and we deserve to suffer, we do indeed."

"You don't mince matters, certainly," said the civilian dryly.

"Why should anybody mince them? Why can't we admit boldly--


the C.-in-C. did it on the sly the other day--that the cartridges are
suspicious? that they leave the muzzle covered with a fat, like
tallow? Why don't we admit it was tallow at first. Why not, at any
rate, admit we are in a hole, instead of refusing to take the common
precaution of having an ammunition wagon loaded up for fear it
should be misconstrued into alarm? Is there no medium between
bribing children with lollipops and torturing them--keeping them on
the strain, under fire, as it were, for hours, watching their best
friends punished unjustly?"

"Unjustly?"

"Yes. To their minds unjustly. And you know what forcible injustice
means to children--and these are really children--simple, ignorant,
obstinate."

They had come back to cantonments again and were rapidly


overtaking the now empty tumbrils going home, for the parade was
over. Further down the road, raising a cloud of dust from their
shackled feet, the eighty-five were being marched jailward under a
native escort.

"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.

"Out a bit, eh?" he said dryly.

"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."

He repeated the remark with even greater fervor twelve hours


later, when, about midnight, he started on his return ride to Delhi.
For though he had spent the whole day in listening, he had scarcely
heard a word of blame for the scene which had roused him to wrath
that morning. The sepoys had gone about their duties as if nothing
had happened; and despite the undoubted presence of a lot of loose
characters in the bazaar, there had been no disturbance. He laughed
cynically to himself at the waste of a day which would have been
better spent in horse dealing. This, however, settled it. If this
intolerable tyranny failed to rouse action there could be no
immediate danger ahead. To a big cantonment like Meerut, the
biggest in Northern India, with two thousand British troops in it,
even the prospect of a rising was not serious; at Delhi, however,
where there were only native troops, it might have been different.
But now he felt that a handful of resolute men ought to be able to
hold their own anywhere against such aimless invertebrate
discontent. He felt a vague disappointment that it should be so, that
the pleasant cool of night should be so quiet, so peaceful. They were
a poor lot who could do nothing but talk!

As he rode through the station the mess-houses were still alight,


and the gay voices of the guests who had been dining at a large
bungalow, bowered in gardens, reached his ears distinctly.
"It's the Sabbath already," said one. "Ought to be in our beds!"

"Hooray! for a Europe morning," came a more boyish one


breaking into a carol, "of all the days within the week I dearly love---
-"

"Shut up, Fitz!" put in a third, "you'll wake the General!"

"What's the odds? He can sleep all day. I'm sure his buggy
charger needs a rest."

"Do shut up, Fitz! The Colonel will hear you."

"I don't care. It's Scriptural. Thou and thy ox and thy ass----"

"You promised to come to evening church, Mr. Fitzgerald,"


interrupted a reproachful feminine voice; "you said you would sing in
the choir."

"Did I? Then I'll come. It will wake me up for dinner; besides, I


shall sit next you."

The last words came nearer, softer. Mr. Fitzgerald was evidently
riding home beside someone's carriage.

Pleasant and peaceful indeed! that clank of a sentry, here and


there, only giving a greater sense of security. Not that it was
needed, for here, beyond cantonments, the houses of the clerks and
civilians lay as peaceful, as secure. In the veranda of one of them,
close to the road, a bearer was walking up and down crooning a
patient lullaby to the restless fair-haired child in his arms.

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.

Stagnant, featureless! A dead sea! A mere waste of waters


without form or void! Not even ready for a spirit to move over them;
for if that morning's work left them apathetic, the Moulvie of
Fyzabad himself need preach no voice of God. For this, surely--this
sense of injustice to others, must be the strongest motive, the surest
word to conjure with. That dull dead beat of iron upon the fetters of
others,--which he still seemed to hear,--the surest call to battle.

He paused in his thought, wondering if what he fancied he heard


was but an echo from memory or real sound! Real; undoubtedly. It
was the distant clang of the iron bells upon oxen. That meant that
he must be seven or eight miles out, halfway to the next stage, so
meeting the usual stream of night traffic toward Meerut. He passed
two or three strings of large, looming, half-seen wains without
drawing bridle, then pulled up almost involuntarily to a trot at the
curiously even tread of a drove of iron-shod oxen, and a low chanted
song from behind it. Bunjârah folk! The rough voice, the familiar
rhythm of the hoofs, reminded him of many a pleasant night-march
in their company.

"A good journey, brothers!" he called in the dialect. The answer


came unerringly, dark though it was.

"The Lord keep the Huzoor safe!"

It made him smile as he remembered that of course a lone man


trotting a horse along a highroad at night was bound to be alien in a
country where horses are ambled and travelers go in twos and
threes. So the rough, broad faces would be smiling over the surprise
of a sahib knowing the Bunjârah talk; unless, indeed, it happened to
be---- The possibility of its being the tanda he knew had not
occurred to him before. He pulled up and looked round. A breathless
shadow was at his stirrup, and he fancied he saw a shadow or two
further behind.

"The Huzoor has mistaken the road," came Tiddu's familiar creak.
"Meerut lies to the north."

Breathless as he was, there was the pompous mystery in his voice


which always prefaced an attempt to extort money. And Jim
Douglas, having no further use for the old scoundrel, did not intend
to give him any, so he simulated an utter lack of surprise.

"Hello, Tiddu!" he said. "I had an idea it might be you. So you


recognized my voice?"

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."

Tiddu looked round furtively. The other shadow, Jhungi or Bhungi,


or both, perhaps--the memory made Jim Douglas smile--had melted
away into the darkness. He and Tiddu were alone. The old man,
even so, reached up to whisper.

"'Tis the yellow fakir, Huzoor! He has come."

"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!"

"Speech that is more than speech," echoed Jim Douglas angrily,


then paused in his turn; the phrase reminded him, vaguely, of his
past thoughts.

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.

"Yea! Speech that is more than speech, though he is dumb.


Whence he comes none know, not even I, the Many-Faced. But I
can see him when he comes, Huzoor! The others, not unless he wills
to be seen. I saw him to-night. He passed me on a white horse not
half an hour agone, going Meerutward. Did not the Huzoor see him?
That is because he has learned from old Tiddu to make others see,
but not to see himself. But the old man will teach him this also if he
is in Meerut by dawn. If he is there by dawn he will see the yellow
fakir who brings the speech that brings more than speech."

The sing-song ceased; the Belooch was stepping briskly back


toward Meerut.

"You infernal old humbug!" began Jim Douglas.

"The Huzoor does not believe, of course," remarked Tiddu, in the


most matter-of-fact creak. "But Meerut is only eight miles off. His
other horse can wait; and if he does not see the yellow fakir there is
no need to open the purse-strings."

The Englishman looked at his half-seen companion admiringly. He


was the most consummate scoundrel! His blending of mystery and
purely commercial commonplace was perfect--almost irresistible.
There was no reason why he should go on; the groom, halfway, had
his usual orders to stay till his master came. For the rest, it would be
pleasant to renew the old pleasant memory--pleasant even to renew
his acquaintance with Tiddu's guile, which struck him afresh each
time he came across it.

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.

"Jhungi will take her to the rest-house, Huzoor, or Bhungi. It will


be safer so. I have a clean cotton quilt in the bundle, and the Huzoor
can have my shoes and rub his legs in the dust. That will do till
dawn."

He gave a jackal's cry, which was echoed from the darkness.

"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.

Five minutes after, with a certain unaccountable pleasure, he


found himself walking beside a laden bullock, one arm resting on its
broad back, his feet keeping step with the remittent clang of its bell.
A strange dreamy companionship, as he knew of old. And once more
the stars seemed, after a time, to twinkle in unison with the bell, he
seemed to forget thought, to forget everything save the peaceful
stillness around, and his own unresting peace.

So, he and the laden beast went on as one living, breathing


mortal, till the little shiver of wind came, which comes with the first
paling of the sky. It was one of those yellow dawns, serene,
cloudless, save for a puff or two of thin gray vapor low down on the
horizon, looking as if it were smoke from an unseen censer swinging
before the chariot of the Sun which heads the procession of the
hours. He was so absorbed in watching the yellow light grow to
those clouds no bigger than a man's hand; so lost in the strange
companionship with the laden beast bound to the wheel of Life and
Death as he was, yet asking no question of the future, that Tiddu's
hand and voice startled him.
"Huzoor!" he said. "The yellow fakir!"

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."

As he spoke, a handsome young fellow came swaggering down


the latter, on his way evidently to riotous living in the bazaar.
Suddenly he paused, his hand went up to his eyes as if the rising
sun were in them. Then he stepped across the road and dropped a
coin into the beggar's bowl. Tiddu nodded his head gravely.

"That man is wanted, Huzoor. That is why he saw. Mayhap he is


to give the word."

"The word?" echoed Jim Douglas. "You said he was dumb?"

"I meant the trooper, Huzoor. The fakir wanted him. To give the
word, mayhap. Someone must always give it."

Jim Douglas felt an odd thrill. He had never thought of that


before. Someone, of course, must always give the word, the speech
which brought more than speech. What would it be? Something
soul-stirring, no doubt; for Humanity had a theory that an angel
must trouble the waters and so give it a righteous cause for stepping
in to heal the evil.

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.

Jim Douglas laughed. The man was certainly a consummate liar;


there was never any possibility of catching him out.
CHAPTER VII.
THE WORD WENT FORTH.

The Procession of the Hours had a weary march of it between the


yellow sunrise and the yellow sunset of the 10th of May, 1857; for
the heavens were as brass, the air one flame of white heat. The
mud huts of the sepoy lines at Meerut looked and felt like bricks
baking in a kiln; yet the torpor which the remorseless glare of noon
brings even to native humanity was exchanged for a strange
restlessness. The doors stood open for the most part, and men
wandered in and out aimlessly, like swarming bees before the queen
appears. In the bazaar, in the city too, crowds drifted hither and
thither, thirstily, as if it were not the fast month of Rumzân, when
the Mohammedans are denied the solace of even a drop of water till
sundown. Drifted hither and thither, pausing to gather closer at a
hint of novelty, melting away again, restless as ever.

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?

No one else, however, among the masters troubled himself to find


a cause for the restlessness; no one even knew of it. To begin with,
it was a Sunday, so that even the bond of a common labor was
slackened between the dark faces and the light. Then a mile or more
of waste deserted land and dry watercourse lay on either side of the
broad white road which split the cantonment into halves. So that the
North knew nothing of what was going on in the South, and while
men were swarming like bees in the sun on one side, on the other
they were shut up in barracks and bungalows gasping with the heat,
longing for the sun to set, and thanking their stars when the
chaplain's memo came round to say that the evening service had
been postponed for half an hour to allow the seething, glowing air to
cool a little.

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."

The postscript was added after rereading the rest with an


uncomfortable remembrance that it was the last letter he meant to
write to her. Then he threw it ready for the post beside the others,
and lay down feeling that he had done his duty. And as he dozed off
his own simile haunted him. From start to finish! How few men rode
straight all the way; and the poor beggars who came to grief over
the last fence weren't so far behind those who came in for the
clapping. It was the finish that did it; that was the win or the lose.
But he would run straight with little Allie--straight as a die! So he lost
consciousness in a glow of virtuous content with the future, and
joined the whole of the northern half of Meerut in their noontide
slumbers; for the future outlook, if not exactly satisfying, was not
sufficiently dubious to keep it awake.

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.

"And we of Delhi will smite also," interrupted the wearer of a


rakish Moghul cap impatiently. "We will smite for the Queen."

"The Queen?" echoed an older man in the same dress. "What


hath the Sheeah woman to do with the race of Timoor?"
"Peace! peace! brothers," put in the agent with authority. "These
times are not for petty squabbles. Let who be the heir, the King must
reign."

A murmur of assent rose; but it was broken in upon by a


dissentient voice from a group of troopers at the door.

"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."

"There be not many of us here," muttered a voice from a dark


corner; "and maybe we could hold our own against the lot of you."
It was Soma's, and the man beside him frowned. But the agent who
knew every petty jealousy, every private quarrel of regiment with
regiment, went on remorselessly. "Let the 3d swagger if it choose.
The Rajpoots and Brahmins know how to obey the stars. The 31st is
the auspicious day. That is the word. The word of the King, of the
Brahmins, of India, of God!"

"The 31st! Then slay and spare not! It is jehad! Deen! Deen!
Futteh Mohammed!" said the Ghâzee.

The cry, though a mere whisper, electrified the Mohammedans,


and an older man in the group of dissentients at the door muttered
that he could hold his troop--if others who had risen to favor quicker
than he--could hold theirs.

"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.

"Rescue them if thou wilt, Havildar-jee," sneered the agent. "But


the man who risks our plot will be held traitor by the Council. And
the men of the 11th," he added sharply, turning to the corner
whence Soma's voice had come, "may remember that also. They
have had the audacity to stipulate for their Colonel's life."

"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.

"Pay thy Colonel's journey home if thou likest, Rajpoot-jee," he


said with a sneer. "Ay! and give him pension, too! All we want is to
get rid of them. And there will be plenty of loot left when the
pension is paid, for it is to be each man for himself when the time
comes. Not share and share alike with every coward who will not
risk his life in looting, as it is with the Sirkar."
It was a deft red-herring to these born mercenaries, and no more
was said. But as the meeting dispersed by twos and threes to avoid
notice, the agent stood at the door giving the word in a final
whisper:

"Patience till the 31st."

"Willst take a seat in our carriage, Ghâzee-jee," said a fat native


officer as he passed out. "'Tis at thy service since thou goest to Delhi
and we must return to-night. God knows we have done enough to
damn us at Meerut over this court-martial! But what would you? If
we had not given the verdict for the Huzoors there would have been
more of us in jail. So we bide our time like the rest. And to-morrow
there is the parade to hear the sentence on the martyrs at
Barrackpore. Do the sahibs think us cowards that they drive us so?
God smite their souls to hell!"

"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.

"Well, come if thou likest," continued the native officer. "That


camel of thine yonder is lame, and we have room. 'Twas Erlton
sahib's dâk by rights, but he goes not; so we got it cheap instead of
an ekka."

"Erlton sahib's!" echoed the fanatic, clutching at his sword. "Ay!


Ay!" he went on half to himself. "I knew he was at Delhi, and the
mem who laughed, and the other mem who would not listen. Nay!
Soubadar-jee! I travel in no carriage of Erlton sahib's. My camel will
serve me."

"'Tis the vehicle of saints," sneered the owner of the rakish


Moghul cap. "Verily, when I saw thee mounted on it, Ghâzee-jee, I
deemed thee the Lord Ali."
"Peace! scoffer," interrupted the fanatic, "lest I mistake thee for
an infidel."

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."

There was a roar of laughter from the group.

Soma gave a beast-like cry, looked as though he were about to


spring, then--recognizing his own helplessness--flung himself away
from all companionship and walked home moodily. They had driven
him too far; he would not stand it. If that tale was spread abroad,
he would side with the Huzoors who did not believe such things--
with the Colonel who understood, like the Colonel before him who
had gone home on pension; for the 11th had a cult of their officers.
And these fools, his countrymen, thought to make him a butcher by
threats; sought to make him take revenge for what deserved
revenge. For it was the Sirkar's fault--it was the Sirkar's fault.

In truth a strange conflict was going on in this man's mind, as it


was in many another such as his, between inherited traditions,
making alike for loyalty and disloyalty. There was the knowledge of
his forbears' pride in their victories, in their sahibs who had led them
to victory, and the knowledge of their pride in the veriest jot or tittle
of ceremonial law. A dull, painful amaze filled him that these two
broad facts should be in conflict; that those, whom in a way he felt
to be part of his life, should be in league against him. All the more
reason, that, for showing them who were the better men; for
standing up fairly to a fair fight. By all the delights of Swargal he
would like to stand up fair, even to the master--the man who, in his
presence, had shot three tigers on foot in half an hour--the demi-
god of his hunting yarns for years.

And then, suddenly, he remembered that this hero of his might be


shot like a dog on the 31st at Delhi--would be shot, since he was
certain to be in the front of anything. Soma's heat-fevered, hemp-
drugged brain seized on the thought fiercely, confusedly. That must
not be! The master, at any rate, must be warned. He would go down
when the sun set, and see if he were still where he had been the
day before; and if not?--Why! then it must be two days leave to
Delhi! He was not going to butcher the master for all the sweepers'
brooms in the world. Fools! those others, to think to drive him,
Soma, Chundrabansi! So he flung himself on his string bed to sleep
till the sunset came, and the tyranny of heat be overpast.

But there was one, close by in the cantonment bazaar, who


waited for sunset with no desire for it to bring coolness. She meant
it to bring heat instead. And this was Nargeeza the courtesan. She
was past the prime of everything save vice, a woman who, once all-
powerful, could not hope for many more lovers; and hers, a man
rich beyond most soldiers, lay in jail for ten years. No wonder, then,
that as she lay half-torpid among a heap of tawdry finery in the
biggest house of the lane set apart by regulation for such as she,
there was all the venom of a snake in her drowsy brain. The air of
the low room was deadly with a scent of musk and roses and
orange-blossom-oil. The half-dozen girls and women who lounged in
it, or in the balcony, were half undressed, their bare brown arms
flung carelessly upon dirty mats and torn quilts. Their harvest time
was not yet; that would come later when sunsetting brought the
men from the lines. This, then, was the time for sleep. But
Nargeeza, recognized head of the recognized regimental women, sat
up suddenly and said sharply:

"Thou didst not tell me, Nasiban, what Gulâbi said. Is she of us?"

A drowsy lump of a girl stirred, yawned, and answered sullenly,


"Yea! Yea! she is of us. She claims our right to kiss no cowards--no
cowards."

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."

He gave a shrug of his shoulders as he turned away to get ready


for his start. So that was it; and even Kate Erlton had not benefited
by his sacrifice. No one had benefited. There had been no chance
for any of them. "Come!" That ended Kate Erlton's hope of
concealment, the Major's career. "No!" That ended his own vague
ambitions. Still, it was a strange chance in itself that those two
laconic renunciations should go the same day by the same hand. No
stranger telegrams, he thought, could have left Meerut, or were
likely to leave it that night.

He was wrong, however. An hour or two later, the strangest


telegram that ever came as sole warning to an Empire that its very
foundation was attacked, left Meerut for Agra; sent by the
postmaster's niece.

"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.

"We of the bazaar kiss no cowards," she said derisively. "Where


are your comrades?"

The man to whom she said it, a young dissolute-faced trooper,


dressed in the loose rakish muslins beloved of his class--the very
man, perchance, who had gone cityward that morning, and dropped
an alms into the yellow fakir's bowl--stood for a second in the
stifling, maddening atmosphere of musk and rose and orange-
blossom; stood before all those insolent allurements, balked in his
passion, checked in his desires. Then, with an oath, he dashed from
her insulting charms; dashed into the street with a cry:

"To horse! To horse, brothers! To the jail! to our comrades!"

The word had been spoken. The speech which brings more than
speech, had come from the painted lips of a harlot.

The first clang of the church bell--which the chaplain had


forgotten to postpone--came faintly audible across the dusty plain,
making other men pause and look at each other. Why not? It was
the hour of prayer--the appointed time. Their comrades could be
easily rescued--there was but a native guard at the jail. And hark!
from another pair of painted derisive lips came the same retort,
flung from a balcony.
"Trra! We of the bazaar kiss no cowards!"

"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.

"To the rescue! To the rescue!"

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."

He thought the voice of a man loved and trusted by one


regiment, a man who could speak to his sepoys without an
interpreter, might have power to steady another.
Jai bahâduri! (Victory to courage!) muttered Soma under his
breath as he watched his Colonel canter quietly into danger. And his
finger hungered on that hot May evening for the cool of the trigger
which was denied him.

Jai bahâduri! A murmur seemed to run through the ranks, they


dressed themselves firmer, squarer. Colonel Finnis, glancing back,
saw a sight to gladden any commandant's heart. A regiment steady
as a rock, drawn up as for parade, absolutely in hand despite that
strange new sound in the air. The sound which above all others gets
into men's brains like new wine. The sound of a file upon fetters--the
sound of escape, of freedom, of license! It had been rising
unchecked for half an hour from the lines of the 3d, whither the
martyrs had been brought in triumph. It was rising now from the
bazaar, the city, from every quiet corner where a prisoner might
pause to hack and hammer at his leg-irons with the first tool he
could find.

What was one man's voice against this sound, strengthened as it


was by the cry of a trooper galloping madly from the north shouting
that the English were in sight? What more likely? Had not ample
time passed for the whole British garrison to be coming with fixed
bayonets and a whoop, to make short work of unarmed men who
had not made up their minds?

That must be no longer!

"Quick! brothers. Quick! Kill! Kill! Down with the officers! Shoot
ere the white faces come!"

It was a sudden wild yell of terror, of courage, of sheer cruelty. It


drowned the scream of the Colonel's horse as it staggered under
him. It drowned his steady appealing voice, his faint sob, as he
threw up his hands at the next shot, and fell, the first victim to the
Great Revolt.
It drowned something else also. It drowned Soma's groan of wild,
half-stupefied, helpless rage as he saw his Colonel fall,--the sahib
who had led him to victory,--the sahib whom he loved, whom he was
pledged to save. And his groan was echoed by many another brave
man in those ranks, thus brought face to face suddenly with the
necessity for decision.

"Steady, men, steady!"

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.

"Steady, men! Steady, for God's sake!"

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.

"To arms, brothers! Quick! fire! fire!"

Upon whom?[2] God knows! Not on their officers, for these were
already being hustled to the rear, hustled into safety.

"Quick, brothers, quick! Kill! Kill!"

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.

So the wave surged on, to what end it scarcely knew, leaving


behind it groups of sullen, startled faces.

"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?"

"Why?" echoed a scornful voice from the gathering clusters of


undecided men, waiting, with growing fear, hope, despair, or
triumph, for what was to come next: waiting, briefly, for the master
to come, or not to come. "Why? because they were afraid of us;
because their time is past, baba jee. Let them go!"

Let them go. Incomprehensible suggestion to that brave worn stiff


in the master's service; so, with a great numb ache in an old heart,
an old body strode away, elbowing younger ones from its path
savagely.

"Old Dhurma hath grown milksop," jeered one spectator; "that is


with doing dry-nurse to his Captain's babies."

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!"

The cry, boastful, jeering, came from a sepoy in the uniform of


the 20th, who, with a face ablaze with mad exultation, forced his
way forward. There was something in his tone which seemed to
send a shiver of fresh excitement through his comrades, for they
paused in their strange, aimless tumult, paused and listened to the
jeers, the reproaches.

"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.

For it was a strange crowd indeed; most of it powerless for good


or ill, sheep without a shepherd, wandering after the rabble of
escaped convicts and the refuse of bazaars as they plundered and
fired the houses. Joining in in the license helplessly, drifting
inevitably to violence, so that some looked on curiously,
unconcernedly, while others, maddened by the smell of blood, the
sounds of murder, dragged helpless Englishmen and Englishwomen
from their carriages and did them to death savagely.

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.

Where was he? He should have come hours ago, irresistible,


overwhelming. But there was no sign. Not a hint of resistance, save
every now and again a clatter of hoofs through the darkness, an
alien voice calling "Mâro! Mâro!" to those behind him, and a fierce
howl of an echo, "Mâro! Mâro! Mâ-roh!" from the faithful troop. For
Captain Craigie, finding none to help him, had changed his cry. It
was "kill, kill, kill" now. And the faithful troop obeyed orders.
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