Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
100% found this document useful (4 votes)
19 views

JavaScript Data Structures and Algorithms An Introduction to Understanding and Implementing Core Data Structure and Algorithm Fundamentals 1st Editon by Sammie Bae ISBN 1484239873 9781484239872 - The ebook in PDF and DOCX formats is ready for download

The document provides information about various eBooks on data structures and algorithms available for instant download at ebookball.com. It includes titles such as 'JavaScript Data Structures and Algorithms' by Sammie Bae and 'Data Structures and Algorithms Made Easy' by Careermonk Publications, along with their respective links and ISBNs. The content emphasizes accessibility and the ability to read on any device.

Uploaded by

elmodicha
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (4 votes)
19 views

JavaScript Data Structures and Algorithms An Introduction to Understanding and Implementing Core Data Structure and Algorithm Fundamentals 1st Editon by Sammie Bae ISBN 1484239873 9781484239872 - The ebook in PDF and DOCX formats is ready for download

The document provides information about various eBooks on data structures and algorithms available for instant download at ebookball.com. It includes titles such as 'JavaScript Data Structures and Algorithms' by Sammie Bae and 'Data Structures and Algorithms Made Easy' by Careermonk Publications, along with their respective links and ISBNs. The content emphasizes accessibility and the ability to read on any device.

Uploaded by

elmodicha
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 91

Instant Ebook Access, One Click Away – Begin at ebookball.

com

JavaScript Data Structures and Algorithms An


Introduction to Understanding and Implementing
Core Data Structure and Algorithm Fundamentals 1st
Editon by Sammie Bae ISBN 1484239873
9781484239872
https://ebookball.com/product/javascript-data-structures-
and-algorithms-an-introduction-to-understanding-and-
implementing-core-data-structure-and-algorithm-
fundamentals-1st-editon-by-sammie-bae-
isbn-1484239873-9781484239872-15798/

OR CLICK BUTTON

DOWLOAD EBOOK

Get Instant Ebook Downloads – Browse at https://ebookball.com


Your digital treasures (PDF, ePub, MOBI) await
Download instantly and pick your perfect format...

Read anywhere, anytime, on any device!

A Practical Introduction to Data Structures And Algorithm


Analysis 3rd Edition by Clifford Shaffer

https://ebookball.com/product/a-practical-introduction-to-data-
structures-and-algorithm-analysis-3rd-edition-by-clifford-
shaffer-15310/

ebookball.com

Data Structures and Algorithms Made Easy Data Structure


and Algorithmic Puzzles 5th Edition by Careermonk
Publications, Narasimha Karumanchi ISBN 9788193245279

https://ebookball.com/product/data-structures-and-algorithms-made-
easy-data-structure-and-algorithmic-puzzles-5th-edition-by-careermonk-
publications-narasimha-karumanchi-isbn-9788193245279-15800/

ebookball.com

Data Structures and Algorithms 1st Edition by Alfred Aho


ISBN 0201000237 9780201000238

https://ebookball.com/product/data-structures-and-algorithms-1st-
edition-by-alfred-aho-isbn-0201000237-9780201000238-25072/

ebookball.com

Data Structures and Algorithm Analysis in JavaTM 3rd


edition by Mark Weiss 9780133465013 0133465012

https://ebookball.com/product/data-structures-and-algorithm-analysis-
in-javatm-3rd-edition-by-mark-weiss-9780133465013-0133465012-18710/

ebookball.com
Data Structures And Algorithm Analysis in C 4th Edition by
Mark Weiss 013284737X 9780132847377

https://ebookball.com/product/data-structures-and-algorithm-analysis-
in-c-4th-edition-by-mark-weiss-013284737x-9780132847377-15292/

ebookball.com

Data Structures and Algorithms in Java 1st Edition by


Peter Drake ISBN 0131469142 9780131469143

https://ebookball.com/product/data-structures-and-algorithms-in-
java-1st-edition-by-peter-drake-isbn-0131469142-9780131469143-12422/

ebookball.com

Data Structures and Algorithms in C 1st edition by Adam


Drozdek ASIN B002WLXMBY

https://ebookball.com/product/data-structures-and-algorithms-in-c-1st-
edition-by-adam-drozdek-asin-b002wlxmby-25076/

ebookball.com

Data Structures and Algorithm Analysis in C++ 3rd edition


by Clifford Shaffer ISBN 048648582X 978-0486485829

https://ebookball.com/product/data-structures-and-algorithm-analysis-
in-c-3rd-edition-by-clifford-shaffer-
isbn-048648582x-978-0486485829-16486/

ebookball.com

Data Structures Algorithms and Applications in C++ 1st


edition by Adam Drozdek ISBN 1133608426 9781133608424

https://ebookball.com/product/data-structures-algorithms-and-
applications-in-c-1st-edition-by-adam-drozdek-
isbn-1133608426-9781133608424-17250/

ebookball.com
JavaScript Data
Structures and
Algorithms
An Introduction to Understanding and
Implementing Core Data Structure and
Algorithm Fundamentals

Sammie Bae
JavaScript Data Structures
and Algorithms
An Introduction to Understanding
and Implementing Core Data
Structure and Algorithm
Fundamentals

Sammie Bae
JavaScript Data Structures and Algorithms
Sammie Bae
Hamilton, ON, Canada

ISBN-13 (pbk): 978-1-4842-3987-2 ISBN-13 (electronic): 978-1-4842-3988-9


https://doi.org/10.1007/978-1-4842-3988-9
Library of Congress Control Number: 2019930417

Copyright © 2019 by Sammie Bae


This work is subject to copyright. All rights are reserved by the Publisher, whether the whole or part of the
material is concerned, specifically the rights of translation, reprinting, reuse of illustrations, recitation,
broadcasting, reproduction on microfilms or in any other physical way, and transmission or information
storage and retrieval, electronic adaptation, computer software, or by similar or dissimilar methodology now
known or hereafter developed.
Trademarked names, logos, and images may appear in this book. Rather than use a trademark symbol with
every occurrence of a trademarked name, logo, or image we use the names, logos, and images only in an
editorial fashion and to the benefit of the trademark owner, with no intention of infringement of the
trademark.
The use in this publication of trade names, trademarks, service marks, and similar terms, even if they are not
identified as such, is not to be taken as an expression of opinion as to whether or not they are subject to
proprietary rights.
While the advice and information in this book are believed to be true and accurate at the date of publication,
neither the authors nor the editors nor the publisher can accept any legal responsibility for any errors or
omissions that may be made. The publisher makes no warranty, express or implied, with respect to the
material contained herein.
Managing Director, Apress Media LLC: Welmoed Spahr
Acquisitions Editor: Louise Corrigan
Development Editor: Chris Nelson
Coordinating Editor: Nancy Chen
Cover designed by eStudioCalamar
Distributed to the book trade worldwide by Springer Science+Business Media New York, 233 Spring Street,
6th Floor, New York, NY 10013. Phone 1-800-SPRINGER, fax (201) 348-4505, e-mail orders-ny@springer-
sbm.com, or visit www.springeronline.com. Apress Media, LLC is a California LLC and the sole member
(owner) is Springer Science + Business Media Finance Inc (SSBM Finance Inc). SSBM Finance Inc is a
Delaware corporation.
For information on translations, please e-mail rights@apress.com, or visit www.apress.com/
rights-permissions.
Apress titles may be purchased in bulk for academic, corporate, or promotional use. eBook versions and
licenses are also available for most titles. For more information, reference our Print and eBook Bulk Sales
web page at www.apress.com/bulk-sales.
Any source code or other supplementary material referenced by the author in this book is available to
readers on GitHub via the book’s product page, located at www.apress.com/9781484239872. For more
detailed information, please visit www.apress.com/source-code.
Printed on acid-free paper
This book is dedicated to Dr. Hamid R. Tizhoosh for inspiring
me in my studies and to my mother, Min Kyoung Seo, for her
kindness and support.
Table of Contents
About the Author �����������������������������������������������������������������������������������������������������xv

About the Technical Reviewer �������������������������������������������������������������������������������xvii

Acknowledgments ��������������������������������������������������������������������������������������������������xix

Introduction ������������������������������������������������������������������������������������������������������������xxi

Chapter 1: Big-O Notation ����������������������������������������������������������������������������������������� 1


Big-O Notation Primer ������������������������������������������������������������������������������������������������������������������� 1
Common Examples ������������������������������������������������������������������������������������������������������������������ 2
Rules of Big-O Notation����������������������������������������������������������������������������������������������������������������� 4
Coefficient Rule: “Get Rid of Constants”���������������������������������������������������������������������������������� 5
Sum Rule: “Add Big-Os Up” ����������������������������������������������������������������������������������������������������� 6
Product Rule: “Multiply Big-Os” ���������������������������������������������������������������������������������������������� 7
Polynomial Rule: “Big-O to the Power of k”����������������������������������������������������������������������������� 8
Summary��������������������������������������������������������������������������������������������������������������������������������������� 8
Exercises ��������������������������������������������������������������������������������������������������������������������������������������� 9
Answers��������������������������������������������������������������������������������������������������������������������������������� 11

Chapter 2: JavaScript: Unique Parts ����������������������������������������������������������������������� 13


JavaScript Scope ������������������������������������������������������������������������������������������������������������������������ 13
Global Declaration: Global Scope������������������������������������������������������������������������������������������� 13
Declaration with var: Functional Scope ��������������������������������������������������������������������������������� 13
Declaration with let: Block Scope ������������������������������������������������������������������������������������������ 15

v
Table of Contents

Equality and Types���������������������������������������������������������������������������������������������������������������������� 16


Variable Types������������������������������������������������������������������������������������������������������������������������ 16
Truthy/Falsey Check�������������������������������������������������������������������������������������������������������������� 17
=== vs ==���������������������������������������������������������������������������������������������������������������������������� 18
Objects���������������������������������������������������������������������������������������������������������������������������������� 18
Summary������������������������������������������������������������������������������������������������������������������������������������ 20

Chapter 3: JavaScript Numbers������������������������������������������������������������������������������ 21


Number System�������������������������������������������������������������������������������������������������������������������������� 21
JavaScript Number Object���������������������������������������������������������������������������������������������������������� 23
Integer Rounding������������������������������������������������������������������������������������������������������������������� 23
Number.EPSILON������������������������������������������������������������������������������������������������������������������� 24
Maximums����������������������������������������������������������������������������������������������������������������������������� 24
Minimums������������������������������������������������������������������������������������������������������������������������������ 25
Size Summary����������������������������������������������������������������������������������������������������������������������� 26
Number Algorithms���������������������������������������������������������������������������������������������������������������� 26
Prime Factorization��������������������������������������������������������������������������������������������������������������� 28
Random Number Generator�������������������������������������������������������������������������������������������������������� 29
Exercises������������������������������������������������������������������������������������������������������������������������������������� 29
Summary������������������������������������������������������������������������������������������������������������������������������������ 34

Chapter 4: JavaScript Strings��������������������������������������������������������������������������������� 35


JavaScript String Primitive��������������������������������������������������������������������������������������������������������� 35
String Access������������������������������������������������������������������������������������������������������������������������� 35
String Comparison����������������������������������������������������������������������������������������������������������������� 36
String Search������������������������������������������������������������������������������������������������������������������������� 36
String Decomposition������������������������������������������������������������������������������������������������������������ 38
String Replace����������������������������������������������������������������������������������������������������������������������� 38
Regular Expressions������������������������������������������������������������������������������������������������������������������� 38
Basic Regex��������������������������������������������������������������������������������������������������������������������������� 39
Commonly Used Regexes������������������������������������������������������������������������������������������������������ 39
Encoding������������������������������������������������������������������������������������������������������������������������������������� 41
Base64 Encoding������������������������������������������������������������������������������������������������������������������� 42

vi
Table of Contents

String Shortening������������������������������������������������������������������������������������������������������������������������ 43
Encryption����������������������������������������������������������������������������������������������������������������������������������� 45
RSA Encryption���������������������������������������������������������������������������������������������������������������������� 46
Summary������������������������������������������������������������������������������������������������������������������������������� 50

Chapter 5: JavaScript Arrays��������������������������������������������������������������������������������� 53


Introducing Arrays����������������������������������������������������������������������������������������������������������������������� 53
Insertion�������������������������������������������������������������������������������������������������������������������������������� 53
Deletion��������������������������������������������������������������������������������������������������������������������������������� 54
Access����������������������������������������������������������������������������������������������������������������������������������� 54
Iteration��������������������������������������������������������������������������������������������������������������������������������������� 54
for (Variables; Condition; Modification)��������������������������������������������������������������������������������� 55
for ( in )���������������������������������������������������������������������������������������������������������������������������������� 56
for ( of )���������������������������������������������������������������������������������������������������������������������������������� 56
forEach( )�������������������������������������������������������������������������������������������������������������������������������� 56
Helper Functions������������������������������������������������������������������������������������������������������������������������� 57
.slice(begin,end)�������������������������������������������������������������������������������������������������������������������� 57
.splice(begin,size,element1,element2…)������������������������������������������������������������������������������ 58
.concat()��������������������������������������������������������������������������������������������������������������������������������� 59
.length Property��������������������������������������������������������������������������������������������������������������������� 59
Spread Operator�������������������������������������������������������������������������������������������������������������������� 60
Exercises������������������������������������������������������������������������������������������������������������������������������������� 60
JavaScript Functional Array Methods����������������������������������������������������������������������������������������� 67
Map��������������������������������������������������������������������������������������������������������������������������������������� 67
Filter�������������������������������������������������������������������������������������������������������������������������������������� 68
Reduce���������������������������������������������������������������������������������������������������������������������������������� 68
Multidimensional Arrays������������������������������������������������������������������������������������������������������������� 68
Exercises������������������������������������������������������������������������������������������������������������������������������������� 71
Summary������������������������������������������������������������������������������������������������������������������������������������ 81

vii
Table of Contents

Chapter 6: JavaScript Objects�������������������������������������������������������������������������������� 83


JavaScript Object Property��������������������������������������������������������������������������������������������������������� 83
Prototypal Inheritance����������������������������������������������������������������������������������������������������������������� 84
Constructor and Variables����������������������������������������������������������������������������������������������������������� 85
Summary������������������������������������������������������������������������������������������������������������������������������������ 86
Exercises������������������������������������������������������������������������������������������������������������������������������������� 87

Chapter 7: JavaScript Memory Management��������������������������������������������������������� 89


Memory Leaks���������������������������������������������������������������������������������������������������������������������������� 89
Reference to an Object���������������������������������������������������������������������������������������������������������� 89
Leaking DOM������������������������������������������������������������������������������������������������������������������������� 90
Global window Object������������������������������������������������������������������������������������������������������������ 91
Limiting Object References��������������������������������������������������������������������������������������������������� 92
The delete Operator��������������������������������������������������������������������������������������������������������������� 92
Summary������������������������������������������������������������������������������������������������������������������������������������ 93
Exercises������������������������������������������������������������������������������������������������������������������������������������� 93

Chapter 8: Recursion���������������������������������������������������������������������������������������������� 99
Introducing Recursion����������������������������������������������������������������������������������������������������������������� 99
Rules of Recursion�������������������������������������������������������������������������������������������������������������������� 100
Base Case���������������������������������������������������������������������������������������������������������������������������� 100
Divide-and-Conquer Method����������������������������������������������������������������������������������������������� 101
Classic Example: Fibonacci Sequence�������������������������������������������������������������������������������� 101
Fibonacci Sequence: Tail Recursion������������������������������������������������������������������������������������ 102
Pascal’s Triangle������������������������������������������������������������������������������������������������������������������ 103
Big-O for Recursion������������������������������������������������������������������������������������������������������������������� 105
Recurrence Relations���������������������������������������������������������������������������������������������������������� 105
Master Theorem������������������������������������������������������������������������������������������������������������������ 106
Recursive Call Stack Memory��������������������������������������������������������������������������������������������������� 107
Summary���������������������������������������������������������������������������������������������������������������������������������� 109
Exercises����������������������������������������������������������������������������������������������������������������������������������� 109

viii
Table of Contents

Chapter 9: Sets����������������������������������������������������������������������������������������������������� 117


Introducing Sets������������������������������������������������������������������������������������������������������������������������ 117
Set Operations�������������������������������������������������������������������������������������������������������������������������� 117
Insertion������������������������������������������������������������������������������������������������������������������������������ 118
Deletion������������������������������������������������������������������������������������������������������������������������������� 118
Contains������������������������������������������������������������������������������������������������������������������������������� 118
Other Utility Functions�������������������������������������������������������������������������������������������������������������� 119
Intersection�������������������������������������������������������������������������������������������������������������������������� 119
isSuperSet��������������������������������������������������������������������������������������������������������������������������� 119
Union����������������������������������������������������������������������������������������������������������������������������������� 120
Difference���������������������������������������������������������������������������������������������������������������������������� 120
Summary���������������������������������������������������������������������������������������������������������������������������������� 121
Exercises����������������������������������������������������������������������������������������������������������������������������������� 122

Chapter 10: Searching and Sorting���������������������������������������������������������������������� 125


Searching���������������������������������������������������������������������������������������������������������������������������������� 125
Linear Search���������������������������������������������������������������������������������������������������������������������� 125
Binary Search���������������������������������������������������������������������������������������������������������������������� 127
Sorting�������������������������������������������������������������������������������������������������������������������������������������� 129
Bubble Sort�������������������������������������������������������������������������������������������������������������������������� 129
Selection Sort���������������������������������������������������������������������������������������������������������������������� 131
Insertion Sort����������������������������������������������������������������������������������������������������������������������� 132
Quicksort����������������������������������������������������������������������������������������������������������������������������� 134
Quickselect�������������������������������������������������������������������������������������������������������������������������� 137
Mergesort���������������������������������������������������������������������������������������������������������������������������� 138
Count Sort���������������������������������������������������������������������������������������������������������������������������� 140
JavaScript’s Built-in Sort����������������������������������������������������������������������������������������������������� 141
Summary���������������������������������������������������������������������������������������������������������������������������������� 142
Exercises����������������������������������������������������������������������������������������������������������������������������������� 143

ix
Table of Contents

Chapter 11: Hash Tables��������������������������������������������������������������������������������������� 151


Introducing Hash Tables������������������������������������������������������������������������������������������������������������ 151
Hashing Techniques������������������������������������������������������������������������������������������������������������������ 152
Prime Number Hashing������������������������������������������������������������������������������������������������������� 152
Probing�������������������������������������������������������������������������������������������������������������������������������� 154
Rehashing/Double-Hashing������������������������������������������������������������������������������������������������� 155
Hash Table Implementation������������������������������������������������������������������������������������������������������� 156
Using Linear Probing����������������������������������������������������������������������������������������������������������� 156
Using Quadratic Probing������������������������������������������������������������������������������������������������������ 158
Using Double-Hashing with Linear Probing������������������������������������������������������������������������� 160
Summary���������������������������������������������������������������������������������������������������������������������������������� 161

Chapter 12: Stacks and Queues���������������������������������������������������������������������������� 163


Stacks��������������������������������������������������������������������������������������������������������������������������������������� 163
Peek������������������������������������������������������������������������������������������������������������������������������������� 165
Insertion������������������������������������������������������������������������������������������������������������������������������ 165
Deletion������������������������������������������������������������������������������������������������������������������������������� 166
Access��������������������������������������������������������������������������������������������������������������������������������� 166
Search��������������������������������������������������������������������������������������������������������������������������������� 167
Queues�������������������������������������������������������������������������������������������������������������������������������������� 167
Peek������������������������������������������������������������������������������������������������������������������������������������� 169
Insertion������������������������������������������������������������������������������������������������������������������������������ 169
Deletion������������������������������������������������������������������������������������������������������������������������������� 169
Access��������������������������������������������������������������������������������������������������������������������������������� 170
Search��������������������������������������������������������������������������������������������������������������������������������� 171
Summary���������������������������������������������������������������������������������������������������������������������������������� 171
Exercises����������������������������������������������������������������������������������������������������������������������������������� 172

Chapter 13: Linked Lists��������������������������������������������������������������������������������������� 179


Singly Linked Lists�������������������������������������������������������������������������������������������������������������������� 179
Insertion������������������������������������������������������������������������������������������������������������������������������ 180
Deletion by Value����������������������������������������������������������������������������������������������������������������� 181

x
Table of Contents

Deletion at the Head������������������������������������������������������������������������������������������������������������ 182


Search��������������������������������������������������������������������������������������������������������������������������������� 183
Doubly Linked Lists������������������������������������������������������������������������������������������������������������������� 184
Insertion at the Head����������������������������������������������������������������������������������������������������������� 185
Insertion at the Tail�������������������������������������������������������������������������������������������������������������� 185
Deletion at the Head������������������������������������������������������������������������������������������������������������ 186
Deletion at the Tail��������������������������������������������������������������������������������������������������������������� 187
Search��������������������������������������������������������������������������������������������������������������������������������� 188
Summary���������������������������������������������������������������������������������������������������������������������������������� 189
Exercises����������������������������������������������������������������������������������������������������������������������������������� 190

Chapter 14: Caching��������������������������������������������������������������������������������������������� 193


Understanding Caching������������������������������������������������������������������������������������������������������������� 193
Least Frequently Used Caching������������������������������������������������������������������������������������������������� 194
Least Recently Used Caching���������������������������������������������������������������������������������������������������� 199
Summary���������������������������������������������������������������������������������������������������������������������������������� 203

Chapter 15: Trees�������������������������������������������������������������������������������������������������� 205


General Tree Structure�������������������������������������������������������������������������������������������������������������� 205
Binary Trees������������������������������������������������������������������������������������������������������������������������������ 206
Tree Traversal���������������������������������������������������������������������������������������������������������������������������� 207
Pre-order Traversal�������������������������������������������������������������������������������������������������������������� 207
In-Order Traversal���������������������������������������������������������������������������������������������������������������� 209
Post-order Traversal������������������������������������������������������������������������������������������������������������ 211
Level-Order Traversal���������������������������������������������������������������������������������������������������������� 212
Tree Traversal Summary������������������������������������������������������������������������������������������������������ 214
Binary Search Trees������������������������������������������������������������������������������������������������������������������ 214
Insertion������������������������������������������������������������������������������������������������������������������������������ 216
Deletion������������������������������������������������������������������������������������������������������������������������������� 218
Search��������������������������������������������������������������������������������������������������������������������������������� 220

xi
Table of Contents

AVL Trees����������������������������������������������������������������������������������������������������������������������������������� 221


Single Rotation�������������������������������������������������������������������������������������������������������������������� 221
Double Rotation������������������������������������������������������������������������������������������������������������������� 225
Balancing the Tree��������������������������������������������������������������������������������������������������������������� 228
Insertion������������������������������������������������������������������������������������������������������������������������������ 229
Putting It All Together: AVL Tree Example����������������������������������������������������������������������������� 231
Summary���������������������������������������������������������������������������������������������������������������������������������� 234
Exercises����������������������������������������������������������������������������������������������������������������������������������� 234

Chapter 16: Heaps������������������������������������������������������������������������������������������������ 245


Understanding Heaps���������������������������������������������������������������������������������������������������������������� 245
Max-Heap���������������������������������������������������������������������������������������������������������������������������� 246
Min-Heap����������������������������������������������������������������������������������������������������������������������������� 247
Binary Heap Array Index Structure�������������������������������������������������������������������������������������������� 248
Percolation: Bubbling Up and Down������������������������������������������������������������������������������������ 250
Implementing Percolation��������������������������������������������������������������������������������������������������� 253
Max-Heap Example������������������������������������������������������������������������������������������������������������� 254
Min-Heap Complete Implementation���������������������������������������������������������������������������������������� 258
Max-Heap Complete Implementation��������������������������������������������������������������������������������������� 259
Heap Sort���������������������������������������������������������������������������������������������������������������������������������� 261
Ascending-Order Sort (Min-Heap)��������������������������������������������������������������������������������������� 261
Descending-Order Sort (Max-Heap)������������������������������������������������������������������������������������ 264
Summary���������������������������������������������������������������������������������������������������������������������������������� 267
Exercises����������������������������������������������������������������������������������������������������������������������������������� 268

Chapter 17: Graphs����������������������������������������������������������������������������������������������� 273


Graph Basics����������������������������������������������������������������������������������������������������������������������������� 273
Undirected Graphs�������������������������������������������������������������������������������������������������������������������� 277
Adding Edges and Vertices�������������������������������������������������������������������������������������������������� 279
Removing Edges and Vertices��������������������������������������������������������������������������������������������� 280
Directed Graphs������������������������������������������������������������������������������������������������������������������������ 282

xii
Table of Contents

Graph Traversal������������������������������������������������������������������������������������������������������������������������� 285


Breadth-First Search����������������������������������������������������������������������������������������������������������� 286
Depth-First Search�������������������������������������������������������������������������������������������������������������� 289
Weighted Graphs and Shortest Path����������������������������������������������������������������������������������������� 293
Graphs with Weighted Edges����������������������������������������������������������������������������������������������� 293
Dijkstra’s Algorithm: Shortest Path�������������������������������������������������������������������������������������� 294
Topological Sort������������������������������������������������������������������������������������������������������������������������ 298
Summary���������������������������������������������������������������������������������������������������������������������������������� 300

Chapter 18: Advanced Strings������������������������������������������������������������������������������ 303


Trie (Prefix Tree)������������������������������������������������������������������������������������������������������������������������ 303
Boyer–Moore String Search������������������������������������������������������������������������������������������������������ 307
Knuth–Morris–Pratt String Search�������������������������������������������������������������������������������������������� 311
Rabin–Karp Search������������������������������������������������������������������������������������������������������������������� 316
The Rabin Fingerprint���������������������������������������������������������������������������������������������������������� 316
Applications in Real Life������������������������������������������������������������������������������������������������������ 319
Summary���������������������������������������������������������������������������������������������������������������������������������� 320

Chapter 19: Dynamic Programming��������������������������������������������������������������������� 321


Motivations for Dynamic Programming������������������������������������������������������������������������������������ 321
Rules of Dynamic Programming����������������������������������������������������������������������������������������������� 323
Overlapping Subproblems��������������������������������������������������������������������������������������������������� 323
Optimal Substructure���������������������������������������������������������������������������������������������������������� 323
Example: Ways to Cover Steps�������������������������������������������������������������������������������������������� 323
Classical Dynamic Programming Examples������������������������������������������������������������������������������ 325
The Knapsack Problem�������������������������������������������������������������������������������������������������������� 325
Longest Common Subsequence������������������������������������������������������������������������������������������ 328
Coin Change������������������������������������������������������������������������������������������������������������������������ 330
Edit (Levenshtein) Distance������������������������������������������������������������������������������������������������� 334
Summary���������������������������������������������������������������������������������������������������������������������������������� 338

xiii
Table of Contents

Chapter 20: Bit Manipulation�������������������������������������������������������������������������������� 339


Bitwise Operators��������������������������������������������������������������������������������������������������������������������� 339
AND�������������������������������������������������������������������������������������������������������������������������������������� 340
OR���������������������������������������������������������������������������������������������������������������������������������������� 340
XOR�������������������������������������������������������������������������������������������������������������������������������������� 341
NOT�������������������������������������������������������������������������������������������������������������������������������������� 341
Left Shift������������������������������������������������������������������������������������������������������������������������������ 342
Right Shift���������������������������������������������������������������������������������������������������������������������������� 342
Zero-Fill Right Shift������������������������������������������������������������������������������������������������������������� 343
Number Operations������������������������������������������������������������������������������������������������������������������� 343
Addition������������������������������������������������������������������������������������������������������������������������������� 343
Subtraction�������������������������������������������������������������������������������������������������������������������������� 344
Multiplication����������������������������������������������������������������������������������������������������������������������� 345
Division�������������������������������������������������������������������������������������������������������������������������������� 347
Summary���������������������������������������������������������������������������������������������������������������������������������� 349

Index��������������������������������������������������������������������������������������������������������������������� 351

xiv
About the Author
Sammie Bae is a data engineer at Yelp and previously
worked for the data platform engineering team at
NVIDIA. He developed a deep interest in JavaScript
during an internship at SMART Technologies (acquired by
Foxconn), where he developed Node.js-based JavaScript
APIs for serial port communication between electronic
board drivers and a web application. Despite how relevant
JavaScript is to the modern software engineering industry,
currently no books besides this one teach algorithms and
data structures using JavaScript. Sammie understands how
difficult these computer science concepts are and aims to
provide clear and concise explanations in this book.

xv
About the Technical Reviewer
Phil Nash is a developer evangelist for Twilio, serving
developer communities in London and all over the world.
He is a Ruby, JavaScript, and Swift developer; Google
Developers Expert; blogger; speaker; and occasional brewer.
He can be found hanging out at meetups and conferences,
playing with new technologies and APIs, or writing open
source code.

xvii
Acknowledgments
Thank you, Phil Nash, for the valuable feedback that helped me improve the technical
content of this book with clear explanations and concise code.
Special thanks to the Apress team. This includes James Markham, Nancy Chen, Jade
Scard, and Chris Nelson. Finally, I want to thank Steve Anglin for reaching out to me to
publish with Apress.

xix
Introduction
The motivation for writing this book was the lack of resources available about data
structures and algorithms written in JavaScript. This was strange to me because
today many of the job opportunities for software development require knowledge of
JavaScript; it is the only language that can be used to write the entire stack, including the
front-end, mobile (native and hybrid) platforms, and back-end. It is crucial for JavaScript
developers to understand how data structures work and how to design algorithms to
build applications.
Therefore, this book aims to teach data structure and algorithm concepts from
computer science for JavaScript rather than for the more typical Java or C++. Because
JavaScript follows the prototypal inheritance pattern, unlike Java and C++ (which follow
the inheritance pattern), there are some changes in writing data structures in JavaScript.
The classical inheritance pattern allows inheritance by creating a blueprint-­like form
that objects follow during inheritance. However, the prototypal inheritance pattern
means copying the objects and changing their properties.
This book first covers fundamental mathematics for Big-O analysis and then lays out
the basic JavaScript foundations, such as primitive objects and types. Then, this book
covers implementations and algorithms for fundamental data structures such as linked
lists, stacks, trees, heaps, and graphs. Finally, more advanced topics such as efficient
string search algorithms, caching algorithms, and dynamic programming problems are
explored in great detail.

xxi
CHAPTER 1

Big-O Notation
O(1) is holy.
—Hamid Tizhoosh

Before learning how to implement algorithms, you should understand how to analyze
the effectiveness of them. This chapter will focus on the concept of Big-O notation for
time and algorithmic space complexity analysis. By the end of this chapter, you will
understand how to analyze an implementation of an algorithm with respect to both time
(execution time) and space (memory consumed).

Big-O Notation Primer


The Big-O notation measures the worst-case complexity of an algorithm. In Big-O
notation, n represents the number of inputs. The question asked with Big-O is the
following: “What will happen as n approaches infinity?”
When you implement an algorithm, Big-O notation is important because it tells you
how efficient the algorithm is. Figure 1-1 shows some common Big-O notations.

1
© Sammie Bae 2019
S. Bae, JavaScript Data Structures and Algorithms, https://doi.org/10.1007/978-1-4842-3988-9_1
Chapter 1 Big-O Notation

Figure 1-1. Common Big-O complexities

The following sections illustrate these common time complexities with some simple
examples.

Common Examples
O(1) does not change with respect to input space. Hence, O(1) is referred to as being
constant time. An example of an O(1) algorithm is accessing an item in the array by its
index. O(n) is linear time and applies to algorithms that must do n operations in the
worst-case scenario.
An example of an O(n) algorithm is printing numbers from 0 to n-1, as shown here:

1 function  exampleLinear(n) {
2                   for  (var  i = 0 ; i <  n; i++ ) {

2
Chapter 1 Big-O Notation

3                              console.log(i);
4                   }
5  }

Similarly, O(n2) is quadratic time, and O(n3) is cubic time. Examples of these
complexities are shown here:

1 function  exampleQuadratic(n) {
2                   for  (var  i = 0 ; i <  n; i++ ) {
3                                 console.log(i);
4                                for  (var  j =  i; j <  n; j++ ) {
5                                             console.log(j);
6                              }
7                   }
8  }

1 function  exampleCubic(n) {
2                   for  (var  i = 0 ; i <  n; i++ ) {
3                                  console.log(i);
4                                for  (var  j =  i; j <  n; j++ ) {
5                                              console.log(j);
6                                                  for  (var  k =  j;
j <  n; j++ ) {
7                                                          console.log(k);
8                                                  }
9                                }
10           }
11 }

Finally, an example algorithm of logarithmic time complexity is printing elements


that are a power of 2 between 2 and n. For example, exampleLogarithmic(10) will print
the following:

2,4,8,16,32,64

3
Chapter 1 Big-O Notation

The efficiency of logarithmic time complexities is apparent with large inputs such
as a million items. Although n is a million, exampleLogarithmic will print only 19
items because log2(1,000,000) = 19.9315686. The code that implements this logarithmic
behavior is as follows:

1 function exampleLogarithmic(n) {
2                   for (var i = 2 ; i <= n; i= i*2 ) {
3                          console.log(i);
4                  }
5 }

Rules of Big-O Notation


Let’s represent an algorithm’s complexity as f(n). n represents the number of inputs,
f(n)time represents the time needed, and f(n)space represents the space (additional
memory) needed for the algorithm. The goal of algorithm analysis is to understand the
algorithm’s efficiency by calculating f(n). However, it can be challenging to calculate f(n).
Big-O notation provides some fundamental rules that help developers compute for f(n).

• Coefficient rule: If f(n) is O(g(n)), then kf(n) is O(g(n)), for any


constant k > 0. The first rule is the coefficient rule, which eliminates
coefficients not related to the input size, n. This is because as n
approaches infinity, the other coefficient becomes negligible.

• Sum rule: If f(n) is O(h(n)) and g(n) is O(p(n)), then f(n)+g(n) is


O(h(n)+p(n)). The sum rule simply states that if a resultant time
complexity is a sum of two different time complexities, the resultant
Big-O notation is also the sum of two different Big-O notations.
• Product rule: If f(n) is O(h(n)) and g(n) is O(p(n)), then f(n)g(n) is
O(h(n)p(n)). Similarly, the product rule states that Big-O is multiplied
when the time complexities are multiplied.

• Transitive rule: If f(n) is O(g(n)) and g(n) is O(h(n)), then f(n) is


O(h(n)). The transitive rule is a simple way to state that the same time
complexity has the same Big-O.

4
Chapter 1 Big-O Notation

• Polynomial rule: If f(n) is a polynomial of degree k, then f(n) is


O(nk). Intuitively, the polynomial rule states that polynomial time
complexities have Big-O of the same polynomial degree.

• Log of a power rule: log(nk) is O(log(n)) for any constant k > 0. With
the log of a power rule, constants within a log function are also
ignored in Big-O notation.

Special attention should be paid to the first three rules and the polynomial rule
because they are the most commonly used. I’ll discuss each of those rules in the
following sections.

Coefficient Rule: “Get Rid of Constants”


Let’s first review the coefficient rule. This rule is the easiest rule to understand. It simply
requires you to ignore any non-input-size-related constants. Coefficients in Big-O are
negligible with large input sizes. Therefore, this is the most important rule of Big-O
notations.

If f(n) is O(g(n)), then kf(n) is O(g(n)), for any constant k > 0.

This means that both 5f(n) and f(n) have the same Big-O notation of O(f(n)).
Here is an example of a code block with a time complexity of O(n):

1   function a(n){
2       var count =0;
3       for (var i=0;i<n;i++){
4           count+=1;
5       }
6       return count;
7   }

This block of code has f(n) = n. This is because it adds to count n times. Therefore,
this function is O(n) in time complexity:

1   function a(n){
2       var count =0;
3       for (var i=0;i<5*n;i++){

5
Chapter 1 Big-O Notation

4           count+=1;
5       }
6       return count;
7   }

This block has f(n) = 5n. This is because it runs from 0 to 5n. However, the first two
examples both have a Big-O notation of O(n). Simply put, this is because if n is close to
infinity or another large number, those four additional operations are meaningless. It is
going to perform it n times. Any constants are negligible in Big-O notation.
The following code block demonstrates another function with a linear time
complexity but with an additional operation on line 6:

1   function a(n){
2       var count =0;
3       for (var i=0;i<n;i++){
4           count+=1;
5       }
6       count+=3;
7       return count;
8   }

Lastly, this block of code has f(n) = n+1. There is +1 from the last operation
(count+=3). This still has a Big-O notation of O(n). This is because that 1 operation is not
dependent on the input n. As n approaches infinity, it will become negligible.

Sum Rule: “Add Big-Os Up”


The sum rule is intuitive to understand; time complexities can be added. Imagine a
master algorithm that involves two other algorithms. The Big-O notation of that master
algorithm is simply the sum of the other two Big-O notations.

If f(n) is O(h(n)) and g(n) is O(p(n)), then f(n)+g(n) is O(h(n)+p(n)).

It is important to remember to apply the coefficient rule after applying this rule.

6
Chapter 1 Big-O Notation

The following code block demonstrates a function with two main loops whose time
complexities must be considered independently and then summed:

1   function a(n){
2       var count =0;
3       for (var i=0;i<n;i++){
4           count+=1;
5       }
6       for (var i=0;i<5*n;i++){
7           count+=1;
8       }
9       return count;
10   }

In this example, line 4 has f(n) = n, and line 7 has f(n) = 5n. This results in 6n.
However, when applying the coefficient rule, the final result is O(n) = n.

Product Rule: “Multiply Big-Os”


The product rule simply states how Big-Os can be multiplied.

If f(n) is O(h(n)) and g(n) is O(p(n)), then f(n)g(n) is O(h(n)p(n)).

The following code block demonstrates a function with two nested for loops for
which the product rule is applied:

1   function (n){
2       var count =0;
3       for (var i=0;i<n;i++){
4           count+=1;
5           for (var i=0;i<5*n;i++){
6               count+=1;
7           }
8       }
9       return count;
10   }

7
Chapter 1 Big-O Notation

In this example, f(n) = 5n*n because line 7 runs 5n times for a total of n iterations.
Therefore, this results in a total of 5n2 operations. Applying the coefficient rule, the result
is that O(n)=n2.

Polynomial Rule: “Big-O to the Power of k”


The polynomial rule states that polynomial time complexities have a Big-O notation of
the same polynomial degree.
Mathematically, it’s as follows:

If f(n) is a polynomial of degree k, then f(n) is O(nk).


The following code block has only one for loop with quadratic time complexity:

1   function a(n){
2       var count =0;
3       for (var i=0;i<n*n;i++){
4           count+=1;
5       }
6       return count;
7   }

In this example, f(n) = nˆ2 because line 4 runs n*n iterations.


This was a quick overview of the Big-O notation. There is more to come as you
progress through the book.

Summary
Big-O is important for analyzing and comparing the efficiencies of algorithms.
The analysis of Big-O starts by looking at the code and applying the rules to simplify
the Big-O notation. The following are the most often used rules:

• Eliminating coefficients/constants (coefficient rule)

• Adding up Big-Os (sum rule)


• Multiplying Big-Os (product rule)

• Determining the polynomial of the Big-O notation by looking at loops


(polynomial rule)

8
Chapter 1 Big-O Notation

Exercises
Calculate the time complexities for each of the exercise code snippets.

EXERCISE 1

1   function someFunction(n) {
2
3       for (var i=0;i<n*1000;i++) {
4           for (var j=0;j<n*20;j++) {
5               console.log(i+j);
6           }
7       }
8
9   }

EXERCISE 2

1   function someFunction(n) {
2
3       for (var i=0;i<n;i++) {
4           for (var j=0;j<n;j++) {
5               for (var k=0;k<n;k++) {
6                   for (var l=0;l<10;l++) {
7                       console.log(i+j+k+l);
8                   }
9               }
10           }
11       }
12
13   }

9
Chapter 1 Big-O Notation

EXERCISE 3

1   function someFunction(n) {
2
3       for (var i=0;i<1000;i++) {
4           console.log("hi");
5       }
6
7   }

EXERCISE 4

1   function someFunction(n) {
2
3       for (var i=0;i<n*10;i++) {
4           console.log(n);
5       }
6
7   }

EXERCISE 5

1   function someFunction(n) {
2
3       for (var i=0;i<n;i*2) {
4           console.log(n);
5       }
6
7   }

10
Chapter 1 Big-O Notation

EXERCISE 6

1   function someFunction(n) {
2
3       while (true){
4           console.log(n);
5       }
6   }

Answers
1. O(n2)
There are two nested loops. Ignore the constants in front of n.

2. O(n3)
There are four nested loops, but the last loop runs only until 10.

3. O(1)
Constant complexity. The function runs from 0 to 1000. This does
not depend on n.

4. O(n)
Linear complexity. The function runs from 0 to 10n. Constants are
ignored in Big-O.
5. O(log2n)
Logarithmic complexity. For a given n, this will operate only log2n
times because i is incremented by multiplying by 2 rather than
adding 1 as in the other examples.

6. O(∞)

Infinite loop. This function will not end.

11
CHAPTER 2

JavaScript: Unique Parts


This chapter will briefly discuss some exceptions and cases of JavaScript’s syntax and
behavior. As a dynamic and interpreted programming language, its syntax is different
from that of traditional object-oriented programming languages. These concepts are
fundamental to JavaScript and will help you to develop a better understanding of the
process of designing algorithms in JavaScript.

J avaScript Scope
The scope is what defines the access to JavaScript variables. In JavaScript, variables
can belong to the global scope or to the local scope. Global variables are variables that
belong in the global scope and are accessible from anywhere in the program.

Global Declaration: Global Scope


In JavaScript, variables can be declared without using any operators. Here’s an example:

1  test = "sss";
2  console.log(test); // prints "sss"

However, this creates a global variable, and this is one of the worst practices in
JavaScript. Avoid doing this at all costs. Always use var or let to declare variables.
Finally, when declaring variables that won’t be modified, use const.

Declaration with var: Functional Scope


In JavaScript, var is one keyword used to declare variables. These variable declarations
“float” all the way to the top. This is known as variable hoisting. Variables declared at the
bottom of the script will not be the last thing executed in a JavaScript program during
runtime.
13
© Sammie Bae 2019
S. Bae, JavaScript Data Structures and Algorithms, https://doi.org/10.1007/978-1-4842-3988-9_2
Chapter 2 JavaScript: Unique Parts

Here’s an example:

1  function scope1(){
2          var top = "top";
3          bottom = "bottom";
4          console.log(bottom);
5
6          var bottom;
7  }
8  scope1(); // prints "bottom" - no error

How does this work? The previous is the same as writing the following:

1  function scope1(){
2          var top = "top";
3          var  bottom;
4          bottom = "bottom"
5          console.log(bottom);
6  }
7  scope1(); // prints "bottom" - no error

The bottom variable declaration, which was at the last line in the function, is floated
to the top, and logging the variable works.
The key thing to note about the var keyword is that the scope of the variable is the
closest function scope. What does this mean?
In the following code, the scope2 function is the function scope closest to the print
variable:

1  function scope2(print){
2          if(print){
3                   var insideIf = '12';
4          }
5          console.log(insideIf);
6  }
7  scope2(true); // prints '12' - no error

14
Chapter 2 JavaScript: Unique Parts

To illustrate, the preceding function is equivalent to the following:

1  function scope2(print){
2          var insideIf;
3
4          if(print){
5                   insideIf = '12';
6          }
7          console.log(insideIf);
8  }
9  scope2(true); // prints '12' - no error

In Java, this syntax would have thrown an error because the insideIf variable is
generally available only in that if statement block and not outside it.
Here’s another example:

1  var a = 1;
2  function four() {
3    if (true) {
4      var a = 4;
5    }
6
7    console.log(a); // prints '4'
8  }

4 was printed, not the global value of 1, because it was redeclared and available in
that scope.

Declaration with let: Block Scope


Another keyword that can be used to declare a variable is let. Any variables declared
this way are in the closest block scope (meaning within the {} they were declared in).

1  function scope3(print){
2          if(print){
3                   let insideIf = '12';
4          }

15
Chapter 2 JavaScript: Unique Parts

5          console.log(insideIf);
6  }
7  scope3(true); // prints ''

In this example, nothing is logged to the console because the insideIf variable is
available only inside the if statement block.

Equality and Types


JavaScript has different data types than in traditional languages such as Java. Let’s
explore how this impacts things such as equality comparison.

Variable Types
In JavaScript, there are seven primitive data types: boolean, number, string, undefined,
object, function, and symbol (symbol won’t be discussed). One thing that stands out
here is that undefined is a primitive value that is assigned to a variable that has just been
declared. typeof is the primitive operator used to return the type of a variable.

1  var is20 = false; // boolean


2  typeof is20; // boolean
3
4  var  age = 19;
5  typeof age; // number
6
7  var  lastName = "Bae";
8  typeof lastName; // string
9
10  var fruits = ["Apple", "Banana", "Kiwi"];
11  typeof fruits; // object
12
13  var me = {firstName:"Sammie", lastName:"Bae"};
14  typeof me; // object
15
16  var nullVar = null;
17  typeof nullVar; // object
18
16
Chapter 2 JavaScript: Unique Parts

19  var function1 = function(){


20          console.log(1);
21  }
22  typeof function1 // function
23
24  var blank;
25  typeof blank; // undefined

Truthy/Falsey Check
True/false checking is used in if statements. In many languages, the parameter inside
the if() function must be a boolean type. However, JavaScript (and other dynamically
typed languages) is more flexible with this. Here’s an example:

1  if(node){
2          ...
3  }

Here, node is some variable. If that variable is empty, null, or undefined, it will be
evaluated as false.
Here are commonly used expressions that evaluate to false:

• false

• 0

• Empty strings ('' and "")


• NaN

• undefined

• null

Here are commonly used expressions that evaluate to true:

• true

• Any number other than 0

• Non-empty strings

• Non-empty object

17
Chapter 2 JavaScript: Unique Parts

Here’s an example:

1  var printIfTrue = ";


2
3  if (printIfTrue) {
4          console.log('truthy');
5  } else {
6          console.log('falsey'); // prints 'falsey'
7  }

=== vs ==
JavaScript is a scripting language, and variables are not assigned a type during
declaration. Instead, types are interpreted as the code runs.
Hence, === is used to check equality more strictly than ==. === checks for both the
type and the value, while == checks only for the value.

1  "5" == 5 // returns true


2  "5" === 5 // returns false

"5" == 5 returns true because "5" is coerced to a number before the comparison.
On the other hand, "5" === 5 returns false because the type of "5" is a string, while 5 is
a number.

Objects
Most strongly typed languages such as Java use isEquals() to check whether two objects
are the same. You may be tempted to simply use the == operator to check whether two
objects are the same in JavaScript.
However, this will not evaluate to true.

1  var o1 = {};
2  var o2 = {};
3
4  o1 == o2 // returns false
5  o1 === o2 // returns false

18
Chapter 2 JavaScript: Unique Parts

Although these objects are equivalent (same properties and values), they are not
equal. Namely, the variables have different addresses in memory.
This is why most JavaScript applications use utility libraries such as lodash1 or
underscore,2 which have the isEqual(object1, object2) function to check two objects
or values strictly. This occurs via implementation of some property-based equality
checking where each property of the object is compared.
In this example, each property is compared to achieve an accurate object equality result.

1  function isEquivalent(a, b) {
2      // arrays of property names
3      var aProps = Object.getOwnPropertyNames(a);
4      var bProps = Object.getOwnPropertyNames(b);
5
6      // If their property lengths are different, they're different objects
7      if (aProps.length != bProps.length) {
8          return false;
9      }
10
11      for (var  i = 0; i < aProps.length; i++) {
12          var propName = aProps[i];
13
14          // If the values of the property are different, not equal
15          if (a[propName] !== b[propName]) {
16              return false;
17          }
18      }
19
20     // If everything matched, correct
21     return  true;
22  }
23  isEquivalent({'hi':12},{'hi':12}); // returns true

1
h ttps://lodash.com/
2
http://underscorejs.org/

19
Chapter 2 JavaScript: Unique Parts

However, this would still work for objects that have only a string or a number as the
property.

1  var obj1 = {'prop1': 'test','prop2': function (){} };


2  var obj2 = {'prop1': 'test','prop2': function (){} };
3
4  isEquivalent(obj1,obj2); // returns false

This is because functions and arrays cannot simply use the == operator to check for
equality.

1  var function1 = function(){console.log(2)};


2  var function2 = function(){console.log(2)};
3  console.log(function1 == function2); // prints 'false'

Although the two functions perform the same operation, the functions have
different addresses in memory, and therefore the equality operator returns false.
The primitive equality check operators, == and ===, can be used only for strings and
numbers. To implement an equivalence check for objects, each property in the object
needs to be checked.

Summary
JavaScript has a different variable declaration technique than most programming
languages. var declares the variable within the function scope, let declares the variable
in the block scope, and variables can be declared without any operator in the global
scope; however, global scope should be avoided at all times. For type checking, typeof
should be used to validate the expected type. Finally, for equality checks, use == to check
the value, and use === to check for the type as well as the value. However, use these only
on non-object types such as numbers, strings, and booleans.

20
CHAPTER 3

JavaScript Numbers
This chapter will focus on JavaScript number operations, number representation, Number
objects, common number algorithms, and random number generation. By the end of
this chapter, you will understand how to work with numbers in JavaScript as well as how
to implement prime factorization, which is fundamental for encryption.
Number operations of a programming language allow you to compute numerical
values. Here are the number operators in JavaScript:

+ : addition
- : subtraction
/ : division
* : multiplication
% : modulus

These operators are universally used in other programming languages and are not
specific to JavaScript.

N
 umber System
JavaScript uses a 32-bit floating-point representation for numbers, as shown in Figure 3-­1.
In this example, the value is 0.15625. The sign bit (the 31st bit) indicates that the number
is negative if the sign bit is 1. The next 8 bits (the 30th to 23rd bits) indicate the exponent
value, e. Finally, the remaining 23 bits represent the fraction value.

Figure 3-1. The 32-bit floating-point number system


21
© Sammie Bae 2019
S. Bae, JavaScript Data Structures and Algorithms, https://doi.org/10.1007/978-1-4842-3988-9_3
Chapter 3 JavaScript Numbers

With the 32 bits, the value is computed by this esoteric formula:

æ 23
ö
value = ( -1) ´ 2e -127 ´ ç 1 + åb23 -t 2 -t ÷
sign

è t =1 ø

Figure 3-1 shows the following break down of the 32 bits:


sign = 0
e = (0111100)2 = 124 (in base 10)
23
1 + åb23 -i 2 -i = 1 + 0 + 0.25 + 0
i =1

This results in the following:

value = 1 x 2124-127 x 1.25 = 1 x 2-3 x 1.25 = 0.15625

With decimal fractions, this floating-point number system causes some rounding
errors in JavaScript. For example, 0.1 and 0.2 cannot be represented precisely.
Hence, 0.1 + 0.2 === 0.3 yields false.

1  0.1 + 0.2 === 0.3; // prints 'false'

To really understand why 0.1 cannot be represented properly as a 32-bit floating-­


point number, you must understand binary. Representing many decimals in binary
requires an infinite number of digits. This because binary numbers are represented by 2n
where n is an integer.
While trying to calculate 0.1, long division will go on forever. As shown in Figure 3-­2,
1010 represents 10 in binary. Trying to calculate 0.1 (1/10) results in an indefinite
number of decimal points.

22
Chapter 3 JavaScript Numbers

Figure 3-2. Long division for 0.1

JavaScript Number Object


Luckily, there are some built-in properties of the Number object in JavaScript that help
work around this.

Integer Rounding
Since JavaScript uses floating point to represent all numbers, integer division does not work.
Integer division in programming languages like Java simply evaluates division
expressions to their quotient.
For example, 5/4 is 1 in Java because the quotient is 1 (although there is a remainder
of 1 left). However, in JavaScript, it is a floating point.

1  5/4; // 1.25
23
Chapter 3 JavaScript Numbers

This is because Java requires you to explicitly type the integer as an integer.
Hence, the result cannot be a floating point. However, if JavaScript developers want to
implement integer division, they can do one of the following:

Math.floor - rounds down to nearest integer


Math.round - rounds to nearest integer
Math.ceil  - rounds up to nearest integer

Math.floor(0.9); // 0
Math.floor(1.1); // 1

Math.round(0.49); // 0
Math.round(0.5); // 1

Math.round(2.9); // 3
Math.ceil(0.1); // 1 Math.ceil(0.9); // 1 Math.ceil(21);
// 21 Math.ceil(21.01); // 22

Number.EPSILON
Number.EPSILON returns the smallest interval between two representable numbers.
This is useful for the problem with floating-point approximation.

1  function numberEquals(x, y) {
2      return Math.abs(x - y) < Number.EPSILON;
3  }
4
5  numberEquals(0.1 + 0.2, 0.3); // true

This function works by checking whether the difference between the two numbers
are smaller than Number.EPSILON. Remember that Number.EPSILON is the smallest
difference between two representable numbers. The difference between 0.1+0.2 and 0.3
will be smaller than Number.EPSILON.

Maximums
Number.MAX_SAFE_INTEGER returns the largest integer.

1  Number.MAX_SAFE_INTEGER + 1 === Number.MAX_SAFE_INTEGER + 2; // true

24
Chapter 3 JavaScript Numbers

This returns true because it cannot go any higher. However, it does not work for
floating-point decimals.

1  
Number.MAX_SAFE_INTEGER + 1.111 === Number.MAX_SAFE_INTEGER + 2.022;
// false

Number.MAX_VALUE returns the largest floating-point number possible.


Number.MAX_VALUE is equal to 1.7976931348623157e+308.

1  Number.MAX_VALUE + 1 === Number.MAX_VALUE + 2; // true

Unlike like Number.MAX_SAFE_INTEGER, this uses double-precision floating-point


representation and works for floating points as well.

1  Number.MAX_VALUE + 1.111 === Number.MAX_VALUE + 2.022; // true

Minimums
Number.MIN_SAFE_INTEGER returns the smallest integer.
Number.MIN_SAFE_INTEGER is equal to -9007199254740991.

1  Number.MIN_SAFE_INTEGER - 1 === Number.MIN_SAFE_INTEGER - 2; // true

This returns true because it cannot get any smaller. However, it does not work for
floating-point decimals.

1  Number.MIN_SAFE_INTEGER - 1.111 === Number.MIN_SAFE_INTEGER - 2.022;


// false

Number.MIN_VALUE returns the smallest floating-point number possible.


Number.MIN_VALUE is equal to 5e-324. This is not a negative number since it is the
smallest floating-point number possible and means that Number.MIN_VALUE is actually
bigger than Number.MIN_- SAFE_INTEGER.
Number.MIN_VALUE is also the closest floating point to zero.

1  Number.MIN_VALUE - 1 == -1; // true

This is because this is similar to writing 0 - 1 == -1.

25
Chapter 3 JavaScript Numbers

Infinity
The only thing greater than Number.MAX_VALUE is Infinity, and the only thing smaller
than Number.MAX_SAFE_INTEGER is -Infinity.

1  Infinity > Number.MAX_SAFE_INTEGER; // true


2  -Infinity < Number.MAX_SAFE_INTEGER // true;
3  -Infinity -32323323 == -Infinity -1; // true

This evaluates to true because nothing can go smaller than -Infinity.

Size Summary
This inequality summarizes the size of JavaScript numbers from smallest (left) to
largest (right):

-Infinity < Number.MIN_SAFE_INTEGER < Number.MIN_VALUE < 0 < Number.MAX_


SAFE_IN- TEGER < Number.MAX_VALUE < Infinity

Number Algorithms
One of the most discussed algorithms involving numbers is for testing whether a number
is a prime number. Let’s review this now.

Primality Test
A primality test can be done by iterating from 2 to n, checking whether modulus division
(remainder) is equal to zero.

1  function isPrime(n){
2      if (n <= 1) {
3              return false;
4      }
5
6      // check from 2 to n-1
7      for (var i=2; i<n; i++) {
8              if (n%i == 0) {
9                      return false;
10          }
26
Chapter 3 JavaScript Numbers

11      }
12
13      return true;
14  }

Time Complexity: O(n)


The time complexity is O(n) because this algorithm checks all numbers from 0 to n.
This is an example of an algorithm that can be easily improved. Think about how this
method iterates through 2 to n. Is it possible to find a pattern and make the algorithm
faster? First, any multiple of 2s can be ignored, but there is more optimization possible.
Let’s list some prime numbers.

2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97

This is difficult to notice, but all primes are of the form 6k ± 1, with the exception of
2 and 3 where k is some integer. Here’s an example:

5 = (6-1) , 7 = ((1*6) + 1), 13 = ((2*6) + 1) etc

Also realize that for testing the prime number n, the loop only has to test until the
square root of n. This is because if the square root of n is not a prime number, n is not a
prime number by mathematical definition.

1  function isPrime(n){
2      if (n <= 1) return false;
3      if (n <= 3) return true;
4
5      // This is checked so that we can skip
6      // middle five numbers in below loop
7      if (n%2 == 0 || n%3 == 0) return false;
8
9      for (var i=5; i*i<=n; i=i+6){
10          if (n%i == 0 || n%(i+2) == 0)
11             return false;
12      }
13
14      return true;
15  }

27
Chapter 3 JavaScript Numbers

Time Complexity: O(sqrt(n))


This improved solution cuts the time complexity down significantly.

P
 rime Factorization
Another useful algorithm to understand is for determining prime factorization of a
number. Prime numbers are the basis of encryption (covered in Chapter 4) and hashing
(covered in Chapter 11), and prime factorization is the process of determining which
prime numbers multiply to a given number. Given 10, it would print 5 and 2.

1  function primeFactors(n){
2          // Print the number of 2s that divide n
3          while (n%2 == 0) {
4              console.log(2);
5              n = n/2;
6          }
7
8          // n must be odd at this point. So we can skip one element
(Note i = i +2)
9          for (var i = 3; i*i <= n; i = i+2) {
10             // While i divides n, print i and divide n
11              while (n%i == 0) {
12                  console.log(i);
13                  n = n/i;
14              }
15          }
16          //This condition is to handle the case when n is a prime number
17          //greater than 2
18          if (n > 2) {
19                  console.log(n);
20          }
21  }
22  primeFactors(10); // prints '5' and '2'

28
Chapter 3 JavaScript Numbers

Time Complexity: O(sqrt(n))


This algorithm works by printing any number that is divisible by i without a
remainder. In the case that a prime number is passed into this function, it would be
handled by printing whether n is greater than 2.

Random Number Generator


Random number generation is important to simulate conditions. JavaScript has a built-­in
function for generating numbers: Math.random().

Math.random() returns a float between 0 and 1.

You may wonder how you get random integers or numbers greater than 1.
To get floating points higher than 1, simply multiply Math.random() by the range.
Add or subtract from it to set the base.

Math.random() * 100; // floats between 0  and  100


Math.random() * 25 + 5; // floats between 5  and  30
Math.random() * 10 - 100; // floats between -100 and -90

To get random integers, simply use Math.floor(), Math.round(), or Math.ceil() to


round to an integer.

Math.floor(Math.random() * 100); // integer between 0 and 99


Math.round(Math.random() * 25) + 5; // integer between 5 and 30
Math.ceil(Math.random() * 10) - 100; // integer between -100 and -90

Exercises
1. Given three numbers x, y, and p, compute (xˆy) % p. (This is
modular exponentiation.)
Here, x is the base, y is exponent, and p is the modulus.
Modular exponentiation is a type of exponentiation performed
over a modulus, which is useful in computer science and used in
the field of public-key encryption algorithms.
At first, this problem seems simple. Calculating this is a one-line
solution, as shown here:
29
Chapter 3 JavaScript Numbers

1  function modularExponentiation ( base, exponent, modulus ) {


2          return Math.pow(base,exponent) % modulus;
3  }

This does exactly what the question asks. However, it cannot


handle large exponents.
Remember that this is implemented with encryption algorithms.
In strong cryptography, the base is often at least 256 bit (78 digits).
Consider this case, for example:
Base: 6x1077, Exponent: 27, Modulus: 497
In this case, (6x1077)27 is a very large number and cannot be stored
in a 32-bit floating point.
There is another approach, which involves some math. One must
observe the following mathematical property:
For arbitrary a and b,

c % m = (a  b) % m
c % m = [(a % m)  (b % m)] % m

Using this mathematical property, you can iterate 1 to the


exponent, recalculating each time by multiplying the current
modulus value with the last.

Here is the pseudocode:

1  Set value = 1, current exponent = 0.


2  Increment current exponent by 1.
3  Set value = (base  value) mod modulus until current
exponent is reached exponent

Example: Base: 4, Exponent: 3, Modulus: 5

4ˆ3 % 5 = 64 % 5 = 4

value = (lastValue x base ) % modulus:


value = (1 x 4) % 5 = 4 % 5 = 4

30
Chapter 3 JavaScript Numbers

value = (4 x 4) % 5 = 16 % 5 = 1

value = (1 x 4) % 5 = 4 % 5 = 4

Finally, here is the code:

1  function modularExponentiation ( base, exponent, modulus ) {


2          if (modulus == 1) return 0;
3
4          var value = 1;
5
6          for ( var i=0; i<exponent; i++ ){
7                  value = (value * base) % modulus;
8          }
9          return value;
10  }

Time Complexity: O(n)

The time complexity is O(n) where n is equal to the exponent value.

2. Print all primes less than n.

To do this, use the isPrime function covered in this chapter.


Simply iterate from 0 to n and print any prime numbers where
isPrime() evaluates to true.

1  function allPrimesLessThanN(n){
2          for (var i=0; i<n; i++) {
3                  if (isPrime(i)){
4                          console.log(i);
5                  }
6          }
7  }
8
9  function isPrime(n){
10      if (n <= 1) return false;
11      if (n <= 3) return true;
12

31
Chapter 3 JavaScript Numbers

13      // This is checked so that we can skip


14      // middle five numbers in below loop
15      if (n%2 == 0 || n%3 == 0) return false;
16
17      for (var i=5; i*i<=n; i=i+6){
18          if (n%i == 0 || n%(i+2) == 0)
19             return false;
20      }
21
22      return true;
23  }
24
25  allPrimesLessThanN(15);
26
27  // prints 2, 3, 5, 7, 11, 13

Time Complexity: O(nsqrt(n))

This is because isPrime (covered earlier in this chapter) with a


time complexity of O(sqrt(n)) is run n times.

3. Check for a set of prime factors.

Let’s define ugly numbers as those whose only prime factors are
2, 3, or 5. The sequence 1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15, … shows the
first 11 ugly numbers. By convention, 1 is included.
To do this, divide the number by the divisors (2, 3, 5) until it
cannot be divided without a remainder. If the number can be
divided by all the divisors, it should be 1 after dividing everything.

1  function maxDivide (number, divisor) {


2          while (number % divisor == 0) {
3                  number /= divisor;
4          }
5          return number;
6  }
7
8  function isUgly (number){
9          number = maxDivide(number, 2);
32
Chapter 3 JavaScript Numbers

10          number = maxDivide(number, 3);


11          number = maxDivide(number, 5);
12          return number === 1;
13  }

Iterate this over n, and now the list of ugly numbers can be
returned.

1  function arrayNUglyNumbers (n) {


2          var counter = 0, currentNumber = 1,
uglyNumbers = [];
3
4          while ( counter != n ) {
5
6                  if ( isUgly(currentNumber) ) {
7                          counter++;
8                          uglyNumbers.push(currentNumber);
9                  }
10
11                  currentNumber++;
12          }
13
14          return uglyNumbers;
15  }

Time Complexity for maxDivide(number, divisor):


O(logdivisor(number))
The time complexity of maxDivide is a logarithmic function which
depends on divisor and the number. When testing primes of 2,
3, and 5, the logarithmic of 2 (log2 (n)) yields the highest time
complexity.

Time Complexity for isUgly: O(log2(n))


Time Complexity for arrayNUglyNumbers: O(n(log2(n)))
The isUgly function is limited by the time complexity of maxDivide(number, 2).
Hence, arrayNUglyNumbers has n times that time complexity.

33
Another Random Document on
Scribd Without Any Related Topics
The Project Gutenberg eBook of A szentlélek
lovagja
This ebook is for the use of anyone anywhere in the United States
and most other parts of the world at no cost and with almost no
restrictions whatsoever. You may copy it, give it away or re-use it
under the terms of the Project Gutenberg License included with this
ebook or online at www.gutenberg.org. If you are not located in the
United States, you will have to check the laws of the country where
you are located before using this eBook.

Title: A szentlélek lovagja

Author: Lajos Biró

Release date: July 17, 2020 [eBook #62681]


Most recently updated: October 18, 2024

Language: Hungarian

Credits: Produced by Albert László from page images generously


made
available by the HathiTrust Digital Library

*** START OF THE PROJECT GUTENBERG EBOOK A SZENTLÉLEK


LOVAGJA ***
Megjegyzések:

Az eredeti képek elérhetők innen:


https://hdl.handle.net/2027/nyp.33433089892461.
Facebook oldalunk: http://www.facebook.com/PGHungarianTeam.
A szentlélek lovagja

BIRÓ LAJOS
KÖNYVEI:

1. Regények
A diadalmas asszony 3.–
Nyári zivatar 3.50

2. Elbeszélések
Ciklámen 3.–
Kunszállási emberek 3.50
A fekete ostor 3.50
Marie és más asszonyok 4.–
Huszonegy novella. 2. kiadás 4.–

3. Szindarabok
1913. Történelmi színmű 3 felv.
Az utolsó csók. (Egy szegény ifju története) 3 felv. 2.50
Tavaszi ünnep. Dráma 3 felv. 3.–
A rablólovag. Színjáték 3 felv. 3.–
Sárga liliom. Színmű 3 felv. 3.–
A cárnő. Irták Biró Lajos és Lengyel Menyhért. Színjáték 3
felv. 3.–

Singer és Wolfner kiadásai


Budapest, VI. ker., Andrássy-út 16. sz.
Biró Lajos

A szentlélek lovagja

Budapest 1914
Singer és Wolfner kiadása
VI., Andrássy-út 16.
Minden jogot fenntartunk
BUDAPESTI HIRLAP NYOMDÁJA
I.
Monostory rákönyökölt a márványasztalra, amely meg volt rakva
pezsgősüveggel; egy pisszenéssel elhallgattatta a cigányt a háta
mögött; elborult szemének egy másodpercnyi ingadozása után
kikereste mulató társai közül a legkülönbet és csendesen
megszólította:
– Mondd, János fiam, buta vagy?
Az aposztrofált Buzát János meghökkenve emelte föl a fejét.
Monostory nyugodtan ismételte:
– Mondd: buta vagy? – Mondd! Mondd, hogy buta vagy; mondd,
hogy tök vagy…
A hangja ingerült lett, fenyegető, mint egy oroszlán dörmögése:
– Ne kapkodd a fejedet, édes fiam, mert én belelátok ám. Én
tudom, édes jó fiam, hogy mi van benne… Nekem hiába nyalod
magadat kivülről angol lordra, belül egy szegény kupecivadék ijedt
lelke reszket benned. Nekem hiába adod a tudóst, én tudom, hogy
csak szorgalmas ujságolvasó vagy, azzal szédíted ezeket a
szamarakat, akik szorgalmasan még ujságot sem tudnak olvasni.
Nekem hiába adod a nagy szónokot, én látom, hogy elsápadsz és
reszketsz, amikor beszélni kezdesz; és én tudom, hogy két hétig
tanulod a rögtönzött beszédeidet. És én nekem hiába adod a
született vezért, én tudom, hogy született közkatona vagy, született
csatlós, született szolga, sima és ügyes lakáj. És én belátok a fejedbe
és tudom, hogy ezt te is tudod; tudom: remegsz tőle, hogy egyszer
csak kisül; tudom: nincs egy győzelmes félórád; tudom: nincs egy
mámoros perced. Ezért tehát, édes fiam, ha én azt kérdezem tőled,
buta vagy-e, akkor ne kapkodd a fejedet, hanem hajtsd meg, és
felelj rendesen és engedelmesen, amint illik: igenis, István bátyám,
buta vagyok.
Monostory befejezte a beszédét. A beszéd azonban még a
pezsgősüvegek között és éjfél után is nagyon kíméletlen volt. A
társaság nem nevetett, hanem csendben lázadozott és boldog
zúgással fogadta azt a választ, amelyre egyikük rátalált:
– Pista bácsi, részeg vagy.
Helyeseltek, nevettek, ütötték az asztalt, tusst parancsoltak a
cigánynak és tíz hang variálta a választ:
– Pista bátyánk berugott! Monostory István részeg, mint a tök.
Dicsőséges atyánk leszopta magát:
Monostory azonban fölugrott; kirugta maga alól a széket,
meghajlott teste úgy egyenesedett ki, mintha acélból lett volna és
fáradt száján harsány kiáltás csattant ki:
– Csend!
Csend lett. A cigány is rögtön elhallgatott. Monostory
félresimította a homlokából fehér szálakkal átszőtt fekete haját,
elborult szeme szikrákat szórt; körülnézett a társaságon, amely
kényelmetlenül és rosszat sejtve lapult meg a tekintete alatt, és
tiszta, meleg és csengő hangon mondta:
– Ti nyálasok és nyálkáslelküek, ti szomjas nyakalók és tisztátlan
berugók, mit tudjátok ti azt, milyen viszonyban vagyok én a
részegséggel. Mit tudjátok ti azt, hogy én meg tudok részegedni egy
korty ital nélkül, ha úgy jön, és hiába öntöm le magamba a világ
minden italát, ha idebent józanság, szomorúság és bánat lakik. Mi
tudjátok ti, hogy én már öt napja akarok hiába lerészegedni, és mit
tudjátok ti, miféle italokat iszom én hajnaltájban, amikor ti piszkosan
horkoltok piszkos ágyaitokban.
Egy másodpercnyi szünetet tartott.
– De mert ezt nem tudjátok, – folytatta azután csendesebben és
szigorúbban, – nem tudhatjátok azt sem, mit tesz az, hogy én most
veletek vagyok és sokszor hajnalig tűröm a hitvány közelléteteket. –
Minthogy pedig szemetek van, de nem láttok, minthogy…
Megakadt. Egy másodpercre megtörten, lehunyt szemmel
hanyatlott le a feje a mellére. De azután fölkapta a fejét és magából
kikelten, kigyulladt arccal és mámorosan ordította:
– Minthogy nem látjátok a géniusz ragyogását a homlokomon;
minthogy továbbá nem ismeritek az áhítatot; mithogy tiszteletlen,
arcátlan plebejus röhögők vagytok, – én titeket, gyáva had, a
szentlélek nevében, amelynek lovagja vagyok, meg foglak fenyíteni…
Az arca lángolt, a szeme mintha szikrázva akart volna kipattanni
üregéből, két keze ökölbe szorulva emelkedett föl, és az asztal körül
ijedt ugrálás támadt.
– Részeg! – Meg van őrülve. – Kitelik tőle. – Le kell fogni. –
Ilyenkor ölni is tud. – Kényszerzubbonyt rá.
Monostory elvakultan nyúlt a pezsgőspalackok után, amelyeket el
akartak kapkodni a keze ügyéből; fölemelte a kezét, hogy azt a
mulató társát, aki hozzá legközelebb volt, megüsse, amikor az öreg
cigányprímás, aki a háta mögött állott, hirtelen előre lépett és halkan
mondta:
– Nagyságos úr, lovas legény jött Erdőmonostorról.
Monostory fölemelt keze megakadt; a cigányprímás pedig már
elébe is tolta az ijedt képü legényt, akit a pincérek nem mertek
bejelenteni. A legény rémülten pislogott; Monostory leeresztette a
kezét:
– Mi kell? – kérdezte halkan.
– A nagyságos asszony kéreti a nagyságos urat, – hadarta a
legény, – tessen azonnal hazajönni. Mert igen rosszul van az öreg
nagyságos úr.
Monostory úgy nézett rá a legényre, mintha álomban látná.
– Micsoda nagyságos asszony? – kérdezte lehunyt szemmel és
nagyon halkan.
– A nagyságos úr felesége, – válaszolta a legény ijedten, de
engedelmesen.
– Ki van rosszul? – kérdezte újra Monostory lomhán és álmosan.
– Az öreg nagyságos úr: a nagyságos úr édesapja.
Monostory behunyta a szemét és mozdulatlanul állt egy darabig.
Azután vállon fogta a legényt, a szemébe nézett, hozzá hajolt és
csendesen így szólt:
– Mondd meg a nagyságos asszonynak, hogy ha az apám
véletlenül csakugyan nagybeteg, – attól, ha engem meglát,
egyszerre halálos lesz a baja. – Eredj.
Meglódította a bámuló legényt, villámgyorsan a kezébe nyomott
egy teli pezsgős palackot és rákiáltott:
– Idd le magad hazáig. Takarodj.
A meghökkent legény elment; a társaság időközben szétsurrant
és Monostory szédülő fejjel egyedült ült le a pezsgőpocsolyás
asztalhoz. A két tenyerébe támasztotta az arcát és hallgatott. Sokáig
hallgatott, azután a két tenyere közül halkan megszólalt:
– Marci.
A cigánybanda csendben várakozott volt a parancsára és az öreg
cigányprímás, akinek a megszólítás szólt, most ijedten kereste
láthatatlan arcát, mert a hangja józan, megtört és kongó hang volt.
– Tessék, nagyságos úr.
A Monostory hangja nyugodtan, egyenletesen, de megtörten jött
a két tenyere mögül:
– Marci, tudsz-e valamit, amitől megrészegszik az ember?
– A borital nagyságos úr…
– Menj a pokolba a tudományoddal.
Monostory fölállott. Az arca sápadt volt és a szeme beesett.
– No várj, – mondta, – majd keresek én magamnak olyan italt.
Odaintette a kalapját és a felöltőjét.
– Ti engem itt megvártok, – mondta a cigányoknak.
Föltette a kalapját és fölvette a felöltőjét; és csöndes, biztos,
egyenes lépésekkel kiment a kávéházból. Kint hüvös tavaszi éjszaka
volt. Fázott; zsebredugta a kezét és gyors lépésekkel indult a Piac-
térre. A Piac-téren kikeresett egy nagy emeletes házat, megállott
előtte és sorra vette a boltajtókat, amelyek éjjel be voltak csukva.
Végre megtalálta, amit keresett: a patika ajtaját. Megnyomta a
csengőt, előbb röviden és udvariasan, azután hosszan, dühbe jötten
és fenyegetően.
A csengő mellett kinyilott egy kis ablak és egy álmos fej jelent
meg benne.
– Mi tetszik?
Monostory most megint nyugodt volt:
– Adjon nekem, – mondta csöndesen, – egy üveg étert.
– Minek az?… Minek most éjszaka? Hozott-e orvosi
rendelvényt?… Nem adok.
Az álmos fej, miután szemügyre vette Monostoryt és miután
három kérdésen át felelet nélkül is eljutott a megtagadásig, vissza
akart vonulni. Visszavonulás közben azonban meg kellett állnia.
Monostoryban ugyanis mérhetetlen düh gyulladt föl és olyat vágott
az öklével az ablak keresztfájára, hogy a kis ablak üvege
csörömpölve hullott be.
– Hallod-e kölyök, – recsegte be az ablakon, – azt akarod, hogy
beküldjek hozzád egypár acélburkolatu golyót?
A dühnek még ebben az indulatában kirántotta a pisztolyát és
rásütötte a nagy házra, mintha gyűlölt, nagy sárga ellenség állna
előtte. A golyó lepattant a kőfalról és süvöltve zúgott el az
éjszakába; a dördülést csöndes mozgolódás követte a nagy téren; de
még mielőtt valaki jöhetett volna, egy remegő kéz már kinyujtott az
ablakon egy nagy üveget; Monostory átvette, egy marék ezüstpénzt
és bankót behajított érte az ablakon; elindult és az üveggel a
kezében befordult egy mellékutcába.
Komolyan és feszülten figyelt lépéseinek a kemény kopogására,
mintha ennek a hangnak a csöndes éjszakában különös fontossága
lett volna számára. Elválasztotta a hangot a visszhangtól és zenei
elemeket keresett bennük, hogy minden figyelme le legyen kötve és
hogy ne kelljen semmi másra gondolnia. Siető, lépései alól azonban
elfogyott az aszfaltozott gyalogjáró, puha földön járt, rosszul
világított, szűk sikátorokba tévedt bele, rozoga fakerítés mellett
rozoga fapadot talált, reszkető lábbal ereszkedett le reá, és ekkor föl
kellett emelnie és meg kellett néznie az üveget, amelyet a kezében
tartott.
Két kézzel körülfogta, fölemelte és magasra tartotta. A folyadék
megcsillant a gyér világításban és Monostory, hogy riadtan dobogó
szívét elhallgattassa, gúnyosan mondta:
– Áldozati kehely… áldozás a gonosznak: különös összetételü kén
és szénvegyületekkel…
Mosolygott. De amint ült a rozoga fapadon, nagy fáradtsága
kezdett elmulni és egyszerre ismét fölsirt a szívében részegség után
való forró vágyakozása. Részegnek lenni! Részegség! Részegség!…
Villámgyors mozdulattal kirántotta az üveg dugóját, két kezébe
keményen belemarkolta az üveget, magához húzta és ráhajolt.
Az éter édeskés szaga rögtön kicsapott az üvegből és elárasztotta
az orrát. Undorítónak találta ezt a szagot és szinte visszahőkölt tőle,
de gyors elhatározással még mélyebben hajolt az üvegre, a száját is
kinyitotta és szomjas, nagy lélekzettel szítta be az éter láthatatlan és
csodálatos gőzeit. Három, négy, öt lélegzet… ah, ez csak undorító,
de soha ettől részeggé nem lesz az ember. – Elszántan kapta föl az
üveget, a szájában érezte az üveg nyakát. Mindjárt, – most!…
A nyelvén, a szájpadlásán, az egész szájában türhetetlen égetést
érzett és a szája, a torka, a gyomra, a feje egyszerre tele lett a
gyülöletes édeskés szaggal. Fuldokolni kezdett és szörnyü utálattal
köpte ki a folyadékot a szájából; az üveget a földhöz vágta; az üveg
összetörött és a folyadék szétcsurgott; a földről is az éter gőzei
szállottak föl; olyan volt, mintha az egész éjszaka, a föld, a
mindenség föl a csillagokig tele volna ezzel a rémületes szaggal;
mintha a tejút odafönt étergőzökből sűrüsödött volna össze…
Ijedten, undorodva és szégyenkezve menekült a rozoga pad
közeléből és köpködve, fuldokolva próbálta eltávolítani a szájából és
az orrából az éter emlékét. Lángoló szégyenkezés és eszeveszett düh
kínozta; józanabb volt, mint amikor este inni kezdett és sírni tudott
volna a teljes, nagy részegség után való vágyában.
Bőszülten rohant bele a sötét sikátortömegbe, amely előtte volt,
és szinte fölordított örömében, amikor egy piszkos lebuj homályosan
megvilágított ajtaja akadt elébe. Ah, ez a Vitriol-kocsma… Itt más
folyadék szokott hajnaltájban megcsordulni, itt hajnaltájban kés
villog és vér folyik. Itt belevetette magát már egyszer egy hajnali
késelésbe… ha most is olyan kimondhatatlan szerencséje volna! Ez
lesz a megváltás, ez lesz az öröm, ez lesz a részegség: vércsordító
ütéseket adni és villogó kések ellen védekezni. Lihegett a
fölindulástól és az az érzése volt, hogy ha egy kést döfnének a
mellébe, ujjongva fogadná a döfést.
Lihegett a fölindulástól és lábbal rúgta be a piszkos ajtót.
Berobbant az ajtón és ökölbeszorított kézzel, villámló szemmel állott
meg a kocsma közepén. Bent azonban csöndes és ijedt mozgolódás
felelt csak a kihívásra; nem volt ünnepnap és a lebuj hajnali élete
csöndes volt és álmos volt; egyetlen toprongyos vendég riadt föl a
sarokból, és az álmos kocsmáros jött hajlongva Monostory elé.
Monostory megszégyenülve nézett le rá és ételt és italt rendelt nála.
Ha most már csak az éter emlékét tudná elűzni a torkából és az
orrából. Fáradtan ült le, éhesen evett és szomjasan itta a pálinkát,
amelyet vizespohárba töltetett magának.
A fölriasztott toprongyos vendég állt egy ideig, azután visszaült a
sarokba. Monostory ekkor ismert rá.
– Hohó, báró úr, – kiáltott föl örömmel.
A báró úr megháborodott szegény zsidó volt, ártatlan bolond, aki
csak akkor jött dühbe és akkor lett veszedelmessé, ha nem akarták
neki elhinni, hogy báró. A Monostory kiáltására gyanakodva emelte
föl a fejét, mert még nem tudta, hivéssel vagy csúfolódással kerül-e
szembe; de Monostory megnyugtatta:
– Báró úr, – mondta, – legyen szerencsém. Tiszteljen meg,
kérem…
A báró úr kijött a sarokból és megállt a Monostory asztala
mellett. Cserzett arcából, elvadult fekete szőrzete közül nedvesen
lángolt ki nagy szeme.
– No mi ujság, báró úr? – kérdezte Monostory.
A báró úr fölemelte kérges hüvelykujját.
– A császár – mondta halkan és figyelmeztetően – nemsokára
eljön…
– És?
– És mindenkit kivégeztet.
– És?
– Engem elismer. És akkor…
Gyönyörűség ragyogása ömlött el sötét arcán.
– És akkor? – kérdezte Monostory.
– És akkor azután, – súgta reszketve és áhítatosan a báró, – a
Morgenrot boltja az enyém lesz.
Monostory rábámult. Ezért kell a császárnak eljönnie és
mindenkit kivégeztetnie? Ebbe lehet beleőrülni? Elnevette magát.
– No jó, báró úr, üljön le.
A báró úr készült leülni, amikor Monostorynak eszébe jutott
valami.
– Nézze, báró úr, – mondta, – ha már ilyen szépen együtt
vagyunk, nem lehetne előkeríteni az ön kitünő barátját: a főurat is?
A báró úr félénken ránézett a kocsmárosra; a kocsmáros, aki
szolgálattételre készen állott a közelben, sietve válaszolt:
– Itt van.
– Hol?
– Az udvaron. Alszik. Nem volt szabad bejönnie, mert nem volt
pénze.
– Jőjjön be, – kiáltotta Monostory, – és ha van még egypár ebből
a nemből a közelben, csak hadd jőjjön. Én fizetek mindent.
A kocsmáros kiment az udvarra és fél perc mulva bejött az álmos,
de jókedvű főúrral. A főúr is csendes bolond volt; a román
papnevelőintézetbe járt valamikor és kétségbeesve ragaszkodott a
papi ruhához, amely mindig szétmállott a testén, mire megint kapott
valahol egy régi reverendát. Az elméjének úgyszólván semmi baja
sem volt; mindig lobogott a jókedve: ez volt az egész; mindig
nevetett és öt percenkint a fejéhez kellett kapnia a kezét és össze
kellett vernie a bokáját, mintha táncolni akarna és mintha egy lelkes
csuhajt akarna elkiáltani.
Á
Bejött. Álmosan mosolygott. Megállott. Monostory ránézett. A
főúr kényesen a fejéhez kapta a kezét és villámgyorsan, hetykén,
mintha táncolni akarna, összecsapta bokáját.
– Ez az! – mondta Monostory. – Üljön le, főúr. Maga az én
emberem. Magam is így mulatok: fölkapom a kezem, összeverem a
bokám, a jó Isten tudja, miért.
A főúr leült az asztalhoz. A báró már ott ült. Monostory ételt és
italt adatott nekik. Az ajtó lassan föl-fölnyilott és egy-egy új rongyos
alak lopódzkodott be. A Monostory intésére azok is odaültek az
asztalhoz és boldogan ettek és ittak. Monostory ott ült közöttük,
csendesen beszélgetett velük, vizes poharából még mindig
szomjasan itta a pálinkát és most végre úgy érezte, hogy a
részegség köde lassan elborítja az agyát. Kellemes fáradtságot
érzett, amely mégis élénkség volt; úgy érezte, hogy lebeg és
elmerül; mosolygott és semmi másra nem gondolt többé, csak arra,
amit kimond.
Végignézett az őrülteken és rongyosokon, akik között ült és
halkan, derűsen mondta:
– Symposion.
Plátóra gondolt; és körültekintett, nem ront-e be a mulató
társaságba Alkibiadesz mámorosan és ibolyakoszorús fejjel, hogy
Szokrateszről beszéljen. Úgy érezte, görög bölcsek között ül és az
őrülteknek és rongyosoknak görög bölcsek álmairól beszélt:
– A léleknek – mondta – valamikor szárnya volt és fent repült az
istenek útján. Van lélek, amely a hitvány testben is emlékszik rá,
hogy valaha szárnya volt. Ez az emlékező lélek csapkod és
vergődik…
Rongyos társasága szájtátva hallgatta és Monostory részegen
magyarázta nekik Eroszt, a Symposiont és Phaidroszt. Kint azonban
hajnalodott és a hajnal kék sugarai befénylettek a kocsma füstös
lámpája köré. Monostory egymásután ürítette ki a pálinkával telt
nagy poharakat és most magasra csapott benne a boldog mámor.
Fölugrott.
– Itt az édes hajnal, – mondta, – mi most megyünk és áldozunk
a Napistennek.
Összegyűjtötte rongyos seregét és otthagyta velük a kocsmát. A
báróra és a főúrra támaszkodott, a többi rongyost maga mögé
rendelte. Lassan haladtak előre és a mögötte lévő rongyos had egyre
nőtt. A kis városnak szinte minden megtépettje, elesettje és koldusa
rátalált a menetre és hozzája csatlakozott. A tömeg zúgva haladt
előre; az ujonnan jöttek kérdezősködtek, majd türelmetlenül
követelőztek. Akik már a kocsmában is ott voltak, azok a Monostory
szavait ismételték:
– A léleknek szárnya volt valamikor, – kiáltozta egy félszemü
kucséber.
– Megyünk áldozni a Napistennek, – mondták mások.
Monostory boldogan haladt elől a báró és a főúr között. Élvezte a
zúgást, amelyet maga mögött hallott; úgy érezte, ez a zúgás, mint
valami nagyszerü folyam, ringatva viszi előre; nevető örömet érzett
azon, hogy hajnalodik és tudta, hogy mámoros hadával valami
nagyszerü dolgot kell csinálnia. Valamit, ami robban és dördül.
Valamit, ami a föld széléig és az ég tetejéig harsog. Valami óriási
tűzvészt fölgyújtani…
A piacon, amely már elevenedett, egy hordó bort üttetett csapra.
Az igyék, aki akar. Egy ezüstpénzt megforgatott a kezében és
odadobta egy szomjasan nyakaló sántának:
– Eredj a Bárányba: a Marci bandája jőjjön ide. És ahány
cigánybanda van, mind jőjjön ide.
Most dadogott már egy kissé, bizonytalanul állt a lábán és
bizonytalanok voltak a tervei.
– A végén, – mondta dadogva, – máglyát raktok, sóval és borral
hintitek meg és engem rajta elégettek…
– Éljen a nagyságos úr, – zúgta a folyton szaporodó tömeg.
Monostory körülnézett és a Piac-tér tulsó oldalán meglátta a
Nagytemplomot. A Nagytemplom hatalmas román ívei ragyogni
kezdtek a feljövő nap fényében; a hatalmas terraszon, amelyre a
templom épült, virágzó akácfák és szentek fehér márványszobrai
állottak. Az egész kép egyre lángolóbb és egyre fényesebb lett;
Monostory kitárt karral indult feléje.
A terrasz alján megállott és bizonytalanul nézett a hatalmas fehér
kőlépcsőre, amely három menetben a templom főbejáratáig vitt.
Most mi legyen? Bemegy-e most a templomba részegen lármázó
hadával? Mámoros pillantása végigsiklott a tömegen és megpihent
egy szines bábún, egy cifraruhás kövesdi parasztlányon, aki bámulva
nézte a részeg, rongyos hadat és a rongyos had úri vezérét.
Ránézett a bámuló parasztleányra és mosolyogni kezdett örömében.
– Parasztpillangó, – mondta magában, – el ne repülj.
Odalépett a leányhoz. A leány ijedten hátrált apjához, anyjához.
Az apja védekezésre készült. Monostory belenyúlt a zsebébe és egy
nagy bankót hajított oda neki.
– Fogd meg, – mondta, – nem szúrom érte gombostűre.
A leány és az apja még mindig nyugtalankodott. Monostory a
pisztolyát mutatta nekik.
– Parasztpillangó, – mondta, – el ne repülj. – Hogy hínak?
– Orosz Zsuzsánna, – mondta a leány remegve.
Monostory megfogta kicsi, durva kezét.
– Orosz Zsuzsánna, – szólt dadogva, – mi most téged imádni
fogunk.
Rongyos hadához fordult:
– Imádni fogjuk most, – mondta, – mi asszonyunkat, Orosz
Zsuzsánnát.
A terrasz a lépcső két szélén erkélybe ugrott ki. Monostory
odavezette Orosz Zsuzsánnát. De itt megállott.
– Nem léphetsz a kőre, – mondta. – Szőnyeget ide.
Szőnyeg nem volt kapható. Monostory bosszúsan ordította:
– Szőnyeget ide, oltártakarót, lágyat…
A tömeg nevetni kezdett és Monostory a pisztolya után nyúlt. Egy
másodpercre úgy volt, hogy belelő a tömegbe, de ekkor a tömeg
fölött elsikló szeme virággal rakott szekeret vett észre. A kocsi lassan
döcögött a Piac-tér felé.
– A virágokat ide, – kiáltotta ekkor Monostory. – Minden virágot
ide.
Tíz ember rohant egyszerre a szekér felé és ordítva magyarázta a
parasztkertésznek, aki rajta ült, hogy a nagyságos úr minden virágját
megveszi. A lovait megfogták, a szekeret megfordították, az óriási
virághalom ott volt a Monostory lábánál. A rémült kertész ordítva
követelte a pénzét. Monostory pénzt dobott neki; a kertész
elhallgatott.
– Minden virágot föl az erkélyre.
A tömeg nekiesett a virágoknak. Sötétpiros pünkösdi rózsák
röpködtek mint a láng és mint a vér és végigcsordultak az erkélyen.
Föléjük lila iriszek borultak bágyadt, hosszu száron. Közbe röppent
még néhány szál késői orgona is, néhány szál szegfü és korai rózsa
és az egészre mint egy-egy ezüst pehely rálibbent néhány fürt
akácvirág. Az erkélyen ki volt terítve a dús szőnyeg.
– Állj rá, Orosz Zsuzsánna, – mondta Monostory.
Orosz Zsuzsánna térdig virágban, szégyenkezve állott a
Nagytemplom terraszának legszélső erkélyén. Monostory ekkor a
cigányokat kereste. A cigányok ott voltak már és gyanakvó arccal
várták a parancsát.
– Marci, – mondta Monostory dadogva a primásnak, – most
valami olyat kell húznotok… Valami hallatlant… Valami csodaszépet…
Valami lángoló himnuszt…
Az öreg cigányprimás kelletlenül vonogatta a vállát, mert lenézte
a csőcseléket, amely körülötte tolongott.
– Hanem kevesen vagytok, – mondta reszketve Monostory. –
Minden cigánybanda jőjjön ide; és szólaljon meg odabent az orgona
is és rendüljön meg a föld a szépség himnuszától.
Keleten, a templom mögött fölbukkant a nap.
– A Napisten, – ordította Monostory. – A Napisten himnuszát! A
föld reszkessen tőle…
Mámorosan és türelmetlenül nyult a hegedü után, de a részeg és
ordító tömegen ekkor egy lovas verte át türelmetlenül a lovát.
Monostoryt ismerős hang riasztotta föl. Visszanézett. A tömeg
közepén ismerős ló állott és a lovas dühösen kiabált:
– Nagyságos úr, itt a levél. Lehúznak ezek a gazemberek.
Monostory bágyadtan intett. A tömeg hozzáeresztette a lovast, az
erdőmonostori legényt, akit az éjjel egyszer már hazakergetett. A
legény most elszánt volt, hangos és határozott. Levelet nyujtott
feléje.
– Tessen rögtön elolvasni, – mondta határozottan.
Monostory kábultan, engedelmesen nyult a levél után és
megborzongott, mielőtt kinyitotta. A felesége levélpapirja, a felesége
írása. Elolvassa-e? Ne rakasson-e óriási máglyát csak azért, hogy ezt
a levelet rátegye és elégesse? Habozott. A cigányokhoz akart
fordulni; meg akarta parancsolni, hogy zúgjon a csodálatos himnusz,
amelyre vágyódott, de azután egy rántással mégis föltépte a
borítékot.
Részeg volt. A betűk táncoltak előtte. A tenyerét rászorította a
szemére, hogy szeme égését hűtse egy kicsit, azután újra megnézte,
mi áll a levélben. A levél a felesége írása volt és ez állott benne:

Jőjjön azonnal haza; apa agyonlőtte magát.


Ida.

Monostory részegen nézte ezeket a kegyetlen szavakat; előbb az


az érzése volt, hogy arccal leveti magát a földre és egy
örökkévalóságon át úgy marad; de azután észrevette maga körül a
tömeget, gőgösen fölemelte a fejét, elrugta magától azokat, akik
hozzá akartak csatlakozni és a tömegen át emelt fejjel, égő
szemmel, visszatérő, hideg józansággal, zakatoló szívvel indult a
kocsija felé.
A kocsija ott állott a Bárány-szálló előtt. Hatodik napja állott már
ott: mindennap estétől hajnalig. A kocsisnak csak akkor volt szabad
aludnia és a lovak csak akkor pihenhettek, mikor ő aludt: nappal. A
lovak most is ott állottak reszkető lábbal és a kocsis álmosan ott ült a
bakon.
Monostory odaért a kocsihoz és lassan felült a hátsó ülésre. A
kocsis ijedten kérdezte, nem ő hajt-e. Monostory szótlanul intett
nemet. Hová menjenek, kérdezte a kocsis. Monostory halkan és
eltorzult szájjal felelte hogy: haza. Nem parancsol-e valami
köpönyeget? Hűvös van. Monostory intett, hogy nem. A kocsis
leszedte a pokrócot a lovakról, a könnyü kocsi megindult és
Monostory lehajtott fővel ült a hátsó ülésen.
Most tökéletesen józan volt és tudott mindent: tudta azt is, hogy
mi történt és tudta azt is, hogy mi vár rá. A kocsis suhogtatta az
ostort, hogy a fáradt lovak egyenletes ügetésben maradjanak; és a
tiszta országúton, a hűvös reggelben Monostory didergő testtel,
magába sülyedve, egy óra alatt átélte egész elmult és egész
eljövendő életét.
II.
A kocsi fölhajtott az erdőmonostori kastély elé, Monostory
leszállott róla, bement a kőkockás előcsarnokba és tudta, hogy itt
találja a feleségét. Valóban ott találta. Eddig egy fonott széken ült
kinyitott levéllel az ölében, most fölkelt, elébe jött és megállt előtte.
Hűvös, tiszta, szőke szépsége fájt Monostorynak. Égő szemét
lesütötte és szótlanul nyult az asszony keze után, hogy megcsókolja.
– Bocsásson meg a levelem durvaságáért, – mondta az asszony.
– Attól tartottam, hogy ha nem írok ilyen nyiltan, azt hiszi, hogy csak
haza akarom csalni. Azért kellett ilyen brutálisan írnom…
– Jól tette, – válaszolt halkan Monostory. – Enélkül csakugyan
nem jöttem volna haza.
Elhallgatott, lehajtotta a fejét, és erre hosszú hallgatás támadt.
– Nem akarja, – kérdezte végre halkan az asszony, – hogy
elmondjam: hogyan történt?
Monostory fölnézett és összeszorított ajakkal felelte:
– Azt hiszem: úgyis tudom. Vacsoránál nem látszott rajta semmi,
vacsora után beszélgettek, ő azután visszavonult a szobájába,
leveleket írt, és tizenkét óra tájban egy dördülés hallatszott a
szobájából…
– Honnan tudja? – kérdezte bámulva az asszony.
Monostory nem válaszolt. Vállat vont és elnézett az asszony
szőke feje fölött. Pár másodperc múlva azonban vissza kellett néznie
az asszony tiszta, kék szemébe, amely nedvesen és megindultan
lángolt rá, mintha látná a gondolatait. Ekkor egyszerre forró és nagy
vágy rohanta meg. Ha most megölelné ezt a tiszta és üde asszonyt,
ha finom, keskeny és hideg ajkát egy izzó csókkal meggyujthatná
úgy, mint a házasságuk első évében… Ha oda lehetne még
menekülni ehhez a tisztasághoz, ehhez a szőkeséghez, ehhez a
nyugalomhoz, ehhez a hűvös és tartós szeretethez. Összeszorította a
fogát és könny szökött a szemébe, úgy viaskodott a vágyával.
Az asszony nem vett észre a küzdelméből semmit. De mert
Monostory nem szólt, ő kérdezte meg jósággal és gyöngéden:
– Nem akar velem beszélgetni egy kicsit arról… arról, hogy mi
lesz?
A Monostory küzdelmének ekkor egyszerre vége lett. Ez a jóság,
amelyet annyiszor tapasztalt, túlságosan pontos volt neki; ez a
gyöngédség, amely annyiszor lefegyverezte és megszégyenítette,
nagyon is gyorsan jelentkezett. Házasságuk ötéves harcában a mai
napon ő szenvedte el a végleges és döntő vereséget; minél
nagylelkűbb a kegyelem, annál nagyobb az ő szégyene.
Rákényszerítette a hangját, hogy hálás legyen:
– Köszönöm, Ida, – mondta, – de előbb szeretnék tájékozódni
egy kicsit. Hol vannak azok a levelek, amelyeket az apám
hátrahagyott?
Azt mondta: az apám, nem így általánosságban: apa. Halott apját
elvette ettől a tiszta, szép, szőke asszonytól. Eddig harcolt az
apjával, eddig sokszor megsebezték egymást, és sokszor úgy volt,
hogy ez a jó és tiszta asszony igazán a lánya az ő apjának, ő pedig
senkije; de most nyilvánvaló lett, hogy ők, ő meg az apja,
összetartoznak és ez a gyöngéd és kedves asszony egy jószívű
idegen, akihez nekik semmi közük sincs.
Az asszony habozva válaszolt a kérdésére:
– Csak két levelet írt.
– És e kettő közül egyik sem szól nekem.
– Egyik sem.
Az asszony aggódva nézett rá, de Monostory komolyan bólintott.
Ezt is tudta.
– A két levél közül, – folytatta azután félénken az asszony, –
egyik nekem szól.
A levél után nyult, amelyet az előbb az ölében tartott.
– Hagyja, Ida, – mondta Monostory. – Azt írja benne, hogy
magát nagyon szereti és hogy maga ne hagyjon el engem, ha meg
tud még nekem bocsátani…
– Honnan tudja? – kérdezte megint rémülten az asszony.
Monostory újra vállat vont. Nem akarta elmondani az asszonynak,
hogy az egy óra alatt, mialatt hazafelé jött, átélte a maga egész
elmult életét, benne az apjával vívott minden harcával és hogy
ezalatt az egy óra alatt értette meg, hogy az apjával azért sebezték
egymást véresre, mert neki nemcsak minden vonása, hanem a
lelkének minden hullámzása olyan, mint az apjáé volt. Ő is így lőtte
volna magát főbe. Ő is így fogja magát főbelőni, amikor majd –.
Egy legyintéssel elhárította az asszony kérdését és ő kérdezte
meg:
– A másik levél?
– A másik levél, – felelte az asszony meghökkenve és elfogódva,
– Rostásnak szól.
– Gondoltam. Átvette már?
– Igen.
– Itt van?
– Igen. Odaát dolgozik az irodában.
– Kedves Ida, – mondta Monostory, – akkor engedje meg, hogy
most átmenjek hozzá. Később azután, ha nincs ellenére,
bekopogtatok magához és akkor beszélgethetünk.
Az asszony elfogódva bólintott és fölment a lépcsőn. Monostory
végigment a folyosón és a folyosó végén bement egy kis szobába,
amelyet uradalmi irodának használtak. Itt találta könyvek és könnyek
között Rostást, öreg tiszttartójukat, akit lecsendesített és akivel
könyvek és írások fölött négy óra hosszat dolgozott. Tíz óra után
kijött az irodából, fölment a szobájába, megfürdött,
megborotválkozott, átöltözködött és azután bekopogtatott a
feleségéhez.
A feleségénél ott volt a fiuk is: négy éves, szép szőke fiú.
Monostory megsímogatta a fia fejét, amelynek egész formája és
minden vonása az anyjáé volt, azután kiküldte őt a szobából. A kis
fiú engedelmesen kiment.
– Én nem mentem volna így ki négy éves koromban, – gondolta
Monostory. – Ennek nem lesz baja az életben.
Elgondolkozva tekintett a fia után, azután visszafordult a
feleségéhez. Az asszony feszült figyelemmel nézett rá, az idegei
szinte megpattantak a várakozástól. Monostory kerülte a felesége
tekintetét, igyekezett elfogulatlanul játszani az óraláncával és úgy
kezdett beszélni, mint aki szeretetreméltó semmiségeket mond:
– Kedves Ida, – kezdte, – a helyzet valóban olyan, mint
amilyennek képzeltem: hogy úgy mondjam… azaz… egy bizonyos
értelemben vígasztalan.
Az asszony sápadtan várakozott és egyelőre nem szólt semmit.
Monostory folytatta:
– Az egész birtok mindenestül úgy meg van terhelve, hogy
oktalanság tovább vesződni vele. Ha olyan termésünk találna lenni,
amilyen száz év óta nem volt, ősszel akkor sem tudjuk még a
kamatokat sem fizetni. Az utolsó nagy kölcsön, amely természetesen
szétrepült a kezünk között, mint a pelyva, betette a kaput. Itt nem
szabad, nem is lehet tovább vergődni; itt gyorsan végezni kell:
eladni mindent, és örülni, ha mindent ki tudunk fizetni.
Az asszony még mindig hallgatott. Monostory egy pillantásra
fölnézett rá, de ezután a futó pillantás után még gondosabban
kerülte a tekintetét.
– Ebben a sivár helyzetben, – mondta halkabban és minden
erejét összeszedve, hogy elfogulatlanul beszélhessen, – ebben a
sivár helyzetben egy van, ami vígasztaló: az, hogy a maga
hozománya teljes épségben megvan. A Lápos-puszta kissé el van
hanyagolva, de teljesen tehermentes; és a pénze egy összegben el
van helyezve egy igen jó budapesti intézetben. Ez, amint mondtam,
vígasztaló… sőt azt mondhatom… igen megnyugtató… igen
örvendetes…
Akadozott. Az asszony elborult homlokkal hallgatta, és mikor
akadozni kezdett, sötéten, röviden közbevetette:
– Miért?
Monostory meglepetve nézett rá:
– De, kedves Ida, – mondta, – bocsásson meg…
Az asszony kék szeme szikrázott.
– Ahogy én magát ismerem, – mondta élesen, – mindezt azért
találja örvendetesnek és megnyugtatónak, mert engem most nemes
módon kitehet, mert elegánsan kidobhat, mert nagylelkű gesztussal
megszabadúlhat tőlem.
Monostory zavarodottan nézett rá. Az asszony lihegett és lángoló
arccal suttogta:
– Mondja meg, hogy azt akarja ajánlani, váljunk el.
Monostory kényszeredetten forgatta a fejét.
– Mondja meg, – sürgette az asszony. – Ugy-e, azt akarja
ajánlani? Ugy-e, azt?
– Azt, – felelte lehajtott fejjel Monostory.
Az asszonynak fölbuggyant az erőszakkal elfojtott zokogása.
Fölállott. A szívére és a szájára szorította a kezét, járkált egy ideig,
azután fölindultan és fuldokolva mondta:
– És nem érzi, milyen kegyetlen ez a maga nagylelkűsége? Nem
érzi, hogy ez a maga nobilitása milyen… milyen ordináré?
Monostory még mélyebbre hajtotta le a fejét és egy ideig megint
úgy ült ott magába sülyedve, mint ahogyan a kocsin ült, amikor
számon vette a multját és a jövendőjét. Az asszony elhallgatott és
várt a feleletére. A Monostory felelete szelid volt és bánatos.
– Jól van, Ida, – mondta, – hát maga hogy képzeli a dolgot?
– Én úgy képzelem, – felelte hevesen az asszony, – hogy amim
nekem van, az a magáé. És azzal, amim nekem van, vagy meg
tudjuk tartani Erdő-Monostort, vagy ha nem tudjuk, akkor
elmegyünk innen és élünk… élünk abból, amim nekem van.
– És?
– Mit és?
– És: hogyan képzeli maga az én életemet? Hogyan kell majd
nekem élnem?
Az asszony megzavarodott.
– Istenem, – mondta, – hát… természetesen… én azt hiszem…
Monostory bólintott. A hangjában nem volt semmi kihívás és
semmi rosszakarat.
– Természetesen, – mondta, – úgy, ahogyan maga akarja.
Az asszony kétségbeesve fakadt ki:
– Hát még most sem látja be, hogy az a helyesebb?
Monostory bánatosan és fáradtan elmosolyodott:
– „Helyesebb!?“, – mondta ajkbiggyesztve, – miért ne… persze,
hogy az a helyesebb…
Az asszony érezte, hogy a beszélgetés rossz irányba téved és
ijedten erőlködött, hogy megint jó hangot üssön meg. Leült,
megfogta a férje fehér és erős kezét és könyörögve mondta:
– Látja: maga most verekedhetne ki még az élettől mindent;
most lehetne minden, ami lenni akart… Ami eddig történt: az a nagy
iskola volt, amelyen át kell mennie mindenkinek, aki valami nagyot
akar elérni…
Monostory bágyadtan kérdezte, inkább magától, mint tőle:
– Hát akarok én?
– Akar! – kiáltotta az asszony. – Akar; és mindent elér, ha énrám
hallgat. Amihez maga komolyan hozzáfog, az sikerül. Ha csak akarja,
ha csak nekem… ha csak velem… ha csak úgy csinálja, ahogyan én
tanácsolom.
Monostory nagyot lélegzett és fölállott.
– Kedves Ida, – mondta lehajtott fejjel, szomorú szívvel és
lankadt lélekkel, – mindennek volna némi értelme akkor…
Megakadt. Még nem merte kimondani, amit akart.
– Arról, – kezdte újra, – hogy mi az igazi nagylelkűség, arról
beszélhetnénk…
Megint megakadt. Próbálta melegebben:
– Arról, hogy én a maga nagy jóságát elfogadjam, arról szó
lehetne akkor, ha én azt hinném, hogy maga mindezt nem csupán
nagylelkűségből mondja, nem csupán azért, mert maga igazán
nemes és előkelő teremtés, hanem azért, mert… még szeret engem.
Az asszony föl akart sikoltani. Monostory egy mozdulattal
elhallgattatta:
– Nézzen a szívébe, – mondta mély szomorúsággal, – legyen
őszinte: maga engem már régen nem szeret.
Az arca elszürkült a rettentő bágyadtságtól, amely most
ereszkedett le rá. Olyan irtózatos fáradtságot érzett, hogy a halál
nyugalma édesnek és kívánatosnak tünt föl előtte. De mint egy
elbúsúlt, nemes és haldokló harcos, végső erőfeszítéssel befejezte a
becsületharc munkáját, amelyet elkezdett:
– És igaza van, – mondta fáradt ajakkal és hunyó szemmel, –
hogy engem nem szeret… nem azért, mert esztendők óta rosszul
bánok magával, hanem azért, mert esztendők óta már: én sem
szeretem magát.
Az asszony összeszorított ajakkal, sápadtan nézett rá, ő
megfordult, a nagy erőfeszítéstől szinte tántorogva kiment, átment a
szobájába, lezuhant az ágyára és húsz óra hosszat aludt.
Amikor fölébredt, minden elő volt készítve a temetésre. Ő még
megnézte az apját a koporsóban, és amikor meglátta, egyedül akart
vele maradni. Egy félóra hosszat egyedül maradt a halottal és az
apjának kemény és makacs vonásaiból, amelyekhez úgy
hasonlítottak az ő vonásai, ismét megpróbálta kiolvasni a saját
sorsát. Megerősödött az az érzése, hogy tud mindent, ami még
számára eljövendő, és amikor leszegeztette a koporsót, nemcsak
nyugodt volt, hanem szinte derült.
A temetés után a felesége hivatta. Fölment hozzá. Az asszony
utiruhában állott a szobája közepén. Vele volt a fia is.
– Isten vele, István, – mondta az asszony. – Én utazom.
– Isten vele, kedves Ida, – mondta Monostory. – én…
Nem tudta folytatni. Az asszony azonban várakozott.
– Én nagyon hálás vagyok magának, – mondta Monostory, – és…
Újra megakadt. Az asszony várakozott.
– És remélem, bizonyos vagyok benne, – mondta Monostory, –
hogy az élet mindenért kárpótlást ad még magának.
Ekkor nem várakozott tovább az asszony. Odafordult a fiához:
– Búcsúzz el édesapádtól, – mondta neki reszkető hangon.
Monostory megölelte a kis fiut; az asszonynak kezet csókolt; az
asszony a kis fiuval azután lement az udvarra és beült a hintóba;
Monostory lekísérte őket; a hintó elrobogott és Monostory egyedül
maradt.
Két hét múlva ő is elutazott. A kastélyt és a birtokot ekkorra
megvette az a bank, amely a legtöbb kölcsönt adta rá;
Monostorynak a finom utiládáin, a cigarettatárcáin, a ruháin és a
pecsétes gyűrűjén kívül volt kerekszámban négy és fél ezer
koronája.
Welcome to Our Bookstore - The Ultimate Destination for Book Lovers
Are you passionate about books and eager to explore new worlds of
knowledge? At our website, we offer a vast collection of books that
cater to every interest and age group. From classic literature to
specialized publications, self-help books, and children’s stories, we
have it all! Each book is a gateway to new adventures, helping you
expand your knowledge and nourish your soul
Experience Convenient and Enjoyable Book Shopping Our website is more
than just an online bookstore—it’s a bridge connecting readers to the
timeless values of culture and wisdom. With a sleek and user-friendly
interface and a smart search system, you can find your favorite books
quickly and easily. Enjoy special promotions, fast home delivery, and
a seamless shopping experience that saves you time and enhances your
love for reading.
Let us accompany you on the journey of exploring knowledge and
personal growth!

ebookball.com

You might also like