100% found this document useful (5 votes)
74 views

Instant Download Data structures and algorithms made easy in Java data structure and algorithmic puzzles 2nd Edition Narasimha Karumanchi PDF All Chapters

Narasimha

Uploaded by

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

Instant Download Data structures and algorithms made easy in Java data structure and algorithmic puzzles 2nd Edition Narasimha Karumanchi PDF All Chapters

Narasimha

Uploaded by

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

Visit https://ebookgate.

com to download the full version and


explore more ebooks

Data structures and algorithms made easy in Java


data structure and algorithmic puzzles 2nd Edition
Narasimha Karumanchi

_____ Click the link below to download _____


https://ebookgate.com/product/data-structures-and-
algorithms-made-easy-in-java-data-structure-and-
algorithmic-puzzles-2nd-edition-narasimha-karumanchi/

Explore and download more ebooks at ebookgate.com


Here are some recommended products that might interest you.
You can download now and explore!

Data Structures Algorithms And Applications In C 2nd


Edition Sartaj Sahni

https://ebookgate.com/product/data-structures-algorithms-and-
applications-in-c-2nd-edition-sartaj-sahni/

ebookgate.com

Java Structures Data Structures in Java for the Principled


Programmer 2nd edition Duane Bailey

https://ebookgate.com/product/java-structures-data-structures-in-java-
for-the-principled-programmer-2nd-edition-duane-bailey/

ebookgate.com

Data structures and abstractions with Java 2nd ed Edition


Carrano

https://ebookgate.com/product/data-structures-and-abstractions-with-
java-2nd-ed-edition-carrano/

ebookgate.com

Data Structures and Algorithms in C 4th Edition Adam


Drozdek

https://ebookgate.com/product/data-structures-and-algorithms-in-c-4th-
edition-adam-drozdek/

ebookgate.com
Data Structures and Algorithms in C 1st Edition Michael
Mcmillan

https://ebookgate.com/product/data-structures-and-algorithms-in-c-1st-
edition-michael-mcmillan/

ebookgate.com

Data Structures and Algorithms Using C 1st Edition Michael


Mcmillan

https://ebookgate.com/product/data-structures-and-algorithms-
using-c-1st-edition-michael-mcmillan/

ebookgate.com

Java Software Structures Designing and Using Data


Structures 3rd Edition John Lewis

https://ebookgate.com/product/java-software-structures-designing-and-
using-data-structures-3rd-edition-john-lewis/

ebookgate.com

Java Foundations Introduction to Program Design and Data


Structures 2nd Edition John Lewis

https://ebookgate.com/product/java-foundations-introduction-to-
program-design-and-data-structures-2nd-edition-john-lewis/

ebookgate.com

Data Structures Outside In with Java 1st Edition Sesh


Venugopal

https://ebookgate.com/product/data-structures-outside-in-with-
java-1st-edition-sesh-venugopal/

ebookgate.com
Data Structures
And
Algorithms
Made Easy In JAVA
Data Structures and Algorithmic Puzzles

By
Narasimha Karumanchi

Concepts Problems Interview Questions


Copyright ©2020 by .
All rights reserved.
Designed by ℎ ℎ

©
Copyright 2020 CareerMonk Publications. All rights reserved.
All rights reserved. No part of this book may be reproduced in any form or by any electronic or mechanical means, including information
storage and retrieval systems, without written permission from the publisher or author.

This book has been published with all efforts taken to make the material error-free after the consent of the author. However, the author and
the publisher do not assume and hereby disclaim any liability to any party for any loss, damage, or disruption caused by errors or omissions,
whether such errors or omissions result from negligence, accident, or any other cause.

While every effort has been made to avoid any mistake or omission, this publication is being sold on the condition and understanding that
neither the author nor the publishers or printers would be liable in any manner to any person by reason of any mistake or omission in this
publication or for any action taken or omitted to be taken or advice rendered or accepted on the basis of this work. For any defect in printing
or binding the publishers will be liable only to replace the defective copy by another copy of this work then available.
Acknowledgements
ℎ and ℎ , it is impossible to thank you adequately for everything you have done, from loving me unconditionally to raising me in
a stable household, where your persistent efforts and traditional values taught your children to celebrate and embrace life. I could not have
asked for better parents or role-models. You showed me that anything is possible with faith, hard work and determination.

This book would not have been possible without the help of many people. I would like to express my gratitude to all of the people who
provided support, talked things over, read, wrote, offered comments, allowed me to quote their remarks and assisted in the editing,
proofreading and design. In particular, I would like to thank the following individuals:

 ℎ , IIT Bombay, Architect, dataRPM Pvt. Ltd.


 , Senior Consultant, Juniper Networks Inc.
 . ℎ ℎ , IIT Kanpur, Mentor Graphics Inc.

- ℎ ℎ
M-Tech,
Founder, .
Preface
Dear Reader,

Please hold on! I know many people typically do not read the Preface of a book. But I strongly recommend that you read this particular
Preface.

It is not the main objective of this book to present you with the theorems and proofs on and ℎ . I have followed
a pattern of improving the problem solutions with different complexities (for each problem, you will find multiple solutions with different,
and reduced, complexities). Basically, it’s an enumeration of possible solutions. With this approach, even if you get a new question, it will
show you a way to think about the possible solutions. You will find this book useful for interview preparation, competitive exams preparation,
and campus interview preparations.

As a , if you read the complete book, I am sure you will be able to challenge the interviewers. If you read it as an , it
will help you to deliver lectures with an approach that is easy to follow, and as a result your students will appreciate the fact that they have
opted for Computer Science / Information Technology as their degree.

This book is also useful for and during their academic preparations. In all the
chapters you will see that there is more emphasis on problems and their analysis rather than on theory. In each chapter, you will first read
about the basic required theory, which is then followed by a section on problem sets. In total, there are approximately 700 algorithmic
problems, all with solutions.

If you read the book as a preparing for competitive exams for Computer Science / Information Technology, the content covers
the topics in full detail. While writing this book, my main focus was to help students who are preparing for these exams.

In all the chapters you will see more emphasis on problems and analysis rather than on theory. In each chapter, you will first see the basic
required theory followed by various problems.

For many problems, solutions are provided with different levels of complexity. We start with the solution and slowly
move toward the possible for that problem. For each problem, we endeavor to understand how much time the algorithm takes
and how much memory the algorithm uses.

It is recommended that the reader does at least one complete reading of this book to gain a full understanding of all the topics that are
covered. Then, in subsequent readings you can skip directly to any chapter to refer to a specific topic. Even though many readings have been
done for the purpose of correcting errors, there could still be some minor typos in the book. If any are found, they will be updated
at . . . You can monitor this site for any corrections and also for new problems and solutions. Also, please provide
your valuable suggestions at: @ . .

I wish you all the best and I am confident that you will find this book useful.

- ℎ ℎ
M-Tech,
Founder, .
Other Books by Narasimha Karumanchi

IT Interview Questions
Elements of Computer Networking
Data Structures and Algorithmic Thinking with Python
Data Structures and Algorithms Made Easy (C/C++)
Coding Interview Questions
Data Structures and Algorithms for GATE
Peeling Design Patterns
Algorithm Design Techniques
Data Structure Operations Cheat Sheet
Space
Average Case Time Complexity Worst Case Time Complexity
Data Structure Complexity
Name Accessing Accessing
Search Insertion Deletion Search Insertion Deletion Worst Case
element element
Arrays O(1) O( ) O( ) O( ) O(1) O( ) O( ) O( ) O( )
Stacks O( ) O( ) O(1) O(1) O( ) O( ) O(1) O(1) O( )
Queues O( ) O( ) O(1) O(1) O( ) O( ) O(1) O(1) O( )
Binary Trees O( ) O( ) O( ) O( ) O( ) O( ) O( ) O( ) O( )
Binary Search
O( ) O( ) O( ) O( ) O( ) O( ) O( ) O( ) O( )
Trees
Balanced
Binary Search O( ) O( ) O( ) O( ) O( ) O( ) O( ) O( ) O( )
Trees
Hash Tables N/A O(1) O(1) O(1) N/A O( ) O( ) O( ) O( )

Note: For best case operations, the time complexities are O(1).

Sorting Algorithms Cheat Sheet


Space
Sorting Time Complexity
Complexity Is Sorting Class
Algorithm Remarks
Best Average Worst Stable? Type
Name Worst Case
Case Case Case
Bubble Sort O( ) O( ) O( ) O(1) Yes Comparison Not a preferred sorting algorithm.
In the best case (already sorted), every
Insertion Sort O( ) O( ) O( ) O(1) Yes Comparison
insert requires constant time
Even a perfectly sorted array requires
Selection Sort O( ) O( ) O( ) O(1) Yes Comparison
scanning the entire array
On arrays, it requires O( ) space; and on
Merge Sort O( ) O( ) O( ) O( ) Yes Comparison
linked lists, it requires constant space
By using input array as storage for the
Heap Sort O( ) O( ) O( ) O(1) No Comparison heap, it is possible to achieve constant
space
Randomly picking a pivot value can help
Quick Sort O( ) O( ) O( ) O( ) No Comparison avoid worst case scenarios such as a
perfectly sorted array.
Performing inorder traversal on the
Tree Sort O( ) O( ) O( ) O( ) Yes Comparison
balanced binary search tree.
Where is the range of the non-negative
Counting Sort O( + ) O( + ) O( + ) O( ) Yes Linear
key values.
Bucket sort is stable, if the underlying
Bucket Sort O( + ) O( + ) O( ) O( ) Yes Linear
sorting algorithm is stable.
Radix sort is stable, if the underlying
Radix Sort O( ) O( ) O( ) O( + ) Yes Linear
sorting algorithm is stable.
Table of Contents
1. Introduction -------------------------------------------------------------------------------------------------------------------------------------------------------------------- 15
1.1 Variables ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ 15
1.2 Data Types --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 15
1.3 Data Structure ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- 16
1.4 Abstract Data Types (ADTs) ------------------------------------------------------------------------------------------------------------------------------------------------- 16
1.5 What is an Algorithm? ---------------------------------------------------------------------------------------------------------------------------------------------------------- 16
1.6 Why the Analysis of Algorithms? ------------------------------------------------------------------------------------------------------------------------------------------- 16
1.7 Goal of the Analysis of Algorithms ----------------------------------------------------------------------------------------------------------------------------------------- 17
1.8 What is Running Time Analysis? ------------------------------------------------------------------------------------------------------------------------------------------- 17
1.9 How to Compare Algorithms------------------------------------------------------------------------------------------------------------------------------------------------- 17
1.10 What is Rate of Growth? ----------------------------------------------------------------------------------------------------------------------------------------------------- 17
1.11 Commonly Used Rates of Growth --------------------------------------------------------------------------------------------------------------------------------------- 17
1.12 Types of Analysis ---------------------------------------------------------------------------------------------------------------------------------------------------------------- 18
1.13 Asymptotic Notation ----------------------------------------------------------------------------------------------------------------------------------------------------------- 19
1.14 Big-O Notation ------------------------------------------------------------------------------------------------------------------------------------------------------------------- 19
1.15 Omega-Ω Notation [Lower Bounding Function] ------------------------------------------------------------------------------------------------------------------- 20
1.16 Theta- Notation---------------------------------------------------------------------------------------------------------------------------------------------------------------- 20
1.17 Why is it called Asymptotic Analysis?----------------------------------------------------------------------------------------------------------------------------------- 21
1.18 Guidelines for Asymptotic Analysis -------------------------------------------------------------------------------------------------------------------------------------- 21
1.20 Simplifying properties of asymptotic notations ---------------------------------------------------------------------------------------------------------------------- 22
1.21 Commonly used Logarithms and Summations ---------------------------------------------------------------------------------------------------------------------- 22
1.22 Master Theorem for Divide and Conquer Recurrences --------------------------------------------------------------------------------------------------------- 23
1.23 Divide and Conquer Master Theorem: Problems & Solutions ----------------------------------------------------------------------------------------------- 23
1.24 Master Theorem for Subtract and Conquer Recurrences------------------------------------------------------------------------------------------------------- 24
1.25 Variant of Subtraction and Conquer Master Theorem----------------------------------------------------------------------------------------------------------- 24
1.26 Method of Guessing and Confirming ----------------------------------------------------------------------------------------------------------------------------------- 24
1.27 Amortized Analysis ------------------------------------------------------------------------------------------------------------------------------------------------------------- 26
1.28 Algorithms Analysis: Problems & Solutions -------------------------------------------------------------------------------------------------------------------------- 26
2. Recursion and Backtracking --------------------------------------------------------------------------------------------------------------------------------------------- 36
2.1 Introduction ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 36
2.2 What is Recursion?--------------------------------------------------------------------------------------------------------------------------------------------------------------- 36
2.3 Why Recursion? ------------------------------------------------------------------------------------------------------------------------------------------------------------------- 36
2.4 Format of a Recursive Function --------------------------------------------------------------------------------------------------------------------------------------------- 36
2.5 Recursion and Memory (Visualization)----------------------------------------------------------------------------------------------------------------------------------- 37
2.6 Recursion versus Iteration ----------------------------------------------------------------------------------------------------------------------------------------------------- 37
2.7 Notes on Recursion -------------------------------------------------------------------------------------------------------------------------------------------------------------- 38
2.8 Example Algorithms of Recursion------------------------------------------------------------------------------------------------------------------------------------------ 38
2.9 Recursion: Problems & Solutions------------------------------------------------------------------------------------------------------------------------------------------- 38
2.10 What is Backtracking?--------------------------------------------------------------------------------------------------------------------------------------------------------- 39
2.11 Example Algorithms of Backtracking ----------------------------------------------------------------------------------------------------------------------------------- 39
2.12 Backtracking: Problems & Solutions------------------------------------------------------------------------------------------------------------------------------------- 39
3. Linked Lists--------------------------------------------------------------------------------------------------------------------------------------------------------------------- 41
3.1 What is a Linked List? ---------------------------------------------------------------------------------------------------------------------------------------------------------- 41
3.2 Linked Lists ADT----------------------------------------------------------------------------------------------------------------------------------------------------------------- 41
3.3 Why Linked Lists? --------------------------------------------------------------------------------------------------------------------------------------------------------------- 41
3.4 Arrays Overview ------------------------------------------------------------------------------------------------------------------------------------------------------------------- 41
3.5 Comparison of Linked Lists with Arrays & Dynamic Arrays ---------------------------------------------------------------------------------------------------- 42
3.6 Singly Linked Lists ---------------------------------------------------------------------------------------------------------------------------------------------------------------- 42
3.7 Doubly Linked Lists ------------------------------------------------------------------------------------------------------------------------------------------------------------- 48
3.8 Circular Linked Lists------------------------------------------------------------------------------------------------------------------------------------------------------------- 54
3.9 A Memory-efficient Doubly Linked List--------------------------------------------------------------------------------------------------------------------------------- 59
3.10 Unrolled Linked Lists --------------------------------------------------------------------------------------------------------------------------------------------------------- 59
3.11 Skip Lists---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 67
3.11 Linked Lists: Problems & Solutions ------------------------------------------------------------------------------------------------------------------------------------- 70
4. Stacks ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ 91
4.1 What is a Stack? ------------------------------------------------------------------------------------------------------------------------------------------------------------------- 91
4.2 How Stacks are used ------------------------------------------------------------------------------------------------------------------------------------------------------------- 91
4.3 Stack ADT --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 91
4.4 Applications ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 92
4.5 Implementation -------------------------------------------------------------------------------------------------------------------------------------------------------------------- 92
4.6 Comparison of Implementations ------------------------------------------------------------------------------------------------------------------------------------------- 97
4.8 Stacks: Problems & Solutions ------------------------------------------------------------------------------------------------------------------------------------------------ 97
5. Queues ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 115
5.1 What is a Queue? --------------------------------------------------------------------------------------------------------------------------------------------------------------- 115
5.2 How are Queues Used? ------------------------------------------------------------------------------------------------------------------------------------------------------ 115
5.3 Queue ADT----------------------------------------------------------------------------------------------------------------------------------------------------------------------- 115
5.4 Exceptions-------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 115
5.5 Applications ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- 115
5.6 Implementation ------------------------------------------------------------------------------------------------------------------------------------------------------------------ 116
5.7 Queues: Problems & Solutions -------------------------------------------------------------------------------------------------------------------------------------------- 121
6. Trees ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 125
6.1 What is a Tree? ------------------------------------------------------------------------------------------------------------------------------------------------------------------ 125
6.2 Glossary ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 125
6.3 Binary Trees----------------------------------------------------------------------------------------------------------------------------------------------------------------------- 126
6.4 Types of Binary Trees--------------------------------------------------------------------------------------------------------------------------------------------------------- 126
6.5 Properties of Binary Trees--------------------------------------------------------------------------------------------------------------------------------------------------- 126
6.4 Binary Tree Traversals -------------------------------------------------------------------------------------------------------------------------------------------------------- 128
6.5 Generic Trees (N-ary Trees)------------------------------------------------------------------------------------------------------------------------------------------------ 149
6.6 Threaded (Stack or Queue less) Binary Tree Traversals-------------------------------------------------------------------------------------------------------- 154
6.7 Expression Trees ---------------------------------------------------------------------------------------------------------------------------------------------------------------- 158
6.10 XOR Trees ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- 160
6.9 Binary Search Trees (BSTs) ------------------------------------------------------------------------------------------------------------------------------------------------ 161
6.10 Balanced Binary Search Trees ------------------------------------------------------------------------------------------------------------------------------------------- 172
6.11 AVL (Adelson-Velskii and Landis) Trees --------------------------------------------------------------------------------------------------------------------------- 172
6.12 Other Variations on Trees ------------------------------------------------------------------------------------------------------------------------------------------------- 183
6.13 Supplementary Questions-------------------------------------------------------------------------------------------------------------------------------------------------- 186
7. Priority Queues and Heaps -------------------------------------------------------------------------------------------------------------------------------------------- 187
7.1 What is a Priority Queue? --------------------------------------------------------------------------------------------------------------------------------------------------- 187
7.2 Priority Queue ADT----------------------------------------------------------------------------------------------------------------------------------------------------------- 187
7.3 Priority Queue Applications ------------------------------------------------------------------------------------------------------------------------------------------------ 187
7.4 Priority Queue Implementations------------------------------------------------------------------------------------------------------------------------------------------ 187
7.5 Heaps and Binary Heaps----------------------------------------------------------------------------------------------------------------------------------------------------- 188
7.6 Binary Heaps---------------------------------------------------------------------------------------------------------------------------------------------------------------------- 189
7.7 Priority Queues [Heaps]: Problems & Solutions ------------------------------------------------------------------------------------------------------------------- 193
8. Disjoint Sets ADT --------------------------------------------------------------------------------------------------------------------------------------------------------- 203
8.1 Introduction ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- 203
8.2 Equivalence Relations and Equivalence Classes -------------------------------------------------------------------------------------------------------------------- 203
8.3 Disjoint Sets ADT -------------------------------------------------------------------------------------------------------------------------------------------------------------- 203
8.4 Applications ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- 203
8.5 Tradeoffs in Implementing Disjoint Sets ADT --------------------------------------------------------------------------------------------------------------------- 204
8.8 Fast UNION Implementation (Slow FIND) ------------------------------------------------------------------------------------------------------------------------- 204
8.7 Fast UNION Implementations (Quick FIND)---------------------------------------------------------------------------------------------------------------------- 206
8.8 Path Compression--------------------------------------------------------------------------------------------------------------------------------------------------------------- 207
8.9 Summary---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 208
8.10 Disjoint Sets: Problems & Solutions ----------------------------------------------------------------------------------------------------------------------------------- 208
9. Graph Algorithms ---------------------------------------------------------------------------------------------------------------------------------------------------------- 210
9.1 Introduction ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- 210
9.2 Glossary ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 210
9.3 Applications of Graphs-------------------------------------------------------------------------------------------------------------------------------------------------------- 212
9.4 Graph Representation --------------------------------------------------------------------------------------------------------------------------------------------------------- 212
9.5 Graph Traversals ---------------------------------------------------------------------------------------------------------------------------------------------------------------- 217
9.6 Topological Sort ----------------------------------------------------------------------------------------------------------------------------------------------------------------- 224
9.7 Shortest Path Algorithms ----------------------------------------------------------------------------------------------------------------------------------------------------- 226
9.8 Minimal Spanning Tree ------------------------------------------------------------------------------------------------------------------------------------------------------ 232
9.9 Graph Algorithms: Problems & Solutions----------------------------------------------------------------------------------------------------------------------------- 235
10. Sorting -------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 249
10.1 What is Sorting? --------------------------------------------------------------------------------------------------------------------------------------------------------------- 249
10.2 Why is Sorting Necessary? ------------------------------------------------------------------------------------------------------------------------------------------------ 249
10.3 Classification of Sorting Algorithms ------------------------------------------------------------------------------------------------------------------------------------ 249
10.4 Other Classifications --------------------------------------------------------------------------------------------------------------------------------------------------------- 249
10.5 Bubble Sort ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- 250
10.6 Selection Sort-------------------------------------------------------------------------------------------------------------------------------------------------------------------- 251
10.7 Insertion Sort-------------------------------------------------------------------------------------------------------------------------------------------------------------------- 252
10.8 Shell Sort-------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 254
10.9 Merge Sort------------------------------------------------------------------------------------------------------------------------------------------------------------------------ 254
10.10 Heap Sort ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- 257
10.11 Quick Sort ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- 257
10.12 Tree Sort ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ 261
10.13 Comparison of Sorting Algorithms ----------------------------------------------------------------------------------------------------------------------------------- 261
10.14 Linear Sorting Algorithms------------------------------------------------------------------------------------------------------------------------------------------------ 261
10.15 Counting Sort------------------------------------------------------------------------------------------------------------------------------------------------------------------ 261
10.16 Bucket sort (Bin Sort)------------------------------------------------------------------------------------------------------------------------------------------------------ 262
10.17 Radix Sort----------------------------------------------------------------------------------------------------------------------------------------------------------------------- 262
10.18 Topological Sort ------------------------------------------------------------------------------------------------------------------------------------------------------------- 263
10.19 External Sorting -------------------------------------------------------------------------------------------------------------------------------------------------------------- 263
10.20 Sorting: Problems & Solutions ----------------------------------------------------------------------------------------------------------------------------------------- 264
11. Searching----------------------------------------------------------------------------------------------------------------------------------------------------------------------- 274
11.1 What is Searching? ----------------------------------------------------------------------------------------------------------------------------------------------------------- 274
11.2 Why do we need Searching?---------------------------------------------------------------------------------------------------------------------------------------------- 274
11.3 Types of Searching------------------------------------------------------------------------------------------------------------------------------------------------------------ 274
11.4 Unordered Linear Search -------------------------------------------------------------------------------------------------------------------------------------------------- 274
11.5 Sorted/Ordered Linear Search------------------------------------------------------------------------------------------------------------------------------------------- 274
11.6 Binary Search ------------------------------------------------------------------------------------------------------------------------------------------------------------------- 275
11.7 Interpolation Search---------------------------------------------------------------------------------------------------------------------------------------------------------- 275
11.8 Comparing Basic Searching Algorithms ------------------------------------------------------------------------------------------------------------------------------ 276
11.9 Symbol Tables and Hashing -------------------------------------------------------------------------------------------------------------------------------------------- 277
11.10 String Searching Algorithms ------------------------------------------------------------------------------------------------------------------------------------------ 277
11.11 Searching: Problems & Solutions-------------------------------------------------------------------------------------------------------------------------------------- 277
12. Selection Algorithms [Medians] -------------------------------------------------------------------------------------------------------------------------------------- 297
12.1 What are Selection Algorithms?----------------------------------------------------------------------------------------------------------------------------------------- 297
12.2 Selection by Sorting----------------------------------------------------------------------------------------------------------------------------------------------------------- 297
12.3 Partition-based Selection Algorithm ----------------------------------------------------------------------------------------------------------------------------------- 297
12.4 Linear Selection Algorithm - Median of Medians Algorithm ------------------------------------------------------------------------------------------------ 297
12.5 Finding the K Smallest Elements in Sorted Order --------------------------------------------------------------------------------------------------------------- 297
12.6 Selection Algorithms: Problems & Solutions ----------------------------------------------------------------------------------------------------------------------- 297
13. Symbol Tables --------------------------------------------------------------------------------------------------------------------------------------------------------------- 305
13.1 Introduction --------------------------------------------------------------------------------------------------------------------------------------------------------------------- 305
13.2 What are Symbol Tables? ------------------------------------------------------------------------------------------------------------------------------------------------- 305
13.3 Symbol Table Implementations ----------------------------------------------------------------------------------------------------------------------------------------- 305
13.4 Comparison Table of Symbols for Implementations ----------------------------------------------------------------------------------------------------------- 306
14. Hashing ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 307
14.1 What is Hashing?-------------------------------------------------------------------------------------------------------------------------------------------------------------- 307
14.2 Why Hashing?------------------------------------------------------------------------------------------------------------------------------------------------------------------ 307
14.3 Hash Table ADT-------------------------------------------------------------------------------------------------------------------------------------------------------------- 307
14.4 Understanding Hashing ----------------------------------------------------------------------------------------------------------------------------------------------------- 307
14.5 Components of Hashing ---------------------------------------------------------------------------------------------------------------------------------------------------- 308
14.6 Hash Table----------------------------------------------------------------------------------------------------------------------------------------------------------------------- 308
14.7 Hash Function ------------------------------------------------------------------------------------------------------------------------------------------------------------------ 309
14.8 Load Factor ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- 309
14.9 Collisions-------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 310
14.10 Collision Resolution Techniques-------------------------------------------------------------------------------------------------------------------------------------- 310
14.11 Separate Chaining ----------------------------------------------------------------------------------------------------------------------------------------------------------- 310
14.12 Open Addressing ------------------------------------------------------------------------------------------------------------------------------------------------------------ 311
14.13 Comparison of Collision Resolution Techniques -------------------------------------------------------------------------------------------------------------- 312
14.14 How Hashing Gets O(1) Complexity -------------------------------------------------------------------------------------------------------------------------------- 312
14.15 Hashing Techniques-------------------------------------------------------------------------------------------------------------------------------------------------------- 312
14.16 Problems for which Hash Tables are not suitable -------------------------------------------------------------------------------------------------------------- 312
14.17 Bloom Filters ------------------------------------------------------------------------------------------------------------------------------------------------------------------ 312
14.18 Hashing: Problems & Solutions---------------------------------------------------------------------------------------------------------------------------------------- 314
15. String Algorithms ----------------------------------------------------------------------------------------------------------------------------------------------------------- 322
15.1 Introduction --------------------------------------------------------------------------------------------------------------------------------------------------------------------- 322
15.2 String Matching Algorithms ----------------------------------------------------------------------------------------------------------------------------------------------- 322
15.3 Brute Force Method --------------------------------------------------------------------------------------------------------------------------------------------------------- 322
15.4 Rabin-Karp String Matching Algorithm ------------------------------------------------------------------------------------------------------------------------------ 323
15.5 String Matching with Finite Automata--------------------------------------------------------------------------------------------------------------------------------- 323
15.6 KMP Algorithm ---------------------------------------------------------------------------------------------------------------------------------------------------------------- 324
15.7 Boyer-Moore Algorithm ---------------------------------------------------------------------------------------------------------------------------------------------------- 326
15.8 Data Structures for Storing Strings-------------------------------------------------------------------------------------------------------------------------------------- 327
15.9 Hash Tables for Strings ----------------------------------------------------------------------------------------------------------------------------------------------------- 327
15.10 Binary Search Trees for Strings ---------------------------------------------------------------------------------------------------------------------------------------- 327
15.11 Tries------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 327
15.12 Ternary Search Trees ------------------------------------------------------------------------------------------------------------------------------------------------------ 329
15.13 Comparing BSTs, Tries and TSTs ----------------------------------------------------------------------------------------------------------------------------------- 332
15.14 Suffix Trees -------------------------------------------------------------------------------------------------------------------------------------------------------------------- 332
15.15 String Algorithms: Problems & Solutions -------------------------------------------------------------------------------------------------------------------------- 334
16. Algorithms Design Techniques --------------------------------------------------------------------------------------------------------------------------------------- 344
16.1 Introduction --------------------------------------------------------------------------------------------------------------------------------------------------------------------- 344
16.2 Classification--------------------------------------------------------------------------------------------------------------------------------------------------------------------- 344
16.3 Classification by Implementation Method--------------------------------------------------------------------------------------------------------------------------- 344
16.4 Classification by Design Method ---------------------------------------------------------------------------------------------------------------------------------------- 345
16.5 Other Classifications --------------------------------------------------------------------------------------------------------------------------------------------------------- 345
17. Greedy Algorithms--------------------------------------------------------------------------------------------------------------------------------------------------------- 346
17.1 Introduction --------------------------------------------------------------------------------------------------------------------------------------------------------------------- 346
17.2 Greedy Strategy----------------------------------------------------------------------------------------------------------------------------------------------------------------- 346
17.3 Elements of Greedy Algorithms ----------------------------------------------------------------------------------------------------------------------------------------- 346
17.4 Does Greedy Always Work? --------------------------------------------------------------------------------------------------------------------------------------------- 346
17.5 Advantages and Disadvantages of Greedy Method -------------------------------------------------------------------------------------------------------------- 346
17.6 Greedy Applications---------------------------------------------------------------------------------------------------------------------------------------------------------- 346
17.7 Understanding Greedy Technique ------------------------------------------------------------------------------------------------------------------------------------- 347
17.8 Greedy Algorithms: Problems & Solutions ------------------------------------------------------------------------------------------------------------------------- 349
18. Divide and Conquer Algorithms ------------------------------------------------------------------------------------------------------------------------------------- 354
18.1 Introduction --------------------------------------------------------------------------------------------------------------------------------------------------------------------- 354
18.2 What is the Divide and Conquer Strategy? ------------------------------------------------------------------------------------------------------------------------- 354
18.3 Does Divide and Conquer Always Work? -------------------------------------------------------------------------------------------------------------------------- 354
18.4 Divide and Conquer Visualization -------------------------------------------------------------------------------------------------------------------------------------- 354
18.5 Understanding Divide and Conquer----------------------------------------------------------------------------------------------------------------------------------- 355
18.6 Advantages of Divide and Conquer ------------------------------------------------------------------------------------------------------------------------------------ 355
18.7 Disadvantages of Divide and Conquer -------------------------------------------------------------------------------------------------------------------------------- 355
18.8 Master Theorem --------------------------------------------------------------------------------------------------------------------------------------------------------------- 355
18.9 Divide and Conquer Applications -------------------------------------------------------------------------------------------------------------------------------------- 356
18.10 Divide and Conquer: Problems & Solutions --------------------------------------------------------------------------------------------------------------------- 356
19. Dynamic Programming -------------------------------------------------------------------------------------------------------------------------------------------------- 368
19.1 Introduction --------------------------------------------------------------------------------------------------------------------------------------------------------------------- 368
19.2 What is Dynamic Programming Strategy?--------------------------------------------------------------------------------------------------------------------------- 368
19.3 Properties of Dynamic Programming Strategy --------------------------------------------------------------------------------------------------------------------- 368
19.4 Greedy vs Divide and Conquer vs DP -------------------------------------------------------------------------------------------------------------------------------- 368
19.5 Can DP solve all problems?----------------------------------------------------------------------------------------------------------------------------------------------- 369
19.6 Dynamic Programming Approaches----------------------------------------------------------------------------------------------------------------------------------- 369
19.7 Understanding DP Approaches ----------------------------------------------------------------------------------------------------------------------------------------- 369
19.8 Examples of DP Algorithms ---------------------------------------------------------------------------------------------------------------------------------------------- 372
19.9 Longest Common Subsequence----------------------------------------------------------------------------------------------------------------------------------------- 372
19.10 Dynamic Programming: Problems & Solutions ----------------------------------------------------------------------------------------------------------------- 374
20. Complexity Classes -------------------------------------------------------------------------------------------------------------------------------------------------------- 396
20.1 Introduction --------------------------------------------------------------------------------------------------------------------------------------------------------------------- 396
20.2 Polynomial/Exponential Time ------------------------------------------------------------------------------------------------------------------------------------------- 396
20.3 What is a Decision Problem? -------------------------------------------------------------------------------------------------------------------------------------------- 396
20.4 Decision Procedure----------------------------------------------------------------------------------------------------------------------------------------------------------- 396
20.5 What is a Complexity Class?---------------------------------------------------------------------------------------------------------------------------------------------- 396
20.6 Types of Complexity Classes --------------------------------------------------------------------------------------------------------------------------------------------- 397
20.7 Reductions------------------------------------------------------------------------------------------------------------------------------------------------------------------------ 398
20.8 Complexity Classes: Problems & Solutions ------------------------------------------------------------------------------------------------------------------------- 400
21. Miscellaneous Concepts ------------------------------------------------------------------------------------------------------------------------------------------------- 402
21.1 Introduction --------------------------------------------------------------------------------------------------------------------------------------------------------------------- 402
21.2 Hacks on Bitwise Programming ----------------------------------------------------------------------------------------------------------------------------------------- 402
21.3 Other Programming Questions ------------------------------------------------------------------------------------------------------------------------------------------ 405
References ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 412
Data Structures and Algorithms Made Easy in Java Introduction

Chapter

INTRODUCTION 1
The objective of this chapter is to explain the importance of the analysis of algorithms, their notations, relationships and solving as many
problems as possible. Let us first focus on understanding the basic elements of algorithms, the importance of algorithm analysis, and then
slowly move toward the other topics as mentioned above. After completing this chapter, you should be able to find the complexity of any
given algorithm (especially recursive functions).

1.1 Variables
Before getting in to the definition of variables, let us relate them to an old mathematical equation. Many of us would have solved many
mathematical equations since childhood. As an example, consider the equation below:
+2 −2 =1
We don’t have to worry about the use of this equation. The important thing that we need to understand is that the equation has names ( and
), which hold values (data). That means the ( and ) are placeholders for representing data. Similarly, in computer science
programming we need something for holding data, and is the way to do that.

1.2 Data Types


In the above-mentioned equation, the variables and can take any values such as integral numbers (10, 20), real numbers (0.23, 5.5), or
just 0 and 1. To solve the equation, we need to relate them to the kind of values they can take, and is the name used in computer
science programming for this purpose. A in a programming language is a set of data with predefined values. Examples of data
types are: integer, floating point, unit number, character, string, etc.
Computer memory is all filled with zeros and ones. If we have a problem and we want to code it, it’s very difficult to provide the solution in
terms of zeros and ones. To help users, programming languages and compilers provide us with data types. For example, takes 2
bytes (actual value depends on compiler), takes 4 bytes, etc. This says that in memory we are combining 2 bytes (16 bits) and calling it
an . Similarly, combining 4 bytes (32 bits) and calling it a . A data type reduces the coding effort. At the top level, there are two
types of data types:
 System-defined data types (also called data types)
 User-defined data types.

System-defined data types (Primitive data types)


Data types that are defined by system are called data types. The primitive data types provided by many programming languages
are: int, float, char, double, bool, etc. The number of bits allocated for each primitive data type depends on the programming languages, the
compiler and the operating system. For the same primitive data type, different languages may use different sizes. Depending on the size of the
data types, the total available values (domain) will also change. For example, “ ” may take 2 bytes or 4 bytes. If it takes 2 bytes (16 bits),
then the total possible values are minus 32,768 to plus 32,767 (-2 2 -1). If it takes 4 bytes (32 bits), then the possible values are between
−2,147,483,648 and +2,147,483,647 (-2 2 -1). The same is the case with other data types.

User-defined data types


If the system-defined data types are not enough, then most programming languages allow the users to define their own data types, called
− . Good examples of user defined data types are: structures in / + + and classes in . For example, in
the snippet below, we are combining many system-defined data types and calling the user defined data type by the name “ ”. This
gives more flexibility and comfort in dealing with computer memory.
public class newType {
public int data1;
public int data 2;
private float data3;

1.1 Variables 15
Data Structures and Algorithms Made Easy in Java Introduction


private char data;
//Operations
}

1.3 Data Structure


Based on the discussion above, once we have data in variables, we need some mechanism for manipulating that data to solve problems.
is a particular way of storing and organizing data in a computer so that it can be used efficiently. A is a
special format for organizing and storing data. General data structure types include arrays, files, linked lists, stacks, queues, trees, graphs and
so on.
Depending on the organization of the elements, data structures are classified into two types:
1) : Elements are accessed in a sequential order but it is not compulsory to store all elements sequentially
(say, Linked Lists). : Linked Lists, Stacks and Queues.
2) − : Elements of this data structure are stored/accessed in a non-linear order. : Trees and
graphs.

1.4 Abstract Data Types (ADTs)


Before defining abstract data types, let us consider the different view of system-defined data types. We all know that, by default, all primitive
data types (int, float, etc.) support basic operations such as addition and subtraction. The system provides the implementations for the primitive
data types. For user-defined data types we also need to define operations. The implementation for these operations can be done when we
want to actually use them. That means, in general, user defined data types are defined along with their operations.
To simplify the process of solving problems, we combine the data structures with their operations and we call this
(ADTs). An ADT consists of parts:
1. Declaration of data
2. Declaration of operations
Commonly used ADTs include: Linked Lists, Stacks, Queues, Priority Queues, Binary Trees, Dictionaries, Disjoint Sets (Union and Find),
Hash Tables, Graphs, and many others. For example, stack uses a LIFO (Last-In-First-Out) mechanism while storing the data in data
structures. The last element inserted into the stack is the first element that gets deleted. Common operations are: creating the stack, push an
element onto the stack, pop an element from the stack, finding the current top of the stack, finding the number of elements in the stack, etc.
While defining the ADTs do not worry about the implementation details. They come into the picture only when we want to use them.
Different kinds of ADTs are suited to different kinds of applications, and some are highly specialized to specific tasks. By the end of this
book, we will go through many of them and you will be in a position to relate the data structures to the kind of problems they solve.

1.5 What is an Algorithm?


Let us consider the problem of preparing an . To prepare an omelette, we follow the steps given below:
1) Get the frying pan.
2) Get the oil.
a. Do we have oil?
i. If yes, put it in the pan.
ii. If no, do we want to buy oil?
1. If yes, then go out and buy.
2. If no, we can terminate.
3) Turn on the stove, etc...
What we are doing is, for a given problem (preparing an omelette), we are providing a step-by-step procedure for solving it. The formal
definition of an algorithm can be stated as:
An algorithm is the step-by-step unambiguous instructions to solve a given problem.
In the traditional study of algorithms, there are two main criteria for judging the merits of algorithms: correctness (does the algorithm give
solution to the problem in a finite number of steps?) and efficiency (how much resources (in terms of memory and time) does it take to
execute the).
Note: We do not have to prove each step of the algorithm.

1.6 Why the Analysis of Algorithms?


To go from city “ ” to city “ ”, there can be many ways of accomplishing this: by flight, by bus, by train and also by bicycle. Depending on
the availability and convenience, we choose the one that suits us. Similarly, in computer science, multiple algorithms are available for solving
the same problem (for example, a sorting problem has many algorithms, like insertion sort, selection sort, quick sort and many more).
Algorithm analysis helps us to determine which algorithm is most efficient in terms of time and space consumed.

1.3 Data Structure 16


Data Structures and Algorithms Made Easy in Java Introduction

1.7 Goal of the Analysis of Algorithms


The analysis of an algorithm can help us understand it better and can suggest informed improvements. The main and important role of
analysis of algorithm is to predict the performance of different algorithms in order to guide design decisions. The goal of the
ℎ is to compare algorithms (or solutions) mainly in terms of running time but also in terms of other factors (e.g.,
memory, developer effort, etc.).
In theoretical analysis of algorithms, it is common to estimate their complexity in the asymptotic sense, i.e., to estimate the complexity function
for arbitrarily large input. The term "analysis of algorithms" was coined by Donald Knuth.
Algorithm analysis is an important part of computational complexity theory, which provides theoretical estimation for the required resources
of an algorithm to solve a specific computational problem. Most algorithms are designed to work with inputs of arbitrary length. Analysis of
algorithms is the determination of the amount of time and space resources required to execute it.
Usually, the efficiency or running time of an algorithm is stated as a function relating the input length to the number of steps, known as time
complexity, or volume of memory, known as space complexity.

1.8 What is Running Time Analysis?


It is the process of determining how processing time increases as the size of the problem (input size) increases. Input size is the number of
elements in the input, and depending on the problem type, the input may be of different types. The following are the common types of inputs.
 Size of an array
 Polynomial degree
 Number of elements in a matrix
 Number of bits in the binary representation of the input
 Vertices and edges in a graph.

1.9 How to Compare Algorithms


To compare algorithms, let us define a few :
Execution times? as execution times are specific to a particular computer.
Number of statements executed? , since the number of statements varies with the programming language as well as the
style of the individual programmer.
Ideal solution? Let us assume that we express the running time of a given algorithm as a function of the input size (i.e., ( )) and compare
these different functions corresponding to running times. This kind of comparison is independent of machine time, programming style, etc.

1.10 What is Rate of Growth?


The rate at which the running time increases as a function of input is called ℎ. Let us assume that you go to a shop to buy a
car and a bicycle. If your friend sees you there and asks what you are buying, then in general you say . This is because the cost
of the car is high compared to the cost of the bicycle (approximating the cost of the bicycle to the cost of the car).
= _ _ + _ _
≈ _ _ ( )
For the above-mentioned example, we can represent the cost of the car and the cost of the bicycle in terms of function, and for a given function
ignore the low order terms that are relatively insignificant (for large value of input size, ). As an example, in the case below, , 2 , 100
and 500 are the individual costs of some function and approximate to since is the highest rate of growth.
+ 2 + 100 + 500 ≈

1.11 Commonly Used Rates of Growth


Below is the list of growth rates you will come across in the following chapters.
Time Complexity Name Description
1 Constant Whatever is the input size , these functions take a constant amount of time.
Logarithmic These are slower growing than even linear functions.
Linear These functions grow linearly with the input size .
Linear Logarithmic Faster growing than linear but slower than quadratic.
Quadratic These functions grow faster than the linear logarithmic functions.
Cubic Faster growing than quadratic but slower than exponential.
2 Exponential Faster than all of the functions mentioned here except the factorial functions.
! Factorial Fastest growing than all these functions mentioned here.

1.7 Goal of the Analysis of Algorithms 17


Data Structures and Algorithms Made Easy in Java Introduction

The diagram below shows the relationship between different rates of growth.

4 D
e
c
2 r
e
a
s
i
log n
g
log ( !)
R
a
t
e
s
2
O
f

G
r
o
w
t
h
log log

1.12 Types of Analysis


To analyze the given algorithm, we need to know with which inputs the algorithm takes less time (performing well) and with which inputs the
algorithm takes a long time. We have already seen that an algorithm can be represented in the form of an expression. That means we represent
the algorithm with multiple expressions: one for the case where it takes less time and another for the case where it takes more time.
In general, the first case is called the and the second case is called the for the algorithm. To analyze an algorithm we
need some kind of syntax, and that forms the base for asymptotic analysis/notation. There are three types of analysis:
 Worst case
o Defines the input for which the algorithm takes a long time (slowest time to complete).
o Input is the one for which the algorithm runs the slowest.
 Best case
o Defines the input for which the algorithm takes the least time (fastest time to complete).
o Input is the one for which the algorithm runs the fastest.
 Average case
o Provides a prediction about the running time of the algorithm.
o Run the algorithm many times, using many different inputs that come from some distribution that generates these
inputs, compute the total running time (by adding the individual times), and divide by the number of trials.
o Assumes that the input is random.
<= <=
For a given algorithm, we can represent the best, worst and average cases in the form of expressions. As an example, let ( ) be the function
which represents the given algorithm.
( )= + 500, for worst case
( )= + 100 + 500, for best case
Similarly for the average case. The expression defines the inputs with which the algorithm takes the average running time (or memory).

1.12 Types of Analysis 18


Data Structures and Algorithms Made Easy in Java Introduction

1.13 Asymptotic Notation


Having the expressions for the best, average and worst cases, for all three cases we need to identify the upper and lower bounds. To represent
these upper and lower bounds, we need some kind of syntax, and that is the subject of the following discussion. Let us assume that the given
algorithm is represented in the form of function ( ).

1.14 Big-O Notation


This notation gives the ℎ upper bound of the given function. Generally, it is represented as ( ) = O( ( )). That means, at larger
values of , the upper bound of ( ) is ( ). For example, if ( ) = + 100 + 10 + 50 is the given algorithm, then is ( ).
That means ( ) gives the maximum rate of growth for ( ) at larger values of .

( )
( )

Rate of growth

Input size,

Let us see the O−notation with a little more detail. O−notation defined as O( ( )) = { ( ): there exist positive constants and such
that 0 ≤ ( ) ≤ ( ) for all ≥ }. ( ) is an asymptotic tight upper bound for ( ). Our objective is to give the smallest rate of
growth ( ) which is greater than or equal to the given algorithms’ rate of growth ( ).
Generally, we discard lower values of . That means the rate of growth at lower values of is not important. In the figure, is the point
from which we need to consider the rate of growth for a given algorithm. Below , the rate of growth could be different. is called threshold
for the given function.

Big-O Visualization
O( ( )) is the set of functions with smaller or the same order of growth as ( ). For example; O( ) includes O(1), O( ), O( ), etc.

O(1): 100,1000, 200,1,20, . O( ):3 + 100, 100 , 2 − 1, 3, .

O( ): 5 , 3 − 100, 2 − O( ): , 5 − 10, 100, −


1, 100, 100 , . 2 + 1, 5, .

Note: Analyze the algorithms at larger values of only. What this means is, below we do not care about the rate of growth.

Big-O Examples
Example-1 Find upper bound for ( ) = 3 + 8
Solution: 3 + 8 ≤ 4 , for all ≥ 8
∴ 3 + 8 = O( ) with c = 4 and =8
Example-2 Find upper bound for ( ) = + 1
Solution: + 1 ≤ 2 , for all ≥ 1
∴ + 1 = O( ) with = 2 and = 1
Example-3 Find upper bound for ( ) = + 100 + 50
Solution: + 100 + 50 ≤ 2 , for all ≥ 11
∴ + 100 + 50 = O( ) with = 2 and = 11
Example-4 Find upper bound for ( ) = 2 − 2
Solution: 2 − 2 ≤ 2 , for all ≥ 1
∴ 2 − 2 = O( ) with = 2 and =1
Example-5 Find upper bound for ( ) =
Solution: ≤ , for all ≥ 1

1.13 Asymptotic Notation 19


Data Structures and Algorithms Made Easy in Java Introduction

∴ = O( ) with = 1 and =1
Example-6 Find upper bound for ( ) = 410
Solution: 410 ≤ 410, for all ≥ 1
∴ 410 = O(1 ) with = 1 and =1

No Uniqueness?
There is no unique set of values for and in proving the asymptotic bounds. Let us consider, 100 + 5 = O( ). For this function there
are multiple and values possible.
Solution1: 100 + 5 ≤ 100 + = 101 ≤ 101 , for all ≥ 5, = 5 and = 101 is a solution.
Solution2: 100 + 5 ≤ 100 + 5 = 105 ≤ 105 , for all ≥ 1, = 1 and = 105 is also a solution.

1.15 Omega-Ω Notation [Lower Bounding Function]


Similar to the O discussion, this notation gives the tighter lower bound of the given algorithm and we represent it as ( ) = ( ( )). That
means, at larger values of , the tighter lower bound of ( ) is ( ). For example, if ( ) = 100 + 10 + 50, ( ) is ( ).

( )
( ))

Rate of growth

Input size,

The Ω notation can be defined as Ω( ( )) = { ( ): there exist positive constants c and such that 0 ≤ ( ) ≤ ( ) for all ≥
}. ( ) is an asymptotic tight lower bound for ( ). Our objective is to give the largest rate of growth ( ) which is less than or equal to
the given algorithm’s rate of growth ( ).

Ω Examples
Example-1 Find lower bound for ( ) = 5 .
Solution:  , Such that: 0  5  5  = 5 and =1
∴5 = ( ) with = 5 and =1
Example-2 Prove ( ) = 100 + 5 ≠ ( ).
Solution:  c, Such that: 0   100 + 5
100 + 5  100 + 5 (  1) = 105
 105  ( – 105)  0
Since is positive  – 105  0   105/
 Contradiction: cannot be smaller than a constant
Example-3 2 = ( ), = ( ), = ( ).

1.16 Theta- Notation


c ( )
( )

Rate of growth c ( )

Input size,

1.15 Omega-Ω Notation [Lower Bounding Function] 20


Data Structures and Algorithms Made Easy in Java Introduction

This notation decides whether the upper and lower bounds of a given function (algorithm) are the same. The average running time of an
algorithm is always between the lower bound and the upper bound. If the upper bound (O) and lower bound () give the same result, then
the  notation will also have the same rate of growth. As an example, let us assume that ( ) = 10 + is the expression. Then, its tight
upper bound ( ) is O( ). The rate of growth in the best case is ( ) = O( ).
In this case, the rates of growth in the best case and worst case are the same. As a result, the average case will also be the same. For a given
function (algorithm), if the rates of growth (bounds) for O and  are not the same, then the rate of growth for the  case may not be the same.
In this case, we need to consider all possible time complexities and take the average of those (for example, for a quick sort average case, refer
to the chapter).
Now consider the definition of  notation. It is defined as ( ( )) = { ( ): there exist positive constants , and such that 0 ≤
( ) ≤ ( ) ≤ ( ) for all ≥ }. ( ) is an asymptotic tight bound for ( ). ( ( )) is the set of functions with the same
order of growth as ( ).

 Examples
Example 1 Find  bound for ( ) = −
Solution: ≤ − ≤ , for all, ≥ 2
∴ − = ( ) with = 1/5, = 1 and =2
Example 2 Prove ≠ ( )
Solution: c 2
≤ ≤ c 2 only holds for: ≤ 1/c1
∴ ≠ ( )
Example 3 Prove 6 ≠ ( )
Solution: ≤6 ≤c  only holds for: ≤ c2 /6
∴6 ≠ ( )
Example 4 Prove ≠ ( )
Solution: c ≤ ≤ c c ≥ log
, ≥ 0 – Impossible

Important Notes
For analysis (best case, worst case and average), we try to give the upper bound (O) and lower bound () and average running time (). From
the above examples, it should also be clear that, for a given function (algorithm), getting the upper bound (O) and lower bound () and
average running time () may not always be possible. For example, if we are discussing the best case of an algorithm, we try to give the upper
bound (O) and lower bound () and average running time ().
In the remaining chapters, we generally focus on the upper bound (O) because knowing the lower bound () of an algorithm is of no practical
importance, and we use the  notation if the upper bound (O) and lower bound () are the same.

1.17 Why is it called Asymptotic Analysis?


From the discussion above (for all three notations: worst case, best case, and average case), we can easily understand that, in every case for a
given function ( ) we are trying to find another function ( ) which approximates ( ) at higher values of . That means ( ) is also a
curve which approximates ( ) at higher values of .
In mathematics we call such a curve an . In other terms, ( ) is the asymptotic curve for ( ). For this reason, we call
algorithm analysis .

1.18 Guidelines for Asymptotic Analysis


There are some general rules to help us determine the running time of an algorithm.
1) Loops: The running time of a loop is, at most, the running time of the statements inside the loop (including tests) multiplied by the
number of iterations.
// executes times
for (i=1; i<=n; i++)
m = m + 2; // constant time, c
Total time = a constant × = = O( ).
2) Nested loops: Analyze from the inside out. Total running time is the product of the sizes of all the loops.
//outer loop executed n times
for (i=1; i<=n; i++) {
// inner loop executed n times
for (j=1; j<=n; j++)
k = k+1; //constant time
}

1.17 Why is it called Asymptotic Analysis? 21


Data Structures and Algorithms Made Easy in Java Introduction

Total time = × × = = O( ).
3) Consecutive statements: Add the time complexities of each statement.
x = x +1; //constant time
// executed n times
for (i=1; i<=n; i++)
m = m + 2; //constant time
//outer loop executed n times
for (i=1; i<=n; i++) {
//inner loop executed n times
for (j=1; j<=n; j++)
k = k+1; //constant time
}
Total time = + + = O( ).
4) If-then-else statements: Worst-case running time: the test, plus ℎ the ℎ part or the part (whichever is the larger).
//test: constant
if(length( ) == 0 ) {
return false; //then part: constant
}
else { // else part: (constant + constant) * n
for (int n = 0; n < length( ); n++) {
// another if : constant + constant (no else part)
if(!list[n].equals(otherList.list[n]))
//constant
return false;
}
}
Total time = + ( + ) ∗ = O( ).
5) Logarithmic complexity: An algorithm is O( ) if it takes a constant time to cut the problem size by a fraction (usually by ½). As
an example let us consider the following program:
for (i=1; i<=n;)
i = i*2;
If we observe carefully, the value of is doubling every time. Initially = 1, in next step = 2, and in subsequent steps = 4, 8 and
so on. Let us assume that the loop is executing some times. At step 2 = , and at ( + 1) step we come out of the .
Taking logarithm on both sides, gives
2 =
2=
= //if we assume base-2
Total time = O( ).
Note: Similarly, for the case below, the worst case rate of growth is O( ). The same discussion holds good for the decreasing sequence as
well.
for (i=n; i>=1;)
i = i/2;
Another example: binary search (finding a word in a dictionary of pages)
 Look at the center point in the dictionary
 Is the word towards the left or right of center?
 Repeat the process with the left or right part of the dictionary until the word is found.

1.20 Simplifying properties of asymptotic notations


 Transitivity: ( ) = ( ( )) and ( ) = (ℎ( ))  ( ) = (ℎ( )). Valid for O and  as well.
 Reflexivity: ( ) = ( ( )). Valid for O and .
 Symmetry: ( ) = ( ( )) if and only if ( ) = ( ( )).
 Transpose symmetry: ( ) = O( ( )) if and only if ( ) = ( ( )).
 If ( ) is in O( ( )) for any constant > 0, then ( ) is in O( ( )).
 If ( ) is in O( ( )) and ( ) is in O( ( )), then ( + )( ) is in O(max( ( ), ( ))).
 If ( ) is in O( ( )) and ( ) is in O( ( )) then ( ) ( ) is in O( ( ) ( )).

1.21 Commonly used Logarithms and Summations


Logarithms
= =
1.20 Simplifying properties of asymptotic notations 22
Data Structures and Algorithms Made Easy in Java Introduction

= + = ( )
= ( ) = –

= =
Arithmetic series
( + 1)
= 1 + 2 + ⋯+ =
2
Geometric series
−1
=1+ + …+ = ( ≠ 1)
−1
Harmonic series
1 1 1
= 1 + + …+ ≈
2
Other important formulae

1
= 1 + 2 +⋯+ ≈
+1

1.22 Master Theorem for Divide and Conquer Recurrences


All divide and conquer algorithms (also discussed in detail in the chapter) divide the problem into sub-problems, each of which
is part of the original problem, and then perform some additional work to compute the final answer. As an example, a merge sort algorithm [for
details, refer to chapter] operates on two sub-problems, each of which is half the size of the original, and then performs O( ) additional
work for merging. This gives the running time equation:
T( ) = 2 + O( )
The following theorem can be used to determine the running time of divide and conquer algorithms. For a given program (algorithm), first
we try to find the recurrence relation for the problem. If the recurrence is of the below form then we can directly give the answer without fully
solving it. If the recurrence is of the form T( ) = ( ) + ( ), where ≥ 1, > 1, ≥ 0 and is a real number, then:
1) If > , then ( ) = Θ
2) If =
a. If > −1, then ( ) = Θ
b. If = −1, then ( ) = Θ
c. If < −1, then ( ) = Θ
3) If <
a. If ≥ 0, then ( ) = Θ( )
b. If < 0, then ( ) = O( )

1.23 Divide and Conquer Master Theorem: Problems & Solutions


For each of the following recurrences, give an expression for the runtime ( ) if the recurrence can be solved with the Master Theorem.
Otherwise, indicate that the Master Theorem does not apply.
Problem-1 ( ) = 3 ( /2) +
Solution: ( ) = 3 ( /2) + => ( ) =Θ( ) (Master Theorem Case 3.a)
Problem-2 ( ) = 4 ( /2) +
Solution: ( ) = 4 ( /2) + => ( ) = Θ( ) (Master Theorem Case 2.a)
Problem-3 ( ) = ( /2) +
Solution: ( ) = ( /2) + => Θ( ) (Master Theorem Case 3.a)
Problem-4 ( ) = 2 ( /2) +
Solution: ( ) = 2 ( /2) + => Does not apply ( is not constant)
Problem-5 ( ) = 16 ( /4) +
1.22 Master Theorem for Divide and Conquer Recurrences 23
Data Structures and Algorithms Made Easy in Java Introduction

Solution: ( ) = 16 ( /4) + => ( ) = Θ( ) (Master Theorem Case 1)


Problem-6 ( ) = 2 ( /2) +
Solution: ( ) = 2 ( /2) + => ( ) = Θ( ) (Master Theorem Case 2.a)
Problem-7 ( ) = 2 ( /2) + /
Solution: ( ) = 2 ( /2) + / => ( ) = Θ( ) (Master Theorem Case 2.b)
.
Problem-8 ( ) = 2 ( /4) +
Solution: ( ) = 2 ( /4) + . => ( ) = Θ( .
) (Master Theorem Case 3.b)
Problem-9 ( ) = 0.5 ( /2) + 1/
Solution: ( ) = 0.5 ( /2) + 1/ => Does not apply ( < 1)
Problem-10 ( ) = 6 ( /3) +
Solution: ( ) = 6 ( /3) + => ( ) = Θ( ) (Master Theorem Case 3.a)
Problem-11 ( ) = 64 ( /8) −
Solution: ( ) = 64 ( /8) − => Does not apply (function is not positive)
Problem-12 ( ) = 7 ( /3) +
Solution: ( ) = 7 ( /3) + => ( ) = Θ( ) (Master Theorem Case 3.as)
Problem-13 ( ) = 4 ( /2) +
Solution: ( ) = 4 ( /2) + => ( ) = Θ( ) (Master Theorem Case 1)
Problem-14 ( ) = 16 ( /4) + !
Solution: ( ) = 16 ( /4) + ! => ( ) = Θ( !) (Master Theorem Case 3.a)
Problem-15 ( ) = √2 ( /2) +
Solution: ( ) = √2 ( /2) + => ( ) = Θ(√ ) (Master Theorem Case 1)
Problem-16 ( ) = 3 ( /2) +
Solution: ( ) = 3 ( /2) + => ( ) = ( ) (Master Theorem Case 1)
Problem-17 ( ) = 3 ( /3) + √
Solution: ( ) = 3 ( /3) + √ => ( ) = Θ( ) (Master Theorem Case 1)
Problem-18 ( ) = 4 ( /2) +
Solution: ( ) = 4 ( /2) + => ( ) = ( ) (Master Theorem Case 1)
Problem-19 ( ) = 3 ( /4) +
Solution: ( ) = 3 ( /4) + => ( ) = Θ( ) (Master Theorem Case 3.a)
Problem-20 ( ) = 3 ( /3) + /2
Solution: ( ) = 3 ( /3) + /2 => ( ) = Θ( ) (Master Theorem Case 2.a)

1.24 Master Theorem for Subtract and Conquer Recurrences


Let ( ) be a function defined on positive , and having the property
, if ≤ 1
( )=
( − ) + ( ), if > 1
for some constants , > 0, > 0, ≥ 0, and function ( ). If ( ) is in O( ), then
O( ), if a < 1
( )= O( ), if a = 1
O , if a > 1

1.25 Variant of Subtraction and Conquer Master Theorem


The solution to the equation ( ) = ( ) + ((1 − ) )+ , where 0 < < 1 and > 0 are constants, is O( ).

1.26 Method of Guessing and Confirming


Now, let us discuss a method which can be used to solve any recurrence. The basic idea behind this method is:
the answer; and then it correct by induction.
In other words, it addresses the question: What if the given recurrence doesn’t seem to match with any of these (master theorem) methods?
If we guess a solution and then try to verify our guess inductively, usually either the proof will succeed (in which case we are done), or the
proof will fail (in which case the failure will help us refine our guess).
As an example, consider the recurrence T( ) = √ T(√ ) + . This doesn’t fit into the form required by the Master Theorems. Carefully
observing the recurrence gives us the impression that it is similar to the divide and conquer method (dividing the problem into √ subproblems

1.24 Master Theorem for Subtract and Conquer Recurrences 24


Data Structures and Algorithms Made Easy in Java Introduction

each with size √ ). As we can see, the size of the subproblems at the first level of recursion is . So, let us guess that T( ) = O( ), and
then try to prove that our guess is correct.
Let’s start by trying to prove an bound T( ) ≤ :
T( ) = √ T(√ ) +
≤ √ . √ √ +
= . √ +
= .c. . +

The last inequality assumes only that 1 ≤ c. . . This is correct if is sufficiently large and for any constant , no matter how small. From
the above proof, we can see that our guess is correct for the upper bound. Now, let us prove the bound for this recurrence.
T( ) = √ T(√ ) +
≥ √ . √ √ +
= . √ +
= . . . +

The last inequality assumes only that 1 ≥ . . . This is incorrect if is sufficiently large and for any constant . From the above proof,
we can see that our guess is incorrect for the lower bound.
From the above discussion, we understood that Θ( ) is too big. How about Θ( )? The lower bound is easy to prove directly:
T( ) = √ T(√ ) + ≥
Now, let us prove the upper bound for this Θ( ).
T( ) = √ T(√ ) +
≤ √ . .√ +
= . +
= ( + 1)

From the above induction, we understood that Θ( ) is too small and Θ( ) is too big. So, we need something bigger than and smaller
than . How about ?
Proving the upper bound for :
T( ) = √ T(√ ) +
≤ √ . .√ √ +
= . . √ +

≤ √
Proving the lower bound for :
T( ) = √ T(√ ) +
≥ √ . .√ √ +
= . . √ +

≱ √
The last step doesn’t work. So, Θ( ) doesn’t work. What else is between and ? How about ?
Proving upper bound for :
T( ) = √ T(√ ) +
≤ √ . .√ √ +
= . . - . +
≤ , if ≥ 1
Proving lower bound for :
T( ) = √ T(√ ) +
≥ √ . .√ √ +
= . . - . +
≥ , if ≤ 1
From the above proofs, we can see that T( ) ≤ , if ≥ 1 and T( ) ≥ , if ≤ 1. Technically, we’re still missing the
base cases in both proofs, but we can be fairly confident at this point that T( ) = Θ( ).

1.26 Method of Guessing and Confirming 25


Data Structures and Algorithms Made Easy in Java Introduction

1.27 Amortized Analysis


Amortized analysis refers to determining the time-averaged running time for a sequence of operations. It is different from average case analysis,
because amortized analysis does not make any assumption about the distribution of the data values, whereas average case analysis assumes
the data are not "bad" (e.g., some sorting algorithms do well on over all input orderings but very badly on certain input orderings).
That is, amortized analysis is a worst-case analysis, but for a sequence of operations rather than for individual operations.
The motivation for amortized analysis is to better understand the running time of certain techniques, where standard worst case analysis
provides an overly pessimistic bound. Amortized analysis generally applies to a method that consists of a sequence of operations, where the
vast majority of the operations are cheap, but some of the operations are expensive. If we can show that the expensive operations are
particularly rare we can ℎ ℎ to the cheap operations, and only bound the cheap operations.
The general approach is to assign an artificial cost to each operation in the sequence, such that the total of the artificial costs for the sequence
of operations bounds the total of the real costs for the sequence. This artificial cost is called the amortized cost of an operation. To analyze
the running time, the amortized cost thus is a correct way of understanding the overall running time — but note that particular operations can
still take longer so it is not a way of bounding the running time of any individual operation in the sequence.
When one event in a sequence affects the cost of later events:
 One particular task may be expensive.
 But it may leave data structure in a state that the next few operations become easier.
Example: Let us consider an array of elements from which we want to find the smallest element. We can solve this problem using sorting.
After sorting the given array, we just need to return the element from it. The cost of performing the sort (assuming comparison based
sorting algorithm) is O( ). If we perform such selections then the average cost of each selection is O( / ) = O( ). This
clearly indicates that sorting once is reducing the complexity of subsequent operations.

1.28 Algorithms Analysis: Problems & Solutions


Note: From the following problems, try to understand the cases which have different complexities (O( ), O( ), O( ) etc.).
Problem-21 Find the complexity of the below recurrence:
3 ( − 1), > 0,
( )=
1, ℎ
Solution: Let us try solving this function with substitution.
( ) = 3 ( − 1)
( ) = 3 3 ( − 2) = 3 ( − 2)
( ) = 3 (3 ( − 3))
.
.
( ) = 3 ( − ) = 3 (0) = 3
This clearly shows that the complexity of this function is O(3 ).
Note: We can use the master theorem for this problem.
Problem-22 Find the complexity of the below recurrence:
2 ( − 1) − 1, > 0,
( )=
1, ℎ
Solution: Let us try solving this function with substitution.
( ) = 2 ( − 1) − 1
( ) = 2(2 ( − 2) − 1) − 1 = 2 ( − 2) − 2 − 1
( ) = 2 (2 ( − 3) − 2 − 1) − 1 = 2 ( − 4) − 2 − 2 − 2
( ) = 2 ( − )−2 −2 −2 ….2 − 2 −2
( ) =2 −2 −2 −2 ….2 −2 −2
( ) = 2 − (2 − 1) [ :2 +2 +⋯+2 = 2 ]
( )=1
∴Complexity is O(1). Note that while the recurrence relation looks exponential, the solution to the recurrence relation here gives a different
result.
Problem-23 What is the running time of the following function?
public void Function(int n) {
int i=1, s=1;
while( s <= n) {
i++;
s= s+i;
System.out.println(“*");
}
}
Solution: Consider the comments in the below function:
public void function (int n) {
int i=1, s=1;
// s is increasing not at rate 1 but i
1.27 Amortized Analysis 26
Data Structures and Algorithms Made Easy in Java Introduction

while( s <= n) {
i++;
s= s+i;
System.out.println(“*");
}
}
We can define the ‘ ’ terms according to the relation = + . The value of ‘ ’ increases by 1 for each iteration. The value contained in
‘ ’ at the iteration is the sum of the first ‘ ’ positive integers. If is the total number of iterations taken by the program, then the ℎ
loop terminates if:
( )
1 + 2+...+ = > ⟹ = O(√ ).
Problem-24 Find the complexity of the function given below.
public void function(int n) {
int i, count =0;
for(i=1; i*i<=n; i++)
count++;
}
Solution:
void function(int n) {
int i, count =0;
for(i=1; i*i<=n; i++)
count++;
}
In the above-mentioned function the loop will end, if > ⟹ ( ) =O(√ ). The reasoning is same as that of Problem-23.
Problem-25 What is the complexity of the program given below?
public void function(int n) {
int i, j, k , count =0;
for(i=n/2; i<=n; i++)
for(j=1; j + n/2<=n; j++)
for(k=1; k<=n; k= k * 2)
count++;
}
Solution: Consider the comments in the following function.
public void function(int n) {
int i, j, k , count =0;
//Outer loop execute n/2 times
for(i=n/2; i<=n; i++)
//Middle loop executes n/2 times
for(j=1; j + n/2<=n; j++)
//Inner loop execute logn times
for(k=1; k<=n; k= k * 2)
count++;
}
The complexity of the above function is O( ).
Problem-26 What is the complexity of the program given below?
public void function(int n) {
int i, j, k , count =0;
for(i=n/2; i<=n; i++)
for(j=1; j<=n; j= 2 * j)
for(k=1; k<=n; k= k * 2)
count++;
}
Solution: Consider the comments in the following function.
public void function(int n) {
int i, j, k , count =0;
//Outer loop execute n/2 times
for(i=n/2; i<=n; i++)
//Middle loop executes logn times
for(j=1; j<=n; j= 2 * j)
//Inner loop execute logn times
for(k=1; k<=n; k= k*2)
count++;
}
The complexity of the above function is O( ).
Problem-27 Find the complexity of the program given below.

1.28 Algorithms Analysis: Problems & Solutions 27


Data Structures and Algorithms Made Easy in Java Introduction

public void function( int n ) {


if(n == 1) return;
for(int i = 1 ; i <= n ; i + + ) {
for(int j= 1 ; j <= n ; j + + ) {
System.out.println(“*" );
break;
}
}
}
Solution: Consider the comments in the following function.
public void function( int n ) {
//constant time
if( n == 1 ) return;
//Outer loop execute times
for(int i = 1 ; i <= n ; i + + ) {
// Inner loop executes only time due to statement.
for(int j= 1 ; j <= n ; j + + ) {
System.out.println(“*" );
break;
}
}
}
The complexity of the above function is O( ). Even though the inner loop is bounded by , due to the break statement it is executing only
once.
Problem-28 Write a recursive function for the running time ( ) of the function given below. Prove using the iterative method that
( ) = ( ).
public void function( int n ) {
if( n == 1 ) return;
for(int i = 1 ; i <= n ; i + + )
for(int j = 1 ; j <= n ; j + + )
System.out.println(“*" ) ;
function( n-3 );
}
Solution: Consider the comments in the function below:
public void function (int n) {
//constant time
if( n == 1 ) return;
//Outer loop execute times
for(int i = 1 ; i <= n ; i + + )
//Inner loop executes n times
for(int j = 1 ; j <= n ; j + + )
//constant time
System.out.println(“*" ) ;
function( n-3 );
}
The recurrence for this code is clearly T( ) = ( − 3) + for some constant > 0 since each call prints out asterisks and calls
itself recursively on n - 3. Using the iterative method we get: ( ) = ( − 3) + . Using the master
theorem, we get: ( ) =Θ( ).
Problem-29 Determine  bounds for the recurrence relation: ( ) = 2 + .
Solution: Using Divide and Conquer master theorem, we get: O( ).
Problem-30 Determine  bounds for the recurrence: ( ) = + + + .
Solution: Substituting in the recurrence equation, we get:
( )≤ 1 ∗ + 2 ∗ + 3 ∗ + ≤ ∗ , where is a constant.
Problem-31 Determine  bounds for the recurrence relation: ( ) = ( /2) + 7.
Solution: Using Master Theorem we get: ( ).
Problem-32 Prove that the running time of the code below is Ω( ).
public void Read(int n) {
int k = 1;
while( k < n )
k = 3k;
}
Solution: The ℎ loop will terminate once the value of ‘ ’ is greater than or equal to the value of ‘ ’. In each iteration the value of ‘ ’ is
multiplied by 3. If is the number of iterations, then ‘ ’ has the value of 3 after iterations. The loop is terminated upon reaching iterations
when 3 ≥ n ↔ ≥ log , which shows that = Ω ( ).

1.28 Algorithms Analysis: Problems & Solutions 28


Data Structures and Algorithms Made Easy in Java Introduction

Problem-33 Solve the following recurrence.


1, =1
( ) =
( − 1) + ( − 1), ≥2
Solution: By iteration:
( ) = ( − 2) + ( − 1)( − 2) + ( − 1)

( ) = (1) + ( − 1)

( ) = (1) + −

(( + 1)(2 + 1) ( + 1)
( )=1+ −
6 2
( ) =( )
Note: We can use the master theorem for this problem.
Problem-34 Consider the following program:
Fib[n]
if(n==0) then return 0
else if(n==1) then return 1
else return Fib[n-1]+Fib[n-2]
Solution: The recurrence relation for the running time of this program is
( ) = ( − 1) + ( − 2) + .
Note T(n) has two recurrence calls indicating a binary tree. Each step recursively calls the program for reduced by 1 and 2, so the depth of
the recurrence tree is O( ). The number of leaves at depth is 2 since this is a full binary tree, and each leaf takes at least O(1) computations
for the constant factor. Running time is clearly exponential in .
Problem-35 Running time of following program?
public void function(n) {
for(int i = 1 ; i <= n ; i + + )
for(int j = 1 ; j <= n ; j+ = i )
System.out.println(“*”) ;
}
Solution: Consider the comments in the function below:
public void function (n) {
//this loop executes n times
for(int i = 1 ; i <= n ; i + + )
//this loop executes j times with j increase by the rate of i
for(int j = 1 ; j <= n ; j+ = i )
System.out.println(“*”) ;
}
In the above program, the inner loop executes n/i times for each value of . Its running time is × (∑ni=1 n/i) = O( ).
Problem-36 What is the complexity of ∑ ?
Solution: Using the logarithmic property, = + , we can see that this problem is equivalent to

= 1+ 2+⋯+ = (1 × 2 × … × ) = ( !) ≤ ( )≤

This shows that the time complexity = O( ).


Problem-37 What is the running time of the following recursive function (specified as a function of the input value )? First write the
recurrence formula and then find its complexity.
public void function(int n) {
if(n <= 1) return ;
for (int i=1 ; i <= 3; i++ )
f( );
}
Solution: Consider the comments in the function below:
public void function (int n) {
//constant time
if(n <= 1) return;
//this loop executes with recursive loop of value
for (int i=1 ; i <= 3; i++ )
f( );

1.28 Algorithms Analysis: Problems & Solutions 29


Data Structures and Algorithms Made Easy in Java Introduction

}
We can assume that for asymptotical analysis =   for every integer ≥ 1. The recurrence for this code is ( ) = 3 ( ) + Θ(1).
Using master theorem, we get ( ) = Θ( ).
Problem-38 What is the running time of the following recursive function (specified as a function of the input value )? First write a
recurrence formula, and show its solution using induction.
public void function(int n) {
if(n <= 1) return;
for (int i=1 ; i <= 3 ; i++ )
function (n − 1).
}
Solution: Consider the comments in the below function:
public void function (int n) {
//constant time
if(n <= 1) return;
//this loop executes 3 times with recursive call of n-1 value
for (int i=1 ; i <= 3 ; i++ )
function (n − 1).
}
The statement requires constant time (O(1)). With the loop, we neglect the loop overhead and only count three times that the function
is called recursively. This implies a time complexity recurrence:
( ) = , ≤ 1;
= + 3 ( − 1), > 1.
Using the master theorem, we get ( ) = Θ(3 ).
Problem-39 Write a recursion formula for the running time ( ) of the function , whose code is given below. What is the running
time of , as a function of ?
public void function (int n) {
if(n <= 1) return;
for(int i = 1; i < n; i + +)
System.out.println(“*”);
function ( 0.8n ) ;
}
Solution: Consider the comments in the below function:
public void function (int n) {
//constant time
if(n <= 1) return;
// this loop executes times with constant time loop
for(int i = 1; i < n; i + +)
System.out.println(“*”);
//recursive call with 0.8n
function ( 0.8n ) ;
}
4
The recurrence for this piece of code is ( ) = (. 8 ) + O( ) = T + O( ) = ( ) + O( ). Applying master theorem, we get
5n
( ) = O( ).
Problem-40 Find the complexity of the recurrence: ( ) = 2 (√ ) +
Solution: The given recurrence is not in the master theorem format. Let us try to convert this to the master theorem format by assuming =
2 . Applying the logarithm on both sides gives, = 2⟹ = . Now, the given function becomes:
( ) = (2 ) = 2 √2 + =2 2 + .
To make it simple we assume ( ) = (2 ) ⟹ ( ) = (2 ) ⟹ ( ) = 2 + . Applying the master theorem would result
( ) =O( ). If we substitute = back, ( ) = ( ) =O(( ) ).
Problem-41 Find the complexity of the recurrence: ( ) = (√ ) + 1

Solution: Applying the logic of Problem-40 gives ( ) = + 1. Applying the master theorem would result in ( ) =O( ).
Substituting = , gives ( ) = ( ) =O( ).
Problem-42 Find the complexity of the recurrence: ( ) = 2 (√ ) + 1

Solution: Applying the logic of Problem-40 gives: ( ) = 2 + 1. Using the master theorem results ( ) =O =O( ).
Substituting = gives ( ) = O( ).
Problem-43 Find the complexity of the function given below.
public int function (int n) {
if(n <= 2) return 1;

1.28 Algorithms Analysis: Problems & Solutions 30


Data Structures and Algorithms Made Easy in Java Introduction

else
return (Function (floor(sqrt(n))) + 1);
}
Solution: Consider the comments in the below function:
public int function (int n) {
if(n <= 2) return 1; //constant time
else
// executes √ + 1 times
return (Function (floor(sqrt(n))) + 1);
}
For the above function, recurrence function can be given as: ( ) = (√ ) + 1. This is same as that of Problem-41.
Problem-44 Analyze the running time of the following recursive psuedocode as a function of .
public void function(int n) {
if( n < 2 ) return;
else counter = 0;
for i = 1 to 8 do
function ( );
for i =1 to do
counter = counter + 1;
}
Solution: Consider the comments in below psuedocode and call running time of function(n) as ( ).
public void function(int n) {
if( n < 2 ) return; //constant time
else counter = 0;
// this loop executes 8 times with n value half in every call
for i = 1 to 8 do
function ( );
// this loop executes times with constant time loop
for i =1 to do
counter = counter + 1;
}
( ) can be defined as follows:
( ) = 1 < 2,
=8 ( ) + 3 + 1 ℎ .
2
Using the master theorem gives: ( ) =Θ( ) = Θ( ).
Problem-45 Find the complexity of the pseudocode given below:
temp = 1
repeat
for i = 1 to n
temp = temp + 1;
n = ;
until n <= 1
Solution: Consider the comments in the pseudocode given below:
temp = 1 // constant time
repeat
// this loops executes n times
for i = 1 to n
temp = temp + 1;
//recursive call with value
n = ;
until n <= 1
The recurrence for this function is ( ) = ( /2) + . Using master theorem we get: ( ) = O( ).
Problem-46 Running time of the following program?
publicvoid function(int n) {
for(int i = 1 ; i <= n ; i + + )
for(int j = 1 ; j <= n ; j * = 2 )
System.out.println(“*”);
}
Solution: Consider the comments in the function given below:
public void function(int n) {
// this loops executes n times
for(int i = 1 ; i <= n ; i + + )

1.28 Algorithms Analysis: Problems & Solutions 31


Data Structures and Algorithms Made Easy in Java Introduction

// this loops executes logn times from our logarithms


//guideline
for(int j = 1 ; j <= n ; j * = 2 )
System.out.println(“*”);
}
Complexity of above program is O( ).
Problem-47 Running time of the following program?
public void function(int n) {
for(int i = 1 ; i <= n/3 ; i + + )
for(int j = 1 ; j <= n ; j += 4 )
System.out.println(“ ∗ ”);
}
Solution: Consider the comments in the function given below:
public void function(int n) {
// this loops executes n/3 times
for(int i = 1 ; i <= n/3 ; i + + )
// this loops executes n/4 times
for(int j = 1 ; j <= n ; j += 4)
System.out.println(“ ∗ ”);
}
The time complexity of this program is: O( ).
Problem-48 Find the complexity of the below function:
public void function(int n) {
if(n <= 1) return;
if(n > 1) {
System.out.println(“ ∗ ”);
function( );
function( );
}
}
Solution: Consider the comments in the function given below:
public void function(int n) {
if(n <= 1) return; //constant time
if(n > 1) {
System.out.println(“ ∗ ”); //constant time
//recursion with n/2 value
function( n/2 );
//recursion with n/2 value
function( n/2 );
}
}
The recurrence for this function is: ( )=2 + 1. Using master theorem, we get ( ) = O( ).
Problem-49 Find the complexity of the below function:
public void function(int n) {
int i=1;
while (i < n) {
int j=n;
while(j > 0)
j = j/2;
i=2*i;
} // i
}
Solution:
public void function(int n) {
int i=1;
while (i < n) {
int j=n;
while(j > 0)
j = j/2; //logn code
i=2*i; //logn times
} // i
}
Time Complexity: O( ∗ ) =O( ).

1.28 Algorithms Analysis: Problems & Solutions 32


Data Structures and Algorithms Made Easy in Java Introduction

Problem-50 ∑ O( ), where O( ) stands for order is:


(a) O( ) (b) O( ) (c) O( ) (d) O(3 ) (e) O(1.5 )
Solution: (b). ∑ O( ) = O( ) ∑ 1 =O( ).
Problem-51 Which of the following three claims are correct
I ( + ) = ( ), where and are constants II 2 = O(2 ) III 2 = O(2 )
(a) I and II (b) I and III (c) II and III (d) I, II and III
Solution: (a). (I) ( + ) = + c1* + ... = ( ) and (II) 2 = 2*2 = O(2 )
Problem-52 Consider the following functions:
f( ) = 2 g( ) = ! h( ) =
Which of the following statements about the asymptotic behavior of f( ), g( ), and h( ) is true?
(A) f( ) = O(g( )); g( ) = O(h( )) (B) f( ) =  (g( )); g( ) = O(h( ))
(C) g( ) = O(f( )); h( ) = O(f( )) (D) h( ) = O(f( )); g( ) =  (f( ))
Solution: (D). According to the rate of growth: h( ) < f( ) < g( ) (g( ) is asymptotically greater than f( ), and f( ) is asymptotically greater than
h( )). We can easily see the above order by taking logarithms of the given 3 functions: < < ( !). Note that, ( !) =
O( ).
Problem-53 Consider the following segment of C-code:
int j=1, n;
while (j <=n)
j = j*2;
The number of comparisons made in the execution of the loop for any > 0 is:
(A) ceil( )+ 1 (B) (C) ceil( ) (D) floor( )+1
Solution: (a). Let us assume that the loop executes times. After step the value of is 2 . Taking logarithms on both sides gives = .
Since we are doing one more comparison for exiting from the loop, the answer is ceil( )+ 1.
Problem-54 Consider the following C code segment. Let T( ) denote the number of times the for loop is executed by the program
on input . Which of the following is TRUE?
public int IsPrime(int n){
for(int i=2;i<=sqrt(n);i++)
if(n%i == 0)
{printf(“Not Prime\n”); return 0;}
return 1;
}
(A) T( ) = O(√ ) and T( ) = (√ ) (B) T( ) = O(√ ) and T( ) = (1)
(C) T( ) = O( ) and T( ) = (√ ) (D) None of the above
Solution: (B). Big O notation describes the tight upper bound and Big Omega notation describes the tight lower bound for an algorithm. The
loop in the question is run maximum √ times and minimum 1 time. Therefore, T( ) = O(√ ) and T( ) = (1).
Problem-55 In the following C function, let ≥ . How many recursive calls are made by this function?
public int gcd(n,m){
if (n%m ==0) return m;
n = n%m;
return gcd(m,n);
}
(A) ( ) (B) ( ) (C) ( ) (D) ( )
Solution: No option is correct. Big O notation describes the tight upper bound and Big Omega notation describes the tight lower bound for
an algorithm. For = 2 and for all = 2 , the running time is O(1) which contradicts every option.
Problem-56 Suppose ( ) = 2 ( /2) + , T(0)=T(1)=1. Which one of the following is FALSE?
(A) ( ) = O( ) (B) ( ) = ( ) (C) ( ) = ( ) (D) ( ) = O( )
Solution: (C). Big O notation describes the tight upper bound and Big Omega notation describes the tight lower bound for an algorithm.
Based on master theorem, we get ( ) = ( ). This indicates that tight lower bound and tight upper bound are the same. That means,
O( ) and ( ) are correct for given recurrence. So option (C) is wrong.
Problem-57 Find the complexity of the below function:
public void function(int n) {
for (int i = 0; i<n; i++)
for(int j=i; j<i*i; j++)
if (j %i == 0){
for (int k = 0; k < j; k++)
printf(" * ");
}
}

1.28 Algorithms Analysis: Problems & Solutions 33


Data Structures and Algorithms Made Easy in Java Introduction

Solution:
public void function(int n) {
for (int i = 0; i<n; i++) // Executes n times
for(int j=i; j<i*i; j++) // Executes n*n times
if (j %i == 0){
for (int k = 0; k < j; k++) // Executes j times = (n*n) times
printf(" * ");
}
}
Time Complexity: O( 5 ).
Problem-58 To calculate 9 , give algorithm and discuss its complexity.
Solution: Start with 1 and multiply by 9 until reaching 9 .
Time Complexity: There are − 1 multiplications and each takes constant time giving a ( ) algorithm.
Problem-59 For Problem-58, can we improve the time complexity?
Solution: Refer to the chapter.
Problem-60 Find the complexity of the below function:
public void function(int n) {
int sum = 0;
for (int i = 0; i<n; i++)
if (i>j)
sum = sum +1;
else {
for (int k = 0; k < n; k++)
sum = sum -1;
}
}
}
Solution: Consider the worst-case.
public void function(int n) {
int sum = 0;
for (int i = 0; i<n; i++) // Executes times
if (i>j)
sum = sum +1; // Executes times
else {
for (int k = 0; k < n; k++) // Executes times
sum = sum -1;
}
}
}
Time Complexity: O( ).
Problem-61 Solve the following recurrence relation using the recursion tree method: T( )=T( ) +T( )+ .
Solution: How much work do we do in each level of the recursion tree?
T( )

T( ) T( )

2
T( ) T( ) T( ) T( )
2 3

T( ) T( ) T( ) T( ) 2 T( ) T( ) T( ) T( ) 2
2 3 2 3
In level 0, we take time. At level 1, the two subproblems take time:
1 2 1 4 25
+ = + =
2 3 4 9 36
1.28 Algorithms Analysis: Problems & Solutions 34
Data Structures and Algorithms Made Easy in Java Introduction

At level 2 the four subproblems are of size , , , and respectively. These two subproblems take time:
1 1 1 4 625 25
+ + + = =
4 3 3 9 1296 36
Similarly the amount of work at level is at most .
Let = , the total runtime is then:

T( ) ≤

1
=
1−∝
1
= 25
1 − 36
1
= 11
36
36
=
11
= O( )
That is, the first level provides a constant fraction of the total runtime.
Problem-62 Find the time complexity of recurrence T(n) = T( ) + T( ) + T( ) + .
Solution: Let us solve this problem by method of guessing. The total size on each level of the recurrance tree is less than , so we guess that
( ) = will dominate. Assume for all < that ≤ T( ) ≤ . Then,
+ + + ≤ T( ) ≤ + + +
( + + + ) ≤ T( ) ≤ ( + + + )
( + ) ≤ T( ) ≤ ( + )
If ≥ 8k and ≤ 8k, then = T( ) = . So, T( ) = Θ( ). In general, if you have multiple recursive calls, the sum of the arguments to
those calls is less than n (in this case + + < ), and ( ) is reasonably large, a good guess is T( ) = Θ(f( )).
Problem-63 Rank the following functions by order of growth: ( + 1)!, n!, 4 , ×3 ,3 + + 20 , ( ) , 4 ,4 , + 200,
/
20 + 500, 2 , , 1.
Solution:
Function Rate of Growth
( + 1)! O( !)
! O( !)
4 O(4 )
×3 O( 3 )
3 + + 20 O(3 )
3 O(( ) )
( ) Decreasing rate of growths
2
4 O( )
4 O( )
+ 200 O( )
20 + 500 O( )
2 O( )
/
O( / )
1 O(1)
.
Problem-64 Can we say 3 = O(3 )?
.
Solution: Yes: because 3 < 3 .
Problem-65 Can we say 2 = O(2 )?
Solution: No: because 2 = (2 ) = 8 not less than 2 .

1.28 Algorithms Analysis: Problems & Solutions 35


Data Structures and Algorithms Made Easy in Java Recursion and Backtracking

Chapter

RECURSION AND
BACKTRACKING 2
2.1 Introduction
In this chapter, we will look at one of the important topics, “ ”, which will be used in almost every chapter, and also its relative
“ ”.

2.2 What is Recursion?


Any function which calls itself is called . A recursive method solves a problem by calling a copy of itself to work on a smaller
problem. This is called the recursion step. The recursion step can result in many more such recursive calls. It is important to ensure that the
recursion terminates. Each time the function calls itself with a slightly simpler version of the original problem. The sequence of smaller
problems must eventually converge on the base case.

2.3 Why Recursion?


Recursion is a useful technique borrowed from mathematics. Recursive code is generally shorter and easier to write than iterative code.
Generally, loops are turned into recursive functions when they are compiled or interpreted. Recursion is most useful for tasks that can be
defined in terms of similar subtasks. For example, sort, search, and traversal problems often have simple recursive solutions.

2.4 Format of a Recursive Function


A recursive function performs a task in part by calling itself to perform the subtasks. At some point, the function
encounters a subtask that it can perform without calling itself. This case, where the function does not recur, is called the . The
former, where the function calls itself to perform a subtask, is referred to as the . We can write all recursive functions using
the format:
if(test for the base case)
return some base case value
else if(test for another base case)
return some other base case value
// the recursive case
else return (some work and then a recursive call)
As an example consider the factorial function: ! is the product of all integers between and 1. The definition of recursive factorial looks
like:
! = 1, if = 0
! = ∗ ( − 1)! if > 0
This definition can easily be converted to recursive implementation. Here the problem is determining the value of !, and the subproblem is
determining the value of ( − )!. In the recursive case, when is greater than 1, the function calls itself to determine the value of ( − )! and
multiplies that with . In the base case, when is 0 or 1, the function simply returns 1. This looks like the following:
class Factorial {
// recursive definition of method factorial
public long factorial(long number) {
if (number <= 1) // test for base case
return 1; // base cases: 0! = 1 and 1! = 1
else
// recursion step
return number * factorial(number - 1);
}

2.1 Introduction 36
Data Structures and Algorithms Made Easy in Java Recursion and Backtracking

public static void main(String args[]) {


Factorial obj = new Factorial();
for (int counter = 0; counter <= 10; counter++)
System.out.printf("%d! = %d\n", counter, obj.factorial(counter));

}
}

2.5 Recursion and Memory (Visualization)


Each recursive call makes a new copy of that method (actually only the variables) in memory. Once a method ends (that is, returns some
data), the copy of that returning method is removed from memory. The recursive solutions look simple but visualization and tracing takes
time. For better understanding, let us consider the following example.
public int Print(int n) {
if( n == 0) // this is the terminating base case
return 0;
else {
System.out.println(n);
return Print(n-1); // recursive call to itself again
}
}
For this example, if we call the print function with n=4, visually our memory assignments may look like:

Print (4)

Print (3)
Returns 0 Print (2)
Returns 0 Print (1)
Returns 0 to main function
Returns 0 Print (0)
Returns 0

Now, let us consider our factorial function. The visualization of factorial function with n = 4 will look like:

4!

4* 3!
4*6=24 is returned 3*2!

3*2=6 is returned 2*1!


Returns 24 to main function 2*1=2 is returned 1
Returns 1

2.6 Recursion versus Iteration


While discussing recursion, the basic question that comes to mind is: which way is better? – iteration or recursion? The answer to this question
depends on what we are trying to do. A recursive approach mirrors the problem that we are trying to solve. A recursive approach makes it
simpler to solve a problem that may not have the most obvious of answers. But, recursion adds overhead for each recursive call (needs space
on the stack frame).

Recursion
 Terminates when a base case is reached.
 Each recursive call requires extra space on the stack frame (memory).
 If we get infinite recursion, the program may run out of memory and result in stack overflow.
 Solutions to some problems are easier to formulate recursively.

Iteration
 Terminates when a condition is proven to be false.
 Each iteration does not require any extra space.
 An infinite loop could loop forever since there is no extra memory being created.
 Iterative solutions to a problem may not always be as obvious as a recursive solution.

2.5 Recursion and Memory (Visualization) 37


Data Structures and Algorithms Made Easy in Java Recursion and Backtracking

2.7 Notes on Recursion


 Recursive algorithms have two types of cases, recursive cases and base cases.
 Every recursive function case must terminate at a base case.
 Generally, iterative solutions are more efficient than recursive solutions [due to the overhead of function calls].
 A recursive algorithm can be implemented without recursive function calls using a stack, but it’s usually more trouble than its worth.
That means any problem that can be solved recursively can also be solved iteratively.
 For some problems, there are no obvious iterative algorithms.
 Some problems are best suited for recursive solutions while others are not.

2.8 Example Algorithms of Recursion


• Fibonacci Series, Factorial Finding
• Merge Sort, Quick Sort
• Binary Search
• Tree Traversals and many Tree Problems: InOrder, PreOrder PostOrder
• Graph Traversals: DFS [Depth First Search] and BFS [Breadth First Search]
• Dynamic Programming Examples
• Divide and Conquer Algorithms
• Towers of Hanoi
• Backtracking Algorithms [we will discuss in next section]

2.9 Recursion: Problems & Solutions


In this chapter we cover a few problems with recursion and we will discuss the rest in other chapters. By the time you complete reading the
entire book, you will encounter many recursion problems.
Problem-1 Discuss Towers of Hanoi puzzle.
Solution: The Towers of Hanoi is a mathematical puzzle. It consists of three rods (or pegs or towers) and a number of disks of different sizes
which can slide onto any rod. The puzzle starts with the disks on one rod in ascending order of size, the smallest at the top, thus making a
conical shape. The objective of the puzzle is to move the entire stack to another rod, satisfying the following rules:
 Only one disk may be moved at a time.
 Each move consists of taking the upper disk from one of the rods and sliding it onto another rod, on top of the other disks that may
already be present on that rod.
 No disk may be placed on top of a smaller disk.
Algorithm
 Move the top − 1 disks from to tower,
 Move the disk from to tower,
 Move the − 1disks from tower to tower.
 Transferring the top − 1 disks from to tower can again be thought of as a fresh problem and can be solved
in the same manner. Once we solve with three disks, we can solve it with any number of disks with the above
algorithm.
public void TowersOfHanoi(int n, char frompeg, char topeg, char auxpeg) {
/* If only 1 disk, make the move and return */
if(n==1) {
System.out.println("Move disk 1 from peg “ + frompeg + “ to peg " + topeg);
return;
}
/* Move top n-1 disks from A to B, using C as auxiliary */
TowersOfHanoi(n-1,frompeg,auxpeg,topeg);
/* Move remaining disks from A to C */
System.out.println("Move disk from peg” + frompeg + “ to peg " + topeg);
/* Move n-1 disks from B to C using A as auxiliary */
TowersOfHanoi(n-1,auxpeg,topeg,frompeg);
}
Problem-2 Given an array, check whether the array is in sorted order with recursion.
Solution:
public int isArrayInSortedOrder(int[] A, int index){

2.7 Notes on Recursion 38


Data Structures and Algorithms Made Easy in Java Recursion and Backtracking

if(A.length() == 1 || index == 1)
return 1;
return (A[index -1] < A[index -2])?0: isArrayInSortedOrder(A, index -1);
}
Time Complexity: O( ). Space Complexity: O( ) for recursive stack space.

2.10 What is Backtracking?


Backtracking is an improvement of the brute force approach. It systematically searches for a solution to a problem among all available options.
In backtracking, we start with one possible option out of many available options and try to solve the problem if we are able to solve the
problem with the selected move then we will print the solution else we will backtrack and select some other option and try to solve it. If none
if the options work out we will claim that there is no solution for the problem.
Backtracking is a form of recursion. The usual scenario is that you are faced with a number of options, and you must choose one of these.
After you make your choice you will get a new set of options; just what set of options you get depends on what choice you made. This
procedure is repeated over and over until you reach a final state. If you made a good sequence of choices, your final state is a goal state; if you
didn't, it isn't.
Backtracking can be thought of as a selective tree/graph traversal method. The tree is a way of representing some initial starting position (the
root node) and a final goal state (one of the leaves). Backtracking allows us to deal with situations in which a raw brute-force approach would
explode into an impossible number of options to consider. Backtracking is a sort of refined brute force. At each node, we eliminate choices
that are obviously not possible and proceed to recursively check only those that have potential.
What’s interesting about backtracking is that we back up only as far as needed to reach a previous decision point with an as-yet-unexplored
alternative. In general, that will be at the most recent decision point. Eventually, more and more of these decision points will have been fully
explored, and we will have to backtrack further and further. If we backtrack all the way to our initial state and have explored all alternatives
from there, we can conclude the particular problem is unsolvable. In such a case, we will have done all the work of the exhaustive recursion
and known that there is no viable solution possible.
 Sometimes the best algorithm for a problem is to try all possibilities.
 This is always slow, but there are standard tools that can be used to help.
 Tools: algorithms for generating basic objects, such as binary strings [2 possibilities for -bit string], permutations
[ !], combinations [ !/ ! ( − )!], general strings [k − ary strings of length has possibilities], etc...
 Backtracking speeds the exhaustive search by pruning.

2.11 Example Algorithms of Backtracking


 Binary Strings: generating all binary strings
 Generating k-ary Strings
 The Knapsack Problem
 N-Queens Problem
 Generalized Strings
 Hamiltonian Cycles [refer to ℎ chapter]
 Graph Coloring Problem

2.12 Backtracking: Problems & Solutions


Problem-3 Generate all the strings of bits. Assume [0. . − 1] is an array of size .
Solution:
import java.util.*;
public class BinaryStrings {
int[] A;
public BinaryStrings(int n) {
A = new int[n];
}
public void binary(int n) {
if (n <= 0) {
System.out.println(Arrays.toString(A));
} else {
A[n - 1] = 0;
binary(n - 1);
A[n - 1] = 1;
binary(n - 1);
}

2.10 What is Backtracking? 39


Data Structures and Algorithms Made Easy in Java Recursion and Backtracking

}
public static void main(String[] args) throws java.lang.Exception {
int n = 4;
BinaryStrings i = new BinaryStrings(n);
i.binary(n);
}
}
Let ( ) be the running time of ( ). Assume function . . takes time O(1).
, if < 0
( )=
2 ( − 1) + , otherwise
Using Subtraction and Conquer Master theorem, we get ( ) =O(2 ). This means the algorithm for generating bit-strings is optimal.
Problem-4 Generate all the strings of length drawn from 0. . . − 1.
Solution: Let us assume we keep current k-ary string in an array [0. . − 1]. Call function - (n, k):
import java.util.*;
class K_aryStrings {
int[] A;
public BinaryStrings(int n) {
A = new int[n];
}
public void base_K_strings(int n, int k) {
//process all k-ary strings of length m
if(n <= 0)
System.out.println(Arrays.toString(A)); //Assume array A is a class variable
else {
for (int j = 0 ; j < k ; j++) {
A[n-1] = j;
base_K_strings(n - 1, k);
}
}
}
public static void main(String[] args) throws java.lang.Exception {
int n = 4;
K_aryStrings obj = new K_aryStrings (n);
obj.base_K_strings(n, 3);
}
}
Let ( ) be the running time of − ( ). Then,
, <0
( )=
( − 1) + , ℎ
Using Subtraction and Conquer Master theorem, we get: ( ) =O( ).
Note: For more problems, refer to ℎ chapter.
Problem-5 Solve the recurrence T( ) = 2T( − 1) + 2 .
Solution: At each level of the recurrence tree, the number of problems is double from the previous level, while the amount of work being
done in each problem is half from the previous level. Formally, the level has 2 problems, each requiring 2 work. Thus the level
requires exactly 2 work. The depth of this tree is , because at the level, the originating call will be T( − ). Thus the total complexity
for T( ) is T( 2 ).

2.12 Backtracking: Problems & Solutions 40


Data Structures and Algorithms Made Easy in Java Linked Lists

Chapter

LINKED LISTS 3
3.1 What is a Linked List?
One disadvantage of using arrays to store data is that arrays are static structures and therefore cannot be easily extended or reduced to fit the
data set. Arrays are also expensive to maintain new insertions and deletions. In this chapter we consider another data structure called Linked
Lists that addresses some of the limitations of arrays. A linked list is a data structure used for storing collections of data. A linked list has the
following properties. A linked list is a linear dynamic data structure. The number of nodes in a list is not fixed and can grow and shrink on
demand. Each node of a linked list is made up of two items - the data and a reference to the next node. The last node has a reference to null.
The entry point into a linked list is called the head of the list. It should be noted that head is not a separate node, but the reference to the first
node. If the list is empty then the head is a null reference.
 Successive elements are connected by pointers.
 The last element points to NULL.
 Can grow or shrink in size during execution of a program.
 Can be made just as long as required (until systems memory exhausts).
 Does not waste memory space (but takes some extra memory for pointers). It allocates memory as list grows.

4 15 7 40 NULL

head

3.2 Linked Lists ADT


The following operations make linked lists an ADT:
Main Linked Lists Operations
 Insert: inserts an element into the list
 Delete: removes and returns the specified position element from the list
Auxiliary Linked Lists Operations
 Delete List: removes all elements of the list (disposes the list)
 Count: returns the number of elements in the list
 Find node from the end of the list

3.3 Why Linked Lists?


There are many other data structures that do the same thing as linked lists. Before discussing linked lists it is important to understand the
difference between linked lists and arrays. Both linked lists and arrays are used to store collections of data, and since both are used for the
same purpose, we need to differentiate their usage. That means in which cases are suitable and in which cases are
suitable.

3.4 Arrays Overview


One memory block is allocated for the entire array to hold the elements of the array. The array elements can be accessed in constant time by
using the index of the particular element as the subscript.
3 2 1 2 2 3
Index 0 1 2 3 4 5

Why Constant Time for Accessing Array Elements?


To access an array element, the address of an element is computed as an offset from the base address of the array and one multiplication is
needed to compute what is supposed to be added to the base address to get the memory address of the element. First the size of an element
of that data type is calculated and then it is multiplied with the index of the element to get the value to be added to the base address. This

3.1 What is a Linked List? 41


Data Structures and Algorithms Made Easy in Java Linked Lists

process takes one multiplication and one addition. Since these two operations take constant time, we can say the array access can be performed
in constant time.

Advantages of Arrays
 Simple and easy to use
 Faster access to the elements (constant access)

Disadvantages of Arrays
 Preallocates all needed memory up front and wastes memory space for indices in the array that are empty.
 Fixed size: The size of the array is static (specify the array size before using it).
 One block allocation: To allocate the array itself at the beginning, sometimes it may not be possible to get the memory for the
complete array (if the array size is big).
 Complex position-based insertion: To insert an element at a given position, we may need to shift the existing elements. This will
create a position for us to insert the new element at the desired position. If the position at which we want to add an element is at
the beginning, then the shifting operation is more expensive.

Dynamic Arrays
Dynamic array (also called , , , or ) is a random access, variable-size list data
structure that allows elements to be added or removed.
One simple way of implementing dynamic arrays is to initially start with some fixed size array. As soon as that array becomes full, create the
new array double the size of the original array. Similarly, reduce the array size to half if the elements in the array are less than half the size.
Note: We will see the implementation for in the , and ℎ chapters.

Advantages of Linked Lists


Linked lists have both advantages and disadvantages. The advantage of linked lists is that they can be in constant time. To create
an array, we must allocate memory for a certain number of elements. To add more elements to the array when full, we must create a new
array and copy the old array into the new array. This can take a lot of time.
We can prevent this by allocating lots of space initially but then we might allocate more than we need and waste memory. With a linked list,
we can start with space for just one allocated element and on new elements easily without the need to do any copying and reallocating.

Issues with Linked Lists (Disadvantages)


There are a number of issues with linked lists. The main disadvantage of linked lists is to individual elements. Array is random-
access, which means it takes O(1) to access any element in the array. Linked lists take O( ) for access to an element in the list in the worst
case. Another advantage of arrays in access time is in memory. Arrays are defined as contiguous blocks of memory, and so
any array element will be physically near its neighbors. This greatly benefits from modern CPU caching methods.
Although the dynamic allocation of storage is a great advantage, the ℎ with storing and retrieving data can make a big difference.
Sometimes linked lists are ℎ to . If the last item is deleted, the last but one must then have its pointer changed to hold a
NULL reference. This requires that the list is traversed to find the last but one link, and its pointer set to a NULL reference. Finally, linked
lists waste memory in terms of extra reference points.

3.5 Comparison of Linked Lists with Arrays & Dynamic Arrays


As with most choices in computer programming and design, no method is well suited to all circumstances. A linked list data structure might
work well in one case, but cause problems in another. This is a list of some of the common tradeoffs involving linked list structures. In general,
if you have a dynamic collection, where elements are frequently being added and deleted, and the location of new elements added to the list
is significant, then benefits of a linked list increase.
Parameter Linked list Array Dynamic array
Indexing O( ) O(1) O(1)
Insertion/deletion at
O(1) O( ), if array is not full (for shifting the elements) O( )
beginning
O(1), if array is not full
Insertion at ending O( ) O(1), if array is not full
O( ), if array is full
Deletion at ending O( ) O(1) O( )
Insertion in middle O( ) O( ), if array is not full (for shifting the elements) O( )
Deletion in middle O( ) O( ), if array is not full (for shifting the elements) O( )
Wasted space O( ) (for pointers) 0 O( )

3.6 Singly Linked Lists


The linked list consists of a series of structures called nodes. We can think of each node as a record. The first part of the record is a field that
stores the data, and the second part of the record is a field that stores a pointer to a node. So, each node contains two fields: a field and

3.5 Comparison of Linked Lists with Arrays & Dynamic Arrays 42


Data Structures and Algorithms Made Easy in Java Linked Lists

a field which is a pointer used to link one node to the next node. Generally "linked list" means a singly linked list. This list consists of a
number of nodes in which each node has a pointer to the following element. The link of the last node in the list is NULL, which
indicates the end of the list. Each node is allocated in the heap with a call to (), so the node memory continues to exist until it is explicitly
deallocated with a call to (). The node called a ℎ is the first node in the list. The last node's next pointer points to NULL value.

4 15 7 40 NULL

Head
Following is a type declaration for a linked list:
public class ListNode {
private int data;
private ListNode next;
public ListNode(int data){
this.data = data;
}
public void setData(int data){
this.data = data;
}
public int getData(){
return data;
}
public void setNext(ListNode next){
this.next = next;
}
public ListNode getNext(){
return this.next;
}
}

Basic Operations on a List


 Traversing the list
 Inserting an item in the list
 Deleting an item from the list

Traversing the Linked List


Let us assume that the ℎ points to the first node of the list. To traverse the list we do the following.
 Follow the pointers.
 Display the contents of the nodes (or count) as they are traversed.
 Stop when the next pointer points to NULL.

4 15 7 40 NULL

head
The ListLength() function takes a linked list as input and counts the number of nodes in the list. The function given below can be used for
printing the list data with extra print function.
public int length(ListNode headNode) {
int length = 0;
ListNode currentNode = headNode;
while(currentNode != null){
length++;
currentNode = currentNode.next;
}
return length;
}
Time Complexity: O( ), for scanning the list of size . Space Complexity: O(1), for creating a temporary variable.

Singly Linked List Insertion


Insertion into a singly-linked list has three cases:
 Inserting a new node before the head (at the beginning)
 Inserting a new node after the tail (at the end of the list)
 Inserting a new node at the middle of the list (random location)
Note: To insert an element in the linked list at some position , assume that after inserting the element the position of this new node is .

3.6 Singly Linked Lists 43


Data Structures and Algorithms Made Easy in Java Linked Lists

Inserting a Node in Singly Linked List at the Beginning


In this case, a new node is inserted before the current head node. needs to be modified (new node’s next pointer)
and it can be done in two steps:
 Update the next pointer of new node, to point to the current head.
new node
data 15 7 40 NULL

head
 Update head pointer to point to the new node.
new node
data 15 7 40 NULL

head

Inserting a Node in Singly Linked List at the Ending


In this case, we need to modify (last nodes next pointer and new nodes next pointer).
 New nodes next pointer points to NULL.
NULL
new node
4 15 7 0 data NULL

head
 Last nodes next pointer points to the new node.
new node
4 15 7 0 data NULL

head

Inserting a Node in Singly Linked List at the Middle


Let us assume that we are given a position where we want to insert the new node. In this case also, we need to modify two next pointers.
 If we want to add an element at position 3 then we stop at position 2. That means we traverse 2 nodes and insert the new node.
For simplicity let us assume that the second node is called node. The new node points to the next node of the position
where we want to add this node.
node
4 15 7 40 NULL

head new node

data
 Position node’s next pointer now points to the new node.
node
4 15 7 40 NULL

head
data
new node
Note: We can implement the three variations of the operation separately.
Time Complexity: O( ). since, in the worst case, we may need to insert the node at the end of the list. Space Complexity: O(1).

Singly Linked List Deletion


Similar to insertion, here we also have three cases.
 Deleting the first node
 Deleting the last node
 Deleting an intermediate node.

3.6 Singly Linked Lists 44


Data Structures and Algorithms Made Easy in Java Linked Lists

Deleting the First Node in Singly Linked List


First node (current head node) is removed from the list. It can be done in two steps:
 Create a temporary node which will point to the same node as that of head.

4 15 7 40 NULL

Head Temp
 Now, move the head nodes pointer to the next node and dispose of the temporary node.

4 15 7 40 NULL

Temp Head

Deleting the Last node in Singly Linked List


In this case, the last node is removed from the list. This operation is a bit trickier than removing the first node, because the algorithm should
find a node, which is previous to the tail. It can be done in three steps:
 Traverse the list and while traversing maintain the previous node address also. By the time we reach the end of the list, we will have
two pointers, one pointing to the node and the other pointing to the node the tail node.

4 15 7 40 NULL

Head Node previous to tail Tail


 Update previous node’s next pointer with NULL.
NULL

4 15 7 40 NULL

Head
Previous node to tail Tail
 Dispose of the tail node.
NULL

4 15 7 40 NULL

Head Previous node to tail Tail

Deleting an Intermediate Node in Singly Linked List


In this case, the node to be removed is two nodes. Head and tail links are not updated in this case. Such a removal
In this case, the node to be removed is two nodes. Head and tail links are not updated in this case. Such a removal
can be done in two steps:
 Similar to the previous case, maintain the previous node while traversing the list. Once we find the node to be deleted, change the
previous node’s next pointer to the next pointer of the node to be deleted.

4 15 7 40 NULL

Head Previous node Node to be deleted


 Dispose of the current node to be deleted.

4 15 7 40 NULL

Head Previous node Node to be deleted


Time Complexity: O( ). In the worst case, we may need to delete the node at the end of the list. Space Complexity: O(1).

Deleting Singly Linked List


This works by storing the current node in some temporary variable and freeing the current node. After freeing the current node, go to the
next node with a temporary variable and repeat this process for all nodes.
Time Complexity: O( ), for scanning the complete list of size . Space Complexity: O(1), for temporary variable.

3.6 Singly Linked Lists 45


Random documents with unrelated
content Scribd suggests to you:
V.

D ie Generalin war sehr stolz auf ihre Abstammung. Wie mußte ihr
nun zumute sein, als ihr so offen und ohne Vorbereitungen
mitgeteilt wurde, daß der letzte Träger ihres Namens nicht viel
mehr als ein bedauernswerter Idiot, fast ganz mittellos sei und sogar
Almosen annehme. Dem General war es um den denkbar größten
Eindruck zu tun, um sogleich ihr Interesse zu erwecken, sie von
anderen Gedanken abzulenken und hierdurch die Frage nach den
Perlen in Vergessenheit zu bringen.
Die Generalin hatte die Angewohnheit, wenn etwas geschehen
war, was ihr nicht behagte, mit weit offenen Augen und
unbestimmtem Blick, den Oberkörper gewöhnlich etwas
zurückgelegt, vor sich in die Luft zu starren und kein Wort zu
sprechen. Sie war eine stattliche Frau, in gleichem Alter wie ihr
Gatte, mit dunklem, schon stark graumeliertem, doch noch recht
dichtem Haar, einer leicht gebogenen Nase, mit gelblichen,
eingefallenen Wangen und dünnen Lippen. Ihre Stirn war hoch und
schmal; ihre grauen, ziemlich großen Augen konnten bisweilen einen
ganz unerwarteten Ausdruck annehmen. Sie hatte einmal die
Schwäche gehabt, zu glauben, daß ihr Blick sehr ausdrucksvoll sei,
und diese Überzeugung ließ sie sich auch jetzt noch nicht nehmen.
„Empfangen? Sie sagen, wir sollen ihn empfangen? Jetzt?
Sogleich?“
Die Generalin sah ihren etwas unsicher geschäftigen Iwan
Fedorowitsch mit besagten großen Augen an.
„Oh, was das betrifft, so braucht man bei dem nicht alle
Etikettevorschriften und Zeremonien zu beobachten, vorausgesetzt,
daß es dir, mein Freund“ (der General redete seine Gattin
gewöhnlich mit „mein Freund“ an), „daß es dir nur zusagt, ihn zu
empfangen,“ beeilte er sich erklärend hinzuzufügen. „Er ist ein
vollständiges Kind und so ein armer Junge: hat da gewisse Anfälle,
wie er sagt, von einer Krankheit wahrscheinlich; kommt soeben aus
der Schweiz, direkt von der Bahn, ist etwas eigenartig gekleidet, so–
o ... nach deutscher Art gewissermaßen, und hat zum Überfluß keine
Kopeke in der Tasche, tatsächlich; er weinte beinahe. Ich habe ihm
fünfundzwanzig Rubel geschenkt und will ihm in einer Kanzlei eine
kleine Schreiberstelle zu verschaffen suchen. Und euch, mesdames,
bitte ich, ihn gefälligst zu bewirten; denn er wird, glaube ich, auch
hungrig sein ...“
„Ich verstehe Sie nicht,“ fuhr die Generalin im selben Ton und mit
demselben Blick fort, „hungrig und hat Anfälle! Was für Anfälle?“
„Oh, die wiederholen sich nicht so oft, und dann – er ist ja fast
noch ein großes Kind, übrigens nicht ungebildet. Und euch wollte ich
bitten, mesdames,“ wandte er sich wieder an seine Töchter, „ihn ein
wenig zu examinieren; denn es ist doch immer gut, wenn man weiß,
was für Eigenschaften er hat.“
„Ex–a–mi–nie–ren?“ fragte die Generalin gedehnt und begann in
größter Verwunderung bald ihre Töchter, bald wiederum ihren
Gatten mit fragendem Blick anzusehen.
„Ach, mein Freund, das war natürlich nicht so gemeint, versteh
mich nicht falsch ... übrigens, wie du willst. Ich hatte die Absicht, ihn
gut zu behandeln und in unser Haus einzuführen; denn das wäre
doch ein gutes Werk.“
„In unser Haus einzuführen? Aus der Schweiz?“
„Die Schweiz ist eine Sache für sich ... doch, übrigens, wie gesagt:
ganz wie du willst. Ich meine ja nur, weil er doch auch ein Myschkin
ist, und vielleicht sogar verwandt mit dir, und dann: er weiß nicht
einmal, wo er sein Haupt hinlegen soll. Ich glaubte, daß es dich
interessieren würde, ihn kennen zu lernen; denn er gehört doch
gewissermaßen, nun ja, zur Familie.“
„Gewiß doch, maman, wenn man mit ihm nicht so zeremoniell zu
sein braucht. Und nach der Reise wird er sicherlich Hunger haben,
weshalb also soll man ihm nicht zu essen geben, wenn er hier sonst
keine Menschenseele hat?“ sagte Alexandra, die älteste Tochter.
„Und dann ist er ja wie ein Kind, mit ihm kann man noch
Blindekuh spielen.“
„Blindekuh spielen? Wie das?“
„Ach, maman, hören Sie doch auf, sich so zu verstellen, bitte!“
unterbrach Aglaja sie ärgerlich.
Die mittlere, Adelaida, konnte sich nicht bezwingen und brach in
helles Lachen aus.
„Lassen Sie ihn nur herbitten, Papa, maman erlaubt es schon,“
entschied Aglaja.
Der General klingelte und ließ den Fürsten zur Generalin bitten.
„Aber nur unter der Bedingung, daß ihm eine Serviette um den
Hals gebunden wird, sobald er sich an den Tisch setzt,“ sagte die
Generalin. „Ruft Fedor – oder Mawra ... sie soll hinter seinem Stuhl
stehen, wenn er ißt. Ist er wenigstens ruhig, wenn er seine Anfälle
hat? Macht er nicht wilde Gesten?“
„Im Gegenteil, er ist sogar sehr nett erzogen, er hat vorzügliche
Manieren. Mitunter ist er vielleicht etwas gar zu treuherzig ... Ah, da
ist er ja selbst! Bitte, hier, stelle euch vor, meine Damen: Fürst Lew
Nikolajewitsch Myschkin, der Letzte dieses Namens. Ein
Namensvetter von dir, liebe Lisaweta Prokofjewna, und vielleicht
sogar ein Verwandter. Bitte, sich seiner gefälligst anzunehmen.
Sogleich wird das Frühstück aufgetragen, Sie erweisen uns doch die
Ehre, Fürst ... Nun, ich aber, Verzeihung, ich habe mich schon
verspätet, ich muß eilen ...“
„Wir wissen schon, wohin Sie eilen,“ sagte die Generalin
bedeutsam.
„Ich eile, ich eile, mein Freund, habe mich nämlich schon
verspätet! Gebt ihm übrigens eure Albums, mesdames, damit er
euch irgend etwas einschreibt. Ihr ahnt gar nicht, was für ein
Kalligraph er ist – einfach ein Phänomen! Angeborenes Talent! Dort
bei mir hat er mit mittelalterlichen Buchstaben eine Unterschrift
geschrieben: ‚In Demut unterzeichnet dieses Igumen Pafnutij‘ –
großartig! ... Nun, also auf Wiedersehen!“
„Pafnutij? Ein Abt? Warten Sie, aber so warten Sie doch, wohin
gehen Sie denn, was ist das für ein Pafnutij?“ rief die Generalin mit
ärgerlicher Gereiztheit und fast aufgebracht ihrem eilig sich
entfernenden Gatten nach.
„Ja, ja, mein Freund, früher hat es einmal einen solchen Abt
gegeben ... ich muß zum Grafen, er erwartet mich, schon lange, und
die Hauptsache: er hat mich selbst bestellt ... Auf Wiedersehen,
Fürst!“
Und Se. Exzellenz verschwand mit schnellen Schritten.
„Ich weiß schon, zu welchem Grafen er geht!“ bemerkte die
Generalin scharf und wandte gereizt ihren Blick dem Fürsten zu.
„Nun – was war’s doch?“ begann sie gereizt, indem sie sich ärgerlich
des vorhergehenden Gespräches zu erinnern suchte. „Wovon
sprachen wir? Ach, richtig! – nun, was war das für ein Abt?“
„Maman,“ wollte Alexandra sich einmischen, und Aglaja klappte
hörbar mit der Fußspitze auf den Boden.
„Unterbrechen Sie mich nicht, Alexandra Iwanowna,“ wandte sich
die Generalin eisig an ihre Älteste. „Ich will es wissen, was es mit
diesem Abt für eine Bewandtnis hat. Setzen Sie sich hierher, Fürst,
hier auf diesen Sessel mir gegenüber, nein, nein, hierher, mehr ins
Licht, rücken Sie der Sonne näher, damit ich Sie besser sehen kann.
Nun, was ist das für ein Abt?“
„Der Abt Pafnutij,“ antwortete der Fürst mit aufmerksamem und
ernstem Gesicht.
„Pafnutij? Das ist interessant. Nun, und was ist’s mit ihm?“
Die Generalin stellte ihre Fragen ungeduldig, schnell, schroff, ohne
den Blick vom Fürsten abzuwenden, und als dieser antwortete,
nickte sie nach jedem Satz mit dem Kopfe.
„Igumen Pafnutij lebte im vierzehnten Jahrhundert,“ begann der
Fürst, „und stand einem Kloster an der Wolga in unserem jetzigen
Gouvernement Kostroma vor. Er war bekannt wegen seines
gottesfürchtigen Lebens und seiner Reise ins Reich der Goldenen
Horde[6]. Ferner half er, Ordnung und Ruhe in unseren damaligen
Fürstentümern wiederherzustellen. Das Faksimile seiner Unterschrift
auf einer Urkunde kam mir zufällig in die Hände. Seine Schrift gefiel
mir, und ich versuchte sie nachzuahmen. Als Ihr Herr Gemahl nun
sehen wollte, wie ich schreibe, um mir vielleicht eine Anstellung zu
verschaffen, schrieb ich einige Sätze auf ein Blatt Papier, unter
anderem auch ‚In Demut unterzeichnet dieses Igumen Pafnutij‘,
genau so, wie der Abt selbst geschrieben hat. Diese Schriftprobe
gefiel Seiner Exzellenz, und deshalb hat er sie auch erwähnt.“
„Aglaja,“ sagte die Generalin „merk dir: Pafnutij, oder notiere den
Namen, denn sonst vergesse ich ihn. Ich glaubte, daß es
interessanter wäre. Wo ist denn diese Schriftprobe?“
„Sie blieb, glaube ich, auf dem Tisch im Kabinett des Generals.“
„Schickt Fedor hin und laßt sie sofort herholen!“ wandte sich die
Generalin an ihre Töchter.
„Aber ich kann es Ihnen ja nochmals aufschreiben, wenn Sie
wollen.“ –
„Gewiß, maman,“ sagte Alexandra, „jetzt aber täten wir besser, zu
frühstücken; wir sind hungrig.“
„Ja, das können wir,“ entschied die Generalin. „Gehen wir, Fürst!
Bringen Sie auch einen großen Hunger mit?“
„Ja, im Augenblick ist er sogar recht groß. Ich danke Ihnen.“
„Das gefällt mir, daß Sie höflich sind, und ich merke, Sie sind
durchaus nicht so ein ... Sonderling, als den man Sie uns zu
schildern beliebt hat. Nun, gehen wir ... Setzen Sie sich dorthin, mir
gegenüber,“ sagte sie, geschäftig dem Fürsten einen Stuhl
anweisend, als sie ins Frühstückszimmer traten, „ich will Sie sehen.
Alexandra, Adelaida, sorgt dafür, daß der Fürst alles Nötige
bekommt. Nicht wahr, er ist doch gar nicht so ... krank? Vielleicht
ist’s auch gar nicht nötig, ihm die Serviette ... Hat man Ihnen bei
Tisch immer eine Serviette umgebunden, Fürst?“
„Früher, als ich etwa siebenjährig war, allerdings, wie ich mich zu
erinnern glaube; jetzt jedoch lege ich die Serviette gewöhnlich auf
die Knie, wenn ich esse.“
„So macht man’s auch. Aber Ihre Anfälle?“
„Anfälle?“ wunderte sich der Fürst ein wenig. „Im allgemeinen
habe ich meine Anfälle jetzt ziemlich selten. Übrigens, ich weiß nicht:
man sagt, das hiesige Klima würde mir schädlich sein.“
„Er spricht sehr gut,“ bemerkte die Generalin, sich an ihre Töchter
wendend, nachdem sie wieder zu jedem Satz des Fürsten genickt
hatte. „Ich hatte es gar nicht erwartet. Das ist wahrscheinlich alles
nur Erfindung, wie gewöhnlich. Essen Sie, Fürst, und erzählen Sie,
wo Sie geboren, wo Sie erzogen sind. Ich will alles wissen; Sie
interessieren mich sehr.“
Der Fürst dankte und begann, während er mit großem Appetit aß,
zwischendurch alles das zu erzählen, was er an diesem Morgen
schon zweimal über seine Person berichtet hatte. Die Generalin
blickte ihn mit wachsender Zufriedenheit an. Die jungen Mädchen
hörten gleichfalls recht aufmerksam zu. Man kam auf die
Verwandtschaft zu sprechen; es zeigte sich, daß der Fürst seinen
Stammbaum kannte, aber wie sehr sie sich auch mühten, es ließ sich
doch so gut wie gar keine Verwandtschaft zwischen ihnen herstellen.
Ihre Großväter und Großmütter hätten sich vielleicht noch als
entfernte Verwandte betrachten können. Dieses verhältnismäßig
trockene Thema gefiel der Generalin ausnehmend gut, da sie sonst
nie Gelegenheit hatte, von ihrem Stammbaum zu sprechen, und so
war sie sehr guter Laune, als sie sich von der Frühstückstafel erhob.
„So, jetzt wollen wir in unser Versammlungszimmer gehen,“ sagte
sie, „der Kaffee kann dort gereicht werden. Wir haben, müssen Sie
wissen, ein bestimmtes Zimmer, in dem wir uns regelmäßig zu
versammeln pflegen, wenn wir allein sind,“ erzählte sie dem Fürsten,
während sie sich mit ihm dorthin begab. „Es ist im Grunde nichts
anderes, als mein kleiner Salon, in dem sich dann eine jede damit
beschäftigt, wozu sie gerade Lust hat. Alexandra, das ist diese hier,
meine älteste Tochter, spielt Klavier, oder sie liest oder näht.
Adelaida malt Landschaften und Porträts – kann aber leider nichts
beenden. Und Aglaja sitzt und tut nichts. Mir selbst fällt jede Arbeit
aus den Händen: was ich auch beginne, es kommt doch nichts dabei
heraus. Nun, da sind wir. Setzen Sie sich, Fürst, hier, an den Kamin,
und erzählen Sie. Ich will wissen, wie Sie eine Sache zu erzählen
verstehen. Jetzt werde ich mich selbst überzeugen ... Ich will Sie gut
kennen lernen und wenn ich die alte Fürstin Bjelokonskaja
wiedersehe, werde ich ihr von Ihnen erzählen. Ich will, daß Sie auch
alle anderen interessieren. Nun, reden Sie jetzt.“
„Aber, maman, so auf Kommando zu erzählen, ist doch sehr
schwer,“ bemerkte Adelaida, die inzwischen ihre Staffelei
zurechtgerückt hatte, jetzt Pinsel und Palette zur Hand nahm und
sich anschickte, an der längst begonnenen Kopie einer Landschaft zu
malen.
Alexandra und Aglaja setzten sich beide auf ein kleines Sofa und
schienen mit müßig im Schoß ruhenden Händen nichts als zuhören
zu wollen. Dem Fürsten fiel es auf, daß von allen Seiten mit ganz
besonderer, aufmerksamer Erwartung die Blicke auf ihn gerichtet
waren.
„Ich würde nichts erzählen, wenn man mir befehlen wollte,“ sagte
Aglaja.
„Warum nicht? Was ist denn dabei so verwunderlich? Warum sollte
er nicht erzählen? Er ist doch nicht stumm. Ich will wissen, wie er zu
erzählen versteht. Nun, bitte, gleichviel wovon. Erzählen Sie, wie
Ihnen die Schweiz gefallen hat, wie war der erste Eindruck? Ihr
werdet sehen, er wird sogleich beginnen und wird sogar vorzüglich
beginnen.“
„Der Eindruck war groß ...,“ begann der Fürst, wurde jedoch sofort
von der Generalin unterbrochen.
„Seht! Was hab’ ich gesagt?“ wandte sie sich äußerst befriedigt an
ihre Töchter, „da hat er doch begonnen!“
„Aber so lassen Sie ihn doch wenigstens weitererzählen, maman,“
versuchte Alexandra sie aufzuhalten. „Dieser Fürst ist vielleicht sogar
sehr gerieben und nichts weniger als ein Idiot,“ raunte sie
unbemerkt Aglaja zu.
„Zweifellos, das habe ich schon längst bemerkt,“ flüsterte Aglaja
ebenso zurück. „Wie dumm von ihm, sich zu verstellen und eine
solche Rolle zu spielen. Glaubt er etwa, dadurch zu gewinnen?“
„Der erste Eindruck war ungeheuer groß,“ wiederholte der Fürst.
„Als man mich aus Rußland fortbrachte und wir durch verschiedene
deutsche Städte fuhren, sah ich nur schweigend, was an uns
vorüberzog, und ich weiß noch, ich stellte keine einzige Frage. Es
war das nach einer ganzen Reihe von sehr starken und qualvollen
Anfällen meiner Krankheit. Und nach einer solchen Zeit, wenn meine
Krankheit so heftig aufgetreten war und die Anfälle sich mehreremal
wiederholt hatten, verfiel ich regelmäßig in vollkommene geistige
Stumpfheit, verlor ganz und gar mein Gedächtnis, und wenn der
Verstand auch noch arbeitete, so wurde doch die logische
Entwicklung meiner Gedanken gleichsam immer abgeschnitten. Mehr
als zwei oder drei Gedanken vermochte ich nicht nacheinander zu
denken. So scheint es mir wenigstens jetzt. Ließen dagegen die
Anfälle nach, so wurde ich wieder gesund und kräftig, ganz so wie
ich jetzt bin. Ja, ich entsinne mich noch; es war eine unerträgliche
Traurigkeit in mir; ich hätte weinen mögen. Ich wunderte mich nur
und war sehr unruhig. Doch am entsetzlichsten wirkte auf mich, daß
alles um mich herum mir so fremd war; das begriff ich. Diese
Fremdheit vernichtete mich förmlich. Aus diesem Zustande, aus
dieser Dunkelheit, dessen entsinne ich mich noch deutlich, erwachte
ich eines Abends – es war in Basel, als wir in der Schweiz angelangt
waren – und was mich erweckte, war der Schrei eines Esels auf dem
Marktplatz. Dieser Esel frappierte mich ungeheuer: er gefiel mir aus
irgendeinem Grunde über alle Maßen. Und im selben Augenblick
wurde es gleichsam hell in mir und die Dunkelheit verschwand.“
„Ein Esel? Das ist sonderbar,“ meinte die Generalin. „Aber
übrigens; was soll denn Sonderbares dabei sein – manch eine
verliebt sich in einen Esel,“ bemerkte sie mit zornigem Blick auf die
lachenden Töchter. „Auch in der Mythologie gibt es etwas Ähnliches.
Fahren Sie fort, Fürst.“
„Seit der Zeit habe ich die Esel sehr lieb. Ich empfinde geradezu
Sympathie für sie. Ich erkundigte mich sofort nach ihnen – es waren
meine ersten Worte seit langer Zeit. Ich wollte Näheres über sie
hören, denn ich hatte ja noch nie welche gesehn; und so überzeugte
ich mich bald selbst, daß sie überaus nutzbare Tiere sind: arbeitsam,
stark, geduldig, billig, ausdauernd. Durch diesen Esel aber begann
mir von Stund’ an die ganze Schweiz zu gefallen, und so verging
meine frühere Traurigkeit.“
„Das ist alles sehr eigentümlich, aber ich denke, vom Esel
brauchen Sie uns jetzt nichts mehr zu erzählen. Gehen wir auf ein
anderes Thema über. Worüber lachst du die ganze Zeit, Aglaja? Und
du, Alexandra? Der Fürst hat ganz vorzüglich vom Esel erzählt. Er
hat ihn selbst gesehn, was aber hast du gesehn? Du bist noch nie im
Auslande gewesen.“
„Ich habe aber doch schon einen Esel gesehn,“ sagte Adelaida.
„Und ich habe sogar einen gehört! Einen vierbeinigen!“
übertrumpfte sie Aglaja.
Da brachen sie alle drei in Lachen aus und der Fürst lachte mit.
„Das ist aber sehr häßlich von euch,“ bemerkte die Generalin, „Sie
müssen sie schon entschuldigen, Fürst, sie sind im Grunde gute
Mädchen. Ich muß sie ewig schelten, aber ich liebe sie doch. Sie sind
flatterhaft, leichtsinnig und im Augenblick einfach
unzurechnungsfähig.“
„Weshalb denn das?“ fragte der Fürst lachend. „Nur weil sie jetzt
lachen? Oh, auch ich würde die Gelegenheit nicht versäumen. Doch
trotzdem: ich habe den Esel in jeder Gestalt gern. Ein Esel ist immer
ein guter und nützlicher Mensch.“
„Aber Sie selbst, Fürst, sind Sie gut? Ich frage aus Neugier,“ sagte
die Generalin ganz harmlos.
Wieder brachen alle in Lachen aus.
„Ach, das war doch nicht so gemeint! Ihr habt wirklich nichts
anderes als den Esel im Sinn!“ rief die Generalin unwillig aus.
„Glauben Sie mir, Fürst, ich habe es nur so gesagt, ganz
gedankenlos, ohne jede ...“
„Anspielung? Oh, ich glaube es Ihnen, zweifellos!“
Und der Fürst konnte gar nicht mehr aufhören zu lachen.
„Es ist nur gut, daß Sie lachen. Das gefällt mir sehr. Ich sehe, Sie
sind ein guter Mensch,“ sagte die Generalin.
„Mitunter auch kein guter,“ antwortete der Fürst.
„Nun, ich bin immer gut,“ bemerkte die Generalin ganz
unerwartet, „ich bin tatsächlich immer gut, und das ist mein einziger
Fehler; denn man soll nicht immer gut sein. Ich ärgere mich sehr oft
über diese drei hier, zum Beispiel, und über Iwan Fedorowitsch
besonders, doch dumm ist nur, daß ich noch besonders gut bin,
wenn ich mich ärgere. Vorhin, kurz bevor Sie kamen, ärgerte ich
mich wieder und tat, als begriffe ich nichts, und als könnte ich auch
nichts begreifen. Das kommt bei mir so vor, ganz als wäre ich ein
Kind. Aglaja hat mir eine Lektion erteilt, hab’ Dank dafür, Aglaja.
Übrigens, das ist ja doch alles Unsinn. Ich bin noch nicht so dumm,
wie ich scheine und wie mich meine kleinen Töchter machen wollen.
Ich habe Charakter und bin nicht zimperlich. Ich sage das jetzt nur
so, nicht etwa, weil ich ihnen böse bin. Komm her, Aglaja, gib mir
einen Kuß ... Nun, genug der Zärtlichkeit,“ sagte sie, als Aglaja ihr
nach einem Kuß auf den Mund auch noch zärtlich die Hand küßte.
„Fahren Sie fort, Fürst. Vielleicht fällt Ihnen noch etwas
Interessanteres ein als das vom Esel.“
„Ich begreife nicht, wie man so auf Kommando erzählen kann,“
wunderte sich Adelaida, „ich würde es wirklich nicht können.“
„Der Fürst aber kann es, wie du siehst. Das kommt natürlich
daher, weil er intelligent ist und mindestens zehnmal klüger als du,
vielleicht sogar zwölfmal. Ich hoffe, daß du es bald selbst einsiehst.
Beweisen Sie es ihnen, Fürst. Fahren Sie fort. Den Esel kann man,
denke ich, auch in dieser Geschichte beiseite lassen. Nun was haben
Sie denn außer dem Esel im Auslande gesehn?“
„Aber auch das, was der Fürst vom Esel sagte, war interessant,“
bemerkte Alexandra. „Der Fürst hat wirklich fesselnd seinen
krankhaften Zustand geschildert und wie ihm dann alles, durch einen
äußeren Stoß gleichsam, mit völlig unerwarteter Plötzlichkeit in
einem ganz anderen Lichte erschien. Es hat mich immer zu wissen
interessiert, wie es wohl sein mag, wenn man den Verstand verliert
und dann später wieder gesund wird. Besonders wenn es ganz
plötzlich geschieht.“
„Nicht wahr? Nicht wahr?“ fragte die Generalin lebhaft. „Ich sehe,
auch du kannst mitunter klug sein. Nun, genug jetzt gescherzt. Sie
blieben, glaube ich, bei der Schweizer Landschaft stehen, Fürst, –
nun?“
„Wir kamen nach Luzern und man brachte mich über den See. Ich
fühlte seine Schönheit, aber es war mir dabei unsäglich schwer
zumute,“ erzählte der Fürst.
„Warum?“ fragte Alexandra.
„Das weiß ich nicht. Beim ersten Anblick einer solchen Natur ist
mir immer schwer zumute und eine gewisse Unruhe erfaßt mich;
schön ist es und doch – beunruhigend. Aber das war ja alles noch
während der Krankheit.“
„Oh, ich möchte gern einmal die Schweiz sehen!“ sagte Adelaida.
„Wann werden wir endlich einmal ins Ausland reisen? Da sitze ich
nun hier und kann seit zwei ganzen Jahren keinen Vorwurf zu einem
Gemälde finden.

‚Was in Westen und Süden wir lieben,


Ist schon längst und vielfach beschrieben‘“

zitierte sie. „Suchen Sie mir ein Sujet, Fürst.“


„Ich verstehe davon nichts. Ich denke: man schaut und malt.“
„Ich verstehe aber nicht zu schauen ...“
„Von was für Rätseln redet ihr? – das soll ein Mensch verstehen!
Kein Wort begreife ich!“ unterbrach sie die Generalin. „Weshalb
verstehst du denn nicht zu schauen? Du hast doch Augen, mach’ sie
auf und sieh. Verstehst du es hier nicht, so wirst du’s auch dort im
Auslande nicht lernen. Erzählen Sie lieber, was und wie Sie selbst
geschaut haben, Fürst.“
„Ja, das wird besser sein,“ meinte auch Adelaida. „Sie haben ja
doch im Auslande das Schauen gelernt.“
„Ich weiß nicht, ob ich es getan habe. Ich habe dort nur Heilung
von meiner Krankheit gesucht. Ob ich aber zu schauen gelernt habe,
das weiß ich wirklich nicht. Ich war die ganze Zeit dort sehr
glücklich.“
„Glücklich! Sie verstehen es, glücklich zu sein?“ rief Aglaja aus.
„Wie können Sie dann sagen, daß Sie nicht zu schauen gelernt
hätten! Sie werden auch uns noch das Schauen lehren.“
„Ach, bitte, lehren Sie’s uns!“ bat Adelaida lachend.
„Ich kann nichts lehren,“ gab auch der Fürst lachend zurück. „Fast
die ganze Zeit, die ich im Auslande gewesen bin, habe ich dort in
jenem Schweizerdorf verbracht; nur selten unternahm ich eine kurze
Reise. Was vermag ich da zu lehren? Anfangs konnte ich nur sagen,
daß ich mich nicht langweilte, dann aber – meine Gesundheit
besserte sich schnell – dann wurde mir jeder Tag teuer, und je
länger ich da war, desto teurer, so daß es mir selbst auffiel. Ich war
so zufrieden, wenn ich zu Bett ging, und wenn ich aufstand, war ich
geradezu glücklich. Weshalb aber das alles so war, ist ziemlich
schwer zu erklären.“
„So daß Sie sich nirgendwohin mehr fortsehnten, sich
nirgendwohin mehr fortgerufen fühlten?“ fragte Alexandra.
„Anfangs, ja, ganz zu Anfang – da rief es mich fort und mich
überkam dann eine große Unruhe. Ich dachte immerwährend daran,
wie ich einst leben würde. Ich wollte mein Schicksal erforschen und
in manchen Augenblicken wurde die Unruhe fast unerträglich.
Wissen Sie, es gibt solche Augenblicke, namentlich in der
Einsamkeit. Wir hatten dort einen Wasserfall, keinen sehr großen;
der fiel von einem hohen Berge. Wie ein schmales, dünnes Band sah
er aus, und er fiel fast senkrecht, – weiß, rauschend, mit
spritzendem, zerstäubendem Gischt. Er stürzte von hoch oben herab
und schien dabei doch gar nicht so hoch zu sein, er war vielleicht
eine halbe Werst entfernt, und es schien, als seien nur fünfzig Schritt
bis zu ihm. Wenn ich nachts nicht schlafen konnte, lauschte ich
seinem Rauschen; in solchen Minuten wuchs dann meine Unruhe
und wurde beklemmend. Auch mitten am Tage, wenn man so
zuweilen irgendwohin in die Berge ging – da blieb man plötzlich
stehen: ringsum nichts als Fichten, alte, große, harzige Stämme;
über einem auf dem Felsen die Ruinen eines mittelalterlichen
Schlosses; unser Dorf weit unten, kaum noch sichtbar; die Sonne so
grell, der Himmel blau, unheimlich wurde die Stille. Da scheint es
einem denn, daß man irgendwohin gerufen wird, und ich dachte oft,
wenn man immer geradeaus und lange, lange ginge, bis dorthin zu
jenem Strich, wo sich Himmel und Erde vereinen – daß dort des
Rätsels Lösung sei und man dort sogleich ein neues Leben sehen
würde, ein tausendmal stärkeres und geräuschvolleres als bei uns.
So dachte ich mir immer eine große Stadt, wie etwa Neapel, in der
nur Paläste sind und Geräusch, und Lärm, und Leben ... Doch wer
kann das alles erzählen, was man so zusammengedacht hat! Und
dann schien mir wiederum, daß man auch im Gefängnis ein
unermeßlich großes Leben finden kann.“
„Diesen löblichen Gedanken habe ich schon in meiner
Chrestomathie gelesen, als ich noch zwölf Jahre alt war,“ sagte
Aglaja.
„Das ist alles Philosophie,“ meinte Adelaida, „Sie sind ein
Philosoph, Fürst, und sind hergekommen, um uns zu belehren.“
„Sie haben vielleicht recht,“ sagte der Fürst lächelnd, „ich bin ...
ja, ich bin tatsächlich ein Philosoph und habe vielleicht auch wirklich
die Absicht, zu lehren ... Das ist schon möglich ... sogar sehr
möglich.“
„Und Ihre Philosophie ist von genau derselben Art, wie die
Jewlampia Nikolajewnas,“ griff wieder Aglaja auf. „Das ist eine
Beamtenfrau – übrigens ist sie Witwe – sie besucht uns oft und sitzt
dann stundenlang. Bei ihr liegt das ganze Lebensrätsel in der –
Billigkeit. Nur wie man billiger leben könnte, nur von Kopeken spricht
sie, und dabei nicht zu vergessen – sie hat Geld. Genau so ist auch
Ihr großes Leben im Gefängnis, und vielleicht auch Ihr vierjähriges
Glück im Dorf, für das Sie Ihre große Stadt Neapel verkauften und,
wie mir scheint, noch mit Profit, wenn auch nur von Kopeken.“
„Was das Leben im Gefängnis betrifft, so kann man auch anderer
Meinung sein,“ sagte der Fürst. „Ich habe einmal gehört, wie ein
Mensch, der zwölf Jahre im Gefängnis verbracht hatte, von diesem
Leben erzählte. Es war das einer von den Patienten meines
Professors. Er hatte Anfälle, war bisweilen sehr unruhig, weinte und
wollte sich einmal sogar das Leben nehmen. Sein Leben im
Gefängnis war ein sehr trauriges gewesen, dessen kann ich Sie
versichern, doch sicherlich nicht nur von Kopekenwert. Seine ganzen
Erlebnisse beschränkten sich auf eine Spinne und einen kleinen
Baum, der unter dem Fenster herangewachsen war ... Doch ich
werde Ihnen lieber von einem anderen Menschen erzählen, den ich
im vorigen Jahre kennen lernte. Hier ist ein Umstand von besonderer
Merkwürdigkeit – eben weil man einen solchen Menschen nur
äußerst selten trifft: dieser Mensch war einmal zusammen mit
anderen aufs Schafott geführt worden und hatte sein Todesurteil
gehört: sie alle sollten wegen eines politischen Verbrechens
erschossen werden. Nach etwa zwanzig Minuten wurde ihre
Begnadigung verlesen, und sie wurden zu einer milderen Strafe
verurteilt. Einstweilen aber, die Zeit zwischen den beiden
Verlesungen, also etwa ganze zwanzig Minuten, hatte er natürlich in
der festen Überzeugung verbracht, daß er nach wenigen Minuten
jählings sterben würde. Ich wollte furchtbar gern einmal hören, wie
er seine damaligen Eindrücke jetzt wohl wiedergeben mochte, und
versuchte mehrmals, das Gespräch auf jenes Erlebnis zu bringen. Er
entsann sich noch jeder Einzelheit ungewöhnlich deutlich und
versicherte, daß er niemals auch nur das Geringste vergessen
würde, was er in diesen Minuten gesehen oder gedacht. Zwanzig
Schritte vom Schafott, das viel Volk und Soldaten umstanden, waren
drei Pfähle eingerammt; denn der Verurteilten waren mehrere. Die
ersten drei wurden zu den Pfählen geführt und angebunden; man
zog ihnen das ‚Sterbekleid‘ an – lange weiße Kittel – und über die
Augen wurden ihnen weiße Kapuzen gezogen, damit sie nicht sähen,
wie auf sie gezielt wurde. Vor jedem Pfahl wurde ein Kommando
Soldaten, bestehend aus einigen Mann, aufgestellt. Mein Bekannter
war der Achte in der Reihe, folglich mußte er als einer der Letzten zu
den Pfählen gehen. Der Geistliche trat an jeden heran und segnete
ihn mit dem Kreuz. Es blieben ihm noch fünf Minuten auf Erden,
nicht mehr. Doch diese fünf Minuten schienen ihm eine unendlich
lange Frist, ein unschätzbarer Reichtum; es schien ihm, daß er in
diesen fünf Minuten noch so viel Leben zu durchleben habe, daß er
an den letzten Augenblick vorläufig noch gar nicht zu denken
brauche, und er entwarf noch einen ganzen Plan für die Ausnutzung
dieser kurzen Zeit: für den Abschied von den Kameraden bestimmte
er zwei Minuten; weitere zwei Minuten bestimmte er dazu, um zum
letztenmal noch einmal still für sich zu denken, und die letzte
Minute, um noch einmal, zum letztenmal, rings um sich zu schauen.
Er entsann sich dieser Zeiteinteilung noch bis auf jede Einzelheit, er
wußte genau, welche Gedanken er gehabt, und daß er sich gerade
diese Reihenfolge vorgenommen. Er war damals siebenundzwanzig
Jahre alt, als er sterben sollte, gesund und kräftig. Als er von seinen
Freunden Abschied nahm, stellte er, dessen entsann er sich noch
deutlich, an einen von ihnen irgendeine nebensächliche Frage und
vernahm sogar sehr interessiert dessen Antwort. Darauf, als er von
ihnen Abschied genommen, begannen die zwei Minuten, die er dazu
bestimmt hatte, um still für sich zu denken. Er wußte, worüber er
nachdenken würde: er wollte es sich immer einmal vorstellen,
möglichst schnell und klar und grell, wie denn das eigentlich sei:
soeben lebt er noch, er ist, nach drei Minuten aber ist er nicht, nach
drei Minuten wird er ein Irgend-etwas sein – aber was denn, wo
denn? Und alles das glaubte er in diesen zwei Minuten entscheiden
zu können. Nicht weit von jenem Platz, auf dem sie erschossen
werden sollten, war eine Kirche, und das vergoldete Dach des
Turmes glänzte im hellen Sonnenschein. Er wußte noch, daß er
unverwandt, daß er fast starr auf diesen goldenen Turm und die
Strahlen, die von ihm ausgingen, gesehen hatte; er vermochte sich
nicht loszureißen von diesen Strahlen: es schien ihm, daß sie seine
neue Natur seien, daß er nach drei Minuten irgendwie mit ihnen
ineinanderfluten würde ... Die Ungewißheit und der Ekel vor diesem
Neuen, das unfehlbar sogleich eintreten mußte und dann ewig sein
würde, waren für ihn auch in der Erinnerung noch grauenvoll. Doch
trotzdem sei ihm in diesen Augenblicken nichts schwerer gewesen,
erzählte er, als der unausgesetzte Gedanke: ‚Wie aber, wenn du nicht
zu sterben brauchtest? Wenn man dir das Leben wiedergeben würde
– welch eine Ewigkeit! Und all das gehörte dann mir! Oh, jede
Minute würde ich in ein ganzes Jahrhundert verwandeln, nichts
würde ich verlieren, jede Minute würde ich zählen, nichts, nichts
würde ich verlieren, keinen Augenblick würde ich ungenützt
vergeuden!‘ Er sagte, daß dieser Gedanke in ihm schließlich zu
einem so brennenden Ingrimm geworden sei, daß er nur noch
gewünscht habe, schneller erschossen zu werden.“
Der Fürst verstummte plötzlich. Alle erwarteten, daß er noch
fortfahren und etwas Besonderes daraus folgern würde.
„Haben Sie beendet, was Sie erzählen wollten?“ fragte Aglaja.
„Was? Ach so – ja,“ sagte der Fürst, aus seiner
Gedankenverlorenheit auffahrend.
„Wozu haben Sie uns denn das erzählt?“
„So ... es fiel mir gerade ein ... weil wir darauf zu sprechen kamen
...“
„Sie scheinen gern so plötzlich abzubrechen,“ bemerkte Alexandra,
„Sie wollten damit gewiß sagen, daß mitunter fünf Minuten
wertvoller als ein Schatz sein können. Das ist ja alles recht schön
und gut, aber, erlauben Sie mal, – was tat denn dieser Ihr
Bekannter, der Ihnen diese Marter geschildert hat: er wurde doch
begnadigt, folglich erhielt er diese ‚Ewigkeit‘ geschenkt. Nun, und
was tat er denn später mit diesem Reichtum? Lebte er wirklich so,
daß er keinen Augenblick mehr ‚ungenützt vergeudete‘?“
„O nein, er hat mir selbst gesagt – auch ich stellte diese Frage an
ihn –, daß er längst nicht so gelebt und viele, viele Augenblicke
vergeudet und verloren habe ...“
„Nun, dann kann Ihnen ja dies sogleich als Beispiel dienen, und
wie Sie daraus sehen, kann man doch nicht so leben, daß man
keinen Augenblick ungenützt vergeudet. Aus irgendeinem Grunde ist
es eben unmöglich.“
„Ja, aus irgendeinem Grunde ist es eben unmöglich,“ sprach der
Fürst gedankenverloren nach, „mir selbst hat es auch so geschienen
... Aber dennoch – man will es gleichsam nicht glauben ...“
„Das heißt, Sie glauben klüger als alle anderen zu leben?“ fragte
Aglaja.
„Ja, auch das habe ich mitunter geglaubt.“
„Und glauben es auch jetzt noch?“
„Und ... glaube es auch jetzt noch,“ antwortete der Fürst, der mit
demselben stillen und nachdenklichen Lächeln Aglaja ansah. Alsbald
jedoch lachte er wieder und sah sie heiter an.
„Sehr bescheiden!“ Aglaja ärgerte sich fast.
„Aber wie mutig Sie sind, Sie lachen ganz harmlos, während mich
das alles so heftig traf und erschütterte, daß es mir noch lange
nachher im Traum erschien; gerade diese fünf Minuten habe ich oft
im Traum durchlebt ...“
Ernst und prüfend betrachtete er nochmals seine Zuhörerinnen.
„Sie ärgern sich doch nicht aus irgendeinem Grunde über mich?“
fragte er plötzlich, offenbar etwas verwirrt, doch blickte er dabei
allen offen in die Augen.
„Weshalb?“ Alle drei Mädchen wunderten sich über seine plötzliche
Frage.
„Nun, weil es doch so den Anschein hat, als wolle ich belehren ...“
Da brachen sie von neuem in Lachen aus.
„Wenn Sie mir böse sind, so ... tragen Sie es mir nicht nach,“ bat
er. „Ich weiß es ja selbst, daß ich weniger als alle anderen gelebt
habe und weniger als alle vom Leben verstehe. Ich spreche mitunter
vielleicht sehr sonderbar ...“
Und der Fürst verstummte, nun wirklich verwirrt.
„Wenn Sie sagen, daß Sie glücklich gewesen sind, so haben Sie
nicht weniger, sondern mehr gelebt – weshalb verstellen Sie sich
dann und entschuldigen sich?“ fragte Aglaja streng, fast
händelsüchtig. „Und beunruhigen Sie sich nicht darüber, daß Sie uns
belehren, hier kann von einem Triumph Ihrerseits gar nicht die Rede
sein. Mit Ihrem Quietismus kann man auch ein Leben von hundert
Jahren mit Glück ausfüllen. Ihnen kann man eine Hinrichtung zeigen
oder einen kleinen Finger, Sie werden aus dem einen wie aus dem
anderen einen gleich lobenswerten Schluß ziehen und überdies noch
sehr zufrieden sein. So kann man schon leben.“
„Weshalb ärgerst du dich wieder – das versteh’ ich nicht!“
unterbrach sie die Generalin, die schon längere Zeit verwundert die
Gesichter der Sprechenden betrachtet hatte, „und wovon ihr redet,
kann ich überhaupt nicht begreifen. Was soll dieser kleine Finger? –
Und dieser ganze Unsinn? Der Fürst spricht vorzüglich, nur ein wenig
traurig. Weshalb entmutigst du ihn? Als er zu erzählen begann,
lachte er noch, jetzt aber hast du ihn ganz verwirrt gemacht.“
„Tut nichts, maman. Schade, daß Sie keine Hinrichtung gesehen
haben, Fürst, ich würde Sie sonst etwas gefragt haben.“
„Ich habe eine Hinrichtung gesehen,“ antwortete der Fürst.
„Ja??“ fragte Aglaja ganz überrascht. „Eigentlich hätte ich es mir
denken können! Das ist nun das Letzte, das fehlte noch! Aber wenn
Sie eine Hinrichtung gesehen haben, wie können Sie dann sagen,
daß Sie die ganze Zeit glücklich gewesen sind? Nun, hab’ ich nicht
recht?“
„Wurde denn auch in Ihrem Dorf hingerichtet?“ fragte Adelaida.
„Nein, ich habe in Lyon eine Hinrichtung gesehen. Ich war mit
Professor Schneider hingefahren, er nahm mich mit. Als wir
ankamen, gerieten wir gerade auf den Platz ...“
„Nun, und es gefiel Ihnen sehr? Es enthielt wohl viel Erbauliches,
Nützliches?“ fragte Aglaja.
„Es gefiel mir durchaus nicht und ich war nachher krank, aber ich
muß gestehen, daß ich wie gebannt hinsah, ich konnte meinen Blick
nicht losreißen.“
„Auch ich hätte meinen Blick nicht losreißen können,“ sagte
Aglaja.
„Dort sieht man es sehr ungern, wenn Frauen einer Hinrichtung
beiwohnen, sogar in den Zeitungen wird dann dagegen
geschrieben.“
„Das heißt also, daß man es nicht für eine Frauensache hält,
sondern nur für eine Männersache, und damit will man’s
rechtfertigen. Ich gratuliere zu dieser Logik. Und Sie sind natürlich
derselben Ansicht.“
„Erzählen Sie uns von jener Hinrichtung,“ unterbrach Adelaida die
Schwester.
„Ich würde jetzt nichts weniger als gern davon erzählen ...,“ sagte
der Fürst sehr ernst, und er runzelte ein wenig die Stirn, während es
wie ein Schatten über sein Gesicht zog.
„Das sieht ja ganz aus, als sei es hier nicht der Mühe wert,“
stichelte Aglaja.
„Nein, ich sagte es nur, weil ich von dieser Hinrichtung vorhin
schon erzählt habe.“
„Wem haben Sie davon erzählt?“
„Ihrem Diener, als ich dort wartete ...“
„Welchem Diener?“ ertönte es von allen Seiten.
„Nun, dem, der dort im Vorzimmer sitzt, mit dem graumelierten
Haar und roten Gesicht. Ich wartete im Vorzimmer, bis Iwan
Fedorowitsch mich empfing.“
„Das ist sonderbar,“ meinte die Generalin.
„Der Fürst ist ein Demokrat,“ warf Aglaja kurz hin. „Freilich, wenn
Sie es unserem Alexei erzählt haben, können Sie es uns nicht mehr
erzählen.“
„Ich will es aber unbedingt hören!“ bestand Adelaida auf ihrem
Wunsch.
„Vorhin,“ wandte sich der Fürst wieder etwas ermutigter an
Adelaida (wie es schien, faßte er sehr schnell Mut und war dann
überhaupt sehr zutraulich), „vorhin hatte ich allerdings einen
Gedanken, als Sie um ein Sujet für ein Bild baten: zeichnen Sie das
Gesicht eines zum Tode Verurteilten, wenn er auf dem Schafott
steht, kurz bevor er den Kopf auf den Block gelegt hat, eine Minute
vor dem Niederfallen des Beiles.“
„Wie, das Gesicht? Nur das Gesicht?“ fragte Adelaida. „Das ist
doch ein etwas eigentümliches Sujet, und was wäre denn das für ein
Bild?“
„Ich weiß nicht ... aber warum nicht?“ fragte der Fürst, der mit
Eifer bei der Sache war. „Ich habe in Basel vor nicht langer Zeit ein
ähnliches Bild gesehen. Ich würde es Ihnen gern beschreiben ...
nun, ein anderes Mal ... Es hat sich mir unvergeßlich eingeprägt.“
„Oh, das Baseler Bild müssen Sie mir unbedingt einmal
beschreiben; jetzt aber sagen Sie mir, wie Sie sich das Bild dieser
Hinrichtung denken. Können Sie es so wiedergeben, wie Sie es sich
selbst vorstellen? Wie soll ich denn das Gesicht malen? Nichts als ein
Gesicht? Was muß denn das für ein Gesicht sein?“
„Das Gesicht eines zum Tode Verurteilten, eine Minute vor der
Hinrichtung,“ begann der Fürst mit ersichtlicher Bereitwilligkeit. Es
hatte den Anschein, als ließe er sich von der Erinnerung ganz
gefangennehmen, und als hätte er alles übrige schon vollständig
vergessen. „Das Gesicht in dem Augenblick, wenn er gerade die
kleine Treppe emporgestiegen ist und sich nun plötzlich auf dem
Schafott sieht ... Er blickte zufällig in die Richtung, in der ich stand:
ich sah sein Gesicht und begriff alles ... Aber wie soll man das in
Worten wiedergeben! Ich würde – ich weiß nicht was darum geben,
wenn Sie oder sonst jemand dieses Gesicht zeichneten! Wenn Sie
das könnten! Ich dachte schon damals, daß ein solches Bild von
großem Nutzen sein würde. Wissen Sie, man müßte in diesem
Gesicht alles wiedergeben, was vorhergegangen ist, alles, alles! Er
hatte im Gefängnis gesessen und, wie ich später las, erst nach einer
Woche die Hinrichtung erwartet. Er hatte auf Verzögerung
gerechnet, darauf, daß die Papiere noch irgendwo eingereicht
werden müßten und nicht vor einer Woche zurückkommen könnten.
Und nun plötzlich hatten alle Formalitäten viel weniger Zeit in
Anspruch genommen. Um fünf Uhr morgens schlief er noch. Es war
Ende Oktober: da ist es um fünf Uhr kalt und dunkel. Der
Gefängnisaufseher trat mit der Wache leise ein und berührte
vorsichtig seine Schulter; jener erwachte, richtete sich auf, sah das
Licht und die Wachen. ‚Was ist?‘ – ‚Um zehn Uhr findet die
Hinrichtung statt.‘ Zuerst soll er es gar nicht geglaubt haben, es
hieß, er habe sogar gestritten und behauptet, die Papiere könnten
nicht vor einer Woche zurückkommen. Doch als er nach dem jähen
Erwachen vollends zu sich kam, da hörte er auf zu widersprechen
und verstummte – so wurde später erzählt. Darauf soll er noch
gesagt haben: ‚Es ist doch schwer, so plötzlich ...‘ worauf er wieder
verstummte. Die ersten drei oder vier Stunden vergehen über den
Vorbereitungen: da kommt der Geistliche, dann das Frühstück, zu
dem er Wein, Kaffee und Rindfleisch erhält – ist das nicht ein wahrer
Spott und Hohn? Wenn man nur bedenkt, wie grausam das alles ist!
Und doch, bei Gott, diese unschuldigen Leute sind in ihrer
Herzenseinfalt vollkommen überzeugt, daß es ein Werk der
Nächstenliebe sei! Darauf folgt das Ankleiden des Verurteilten – Sie
wissen doch, worin das besteht? – nun, und dann wird er durch die
Stadt zum Schafott geführt ... Ich glaube, auch hier muß es dem
Betreffenden scheinen, daß noch ein unendlich langes Leben vor ihm
liegt, während er hingeführt wird. Sicherlich denkt er unterwegs:
‚Oh, es ist ja noch weit, noch drei ganze Straßen weit habe ich zu
leben; jetzt habe ich noch die erste vor mir, dann kommt erst die
zweite und dann erst die dritte, wo rechts der Bäckerladen ist ... oh,
bis wir erst zum Bäckerladen kommen!‘ Ringsum drängt sich das
Volk, ringsum Geschrei und Lärm, zehntausend Gesichter,
zehntausend Augenpaare – alles das muß er ertragen, doch das
Schrecklichste ist der Gedanke: ‚Da sind ihrer zehntausend, und von
ihnen wird keiner hingerichtet, nur ich allein werde hingerichtet!‘
Und das ist alles erst der Anfang! Eine kleine Treppe führt zum
Schafott hinauf; vor dieser Treppe brach er plötzlich in Tränen aus
und war doch dabei ein starker Mensch mit männlichem Charakter
und ein großer Missetäter, wie man erzählte. Der Geistliche wich
keinen Augenblick von seiner Seite, er fuhr auch im
Verbrecherkarren mit ihm zum Richtplatz und sprach die ganze Zeit
auf ihn ein, doch wird dieser ihm wohl kaum zugehört haben, – und
wenn er auch hingehört haben sollte, so wird er ihn nach dem
dritten Wort doch nicht mehr verstanden haben. So hat es unbedingt
sein müssen. Endlich begann er die Treppe emporzusteigen. Die
Füße waren ihm ja gefesselt, und so bewegte er sich nur mit kleinen
Schritten vorwärts. Der Geistliche muß ein verständiger Mann
gewesen sein: er hörte auf zu reden und hielt ihm immer nur das
Kreuz zum Küssen hin. Vor der Treppe war er sehr bleich, als er aber
oben anlangte und auf dem Schafott stand, da wurde er plötzlich
weiß, buchstäblich so weiß wie Papier, vollkommen wie ein Blatt
weißes Schreibpapier. Zweifellos wurden seine Füße schwach und
steif, und es quälte ihn eine gewisse Übelkeit – als wenn ihn etwas
auf die Kehle drücke und dort gewissermaßen ein Kitzeln erzeuge –,
haben Sie noch nie diese Empfindung gehabt, nach einem großen
Schreck vielleicht oder im Augenblick entsetzlicher Angst, wenn die
Vernunft zwar noch in Ordnung bleibt, jedoch gar keine Macht mehr
besitzt? Ich glaube, daß, wenn man zum Beispiel unabwendbarem
Untergang preisgegeben ist, wenn etwa ein Haus auf einen
niederstürzt oder etwas Ähnliches geschieht, daß man dann am
liebsten sich hinsetzen und die Augen schließen möchte: laß
kommen, was da kommen mag! ... Hier nun, als diese Schwäche bei
ihm eintrat, hielt ihm der Geistliche mit einer schnellen Geste und
ohne ein Wort zu sagen, das Kreuz zum Kuß hin, fast so nah, daß es
die Lippen berührte – es war ein kleines silbernes Kreuz – und
immer wieder hielt er es ihm hin, in jeder Minute. Und sobald nur
das Kreuz seine Lippen berührte, öffnete der Verurteilte die Augen
und belebte sich wieder für ein paar Sekunden ... und die Füße
gingen wieder. Gierig küßte er das Kreuz, ja, er beeilte sich
geradezu, es zu küssen, ganz wie man sich beeilt, irgend etwas als
Vorrat für alle Fälle mitzunehmen; doch ist es nicht anzunehmen,
daß er dabei irgendeinen religiösen Gedanken hatte oder sich einer
religiösen Handlung bewußt war. Und so ging er bis zum Block ... Ist
es nicht merkwürdig, daß in diesen letzten Sekunden so selten ein
Verurteilter in Ohnmacht fällt? Im Gegenteil, das Gehirn scheint
ungemein tätig zu sein, es arbeitet rastlos, unermüdlich, ohne
Unterlaß, wie eine Maschine in vollem Gang. Ich denke mir, daß es
sehr verschiedene Gedanken sind, die einem dann durch den Sinn
jagen, die man alle nicht zu Ende denkt, und vielleicht sind es sogar
sehr lächerliche und ganz nebensächliche Gedanken, wie zum
Beispiel: ‚Dieser lange Mensch dort hat eine Warze auf der Stirn –
hier der untere Knopf am Kittel des Scharfrichters ist verrostet ...‘
Gleichzeitig aber kann er doch nichts vergessen, kann er nicht
einmal in Ohnmacht fallen. Und um dieses eine Unvergeßliche dreht
sich alles in seinem Hirn. Und das dauert bis zur letzten
Viertelsekunde, wenn der Kopf bereits auf dem Block liegt und
wartet und – weiß und dann plötzlich hört, wie das Eisen über ihm
rutscht! Das muß man ja doch unbedingt noch hören! Ich würde,
wenn mein Kopf auf dem Block läge, absichtlich hinhorchen und
unfehlbar das Geräusch des Niederfallens hören. Es dauert das
vielleicht nur ein Zehntel eines Augenblicks, aber man muß es doch
unbedingt hören! Und denken Sie, bis jetzt noch streitet man
darüber, ob nicht der Kopf, wenn er schon abgeschlagen ist, noch
eine Sekunde lang weiß, daß er jetzt abgeschlagen ist und
herunterfliegt – können Sie sich das vorstellen? Und wenn er es nun
nicht nur eine Sekunde, sondern ganze fünf Sekunden lang weiß? ...
Zeichnen Sie das Schafott so, daß man nur die oberste Stufe ganz
deutlich und möglichst nah sieht. In der Mitte steht der Verurteilte,
sein Gesicht ist weiß, vollkommen weiß, der Priester hält ihm das
Kreuz hin, das jener gierig mit seinen blauen Lippen küssen will – er
streckt schon die Lippen vor und sieht und sieht und – weiß alles.
Das Kreuz und der Kopf – das ist die Hauptsache, das Gesicht des
Priesters, der Henker, dessen zwei Gehilfen, und dann noch unten
ein paar Köpfe und Augen, – das kommt alles erst in dritter Linie, als
Beiwerk ... Das wäre das ganze Gemälde.“
Der Fürst verstummte und sah seine Zuhörerinnen an.
„Das sieht jedenfalls nicht nach Quietismus aus,“ sagte Alexandra
halblaut vor sich hin.
„Nun, und jetzt erzählen Sie mal, wie Sie verliebt waren,“ bat
Adelaida.
Der Fürst blickte sie verwundert an.
„Hören Sie,“ fuhr Adelaida schnell fort, als wolle sie sich mit der
Begründung ihrer Bitte beeilen, „Sie sind mir noch die Beschreibung
des Baseler Bildes schuldig, ich weiß, aber zuerst will ich hören, wie
und wo und wann Sie verliebt gewesen sind. Leugnen Sie es nicht,
Sie sind verliebt gewesen. Zudem hören Sie sogleich auf Philosoph
zu sein, sobald Sie zu erzählen beginnen.“
„Wenn Sie etwas erzählt haben, scheinen Sie sich sogleich dessen
zu schämen, was Sie erzählt haben. Weshalb das?“ fragte Aglaja.
„Pfui, das ist mir denn doch zu dumm!“ schnitt ihr die Generalin
ungehalten das Wort ab.
„Ja, es ist nicht gerade klug,“ pflichtete ihr Alexandra bei.
„Achten Sie nicht auf sie, Fürst,“ wandte sich die Generalin an
ihren Gast, „sie sagt es nur, um sich über Sie lustig zu machen. Sie
ist gar nicht so schlecht erzogen. Denken Sie, bitte, nichts
Schlechtes von ihnen, weil sie Ihnen so zusetzen; sie haben sich
wohl wieder etwas in den Kopf gesetzt, aber ich sehe schon, daß sie
Sie trotzdem liebhaben. Ich kenne ihre Gesichter.“
„Auch ich kenne ihre Gesichter,“ sagte der Fürst mit besonderem
Nachdruck.
„Wie das?“ fragte Adelaida neugierig.
„Was wissen Sie von unseren Gesichtern?“ fragten wißbegierig
auch die anderen.
Doch der Fürst schwieg und blieb ernst; alle warteten, was er
wohl antworten würde.
„Ich werde es Ihnen später sagen,“ sagte er schließlich halblaut
und mit ernstem Gesicht.
„Sie wollen ja durchaus unser Interesse erwecken,“ neckte Aglaja,
„und dazu welche Feierlichkeit!“
„Nun gut,“ fiel wieder Adelaida in ihrer schnellen Redeweise lustig
ein, „aber wenn Sie ein solcher Kenner der Menschengesichter sind,
so sind Sie gewiß auch verliebt gewesen, folglich habe ich ganz
richtig geraten. Erzählen Sie also!“
„Ich bin nicht verliebt gewesen,“ antwortete der Fürst ebenso leise
und ernst, „ich bin anders glücklich gewesen.“
„Wie das? Auf welche Weise?“
„... Gut, ich werde es Ihnen erzählen,“ sagte der Fürst nach einer
Weile, wie in Gedanken verloren.
VI.

DaFürst,
sehen Sie mich nun alle mit solcher Neugier an,“ begann der
„daß Sie mir womöglich böse sein werden, wenn ich Sie
nicht ganz zufriedenstelle. Doch – das sagte ich ja nur zum Scherz,“
fügte er schnell mit einem Lächeln hinzu.
„Dort ... dort gab es viele Kinder, und ich habe meine ganze Zeit
mit Kindern zugebracht, nur mit Kindern. Das waren die Dorfkinder,
die die Schule besuchten, eine ganze Schar. Ich kann nicht sagen,
daß ich sie gerade unterrichtet hätte, o nein; denn sie hatten ja
einen Schulmeister, Jules Thibaut; ich aber, nun ja – wenn ich sie
auch unterwies, so war ich eigentlich doch nur so mit ihnen
zusammen, und in dieser Weise vergingen die ganzen vier Jahre. Ich
wollte auch nichts anderes. Ich habe ihnen alles erzählt, nichts habe
ich ihnen verheimlicht. Ihre Eltern und Verwandten waren nicht
wenig ungehalten über mich, denn die Kinder konnten zu guter Letzt
gar nicht mehr ohne mich auskommen und saßen den ganzen Tag
bei mir. Der Schulmeister war bald mein erbittertster Feind.
Überhaupt machte ich mir dort viele Feinde, und immer nur wegen
der Kinder. Sogar Schneider machte mir Vorwürfe. Und weshalb nur,
was befürchteten sie denn? Einem Kinde kann man doch alles sagen,
alles! Es hat mich oft stutzig gemacht, wie schlecht Erwachsene
Kinder verstehen, selbst Väter und Mütter ihre eigenen Kinder.
Kindern sollte man nichts verheimlichen, wie man es gewöhnlich
unter dem Vorwande tut, daß sie zu jung seien, und es für sie noch
zu früh sei, etwas zu wissen. Was das doch für eine traurige und
klägliche Auffassung ist! Und wie gut es die Kinder begreifen, daß
die Eltern sie für zu klein und zu dumm zum Verstehen halten,
während sie doch tatsächlich alles verstehen! Die Erwachsenen
wissen nicht, daß ein Kind sogar in der schwierigsten Angelegenheit
einen äußerst guten Rat zu geben vermag. Mein Gott! wenn so ein
Kind mit seinen hellen Augen wie ein kleiner Vogel einen treuherzig
und glücklich ansieht – da muß man sich doch schämen, es zu
belügen! Ich nenne sie deshalb kleine Vögel, weil es etwas
Reizenderes als kleine Vögel nicht gibt. Übrigens hatte mir ein ganz
besonderer Fall die Feindschaft des Dorfes eingetragen ... Thibaut
übrigens war einfach neidisch. Anfangs schüttelte er nur den Kopf
und wunderte sich, wie es zugehen mochte, daß die Kinder bei mir
alles begriffen, bei ihm aber so gut wie überhaupt nichts. Und dann
machte er sich über mich lustig, als ich ihm sagte, daß wir beide sie
in nichts unterrichten könnten, daß im Gegenteil sie uns
unterrichteten. Wie konnte er mich nur beneiden und verleumden,
wenn er doch selbst unter Kindern lebte! Durch Umgang mit Kindern
gesundet die Seele ... Dort in der Anstalt war ein Kranker, den
Professor Schneider behandelte, ein armer Unglücklicher. Sein
Unglück war so groß, daß man es kaum für möglich zu halten
vermag, wie ein Mensch so etwas ertragen kann. Er sollte dort vom
Irrsinn geheilt werden, doch meiner Ansicht nach war er nicht
irrsinnig, sondern litt nur unsäglich – Leiden war seine ganze
Krankheit. Wenn Sie wüßten, was diesem Menschen schließlich
unsere Kinder wurden! ... Doch ich werde Ihnen lieber ein anderes
Mal von diesem Kranken erzählen. Jetzt aber werde ich erzählen, wie
das alles damals begann. Zu Anfang liebten mich die Kinder gar
nicht. Ich war so lang und immer so unbeholfen; ich weiß, daß ich
auch sonst häßlich bin ... und dann war ich auch noch ein Ausländer.
Zuerst lachten sie nur über mich und begannen sogar, mit Steinen
nach mir zu werfen, nachdem sie gesehen hatten, wie ich Marie
küßte. Ich habe sie aber im ganzen nur ein einziges Mal geküßt ...
Nein, lachen Sie nicht,“ unterbrach sich der Fürst, als er das Lächeln
seiner Zuhörerinnen bemerkte, „ich küßte sie nicht, weil ich in sie
etwa verliebt war. Wenn Sie wüßten, was für ein unglückliches
Geschöpf sie war, Sie würden sie ebenso bemitleiden, wie ich es
getan habe. Sie war ein Mädchen aus unserem Dorf. Ihre Mutter war
eine alte, kranke Frau, die in ihrem kleinen, baufälligen Häuschen
hinter dem einen der beiden kleinen Fenster mit Erlaubnis der
Dorfobrigkeit einen Krämerladen eingerichtet hatte. Aus diesem
Fenster verkaufte sie Stiefelschmiere, Garn, Tabak, Seife; lauter
Kleinigkeiten, die wenig einbrachten, und von diesem kleinen
Verdienst lebte sie. Sie war schon lange krank, ihre Füße waren
geschwollen, so daß sie immer auf ein und demselben Fleck saß und
sich nicht rühren konnte. Marie war ihre einzige Tochter, zwanzig
Jahre alt, schwächlich und mager; sie war schon seit längerer Zeit
schwindsüchtig, verrichtete aber trotzdem die schwerste Arbeit als
Tagelöhnerin bei fremden Leuten: sie scheuerte die Fußböden,
wusch Wäsche, fegte die Höfe rein, besorgte das Vieh. Nun geschah
es, daß ein französischer Kommis auf der Durchreise ins Dorf kam,
sie verführte und sie mit sich nahm. Er verließ sie jedoch schon nach
einer Woche und fuhr heimlich davon. Sie machte sich zu Fuß auf
den Heimweg, bettelte sich unterwegs das Notwendigste zusammen,
bis sie dann endlich schmutzig und zerlumpt und mit zerrissenen
Stiefeln wieder im Dorf ankam. Eine ganze Woche war sie
gewandert; genächtigt hatte sie unter freiem Himmel und sich dabei
natürlich erkältet. Ihre Füße und Hände waren wund und
geschwollen. Sie war auch früher nicht hübsch gewesen, nur ihre
Augen waren so still und gut und unschuldig. Auffallend an ihr war
ihre Schweigsamkeit. Früher hatte sie einmal bei der Arbeit zu
singen begonnen, und da hatten alle sie ganz erstaunt angesehen,
bis sie in Lachen ausgebrochen waren: ‚Marie singt! Denkt doch,
Marie singt!‘ Marie aber soll sehr verlegen gewesen sein, und seit
dem Tage hat sie niemand mehr singen hören. Damals war man
noch freundlich zu ihr gewesen; als sie nun aber krank und erschöpft
zurückkehrte, da hatte kein einziger auch nur das geringste Mitleid
für sie übrig! Wie grausam die Menschen doch sind! Was für enge
Begriffe sie haben! Ihre Mutter war die erste, die sie mit bösen
Worten und offener Verachtung empfing. ‚Du hast mich jetzt
entehrt,‘ sagte sie. Und die Mutter gab sie auch als erste der
Schande und den Schmähungen der anderen preis. Als man im Dorf
erfuhr, daß Marie zurückgekehrt war, lief alles hin, um sie zu sehen:
fast das ganze Dorf versammelte sich in der Hütte der Alten –
Greise, Kinder, Weiber, Mädchen, alle eilten neugierig herbei. Marie
kniete zu Füßen der Mutter, hungrig und zerlumpt, und schluchzte.
Als nun die Menschen sich so in die Stube drängten, um die
Sünderin zu betrachten, verbarg Marie ihr Gesicht im aufgelösten
Haar und warf sich in ihrer Verzweiflung auf den Fußboden, wo sie
schluchzend liegen blieb. Alle, die sie rings umstanden, blickten auf
sie herab, als wäre sie irgendein Geschmeiß gewesen. Die Männer
verurteilten sie schonungslos, die jüngeren lachten und machten sich
über sie lustig, am meisten aber schalten die Weiber, die sie wie eine
scheußliche Spinne oder etwas noch Ekelhafteres behandelten. Und
die Mutter ließ das zu, saß dabei, nickte mit dem Kopf und fand es
ganz in der Ordnung. Die Alte war damals von den Ärzten bereits
aufgegeben. Nach zwei Monaten starb sie denn auch. Sie wußte,
daß ihre Tage gezählt waren, aber sie söhnte sich nicht mit der
Tochter aus, ließ sie im kalten Vorhaus schlafen und gab ihr kaum
etwas zu essen. Die kranken Füße der Alten mußten alle paar
Stunden in warmes Wasser gesetzt werden, was Marie denn auch
pünktlich und sorgsam tat. Sie wusch ihr die Füße und pflegte sie
überhaupt aufopfernd. Die Alte aber nahm alle Dienste der Tochter
als etwas Selbstverständliches hin und sagte ihr nicht einmal ein
freundliches Wort. Marie ertrug alles, und wie ich später bei näherer
Bekanntschaft sah, empfand sie diese Behandlung von seiten der
Mutter als vollkommen gerecht und hielt sich selbst für die
Verworfenste aller Verworfenen. Als man dann die Alte in ihren
letzten Wochen zu Bett hatte legen müssen, kamen die Dorfweiber
abwechselnd zu ihr, um sie zu pflegen, wie es dort Sitte ist. Nun
bekam Marie überhaupt nichts mehr zu essen; im ganzen Dorf
wurde sie verfolgt, und man wollte ihr nicht einmal Arbeit geben wie
früher. Alle spien hinter ihr her, und die Männer betrachteten sie
wohl überhaupt nicht mehr als ein Weib – solche Schändlichkeiten
sagten sie ihr. Nur sehr selten, wenn sie sich betranken, Sonntags
gewöhnlich, warfen sie ihr in der Trunkenheit zum Spott ein
Kupferstück hin, so – einfach auf die Erde, und Marie hob es
schweigend auf. Sie hustete damals bereits sehr stark und begann
Blut zu speien. Schließlich hingen ihre Kleider nur noch wie Lumpen
an ihrem Körper, so daß sie sich schämte, sich im Dorf zu zeigen.
War sie doch seit ihrer Rückkehr immer nur barfuß gegangen! Da
begannen denn besonders die Kinder – es waren ihrer dort eine
ganze Schar, mindestens vierzig Schulrangen – ja, besonders die
Kinder begannen, sie zu necken und ihr mit Straßenschmutz
nachzuwerfen. Sie bat den Hirten, daß er ihr erlauben möge, seine
Kühe zu hüten, aber der Hirt jagte sie davon. Sie jedoch nahm eine
Gelegenheit wahr und zog ohne seine Erlaubnis mit der Herde
hinaus und blieb den ganzen Tag fort, worauf der Hirt einsah, daß
sie ihm großen Nutzen bringen konnte, und sie nicht mehr fortjagte
und ihr bisweilen sogar die Überreste seiner Mahlzeit gab, etwas
Käse und Brot. Das hielt er natürlich für eine große Gnade. Als ihre
Mutter endlich gestorben war und beerdigt wurde, schämte sich der
Pastor nicht, sie öffentlich zu schmähen, und er tat das noch dazu in
der Kirche. Marie stand in ihren Lumpen hinter dem Sarge und
weinte. Viel Volks hatte sich versammelt, um zu sehen, wie sie
weinen und hinter dem Sarge hergehen würde. Da hub der Pastor
an – er war ein noch junger Mensch, der den Ehrgeiz hatte, ein
großer Redner zu werden – wandte sich an alle Anwesenden und
wies auf Marie. ‚Seht, dort steht sie, die die Schuld am Tode dieser
alten Frau trägt,‘ begann er – es war gar nicht wahr, denn die Alte
war doch ganze zwei Jahre lang krank gewesen – ‚seht, da steht sie
nun vor euch und wagt nicht, den Blick zu erheben; denn der Zorn
des Herrn ruht auf ihr! Da steht sie barfuß und in Lumpen – ein
Beispiel aus der Schar jener, die den Pfad der Tugend verlassen! Und
wer ist sie? Wer ist sie, die diese fromme Frau ins Grab gebracht?
Sie ist ihre – Tochter!‘ – und so weiter, immer in demselben Ton. Und
können Sie sich so etwas denken: diese Gemeinheit gefiel allen!
Doch ... da kam etwas anderes dazwischen: die Kinder traten für sie
ein; denn damals waren sie bereits alle auf meiner Seite und hatten
Marie gern. Das war folgendermaßen geschehen: Ich wollte etwas
für Marie tun, man mußte ihr Geld verschaffen, denn sie hatte es
sehr nötig. Ich besaß aber – dort, bei Schneider – nie Geld. Dafür
hatte ich eine kleine Krawattennadel mit einem Brillanten, die
verkaufte ich an einen Aufkäufer alter Sachen; es war dort gerade
einer, der von Dorf zu Dorf fuhr und mit alten Kleidern handelte. Er
gab mir acht Franken, während die Nadel wenigstens vierzig wert
war. Darauf bemühte ich mich lange Zeit vergeblich, Marie einmal
allein zu treffen. Endlich gelang es mir: wir begegneten uns hinter
dem Dorf auf einem einsamen Fußsteig, der auf die Berge
hinaufführte, gerade hinter einem Baum. Ich gab ihr die acht
Franken und sagte ihr, daß sie sparsam mit ihnen umgehen müsse;
denn mehr Geld hätte ich nicht, und dann küßte ich sie und sagte,
sie solle nicht denken, daß ich irgendeine schlechte Absicht hätte,
daß ich sie nicht deshalb geküßt, weil ich etwa in sie verliebt sei,
sondern nur, weil sie mir sehr leid täte und ich sie niemals für
schuldig, sondern nur für sehr unglücklich halten würde. Ich wollte
sie gern noch etwas trösten und ihr klarmachen, daß sie sich doch
nicht für so tief unter den anderen stehend zu halten brauche; aber
ich sah es ihr an, daß sie mich nicht verstand, obschon sie kein Wort
sagte, mit gesenktem Blick vor mir stand und sich entsetzlich
schämte. Als ich geendet hatte, beugte sie sich plötzlich nieder und
küßte mir die Hand, worauf ich sofort ihre Hand nahm, um sie
gleichfalls zu küssen, doch sie zog sie erschrocken zurück. Da
tauchten plötzlich die Kinder auf, eine ganze Schar. Wie ich später
erfuhr, hatten sie mich beobachtet und waren mir sogar heimlich
gefolgt. Kaum hatten sie uns erblickt, als sie auch schon in ein
Hohngelächter ausbrachen, pfiffen, schrien und in die Hände
klatschten. Marie lief natürlich fort, so schnell sie nur konnte. Ich
wollte zu den Kindern reden, aber sie warfen mit Steinen nach mir.
Noch am selben Abend wußte es das ganze Dorf, und Marie mußte
dafür büßen: sie wurde noch mehr verfolgt und gehaßt. Wie ich
hörte, wollte man sie sogar gerichtlich zu einer Strafe verurteilen
lassen, doch zum Glück kam es nicht so weit. Dafür aber ließen die
Kinder sie keinen Augenblick mehr in Ruhe: sie schalten sie mit
häßlichen Worten, warfen ihr Schmutz nach, trieben sie fort, und sie
mußte mit ihrer schwachen Brust laufen, keuchend, atemlos, die
Kinder mit Geschrei hinter ihr her. Einmal trat ich der Schar entgegen
und prügelte mich sogar mit den Jungen. Dann begann ich mit ihnen
zu reden. Und so redete ich jeden Tag, wenn sich nur Gelegenheit
dazu bot. Bisweilen blieben sie dann stehen und hörten zu, wenn sie
auch das Schelten noch nicht ließen. Ich erzählte ihnen, wie
unglücklich Marie sei, und bald hörten sie auf, sie zu verfolgen und
gingen nur schweigend fort, wenn sie kam. Mit der Zeit begannen
sie auch mit mir zu sprechen, und wir unterhielten uns; ich
verheimlichte ihnen nichts, ich erzählte ihnen alles. Sie hörten mir
sehr neugierig zu und bald empfanden auch sie Mitleid mit Marie.
Einzelne von ihnen gingen sogar so weit, daß sie sie jetzt freundlich
grüßten, wenn sie ihr begegneten. Es ist dort Sitte, daß einander
Begegnende, gleichviel ob sie sich kennen oder nicht, ‚Grüß Gott‘
sagen. Ich kann mir denken, wie erstaunt Marie anfangs gewesen
sein muß. Einmal hatten zwei kleine Mädchen sich irgendwoher
Essen verschafft, und kamen dann zu mir, um es mir zu erzählen. Sie
sagten, Marie habe angefangen zu weinen, und sie hätten sie jetzt
sehr lieb. Es dauerte nicht lange, und sie wurde von allen geliebt,
und durch sie gewannen die Kinder auch mich plötzlich lieb. Von der
Zeit an kamen sie oft zu mir und baten mich, ihnen zu erzählen. Ich
glaube, ich habe nicht schlecht erzählt, denn sie hörten mir sehr
gern zu. Späterhin lernte und las ich nur zu dem Zweck, um ihnen
dann das Gelesene erzählen zu können, und so habe ich ihnen ganze
drei Jahre lang erzählt. Als mich dann später alle, selbst Schneider
nicht ausgenommen, verurteilten, weil ich mit ihnen wie mit
Erwachsenen redete und ihnen nichts verheimlichte, sagte ich, daß
man sich schämen müßte, Kinder zu belügen, daß sie ja sowieso
alles wüßten, wie sehr man es auch vor ihnen geheimhalten wollte.
Wenn sie all das dann aber im Leben erfahren würden, dann würden
sie es als etwas Schmutziges erfahren, von mir aber erführen sie es
als etwas Reines. Es sollte, meinte ich, doch ein jeder nur daran
denken, wie es gewesen war, als er selbst noch ein Kind war. Die
Menschen waren aber anderer Meinung ... Daß ich Marie geküßt
hatte, war ungefähr zwei Wochen vor dem Tode ihrer Mutter
gewesen, so daß die Kinder, als der Pastor die Beerdigungsrede hielt,
schon alle auf meiner Seite waren. Ich erklärte ihnen unverzüglich
die ganze Schändlichkeit dieser Rede, und sie wurden alle böse auf
ihn, einige sogar in dem Maße, daß sie mit Steinen seine
Fensterscheiben einwarfen. Ich verbot es ihnen natürlich, denn das
ging doch nicht an; aber im Dorf hatte man schon den ganzen
Zusammenhang erfahren, und alle beschuldigten mich, daß ich die
Kinder verderbe. Gleichzeitig erfuhren sie auch den Grund: daß die
Kinder Marie liebten – und sie erschraken unsäglich. Marie aber war
glücklich. Den Kindern wurde strengstens verboten, mit ihr
zusammenzukommen. Da liefen sie denn heimlich fort und stahlen
sich auf Umwegen zur Herde, die sie hütete. Es war ziemlich weit –
Welcome to our website – the ideal destination for book lovers and
knowledge seekers. With a mission to inspire endlessly, we offer a
vast collection of books, ranging from classic literary works to
specialized publications, self-development books, and children's
literature. Each book is a new journey of discovery, expanding
knowledge and enriching the soul of the reade

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

Let us accompany you on the journey of exploring knowledge and


personal growth!

ebookgate.com

You might also like