Data structures and algorithms made easy in Java data structure and algorithmic puzzles 2nd Edition Narasimha Karumanchi download
Data structures and algorithms made easy in Java data structure and algorithmic puzzles 2nd Edition Narasimha Karumanchi download
https://ebookgate.com/product/data-structures-and-algorithms-
made-easy-in-java-data-structure-and-algorithmic-puzzles-2nd-
edition-narasimha-karumanchi/
https://ebookgate.com/product/data-structures-algorithms-and-
applications-in-c-2nd-edition-sartaj-sahni/
ebookgate.com
https://ebookgate.com/product/java-structures-data-structures-in-java-
for-the-principled-programmer-2nd-edition-duane-bailey/
ebookgate.com
https://ebookgate.com/product/data-structures-and-abstractions-with-
java-2nd-ed-edition-carrano/
ebookgate.com
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
https://ebookgate.com/product/data-structures-and-algorithms-
using-c-1st-edition-michael-mcmillan/
ebookgate.com
https://ebookgate.com/product/java-software-structures-designing-and-
using-data-structures-3rd-edition-john-lewis/
ebookgate.com
https://ebookgate.com/product/java-foundations-introduction-to-
program-design-and-data-structures-2nd-edition-john-lewis/
ebookgate.com
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
©
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:
- ℎ ℎ
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).
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.1 Variables 15
Data Structures and Algorithms Made Easy in Java Introduction
…
private char data;
//Operations
}
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
( )
( )
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.
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
∴ = 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.
( )
( ))
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 = ( ), = ( ), = ( ).
Rate of growth c ( )
Input size,
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.
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.
= + = ( )
= ( ) = –
= =
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
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( ) = Θ( ).
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) + ( − 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 × … × ) = ( !) ≤ ( )≤
}
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;
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 + + )
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 .
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.1 Introduction 36
Data Structures and Algorithms Made Easy in Java Recursion and Backtracking
}
}
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!
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.
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.
}
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 ).
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
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.
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;
}
}
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.
head
Update head pointer to point to the new node.
new node
data 15 7 40 NULL
head
head
Last nodes next pointer points to the new node.
new node
4 15 7 0 data NULL
head
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).
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
4 15 7 40 NULL
4 15 7 40 NULL
Head
Previous node to tail Tail
Dispose of the tail node.
NULL
4 15 7 40 NULL
4 15 7 40 NULL
4 15 7 40 NULL
THE END.
There was one thing which Sir Thomas got out of his matrimonial
arrangements which was more than he expected, and that was a great deal
of fun. After he had received, in the way above described, the angry
submission of the two whom he chiefly feared, he had entered into the spirit
of the thing, and determined that he would faithfully obey the will, and
obtain the assent of all that marriage committee, who expected to make
Lucy’s marrying so difficult a matter. He was even visited by some
humorous compunctions as he went on. The entire failure of poor old
Trevor’s precautions on this point awakened a kind of sympathetic regret in
his mature mind. “Poor old fellow!” he said; “probably I was the last person
he would have given his heiress to: most likely all these fences were made
to keep me out,” he laughed; yet he felt a kind of sympathy for the old man,
who, indeed, however, would have had no such objection to Sir Thomas as
Sir Thomas thought. Next morning Lucy’s suitor went to the rector, who, to
be sure, had it in his power to stop the whole proceedings, advanced as they
were. But the rector had heard, by some of the subtle secret modes of
communication which convey secrets, of something going on, and patted
Sir Thomas on the shoulder.
“My dear Sir Tom,” he said, “I never for a moment attached any
importance to the vote given to me. Why should I interfere with Miss
Trevor’s marriage? Your father-in-law that is to be (if one can speak in the
future tense of a person who is in the past) entertained some odd ideas. He
was an excellent man, I have not a doubt on that point, but— Now what
could I know about it, for instance? I know Lucy—she’s a very nice girl,
my girls like what they have seen of her immensely; but I know nothing
about her surroundings. I am inclined to think she is very lucky to have
fallen into no worse hands than yours.”
“The compliment is dubious,” said Sir Tom, “but I accept it; and I may
take it for granted that I have your consent?”
“Certainly, certainly, you have my consent. I never thought of it but as a
joke. That old man— I beg your pardon—your father-in-law must have had
queer ideas about many things. I hear he left his heiress great latitude about
spending—allowed her, in short, to give away her money.”
“I wonder how you heard that?”
“Ah! upon my word I can scarcely tell you. Common talk. They say, by
the way, she is going to give a fortune to Katie Russell on her marriage with
young Rainy, the school-master; compensation, that! Rainy (who is a young
prig, full of dissenting blood, though it suits him to be a churchman) no
doubt thought he had a good chance for the heiress herself.”
“Don’t speak any worse than you can help of my future relations,” said
Sir Tom, with a laugh: “it might make things awkward afterward;” upon
which the rector perceived that he had gone half a step too far.
“Rainy is a very respectable fellow; there is not a word to be said against
him. I wish I could say as much for all my own relations,” he said; “but,
Randolph, as I am a kind of a guardian, you know, take my advice in one
thing. It is all very fine to be liberal; but I would not let her throw her
money away.”
Sir Tom made no direct reply. He shook the rector’s hand, and laughed.
“I’ll tell Lucy you send her your blessing,” he said.
And then he went off in a different direction, from the fine old red-brick
rectory, retired in its grove of trees, to the little, somewhat shabby street in
which Mr. Williamson, the Dissenting minister, resided—if a man can be
said to reside in a back street. The house was small and dingy, the door
opening into a very narrow passage, hung with coats and hats, for Mr.
Williamson, as was natural, had a large family. It was only after an interval
of running up and down-stairs, and subdued calling of one member of the
household after another, that the minister was unearthed and brought from
the little back room, called his study, in his slippers and a very old coat, to
receive the unlikely visitor. Sir Thomas Randolph! what could he want?
There is always a certain alarm in a humble household attendant upon the
unexpectedness of such a visit. Could anything have happened? Could some
one have gone wrong, was the anxious question of the Williamsons, as the
minister was roused, and gently pushed into the parlor, where Sir Thomas,
surrounded by all the grim gentility of the household gods, was awaiting
him. The mother and daughter were on tiptoe in the back room, not
listening at the door certainly, but with excited ears ready for every
movement. The vague alarm that they felt was reflected in the minister’s
face. Sir Thomas Randolph! What could he want? It was a relief to Mr.
Williamson when he heard what it was; but he was not so easy in his assent
as the rector. He took a seat near the suitor, with an air of great importance
replacing the vague distrust and fear that had been in his face.
“It is a great trust, Sir Thomas,” he said. “And I must be faithful. You
will not expect me to do anything against my conscience. Lucy Trevor is a
lamb of the flock, though spiritually no longer under my charge, her mother
was an excellent woman, and our late friend, Mr. Trevor— This is an
altogether unexpected application, you must allow me to think it over. I owe
it to—to our late excellent friend who committed this trust to my unworthy
hands.”
“I thought,” said Sir Tom, “that it was a matter of form merely; but,” he
added, with a better inspiration, “I quite see how, to a delicate sense of duty
like yours, it must take an aspect—”
“That is it, Sir Thomas—that is it,” Mr. Williamson said. “I must be
faithful at whatever cost. Yourself now, you will excuse me; there are
reports—”
“A great many, and at one time very well founded,” said Sir Thomas,
with great seriousness, looking his judge in the face.
This took the good minister by surprise, and the steady look confused
him. A great personage, the greatest man in the county, a baronet, a man
whose poverty (for he was known to be poor) went beyond Mr.
Williamson’s highest realization of riches! It gave the excellent minister’s
bosom an expansion of solemn pride, and, at the same time, a thrill of
alarm. Persecution is out of date, but to stand up in the presence of one of
the great ones of the earth, and convict him of evil—this is still occasionally
possible. Mr. Williamson rose to the grandeur of his position. Such an
opportunity had never been given to him before, and might never be again.
“I am glad that you do not attempt to deny it, Sir Thomas; but at the
same time there is a kind of bravado that boasts of evil-doing. I hope that is
not the source of your frankness. The happiness of an innocent young girl is
a precious trust, Sir Thomas. Unless we have guarantees of your change of
life, and that you are taking a more serious view of your duties, how can I
commit such a trust into your hands?”
“What kind of guarantees can I offer?” said Sir Thomas, with great
seriousness. “I can not give securities for my good conduct, can I? I will
cordially agree to anything that your superior wisdom and experience can
suggest.”
“Do not speak of my wisdom, for I have none—experience, perhaps, I
may have a little; and I think we must have guarantees.”
“With all my heart—if you will specify the kind,” Sir Thomas said.
But here the good minister was very much at a loss, for he did not in the
least know what kind of guarantees could be given, or taken. He was not
accustomed to have his word taken so literally. He cleared his throat, and a
flush came over his countenance, and he murmured, “Ah!” and “Oh!” and
all the other monosyllables in which English difficulty takes refuge. “You
must be aware,” he said, “Sir Thomas—not that I mean to be disagreeable
—that there are many things in your past life calculated to alarm the
guardians.”
“But, my dear sir, when I confess it,” said Sir Thomas, “when I admit it!
when I ask only—tell me what guarantees I can give—what I can do or say
—”
“Guarantees are necessary—certainly guarantees are necessary,” said the
minister, shaking his head; and then he gave to his attentive hearer a little
sermon upon marriage, which was one of the good man’s favorite subjects.
Sir Thomas listened with great gravity and sympathy. He subdued the
twinkling in his eyes—he wanted to take advantage of the honorable estate.
He said very little, and allowed his mentor to discourse freely. And nothing
was said further about guarantees. Mr. Williamson gave his consent with
effusion before the interview was over. “You have seen the folly of a
careless life,” he said, “I can not but hope that your heart is touched, Sir
Thomas, and that all the virtues of maturity will develop in you; and if my
poor approval and blessing can do you any good, you have it. I am not of
those who think much of, neither do I belong to a denomination which
gives special efficacy to, any man’s benediction; but as Jacob blessed
Joseph, I give you my blessing.” Then as his visitor rose content, and
offered him his hand, an impulse of hospitality came over the good man.
“My wife would say I was letting you go coldly, without offering you
anything; but I believe it is quite out of fashion to drink wine in the morning
—which is a very good thing, an excellent thing. But if you will come to tea
—any afternoon, Sir Thomas. If you will bring Lucy to tea!”
Afterward, after the door was shut, the minister darted out again and
called after his visitor, “My wife says if you would name an afternoon, or if
Lucy would write to her what day we may expect you—not to make
preparations,” said the minister, waving his hand, “but in case we should be
out, or engaged.”
Sir Thomas promised fervently. “You shall certainly hear a day or two
before we come,” he said, and walked away with a smile on his face. To be
sure he never meant to go back to tea, but his conscience did not smite him.
He had got off safe and sound without any guarantees.
“Now there is only my aunt’s consent to get,” he said, when he had gone
back to the Terrace. “We have stuck to the very letter of the will, and you
see all has gone well. I am going off to Fairhaven to-morrow. I know she is
there.”
“But must you ask her consent? you know she will give it,” Lucy said.
“How do I know she will give it? Perhaps she would prefer to keep you
to herself.” Lucy smiled at the thought; but Sir Thomas did not feel so sure.
His aunt meant him to marry Lucy eventually; but that was a very different
thing from carrying her off now.
When Sir Thomas went away, Lucy had a great many visitors. Even Mrs.
Rushton came, embarrassed, but doing her best to look at her ease. “Why
did you not tell me that this was going on, you silly child? I should have
understood everything, I should have made allowances for everything. But,
perhaps, he had never come to the point till the other day? Mr. Rushton and
Raymond send you their very best wishes. And Emmie has hopes that after
seeing so much of each other all the autumn, you will choose her for one of
your brides-maids, Lucy. And I wish you every happiness, my dear,” Mrs.
Rushton cried, kissing her with a little enthusiasm, having talked all her
embarrassment away. Lucy was surprised by this change, but she was no
casuist, and she did not inquire into it. It was a relief which she accepted
thankfully. Mrs. Stone came also with her congratulations. “Lady Randolph
was very wise to forestall everybody,” she said. “And, Lucy, I shall be very
glad to have you near me, to watch how you go on in your new life. Never
hesitate to come to me in a difficulty.” This was the way in which she took
her pupil’s elevation. Had Lucy been raised to a throne, she would have
made a similar speech to her. She would have felt that she could instruct her
how to reign. As for Mr. St. Clair, Lucy still had much trouble to go through
on his account. She was very reluctant to give up her scheme for his help,
but at last, after a great many interviews with Miss Southwood, was got to
perceive that the thing to be done was to make Sir Thomas “find an
appointment” for her unfortunate suitor. “He can easily do it,” said Miss
Southwood, with that innocent faith in influence which so many good
people still retain.
Bertie Russell disappeared from Farafield on the day after the advent of
Sir Thomas. He was the most angry of all Lucy’s suitors, and he put her this
time into his book in colors far from flattering. But, fortunately, nobody
knew her, and the deadly assault was never found out, not even by its
immediate victim, for, like many writers of fiction, and, indeed, like most
who are worth their salt, Bertie was not successful in the portraiture of real
character. His fancy was too much for his malevolence, and his evil
intentions thus did no harm.
Sir Thomas traveled as fast as expresses could take him to the house in
which his aunt was paying one of her many autumn visits—for I need not
say that she had returned from Homburg some time before. The house was
called Fairhaven. It was the house of a distinguished explorer and
discoverer; and the company assembled there included various members of
Lady Randolph’s special “society.” When Sir Thomas walked into the
room, where, all the male portion of the party being still in the covers, the
ladies were seated at tea, his aunt rose to meet him, from out of a little
group of her friends. Her privy council, that dread secret tribunal by which
her life was judged, were all about her in the twilight and firelight. When
his name was announced, to the great surprise of everybody, Lady
Randolph rose up with a similar but much stronger sense of vague alarm
than that which had moved the minister the previous day. “Tom!” she cried,
with surprise which she tried to make joyful; but indeed she was frightened,
not knowing what kind of news he might have come to tell. Mrs. Berry-
Montagu who was sitting as usual with her back to the light, though there
was so little of that, gave a little nod and glance aside to Lady Betsinda,
who was seated high in a throne-like, antique chair, and did not care how
strong the light was which fell on her old shiny black satin and yellow lace.
“I told you!” said Mrs. Berry-Montagu. She thought all her friend’s hopes,
so easily penetrated by those keen-eyed spectators, were about to be thrown
to the ground, and the desire to observe “how she would bear it,”
immediately stirred up those ladies to the liveliest interest. Sir Thomas,
however, when he had greeted his aunt, sat down with his usual friendly
ease, and had some tea. He was quite ready to answer all their questions,
and he was not shy about his good news, but ready to unfold them
whenever it might seem most expedient so to do.
“Straight from the Hall?” Lady Randolph said, with again a tremor. Did
this mean that he had been making preparations for his setting out?
“I got there three days ago,” said Sir Tom; “poor old house, it is a pity to
see it so neglected. It is not such a bad house—”
“A bad house! there is nothing like it in the county. If I could but see you
oftener there, Tom,” his aunt cried in spite of herself.
Sir Tom smiled, pleased with the consciousness which had not yet lost
its amusing aspect; but he did not make any reply.
“He likes his own way,” said Lady Betsinda; “I don’t blame him. If I
were a young man—and he is still a young man— I’d take my swing. When
he marries, then he’ll range himself, like all the rest, I suppose.”
“Lady Betsinda talks like a book—as she always does,” said Sir Tom,
with his great laugh; “when I marry, everything shall be changed.”
“That desirable consummation is not very near at hand, one can see,”
said Mrs. Berry-Montagu, out of the shadows, in her thin, fine voice.
Sir Tom laughed again. There was something frank, and hearty, and
joyous in the sound of his big laugh; it tempted other people to laugh too,
even when they did not know what it was about. And Lady Randolph did
not in the least know what it was about, yet the laugh gained her in spite of
herself.
“Apropos of marriage,” said Mrs. Montagu once more, “have you seen
little Miss Trevor in your wilds, Sir Tom? Our young author has gone off
there, on simulated duty of a domestic kind, but to try his best for the
heiress, I am sure. Do you think he has a chance? I am interested,” said the
little lady. “Come, the latest gossip! you must know all about it. In a
country neighborhood every scrap is worth its weight in gold.”
“I know all about it,” said Sir Tom.
“That you may be sure he does; where does all the gossip come from but
from the men? we are never so thorough. He’ll give you the worst of it, you
may take my word for that. But I like that little Lucy Trevor,” cried old
Lady Betsinda; “she was a nice, modest little thing. She never looked her
money; she was more like a little girl at home, a little kitten to play with. I
hope she is not going to have the author. I always warned you, Mary
Randolph, not to let her have to do with authors, and that sort of people; but
you never take my advice till it’s too late.”
“She is not going to marry the author,” said Sir Tom, with another laugh;
and then he rose up, almost stumbling over the tea-table. “My dear ladies,”
he said, “who are so much interested in Lucy Trevor, the fact is that the
author never had the slightest chance. She is going to marry—me. And I
have come, Aunt Mary, if you please, to ask if you will kindly give your
consent? The other guardians have been good enough to approve of me,” he
added, making her a bow, “and I hope I may not owe my disappointment to
you.”
“The other guardians— Tom!” cried Lady Randolph, falling upon him
and seizing him with both hands, “is this true?”
Sir Tom kissed her hand with a grace which he was capable of when he
pleased, and drew it within his arm.
“I presume, then,” he said, as he led her away, “that I shall get your
consent too.”
Thus old Mr. Trevor’s will was fulfilled. It was not fulfilled in the way
he wished or thought of, but what then? He thought it would have kept his
daughter unmarried, whereas her mourning for him was not ended when she
became Lady Randolph—which she did very soon after the above scene, to
the apparent content of everybody. Even Philip Rainy looked upon the
arrangement with satisfaction. Taking Lucy’s fortune to redeem the great
Randolph estate, and to make his little cousin the first woman in the county,
was not like giving it “to another fellow;” which was the thing he had not
been able to contemplate with patience. The popular imagination, indeed,
was more struck with the elevation of little Lucy Trevor to be the mistress
of the Hall than with Sir Thomas’s good fortune in becoming the husband
of the greatest heiress in England. But when his settlements were signed,
both the guardians, Mr. Chervil and Mr. Rushton, took the bridegroom-elect
aside.
“We can not do anything for you about that giving-away clause,” Mr.
Chervil said, shaking his head.
“But Sir Thomas is not the man I take him for, if he don’t find means to
keep that in check,” said Mr. Rushton.
Sir Tom made no reply, and neither of these gentlemen could make out
what was meant by the humorous curves about his lips and the twinkle in
his eye.
THE END.
*** END OF THE PROJECT GUTENBERG EBOOK THE GREATEST
HEIRESS IN ENGLAND ***
Updated editions will replace the previous one—the old editions will
be renamed.
1.D. The copyright laws of the place where you are located also
govern what you can do with this work. Copyright laws in most
countries are in a constant state of change. If you are outside the
United States, check the laws of your country in addition to the
terms of this agreement before downloading, copying, displaying,
performing, distributing or creating derivative works based on this
work or any other Project Gutenberg™ work. The Foundation makes
no representations concerning the copyright status of any work in
any country other than the United States.
1.E.6. You may convert to and distribute this work in any binary,
compressed, marked up, nonproprietary or proprietary form,
including any word processing or hypertext form. However, if you
provide access to or distribute copies of a Project Gutenberg™ work
in a format other than “Plain Vanilla ASCII” or other format used in
the official version posted on the official Project Gutenberg™ website
(www.gutenberg.org), you must, at no additional cost, fee or
expense to the user, provide a copy, a means of exporting a copy, or
a means of obtaining a copy upon request, of the work in its original
“Plain Vanilla ASCII” or other form. Any alternate format must
include the full Project Gutenberg™ License as specified in
paragraph 1.E.1.
• You pay a royalty fee of 20% of the gross profits you derive
from the use of Project Gutenberg™ works calculated using the
method you already use to calculate your applicable taxes. The
fee is owed to the owner of the Project Gutenberg™ trademark,
but he has agreed to donate royalties under this paragraph to
the Project Gutenberg Literary Archive Foundation. Royalty
payments must be paid within 60 days following each date on
which you prepare (or are legally required to prepare) your
periodic tax returns. Royalty payments should be clearly marked
as such and sent to the Project Gutenberg Literary Archive
Foundation at the address specified in Section 4, “Information
about donations to the Project Gutenberg Literary Archive
Foundation.”
• You comply with all other terms of this agreement for free
distribution of Project Gutenberg™ works.
1.F.
1.F.4. Except for the limited right of replacement or refund set forth
in paragraph 1.F.3, this work is provided to you ‘AS-IS’, WITH NO
OTHER WARRANTIES OF ANY KIND, EXPRESS OR IMPLIED,
INCLUDING BUT NOT LIMITED TO WARRANTIES OF
MERCHANTABILITY OR FITNESS FOR ANY PURPOSE.
Please check the Project Gutenberg web pages for current donation
methods and addresses. Donations are accepted in a number of
other ways including checks, online payments and credit card
donations. To donate, please visit: www.gutenberg.org/donate.
Most people start at our website which has the main PG search
facility: www.gutenberg.org.
ebookgate.com