(Ebook) Data Structures & Algorithms using Kotlin, Second Edition by Hemant Jain - Read the ebook now with the complete version and no limits
(Ebook) Data Structures & Algorithms using Kotlin, Second Edition by Hemant Jain - Read the ebook now with the complete version and no limits
com
https://ebooknice.com/product/data-structures-algorithms-
using-kotlin-second-edition-52573652
OR CLICK BUTTON
DOWLOAD EBOOK
(Ebook) Problem Solving in Data Structures & Algorithms Using C# by Hemant Jain
https://ebooknice.com/product/problem-solving-in-data-structures-algorithms-
using-c-38289180
ebooknice.com
https://ebooknice.com/product/data-structures-algorithms-in-go-6857714
ebooknice.com
(Ebook) Problem Solving in Data Structures & Algorithms Using C by Jain, Hemant ISBN
9781730953552, 1730953557
https://ebooknice.com/product/problem-solving-in-data-structures-algorithms-
using-c-11826850
ebooknice.com
(Ebook) Problem Solving in Data Structures & Algorithms Using C#: Programming
Interview Guide by Hemant Jain ISBN 9781540407306, 1540407306
https://ebooknice.com/product/problem-solving-in-data-structures-algorithms-
using-c-programming-interview-guide-6786270
ebooknice.com
(Ebook) Problem Solving in Data Structures & Algorithms Using C++: Programming
Interview Guide by Hemant Jain ISBN 9781542396479, 1542396476
https://ebooknice.com/product/problem-solving-in-data-structures-algorithms-
using-c-programming-interview-guide-10413172
ebooknice.com
(Ebook) Problem Solving in Data Structures & Algorithms Using Python: Programming
Interview Guide by Hemant Jain ISBN 9781541128255, 1541128257
https://ebooknice.com/product/problem-solving-in-data-structures-algorithms-
using-python-programming-interview-guide-43260266
ebooknice.com
https://ebooknice.com/product/data-structures-algorithms-in-go-35833180
ebooknice.com
https://ebooknice.com/product/data-structures-algorithms-in-kotlin-implementing-
practical-data-structures-in-kotlin-10996304
ebooknice.com
(Ebook) Problem Solving with Algorithms and Data Structures Using Python SECOND
EDITION by Bradley N. Miller, David L. Ranum ISBN 9781590282571, 1590282574
https://ebooknice.com/product/problem-solving-with-algorithms-and-data-
structures-using-python-second-edition-4744554
ebooknice.com
Data Structures &
Algorithms using
Kotlin
Second Edition
By Hemant Jain
https://t.me/KotlinSenior
Data Structures & Algorithms using Kotlin
Hemant Jain
Hemant Jain asserts the moral right to be identified as the author of this work.
The author is very grateful to GOD ALMIGHTY for his grace and blessing.
I would like to express profound gratitude to my family and friends for their invaluable
encouragement, supervision and useful suggestions throughout this book writing work.
Their support and continuous guidance enable me to complete my work successfully.
Hemant Jain
Table of Contents
CHAPTER 0: ABOUT THIS BOOK...............................................................................................................................1
CHAPTER 1: ALGORITHMS ANALYSIS.......................................................................................................................2
CHAPTER 2: APPROACH TO SOLVE PROBLEMS......................................................................................................24
CHAPTER 3: ABSTRACT DATA TYPE........................................................................................................................29
CHAPTER 4: SORTING............................................................................................................................................43
CHAPTER 5: SEARCHING........................................................................................................................................82
CHAPTER 6: LINKED LIST......................................................................................................................................153
CHAPTER 7: STACK...............................................................................................................................................206
CHAPTER 8: QUEUE.............................................................................................................................................243
CHAPTER 9: TREE.................................................................................................................................................267
CHAPTER 10: PRIORITY QUEUE / HEAPS..............................................................................................................346
CHAPTER 11: HASH TABLE...................................................................................................................................381
CHAPTER 12: GRAPHS..........................................................................................................................................396
CHAPTER 13: STRING ALGORITHMS....................................................................................................................447
CHAPTER 14: ALGORITHM DESIGN TECHNIQUES................................................................................................467
CHAPTER 15: BRUTE FORCE ALGORITHM............................................................................................................470
CHAPTER 16: GREEDY ALGORITHM.....................................................................................................................475
CHAPTER 17: DIVIDE AND CONQUER..................................................................................................................492
CHAPTER 18: DYNAMIC PROGRAMMING............................................................................................................503
CHAPTER 19: BACKTRACKING..............................................................................................................................541
CHAPTER 20: COMPLEXITY THEORY.....................................................................................................................550
APPENDIX............................................................................................................................................................559
Table of Contents
CHAPTER 0: ABOUT THIS BOOK...............................................................................................................................1
WHAT THIS BOOK IS ABOUT........................................................................................................................................1
PREREQUISITES.........................................................................................................................................................1
WHO SHOULD TAKE THIS COURSE ?..............................................................................................................................1
CODE DOWNLOADS...................................................................................................................................................1
END....................................................................................................................................................................... 1
CHAPTER 1: ALGORITHMS ANALYSIS.......................................................................................................................2
INTRODUCTION........................................................................................................................................................2
ASYMPTOTIC ANALYSIS OR ASYMPTOTIC NOTATIONS.......................................................................................................2
BIG-O NOTATION.....................................................................................................................................................2
OMEGA-Ω NOTATION...............................................................................................................................................3
THETA-Θ NOTATION.................................................................................................................................................4
COMPLEXITY ANALYSIS OF ALGORITHMS........................................................................................................................4
GROWTH OF FUNCTIONS............................................................................................................................................5
DERIVING AN ALGORITHM'S RUNTIME FUNCTION...........................................................................................................7
TIME COMPLEXITY EXAMPLES.....................................................................................................................................7
RECURSIVE FUNCTION.............................................................................................................................................13
COMPLEXITIES FROM RECURRENCE RELATION..............................................................................................................18
MASTER THEOREM.................................................................................................................................................21
EXERCISE...............................................................................................................................................................23
CHAPTER 2: APPROACH TO SOLVE PROBLEMS......................................................................................................24
INTRODUCTION.......................................................................................................................................................24
CONSTRAINTS........................................................................................................................................................24
IDEA GENERATION..................................................................................................................................................25
COMPLEXITIES........................................................................................................................................................26
CODING................................................................................................................................................................27
TESTING................................................................................................................................................................27
EXAMPLE..............................................................................................................................................................28
SUMMARY.............................................................................................................................................................28
CHAPTER 3: ABSTRACT DATA TYPE........................................................................................................................29
ABSTRACT DATA TYPE (ADT)...................................................................................................................................29
DATA-STRUCTURE...................................................................................................................................................29
KOTLIN COLLECTION FRAMEWORK.............................................................................................................................30
ARRAY..................................................................................................................................................................30
LINKED LIST...........................................................................................................................................................31
STACK..................................................................................................................................................................33
QUEUE.................................................................................................................................................................34
TREE.................................................................................................................................................................... 35
BINARY SEARCH TREE (BST).....................................................................................................................................35
HEAP / PRIORITY QUEUE.........................................................................................................................................37
HASH TABLE..........................................................................................................................................................39
ENDNOTE..............................................................................................................................................................42
CHAPTER 4: SORTING............................................................................................................................................43
INTRODUCTION.......................................................................................................................................................43
TYPES OF SORTING..................................................................................................................................................43
COMPARISON FUNCTION..........................................................................................................................................43
BUBBLE SORT........................................................................................................................................................44
INSERTION SORT.....................................................................................................................................................46
SELECTION SORT.....................................................................................................................................................47
MERGE SORT.........................................................................................................................................................49
PROS AND CONS OF MERGE-SORT ALGORITHM............................................................................................................51
EXTERNAL SORT (EXTERNAL MERGE-SORT).................................................................................................................51
QUICK SORT..........................................................................................................................................................52
QUICK SELECT........................................................................................................................................................54
COUNTING SORT....................................................................................................................................................56
RADIX SORT...........................................................................................................................................................57
HEAP SORT...........................................................................................................................................................59
TREE SORTING.......................................................................................................................................................59
SHELL SORT...........................................................................................................................................................59
BUCKET SORT........................................................................................................................................................61
GENERALISED BUCKET SORT.....................................................................................................................................62
STABLE SORTING....................................................................................................................................................63
COMPARISONS OF THE VARIOUS SORTING ALGORITHMS..................................................................................................63
SELECTION OF BEST SORTING ALGORITHM...................................................................................................................64
PROBLEMS BASED ON SORTING..................................................................................................................................65
EXERCISE...............................................................................................................................................................80
CHAPTER 5: SEARCHING........................................................................................................................................82
INTRODUCTION.......................................................................................................................................................82
WHY SEARCHING?..................................................................................................................................................82
DIFFERENT SEARCHING ALGORITHMS..........................................................................................................................82
LINEAR SEARCH OR SEQUENTIAL SEARCH – UNSORTED INPUT.........................................................................................82
LINEAR SEARCH – SORTED........................................................................................................................................83
BINARY SEARCH......................................................................................................................................................84
BINARY SEARCH IMPLEMENTATION USING RECURSION....................................................................................................85
FIBONACCI SEARCH.................................................................................................................................................86
HOW IS SORTING USEFUL IN SELECTION ALGORITHMS?..................................................................................................87
PROBLEMS IN SEARCHING........................................................................................................................................88
EXERCISE.............................................................................................................................................................151
CHAPTER 6: LINKED LIST......................................................................................................................................153
INTRODUCTION.....................................................................................................................................................153
LINKED LIST.........................................................................................................................................................153
TYPES OF LINKED LIST............................................................................................................................................153
SINGLY LINKED LIST...............................................................................................................................................154
DOUBLY LINKED LIST.............................................................................................................................................178
CIRCULAR LINKED LIST...........................................................................................................................................189
DOUBLY CIRCULAR LIST..........................................................................................................................................197
SKIP LIST.............................................................................................................................................................201
USES OF LINKED LIST.............................................................................................................................................203
EXERCISE.............................................................................................................................................................204
CHAPTER 7: STACK...............................................................................................................................................206
INTRODUCTION.....................................................................................................................................................206
THE STACK ABSTRACT DATA TYPE............................................................................................................................206
STACK USING ARRAY..............................................................................................................................................207
STACK USING ARRAY WITH MEMORY MANAGEMENT....................................................................................................209
STACK USING LINKED LIST.......................................................................................................................................210
SYSTEM STACK AND FUNCTION CALLS.......................................................................................................................213
PROBLEMS IN STACK.............................................................................................................................................214
USES OF STACK....................................................................................................................................................241
EXERCISE.............................................................................................................................................................241
CHAPTER 8: QUEUE.............................................................................................................................................243
INTRODUCTION.....................................................................................................................................................243
THE QUEUE ABSTRACT DATA TYPE..........................................................................................................................243
QUEUE USING ARRAY............................................................................................................................................244
QUEUE USING CIRCULAR LINKED LIST.......................................................................................................................245
PROBLEMS IN QUEUE............................................................................................................................................248
USES OF QUEUE...................................................................................................................................................265
EXERCISE.............................................................................................................................................................265
CHAPTER 9: TREE.................................................................................................................................................267
INTRODUCTION.....................................................................................................................................................267
TERMINOLOGY IN TREE..........................................................................................................................................267
BINARY TREE.......................................................................................................................................................269
TYPES OF BINARY TREES.........................................................................................................................................270
PROBLEMS IN BINARY TREE....................................................................................................................................272
BINARY SEARCH TREE (BST)...................................................................................................................................292
PROBLEMS IN BINARY SEARCH TREE (BST)................................................................................................................292
SEGMENT TREE....................................................................................................................................................306
BINARY INDEX TREE / FENWICK TREE.......................................................................................................................310
AVL TREE...........................................................................................................................................................313
RED-BLACK TREE..................................................................................................................................................319
SPLAY TREE.........................................................................................................................................................331
B TREE...............................................................................................................................................................336
B+ TREE.............................................................................................................................................................341
THREADED BINARY TREE........................................................................................................................................342
USES OF TREES.....................................................................................................................................................343
EXERCISE.............................................................................................................................................................343
CHAPTER 10: PRIORITY QUEUE / HEAPS..............................................................................................................346
INTRODUCTION.....................................................................................................................................................346
TYPES OF HEAP....................................................................................................................................................347
HEAP ADT OPERATIONS........................................................................................................................................348
OPERATION ON HEAP............................................................................................................................................348
HEAP SORT.........................................................................................................................................................358
PROBLEMS IN HEAP..............................................................................................................................................363
BINOMIAL HEAP...................................................................................................................................................369
FIBONACCI HEAP..................................................................................................................................................374
USES OF HEAP.....................................................................................................................................................378
EXERCISE.............................................................................................................................................................379
CHAPTER 11: HASH TABLE...................................................................................................................................381
INTRODUCTION.....................................................................................................................................................381
HASH-TABLE........................................................................................................................................................381
HASHING WITH OPEN ADDRESSING..........................................................................................................................383
HASHING WITH SEPARATE CHAINING.........................................................................................................................387
SET IMPLEMENTATION OF KOTLIN COLLECTIONS.........................................................................................................389
DICTIONARY IMPLEMENTATION IN KOTLIN COLLECTION................................................................................................389
PROBLEMS IN HASHING.........................................................................................................................................390
USES OF HASH-TABLE...........................................................................................................................................393
EXERCISE.............................................................................................................................................................393
CHAPTER 12: GRAPHS..........................................................................................................................................396
INTRODUCTION.....................................................................................................................................................396
GRAPH TERMINOLOGY...........................................................................................................................................397
GRAPH REPRESENTATION.......................................................................................................................................401
GRAPH TRAVERSALS..............................................................................................................................................404
DEPTH FIRST TRAVERSAL........................................................................................................................................405
BREADTH FIRST TRAVERSAL....................................................................................................................................407
DFS & BFS BASED PROBLEMS................................................................................................................................410
MINIMUM SPANNING TREE (MST)..........................................................................................................................426
EULER PATH AND EULER CIRCUIT.............................................................................................................................431
SHORTEST PATH ALGORITHMS IN GRAPH..................................................................................................................433
HAMILTONIAN PATH.............................................................................................................................................441
HAMILTONIAN CIRCUIT..........................................................................................................................................443
TRAVELLING SALESMAN PROBLEM (TSP)..................................................................................................................444
USES OF GRAPH ALGORITHMS.................................................................................................................................446
EXERCISE.............................................................................................................................................................446
CHAPTER 13: STRING ALGORITHMS....................................................................................................................447
INTRODUCTION.....................................................................................................................................................447
STRING MATCHING...............................................................................................................................................447
DICTIONARY / SYMBOL TABLE.................................................................................................................................451
PROBLEMS IN STRING............................................................................................................................................458
EXERCISE.............................................................................................................................................................465
CHAPTER 14: ALGORITHM DESIGN TECHNIQUES................................................................................................467
INTRODUCTION.....................................................................................................................................................467
BRUTE FORCE ALGORITHM.....................................................................................................................................467
GREEDY ALGORITHM.............................................................................................................................................468
DIVIDE AND CONQUER...........................................................................................................................................468
DYNAMIC PROGRAMMING......................................................................................................................................468
BACKTRACKING....................................................................................................................................................469
CONCLUSION.......................................................................................................................................................469
CHAPTER 15: BRUTE FORCE ALGORITHM............................................................................................................470
INTRODUCTION.....................................................................................................................................................470
PROBLEMS IN BRUTE FORCE ALGORITHM..................................................................................................................470
CONCLUSION.......................................................................................................................................................474
CHAPTER 16: GREEDY ALGORITHM.....................................................................................................................475
INTRODUCTION.....................................................................................................................................................475
PROBLEMS ON GREEDY ALGORITHM.........................................................................................................................475
CONVEX-HULL PROBLEM........................................................................................................................................489
CONCLUSION.......................................................................................................................................................491
CHAPTER 17: DIVIDE AND CONQUER..................................................................................................................492
INTRODUCTION.....................................................................................................................................................492
GENERAL DIVIDE & CONQUER RECURRENCE..............................................................................................................493
PROBLEMS ON DIVIDE & CONQUER ALGORITHM........................................................................................................493
STRASSEN’S MATRIX MULTIPLICATION......................................................................................................................499
EXERCISE.............................................................................................................................................................501
CHAPTER 18: DYNAMIC PROGRAMMING............................................................................................................503
INTRODUCTION.....................................................................................................................................................503
DYNAMIC PROGRAMMING METHODS.......................................................................................................................504
TABULATION (BOTTOM-UP)...................................................................................................................................504
MEMOIZATION (TOP-DOWN).................................................................................................................................505
DYNAMIC PROGRAMMING PATTERNS.......................................................................................................................506
TYPE 1 : MAXIMUM / MINIMUM COST TO REACH SOME STATE PROBLEMS......................................................................508
TYPE 2 : DISTINCT WAYS TO REACH SOME STATE PROBLEMS.........................................................................................513
TYPE 3 : MERGING INTERVALS TO GET OPTIMAL SOLUTION PROBLEMS............................................................................517
TYPE 4 : SUBSEQUENCE, SUBSTRINGS AND STRING MANIPULATION PROBLEMS................................................................525
TYPE 5 : STATE SELECTION KIND OF PROBLEMS..........................................................................................................534
EXERCISE.............................................................................................................................................................539
CHAPTER 19: BACKTRACKING..............................................................................................................................541
INTRODUCTION.....................................................................................................................................................541
PROBLEMS ON BACKTRACKING ALGORITHM...............................................................................................................542
EXERCISE.............................................................................................................................................................549
CHAPTER 20: COMPLEXITY THEORY.....................................................................................................................550
INTRODUCTION.....................................................................................................................................................550
DECISION PROBLEM..............................................................................................................................................550
COMPLEXITY CLASSES............................................................................................................................................550
CLASS P PROBLEMS..............................................................................................................................................551
CLASS NP PROBLEMS............................................................................................................................................552
REDUCTION.........................................................................................................................................................553
NP HARD PROBLEMS............................................................................................................................................554
NP-COMPLETE PROBLEMS.....................................................................................................................................554
CLASS CO-NP PROBLEMS.......................................................................................................................................558
END NOTE..........................................................................................................................................................558
APPENDIX............................................................................................................................................................559
CHAPTER 0: ABOUT THIS BOOK
Designing an efficient algorithm is a very important skill that all software companies pursue. Most of
the interviews for software companies are focused on knowledge of data structures and algorithms.
Apart from knowing a programming language, you also need to have a good command of these key
computer fundamentals to not only crack the interview but also excel in your jobs as a software
engineer.
Prerequisites
You should have a working knowledge of Kotlin programming language. You are not an expert in the
Kotlin language, but you are well familiar with concepts of classes, functions, references, and
recursion.
Code downloads
You can download the code of solved examples in the book from the author's GitHub repositories at
https://GitHub.com/Hemant-Jain-Author/. Hear the author had solved examples in various
programming languages like C, C++, C#, Java, Python, JavaScript, Swift, GoLang, Ruby, etc.
End
It is highly recommended that you should read the problem statement, try to solve the problems by
yourself and then only you should look into the solution to find the approach of this book. Practising
more and more problems will increase your thinking capacity, and you will be able to handle unseen
problems in an interview. We recommend you to practice all the problems given in this book, then
solve more and more problems from online resources like www.topcoder.com, www.careercup.com,
https://leetcode.com/ etc.
1
CHAPTER 1: ALGORITHMS ANALYSIS
Introduction
An Algorithm is a finite set of unambiguous steps or instructions to solve a given problem. Knowledge
of algorithms helps us to get desired results faster by applying the appropriate algorithm. We learn by
experience. With experience, it becomes easy to solve new problems. By looking into various problem-
solving algorithms or techniques, we begin to develop a pattern that will help us in solving similar
problems.
The complexity of an algorithm is the amount of Time or Space required by the algorithm to process
the input and produce the output.
In most cases, we are interested in the order of growth of the algorithm instead of the exact time
required for running an algorithm. This time is also known as Asymptotic Running Time.
Big-O Notation
Definition: “f(n) is big-O of g(n)” or f(n) = O(g(n)), if there are two +ve constants c and n1 such that f(n)
≤ c g(n) for all n ≥ n1,
2
Chapter 1: Algorithms Analysis Big-O Notation
In other words, c g(n) is an upper bound for f(n) for all n ≥ n0. The function f(n) growth is slower than c
g(n). For a sufficiently large value of input n, the (c.g(n)) will always be greater than f(n).
Omega-Ω Notation
Definition: “f(n) is omega of g(n)” or f(n)=Ω(g(n)) if there are two +ve constants c and n1 such that c
g(n) ≤ f(n) for all n ≥ n1
In other words, c g(n) is the lower bound for f(n). Function f(n) growth is faster than c g(n)
3
Chapter 1: Algorithms Analysis Theta-Θ Notation
Theta-Θ Notation
Definition: “f(n) is theta of g(n).” or f(n) = Θ(g(n)) if there are three +ve constants c1, c2 and n1 such
that c1 g(n) ≤ f(n) ≤ c2 g(n) for all n ≥ n1
Function g(n) is an asymptotically tight bound on f(n). Function f(n) grows at the same rate as g(n).
Note: Worst-case complexity is used to find the guarantee in how much time some particular algorithm
will finish. This is the most important time complexity. If the type of complexity is not mentioned, then
always consider Worst-Case time complexity.
4
Chapter 1: Algorithms Analysis Growth of functions
Growth of functions
Let’s look at these growth rates of various functions. The size of the input is n.
Examples:
1 Accessing an nth element of an Array
2 Push and pop of a stack.
3 Add and remove from a queue.
4 Accessing an element of Hash-Table.
Examples:
1 Array operations like search element, find min, find max etc.
2 Linked list operations like traversal, find min, find max etc.
Note: If we need to traverse all the nodes of a data structure for some task, then complexity cant be
less than O(n)
An example is the Binary search algorithm. We will read about this algorithm in this book.
5
Chapter 1: Algorithms Analysis Growth of functions
The time taken by certain algorithms to run varies dramatically with the size of the input. Some
algorithms take minutes or even seconds to run on huge input, whereas others may take days to
complete their execution. To understand how the rate of growth changes with the size of the input in
different functions, the following table presents the approximate number of steps required to run an
algorithm:
6
Chapter 1: Algorithms Analysis Deriving an Algorithm's Runtime Function
Constants
If any line of code is a statement with basic operations, e.g., comparisons, assignments, or reading a
variable, they take constant time each. Thus, the time complexity of each statement is O(1).
Loops
In loop, a repetition of a particular code for n times, where n is the size of the loop. Every statement
inside the loop has a runtime of O(1). The running time of a loop is a product of the running time of the
statement inside a loop and the number of iterations in the loop. Time Complexity is O(n)
Nested Loops
The running time of a nested loops is a product of the running time of the statements inside the loop
multiplied by a product of the size of all the loops. Time Complexity is O(n^c). Where c is the number of
loops. For two loops, it will be O(n^2)
Consecutive Statements
In this case, we add the running time of all the consecutive lines of code.
If-Else Statement
In this case, either “if” will run or “else” will run. So, the block with larger runtime will be considered.
Logarithmic Statement
In this case, each iteration will cut the input size into b pieces and consider one of the pieces for the
next iteration. Time complexity in this situation will be O(logb(n)).
// Testing code.
fun main() {
println("N = 100, Number of instructions O(n):: " + fun1(100))
}
Output:
N = 100, Number of instructions in O(n)::100
7
Chapter 1: Algorithms Analysis Time Complexity Examples
// Testing code.
fun main() {
println("N = 100, Number of instructions O(n^2):: " + fun2(100))
}
Output:
N = 100, Number of instructions in O(n^2)::10000
Time Complexity: O(n^2), two nested for loop, takes quadratic time. Both the “for” loop is executed n
number of times, so the internal statement executed n^2 number of times.
// Testing code.
fun main() {
println("N = 100, Number of instructions O(n^3):: " + fun3(100))
}
Output:
N = 100, Number of instructions in O(n^3)::1000000
Time Complexity: O(n^3), All the three nested loops run for n number of iterations. So the statement
inside the innermost loop will run for n^3 number of times.
8
Chapter 1: Algorithms Analysis Time Complexity Examples
}
return m
}
// Testing code.
fun main() {
println("N = 100, Number of instructions O(n^3):: " + fun4(100))
}
Output:
N = 100, Number of instructions in O(n^3)::166650
Time Complexity: Three nested loops each run for n number of times. The innermost statement will
run for n^3 number of times. Time complexity is O(n^3)
// Testing code.
fun main() {
println("N = 100, Number of instructions O(n^2):: " + fun5(100))
}
Output:
N = 100, Number of instructions in O(n^2)::4950
Time Complexity: Statement inside inner loop executes for 1 time in first iteration then 2 times then 3
times and so on for n iterations. Total number of times the inner statement is executed = 1 + 2+ 3 +…..
+ n. This series is an arithmetic progression, which sums to n(n+1)/2. So the final time complexity is
O(n(n+1)/2) ignoring the constant factors, time complexity will be O(n^2).
// Testing code.
fun main() {
println("N = 100, Number of instructions O(n^2):: " + fun6(100))
}
9
Chapter 1: Algorithms Analysis Time Complexity Examples
Output:
N = 100, Number of instructions in O(n^2)::5050
Time Complexity: The inner loop will run 1 time in the first iteration, then 2 times in the second
iteration and so on. It is an arithmetic progression, so time complexity will be O(n^2).
// Testing code.
fun main() {
println("N = 100, Number of instructions O(n):: " + fun7(100))
}
Output:
N = 100, Number of instructions in O(n)::197
For nested loops, look for inner loop iterations. Time complexity will be calculated by looking into the
inner loop. First, it will run for n number of times then n/2 and so on. (n+n/2 +n/4+n/8+n/16 ……)
Time Complexity: O(n)
// Testing code.
fun main() {
println("N = 100, Number of instructions O(n):: " + fun8(100))
}
10
Chapter 1: Algorithms Analysis Time Complexity Examples
Output:
N = 100, Number of instructions in O(n)::134
Time Complexity: The inner loop will run for 1, 2, 4, 8,… n times in successive iteration of the outer
loop. T(n) = O(1+ 2+ 4+ ….+n/2+n) = O(n)
// Testing code.
fun main() {
println("N = 100, Number of instructions O(log(n)):: " + fun9(100))
}
Output:
N = 100, Number of inst in O(log(n))::7
In each iteration, i value is doubled. So the value of i after k iterations will be 2^k.
2^k = n ...Will be the condition at the time of exit.
log(2^k) = log(n) ….Taking log both sides.
k = log(n)
Time Complexity: O(log(n))
// Testing code.
fun main() {
println("N = 100, Number of instructions O(log(n)):: " + fun10(100))
}
Output:
N = 100, Number of instructions in O(log(n))::7
11
Chapter 1: Algorithms Analysis Time Complexity Examples
for (i in 0 until n) {
for (k in 0 until n) {
m += 1
}
}
return m
}
// Testing code.
fun main() {
println("N = 100, Number of instructions O(n^2):: " + fun11(100))
}
Output:
N = 100, Number of instructions in O(n^2)::20000
These two groups of loops are consecutive, so their complexity will add up to form the final complexity
of the program.
Time Complexity: O(n^2) + O(n^2) = O(n^2)
Example 1.12:
fun fun12(n: Int): Int {
var m = 0
for (i in 0 until n) {
for (j in 0 until Math.sqrt(n.toDouble()).toInt()) {
m += 1
}
}
return m
}
// Testing code.
fun main() {
println("N = 100, Number of instructions O(n^(3/2)):: " + fun12(100))
}
Output:
N = 100, Number of instructions in O(n^(3/2))::1000
12
Chapter 1: Algorithms Analysis Time Complexity Examples
Time Complexity: Inner loop always runs for √n times. O(n * √n ) = O(n^3/2)
// Testing code.
fun main() {
println("N = 100, Number of instructions O(n):: " + fun13(100))
}
Output:
N = 100, Number of instructions in O(n)::100
Time Complexity: In this example, j is not initialised for every iteration. For i=0, the loop of j executes
completely, making the value of j as n. But for the remaining values of i, the loop of j does not execute.
So the time complexity in this case is O(n).
Recursive Function
Recursion: A recursive function is a function that calls itself, directly or indirectly. A recursive method
consists of two parts: Termination Condition and Body (which includes recursive expansion).
1 Termination Condition: A recursive method always contains one or more terminating conditions.
A condition in which a recursive method processes a simple case and does not call itself.
2 Body (including recursive expansion): The main logic of the recursive method is contained in the
body of the method. It also contains the recursion expansion statement that, in turn, calls the
method itself.
Note: The speed of a recursive program is slower because of stack overheads. If the same problem
can be solved using an iterative solution (using loops), then we should prefer an iterative solution in
place of recursion to avoid stack overhead.
Note: Without termination conditions, the recursive method may run forever and consume full-stack
memory.
13
Chapter 1: Algorithms Analysis Recursive Function
Factorial
Problem: Given a value N find N!. Where N! = N* (N-1)…. 2*1. Use recursion to solve the problem.
// Testing code.
fun main() {
println("Factorial:" + factorial(5))
}
Output:
Factorial:120
14
Chapter 1: Algorithms Analysis Recursive Function
// Testing code.
fun main() {
var i = 1000
printInt(i, 16)
}
Output:
3E8
Analysis:
1 The base value is provided along with the number in the function parameter.
2 The remainder of the number is calculated and stored in digits.
3 If the number is greater than the base, then the number divided by the base is passed recursively
as an argument to the print() method.
4 The number will be printed higher-ordered first, then the lower order digits.
Tower of Hanoi
Problem: In the Tower of Hanoi, we are given three rods and N number of disks, initially all the disks
are added to the first rod (the leftmost one) such that no smaller disk is under the larger one. The
objective is to transfer the entire stack of disks from the first tower to the third tower (the rightmost
one), moving only one disk at a time. Moving a larger disk onto a smaller one is not allowed.
Solution: If we want to transfer N disks from source to destination tower. Let's consider the bottom-
most disk, it is the largest disk so can not be placed to any other tower except the destination tower.
Also, all the disks above the largest disk need to be placed in the temporary tower, then only the
largest disk can be moved to the destination tower. So we move N-1 disks from source to temporary
tower and then move the lowest Nth disk from source to destination. Then we will move N-1 disks from
the temporary tower to the destination tower.
Example 1.16:
fun towerOfHanoi(num:Int, src:Char, dst:Char, temp:Char) {
if (num < 1) {
return
}
15
Chapter 1: Algorithms Analysis Recursive Function
// Testing code.
fun main() {
var num = 3
println("Moves involved in the Tower of Hanoi are:")
towerOfHanoi(num, 'A', 'C', 'B')
}
Output:
Moves involved in the Tower of Hanoi are:
Move 1 disk from peg A to peg C
Move 2 disk from peg A to peg B
Move 1 disk from peg C to peg B
Move 3 disk from peg A to peg C
Move 1 disk from peg B to peg A
Move 2 disk from peg B to peg C
Move 1 disk from peg A to peg C
Analysis:
Recurrence Relation: T(n) = 1 + 2T(n-1)
T(n-1) = 1 + 2*T(n-2)
T(n-2) = 1 + 2*T(n-3)
T(n) = 1 + 2*( 1 + 2*T(n-2)) = 1 + 2 + 4*T(n-2) = 1 + 2 + 4*( 1 + 2*(T(n-3)) = 1 + 2+ 22+ 23T(n-3)
= 1 + 2 + 22 …. + 2nT(0) = 1(2n+1 – 1)/2 – 1 = 2n+1 – 1 // Geometric progression sum
Time complexity will be O(2^n) ignoring the constants.
Solution: There are many ways to find the greatest common divisor (GCD). We are using Euclid’s
algorithm to find the GCD. The following are steps of Euclid’s algorithm:
1. If n = 0 then GCD(n, m) = m, and this is a termination condition.
2. If m = 0 then GCD(n, m) = n, and this is a termination condition.
3. Write n in the form of a quotient remainder n = mq + q. q is the quotient, and r is the remainder.
4. Since GCD(n, m) = GCD(m, r), use the Euclidean Algorithm to find GCD(m , r).
Example 1.17:
fun gcd(m:Int, n:Int):Int {
if (m == 0) {
return n
}
if (n == 0) {
return m
}
16
Chapter 1: Algorithms Analysis Recursive Function
return gcd(n, m % n)
}
// Testing code.
fun main() {
println("Gcd is:: " + gcd(5, 2));
}
Output:
Gcd is:: 1
Time-Complexity: O(Max(log(m), log(n))), Each step input is reduced by nearly half or more.
Fibonacci number
Problem: Given N, find the Nth number in the Fibonacci series.
Solution: Fibonacci numbers are calculated by adding the sum of the previous two numbers.
Example 1.18:
fun fibonacci(n:Int):Int {
if (n <= 1) {
return n
}
// Testing code.
fun main() {
println(fibonacci(10));
}
Output:
55
Note: - There is an inefficiency in the solution. We will look for a better solution in the coming chapters.
17
Chapter 1: Algorithms Analysis Complexities from Recurrence Relation
Example 1.20: Find complexity of the function with the following recurrence relation.
T(n) =
{T ( n−11)+nif n=0if n>0
Solution:
T(n) = T(n-1) + n
T(n-1) = T(n-2) + n
T(n-2) = T(n-3) + n
T(n) = ( T(n-2) + n) + n = T(n-2) + 2n = (T(n-3) + n) + 2n = T(n-3) + 3n
T(n) = T(n-k) + kn
base case when T(0) = 1, n-k = 0 => n = k
T(n) = T(0) + n*n = 1 + n^2
Time Complexity is O(n^2)
Example 1.21: Find complexity of the function with the following recurrence relation.
T(n) =
{1T (n− 1)+ log (n) ififn=0
n>0
Solution:
T(n) = T(n-1) + log(n)
T(n-1) = T(n-2) + log(n) // for simplicity make log(n-1) as log(n)
T(n-2) = T(n-3) + log(n)
T(n) = ( T(n-2) + log(n)) + log(n) = T(n-2) + 2log(n) = (T(n-3) + log(n)) + 2log(n) = T(n-3) + 3log(n)
18
Chapter 1: Algorithms Analysis Complexities from Recurrence Relation
Example 1.22: Find complexity of the function with the following recurrence relation.
T(n) =
{T (n/12)+nif n=1if n>1
Solution:
T(n) = T(n/2) + n
T(n/2) = T(n/22) + (n/2) // substituting n as n/2
T(n/22) = T(n/23) + (n/22) // substituting n as n/22
T(n) = ( T(n/22) + (n/2) ) + n = T(n/22) + n/2 + n
T(n) = ( T(n/23) + (n/22) ) + n/2 + n = T(n/23) + n/22 + n/2 + n
T(n) = T(n/2^k) + n/2^(k-1) + …… + n/22 + n/2 + n
base case when n = 2^k,
T(n) = T(1) + n/2^k-1 + …… + n/22 + n/2 + n
T(n) = T(1) + n * ( 1/2^(k-1) + …… + 1/22 + 1/2 + 1 )
T(n) = 1 + n*2
Time Complexity is O(n)
Example 1.23: Find complexity of the function with the following recurrence relation.
T(n) =
{2∗
1 if n=1
T (n/2)+ n if n>1
Solution:
T(n) = 2 T(n/2) + n
T(n/2) = 2 T(n/22) + (n/2) // substituting n as n/2
T(n/22) = 2 T(n/23) + (n/22) // substituting n as n/22
19
Chapter 1: Algorithms Analysis Complexities from Recurrence Relation
Example 1.24: Find complexity of the function with the following recurrence relation.
T(n) =
{12∗ T (n −1)+1 if n=0
if n>0
Solution:
T(n) = 2 T(n-1) + 1
T(n-1) = 2T(n-2) + 1
T(n-2) = 2T(n-3) + 1
T(n) = 2( 2T(n-2) + 1) + 1 = 22T(n-2) + 2 + 1 = 22 (2T(n-3) + 1) + 2 + 1 = 23T(n-3) + 22 + 2 + 1
T(n) = 2kT(n-k) + 2(k-1) + ….. + 22 + 2 + 1
base case when T(0) = 1, n-k = 0 => n = k
T(n) = 2nT(0) + 2(n-1) + ….. + 22 + 2 + 1 = 2n + 2(n-1) + ….. + 22 + 2 + 1 = 2(n+1) – 1 // GP
Time Complexity O(2^n)
Example 1.25: Find complexity of the function with the following recurrence relation.
T(n) =
{T (√1 n)+1 if n ≤2
if n>2
Solution:
T(n) = T(n1/2) + 1
T(n1/2) = T( n1/4) + 1
T(n1/4) = T( n1/8) + 1
T(n) = T(n1/2) + 1 = (T( n1/4) + 1) + 1 = T( n1/4) + 2 = (T( n1/8) + 1) + 2 = T( n1/8) + 3
T(n) = T(n1/2k) + k
for base case n,1/2k = 2
(1/(2^k) ) * log(n)= log2 = 1 // taking log.
log(n) = 2^k
log(log(n)) = k log(2) = k // taking log again.
Time Complexity is O(log(log(n)))
20
Chapter 1: Algorithms Analysis Master Theorem
Master Theorem
The master theorem solves recurrence relations of the form: T(n) = a T(n/b) + f(n), Where a≥1 and
b>1. In this relation, “n” is the size of the input. "a" is the number of sub-problems in the recursion.
“n/b” is the size of each sub-problem. "f(n)" is the cost of the division of the problem into sub-problems
and merging the individual solutions of the sub-problems into the solution.
T(n) = Θ(n
logba. k+1
log n)
logba+ε
Case 3: When f(n) = Ω(n ) and constant Є > 1, then the final time complexity is T(n) = Θ(f(n))
Example 1.26: In the case of Merge Sort. Its time complexity is T(n) = 2 T(n/2) + n
Solution: In this example, a and b both equal to 2. So, logba = log22 = 1.
Which means, f(n) = n = Θ(nlog22log0n). That means case 2 is applied and T(n) = Θ(nlog22log0+1n).
So, its final time complexity will be T(n) = Θ(n.log(n))
Example 1.27: It is the case of Binary Search, Its time complexity is T(n) = T(n/2) + 1
Solution: In this example, a is equal to 1 and b is equal to 2. So, logba = log21 = 0
Which means, f(n) = 1 = Θ(nlog21log0n). That means case 2 is applied and T(n) = Θ(nlog21log0+1n).
So, its final time complexity will be T(n) = Θ(log(n))
21
Chapter 1: Algorithms Analysis Master Theorem
Example 1.28: In the case of binary tree traversal, Its time complexity is T(n) = 2T(n/2) + 1
Solution: In this example, a is equal to 2 and b is also equal to 2. So, logba = log22 = 1
Which means, f(n) =1 = O(nlog22 - 1). That means case 1 is applied and T(n) = Θ(nlog22).
So, its final time complexity will be T(n) = Θ(n)
22
Chapter 1: Algorithms Analysis Master Theorem
Exercise
1 True or false
➢ 5 n + 10 n^2= O(n^2)
➢ n.log(n) + 4 n = O(n)
➢ log(n^2) + 4 log(log(n)) = O(log(n))
➢ 12.n1/2+ 3 = O(n^2)
➢ 3^n + 11.n^2 + n^20= O(2^n)
2 What is the best-case runtime complexity of searching an Array?
3 What is the average-case runtime complexity of searching an Array?
4 Given an array of positive numbers, you need to find the maximum sum under the constraint
that no two elements should be adjacent.
23
CHAPTER 2: APPROACH TO SOLVE PROBLEMS
Introduction
Theoretical knowledge of the algorithm is essential, but it is insufficient. When an interviewer asks the
interviewee to solve a problem, then the interviewee can use our five-step approach to solve problems.
If you master this technique, you will outperform the majority of applicants in interviews.
Constraints
Solving a technical question is not just about knowing the algorithms and designing a good software
system. The interviewer is interested in seeing your approach to any given problem. Often, people
make mistakes by failing to ask clarifying follow-up questions about a given problem. They make a lot
of assumptions at once and start working with them. Before you start solving a problem, you need to
collect a lot of missing information from your interviewer.
In this step, you will write down all the problem’s constraints. Never attempt to solve a problem that
isn’t completely defined. Interview questions are not like exam paper questions, where all the details
about a problem are well-defined. The interviewer wants you to ask questions and clarify the problem
during the interview.
Suppose, when the interviewer says to write an algorithm to sort numbers. You need to ask the
following clarifying question:
1. The first thing you need to know is what sort of data is being given. Assume the interviewer
gives you the answer Integer.
2. The size of the data is the second piece of information you need to know. If the input data is
100 integers or 1 billion integers, the algorithm is different.
24
Chapter 2: Approach to Solve Problems Constraints
We will see in the graph chapter that depending upon the constraints the algorithm applied changes
and so is the complexity of the solution.
Idea Generation
We will cover a lot of theoretical knowledge in this book. It is impossible to cover all the questions, as
new questions are created every day. Therefore, you should know how to handle new problems. Even
if you know the solution to the problem asked by the interviewer, then also you need to have a
discussion with the interviewer and try to reach the solution. You need to analyse the problem also
because the interviewer may modify a question a bit, so the approach to solve it will vary.
How to solve an unseen problem? The solution to this problem is to learn a lot, and the more you
practice, the more you will be able to answer any unseen problem. When you’ve solved enough
problems, you’ll see a pattern in the questions and be able to answer unseen problems with ease.
Following is the strategy that you need to follow to solve an unknown problem:
1. Try to simplify the task at hand.
2. Try a few examples
3. Think of a suitable data structure.
4. Think about similar problems that you have already solved.
25
Chapter 2: Approach to Solve Problems Idea Generation
At first look, it looks complicated, but it is a simple problem. Try to find a relation to the final position.
P(Hi) = i * 2 – 1 and P(Wi) = i * 2
We are leaving an exercise for you to do something like Insertion-Sort for the rest of the algorithm, and
you are done.
Problem 2: We are given a stream of data, at any time, we can be asked to tell the median value of
the data, and maybe we can be asked to pop median data.
Analysis: We may visualise a tree, maybe a balanced tree with the median at the root. Wait a minute!
It’s not straightforward to ensure that the tree root is a median. We can’t get the median from a heap,
although it can give us the minimum or maximum. What if we use two heaps, a max-heap and a min-
heap? The max heap will hold the smaller values, while the min-heap will have the larger values.
Furthermore, we will keep track of how many elements are in the heaps. It would help if you came up
with the rest of the algorithm on your own.
For every unseen problem, think about the data structures you know, and maybe one of them or some
combination of them will solve your problem. Think about similar problems you have already solved.
Problem 3: Given head pointers of two linked lists that intersect at some point. Find the point of
intersection. However, in place of the end of the linked list to be a null pointer, there is a loop.
Analysis: You know how to find the intersection point of two intersecting linked lists, and you know
how to find if a linked list has a loop (three-pointer solution). Therefore, you can combine both solutions
to solve the problem at hand.
Complexities
Solving a problem is not just finding a correct solution. The solution should be fast and should have
reasonable memory requirements. In the previous chapters, you learned about big-O notation. You
should be able to perform Big-O analysis. If you believe the solution you have provided is not optimal
and there is a better solution, then try to figure it out.
26
Chapter 2: Approach to Solve Problems Complexities
Most interviewers expect that you should be able to find the Time and Space Complexity of the
algorithms. You should be able to calculate the Time and Space Complexity quickly. Whenever you
are solving any problem, you should find the complexity associated with it. From this, you would be
able to choose the best solutions. In some problems there are some trade-offs between Space and
Time Complexity, so you should know these trade-offs. Taking a little extra space will save you a lot of
time and make your algorithm much faster.
Coding
At this stage, you have already captured all the constraints of the problem, suggested a few solutions,
evaluated the complexities of those solutions and selected the one for final coding. Never begin coding
without first discussing with the interviewer about constraints, Idea generation and complexity.
We are used to writing code in an IDE like a Visual Studio. So several people struggle when asked to
write code on a whiteboard or some blank sheet. Therefore, you should do some practice coding on a
sheet of paper. You should think before coding because there is no back button on the sheet of paper.
Always try to write modular code. Small functions need to be created so that the code is clean and
managed. If there is a requirement for a swap function, just use this function and tell the interviewer
that you will write it later. Everybody knows that you can write a swap function.
Testing
You’re not done even if the code is written. It is essential to validate the code using a variety of small
test cases. It shows that you understand the importance of testing. It also gives the interviewer
confidence that you would not write a bug-ridden program. Once you have finished coding, you should
go over the code line-by-line for some small test cases. This is to ensure that the code is functioning as
intended.
Note: Always follow these five steps, never jump to coding before doing constraint analysis, idea
generation, and complexity analysis: At last, never miss the testing step.
27
Chapter 2: Approach to Solve Problems Example
Example
Let us suppose the interviewer asks you to give the best sorting algorithm.
Some interviewees will directly jump to Quick-Sort O(n.log(n)). Oops, mistake! You need to ask many
questions before beginning to solve this problem.
Question 5: Can we modify the given data structure? And many, many more questions…
Answer: No, you cannot modify the data structure provided
So, we are all set to use the given information to make a perfect solution. From the first answer, we will
know the type of data we are going to get is an integer. From the second answer, we can conclude that
data size is limited. It’s only in some thousands. From the next answer, we can conclude that it’s age-
related data. So we can assume that a person’s age will be between 1 to 150. And lastly, we know that
data is in the form of a list and cannot change it.
To summarise, we can use bucket sort to sort the data. Since the range is only 1-150, we only need an
integer list of 150 elements. We don’t have to think about data overflow because the data is in
thousands, and we get the solution in linear time.
Summary
At this point, you know the process of handling unseen problems very well. In the coming chapter, we
will be looking into various data structures and the problems they solve. It may be possible that the
user cannot understand some portion of this chapter as knowledge of the rest of the book is needed,
so they can reread this chapter after reading the rest of the data structures portion. A huge number of
problems are solved in this book. However, it is recommended that you first try to solve them yourself
and then look for the solution. Always think about the complexity of the problem. In the interview,
interaction is the key to get the problem described completely and discuss your approach with the
interviewer.
28
CHAPTER 3: ABSTRACT DATA TYPE
For example, a user wants to store some integers and find their mean value. ADT for this data
structure would have two functions, one for adding integers and another to get the mean value. ADT
for this data structure does not talk about how exactly it will be implemented.
Data-Structure
Data structures are concrete representations of data that are defined from the perspective of a
programmer. The data structure represents how data can be stored in memory. Each data structure
has its own set of advantages and disadvantages. Depending on the type of problem, we choose the
most appropriate data structure.
For example, according to the question, we can store data in arrays, stack, queue, linked list, and
many more.
Note: - In this chapter, we will be studying various data structures and their API. So that the user can
use them without knowing their internal implementation.
29
Chapter 3: Abstract Data Type Kotlin Collection Framework
Array
Arrays are the simplest data structures that store items of the same data type.
Example 3.1:
fun main() {
val arr = IntArray(10)
for (i in 0..9) {
arr[i] = i
}
for (i in arr){
print(" " + i)
}
}
Output:
0 1 2 3 4 5 6 7 8 9
30
Chapter 3: Abstract Data Type Array
Application of Arrays
Applications of Arrays are:
1. Storing data in tabular format.
2. Used in the creation of Matrices. Online ticket booking system in which seats are represented
in the form of Matrices.
3. Used in the creation of various higher level data structures like Stacks, Queues, Heaps,
HashTables etc.
Example 3.2:
fun main() {
val al = ArrayList<Int>()
al.add(1) // add 1 to the end of the list
al.add(2) // add 2 to the end of the list
println("Array : $al")
println("Array Size : " + al.size)
println("Array IsEmpty : " + al.isEmpty())
Output:
Array : [1, 2]
Array Size : 2
Array IsEmpty : false
Array : [1]
Array IsEmpty : true
Linked List
Linked list is a dynamic data structure and memory is allocated at run time. The concept of linked list is
not to store data contiguously. Nodes of linked list contain links that point to the next elements in the
list.
31
Chapter 3: Abstract Data Type Linked List
Performance-wise, linked lists are slower than arrays because there is no direct access to linked list
elements. A linked list is a useful data structure when we do not know the number of elements to be
stored ahead of time. There are many types of linked lists: linear, circular, doubly, doubly circular etc.
Example 3.3:
import java.util.LinkedList
fun main() {
val ll = LinkedList<Int>()
ll.addFirst(2) // 2 is added to the list.
ll.addLast(10) // 10 is added to last of the list.
ll.addFirst(1) // 1 is added to first of the list.
ll.addLast(11) // 11 is added to last of the list.
ll.removeFirst()
ll.removeLast()
println("Contents of Linked List: $ll")
}
Output:
Contents of Linked List: [1, 2, 10, 11]
Contents of Linked List: [2, 10]
32
Chapter 3: Abstract Data Type Linked List
Analysis: Values are added to the back and front of the linked list. Then the values stored in the linked
list are printed. Then values are removed from the linked list from the front and back and again linked
list content is printed to the screen.
Stack
Stack is a data structure that follows the Last-In-First-Out (LIFO) principle. This means that the
element that is added last will be removed first.
Note: All the above stack operations are implemented in O(1) time Complexity.
Example 3.4:
import java.util.Stack
fun main() {
val stack = Stack<Int>()
stack.push(1)
stack.push(2)
stack.push(3)
println("Stack : $stack")
println("Stack size : " + stack.size)
println("Stack pop : " + stack.pop())
println("Stack top : " + stack.peek())
println("Stack isEmpty : " + stack.isEmpty())
}
33
Chapter 3: Abstract Data Type Stack
Output:
Stack : [1, 2, 3]
Stack size : 3
Stack pop : 3
Stack top : 2
Stack isEmpty : false
Stack is also implemented by calling push and pop methods of the ArrayDeque<T> class.
Queue
A queue is a data structure that follows the First-In-First-Out (FIFO) principle. The first element added
to the queue first would be the first to be removed, and vice versa.
Note: All the above queue operations are implemented in O(1) Time Complexity.
Example 3.5:
fun main() {
val que = ArrayDeque<Int>()
que.add(1)
que.add(2)
que.add(3)
34
Chapter 3: Abstract Data Type Queue
println("Queue : $que")
println("Queue size : " + que.size)
println("Queue peek : " + que.first())
println("Queue remove : " + que.removeFirst())
println("Queue isEmpty : " + que.isEmpty())
}
Output:
Queue : [1, 2, 3]
Queue size : 3
Queue peek : 1
Queue remove : 1
Queue isEmpty : false
Analysis: Values are added to the queue and printed to the screen. Since the queue is first-in-first-out,
the values that are added first are the first to come out of the queue.
Tree
A tree is a data structure that is organised in a hierarchy. Each element of the tree data structure is
called a node. The top node of the tree is called the root node. Each node in a tree, except the root,
has a parent node and zero or more child nodes. In the case of the last level of nodes, they have no
child. They are called leaf nodes. Where you need to store hierarchical records, the tree is the most
appropriate data structure to use.
A binary tree is a type of tree in which each node has at most two children ( 0, 1, or 2 ) which are
referred to as left child and right child.
35
Chapter 3: Abstract Data Type Binary Search Tree (BST)
The average time complexity of all the above operations on a binary search tree is O(log(n)), the case
when the tree is balanced. The worst-case time complexity is O(n) when the tree is not balanced.
Example 3.6:
import java.util.TreeSet
fun main() {
// Create a tree set.
val ts = TreeSet<String>()
// Add elements to the tree set.
ts.add("Banana")
ts.add("Apple")
ts.add("Mango")
println(ts)
println("Apple present : " + ts.contains("Apple"))
println("Grapes present : " + ts.contains("Grapes"))
ts.remove("Apple")
println("Apple present : " + ts.contains("Apple"))
}
Output:
[Apple, Banana, Mango]
Apple present : true
Grapes present : false
Apple present : false
Note: TreeSet is implemented using a binary search tree so add, remove, and contain methods have
logarithmic time complexity O(log(n)), where n is the number of elements in the set.
36
Discovering Diverse Content Through
Random Scribd Documents
CHAPTER III
A Secret Mission
On the same afternoon of Dick Thornton's coming into Belgium
Eugenia started out alone on her unexplained errand. She left her
recently acquired family in charge of the little French girl, Nicolete.
Nicolete seemed happier with the children than she had been since
her removal from France. Indeed, the three American girls had
sometimes wondered over her unfriendliness toward them and her
unusual quiet. At their first meeting she had appeared such a gay,
gypsy-like person.
But Eugenia did not walk to her engagement. By making a
tremendous effort she had managed to hire an old horse and buggy.
Then, after she felt sure the other three Red Cross girls had
departed on the road toward Brussels, she set out. Inside the wagon
she carefully hid out of sight her bag of Red Cross supplies, although
she did not wear her nurse's uniform.
Earlier in the day Barbara had brought down her suitcase, so that
she could appear in an ordinary street dress.
Driving along the road Eugenia hoped to suggest that she was only
off on an ordinary errand which could not interest any one who
chanced to observe her.
She was looking rather plain and tired and was unusually nervous,
but this it would have been difficult to guess from her quiet manner.
The country through which she passed was one of queer contrasts.
There were many houses that had been destroyed by fire, but others
that had not even been touched. In these places people were
evidently making an effort to lead an ordinary, everyday existence.
But they were all listless and discouraged. Eugenia thought that the
children must have forgotten how to play in this last year, when their
land had suffered such sorrow.
She wished that she might gather them all together in one great
circle that should extend all over Belgium and set them to laughing
and playing once more.
However, Eugenia soon left the populated part of the neighborhood.
She and her old horse wound their way along a stream and then
came to a gate. There was no house in sight from the gate, but just
as if she had been there before, Eugenia got down and opened it.
Then she tied her horse behind a clump of trees inside the woods
and with her bag of nursing supplies in her hand crept along on foot
up a narrow path. Every once and a while she would stop and
glance cautiously about her. But no one was in sight to be interested
in her proceedings. Moreover, where could she be going? She
seemed to have some end in view, and yet there was no place or
person in the vicinity. Any one familiar with the neighborhood could
have explained that Eugenia must be bent upon an utterly ridiculous
errand. There was an old house about half a mile farther along, but
it had been deserted long before the Germans had ever set foot on
conquered Belgium.
A tragedy had occurred in the house ten or fifteen years before, and
ever afterwards the place had been supposed to be haunted.
No one believed such nonsense, of course, since intelligent persons
do not believe in ghosts. But the house was too far from the village,
and was in too bad a state of repair to be a desirable residence.
Indeed, there were dozens of reasons why, after its owners moved,
no one else cared to rent it.
Moreover, the house had also escaped the interest of the German
invaders of the land. So why in the world should it be of so great
interest to Eugenia that she was making this lonely pilgrimage,
without taking any one of the three Red Cross girls into her
confidence?
The house was of brick and a large one. Every outside shutter was
closed in front and the vines had so grown over them that they were
half covered. There was a porch also in front, but the boards of the
steps had long since rotted away.
At first only a large toad appeared to greet Eugenia. He eyed her
distrustfully for a second, his round eyes bulging and his body rigid
with suspicion. Then he hopped behind his stone fortress, which
chanced to be a large stone at the end of the path before the house.
However, Eugenia did not see him. Neither did she attempt to go up
the rickety steps. How absurd it would have been anyhow to have
battered at the door of a mansion that had been uninhabited for
years!
Instead she marched deliberately around the house and knocked at
a door at the side.
A few seconds after, this door was opened by a woman of middle
age.
She looked very worn and unhappy, but her face brightened at the
sight of her guest.
"I was so afraid you wouldn't, couldn't get here," she said. "I
suppose you know you are taking a risk."
Eugenia nodded in her usual matter of fact fashion.
"I promised your friend I would do my best," she returned. "Will you
please take me up to the room. You must make up your mind to get
more air into this house. I don't think you need fear you will be
suspected, if you managed to arrive here without being detected."
"I am afraid," the older woman answered. She was leading the way
up a pair of back stairs that were in almost total darkness.
"You see, I know I have been accused of sending information to my
husband who is supposed to be at the front with the Belgian army. I
was about to be arrested and tried by a military court. I should have
been sent to prison and I could not be separated from my family at
such a time!"
The last few words were whispered. Because at this moment the
woman's hand had touched a door knob which she was gently
turning. The next she and Eugenia were entering a large room at the
back of the apparently deserted house.
A window had been opened and an attempt made to clean this
room. On the bed, with a single scanty cover over them, two
persons were lying. One of them was a young boy and the other a
man.
Both of them were extremely ill. Eugenia realized this at a glance,
but paid little attention to the man at first. For she suddenly had a
complete understanding of Madame Carton's last words.
The boy was such an exquisite little fellow of about ten years old. He
had straight golden hair and gray eyes with darker lashes. There was
the same high-bred, delicate look that one remembers in the picture
of "The Two Little Princes in the Tower."
Through a peculiar source Eugenia had already learned a portion of
Madame Carton's story. She was a Belgian woman whose home was
one of the handsomest in the city of Brussels. But after the city had
been forced to surrender to the Germans, Madame Carton had
refused to give up her home unless the authorities expelled her by
force. This for some reason they had appeared unwilling to do.
However, a short time after the German occupancy of Brussels,
reports accusing Madame Carton of treason and rebellion began to
be circulated. It was said that she was sending secret information to
her husband, who was a colonel in the Belgian army and on the
personal staff of King Albert. Finally Madame Carton learned that her
arrest was only a matter of a few hours. Then it was that she had
managed to escape to this deserted house with her family. So far it
looked as if her whereabouts had remained undiscovered.
One hour after Eugenia's arrival she and Madame Carton were once
more at the foot of the stairs. They had opened the side door to let
in a tiny streak of light and air.
"But, Madame Carton, I don't think it is possible," Eugenia
announced with her usual directness. "I am willing to do whatever I
can to help nurse your little boy and the other patient, but I can
come to you very seldom without being discovered. You see, I may
be ordered to nurse in any part of Belgium and I must do what I am
told. Is there any one here to assist you?"
Madame Carton nodded. She had once been a very beautiful woman
with the gray eyes and fair hair of her son. But the last year of
witnessing the desolation of her people and her country had
whitened her hair and made many lines in her face.
"Yes, I have an old family servant with me. I should never have been
able to make the journey without her help. She and my little girl,
who is six years old, are in hiding in another room in the attic of this
house. Years ago when I was a child I used to come here to play
with friends who then owned this place. I suppose that is why I
thought of our hiding here when the crisis came," Madame Carton
explained quietly. "Now if I return to Brussels perhaps Paul may be
cared for. But you know what else would happen. It would be
inevitable! Even if I were not shot I must go to prison. Can't you
help me? Can't you think of some way to save us all?"
The older woman took hold of Eugenia's hands and clung to them
despairingly.
"I know I am asking what looks like an impossible thing of you, and
you a complete stranger! Yet you look so strong and fine," Madame
Carton's voice broke, but Eugenia's touch was reassuring.
"If only a doctor could come to us, perhaps with your advice I might
manage the nursing myself," she continued.
Eugenia shook her head.
"When Dr. Le Page asked me to see you and gave me the directions,
he said it was only because he dared not visit you himself," Eugenia
explained kindly, but with her usual avoidance of anything but the
truth. "He insists that, although he is an American, he is suspected
of feeling too much sympathy for the Belgians. After warning you to
escape he was questioned and believes he is still being watched.
That is why he confided you to me, asking me to do the little I can
to aid you. So if he should attempt to reach you out here, it would
mean his arrest as well as yours. I am sorry," the girl ended.
Her words were simple enough in the face of so great a calamity. Yet
there was no mistaking their sympathy.
Madame Carton appeared to surrender her judgment and her
problem to Eugenia for solution.
"Tell me, Miss Peabody, what do you think I should do?" she asked.
"It is not worth while for me to say that I care little what becomes of
me. Shall I return to Brussels and give us all up to the authorities?"
Eugenia did not answer immediately. When she spoke again she
offered no explanation of her own meaning.
"Please wait a while, Madame Carton, if possible, until I can see you
again?" she asked. "In case you are not discovered before then I
may have a plan to suggest that will help you. But I cannot be sure.
Good-by and a good courage."
Then Eugenia marched deliberately back to the place where her old
horse was in waiting. She then drove unmolested to the tiny house
that was sheltering Nicolete and the three stray children.
But on her way she was repeating to herself a phrase she had
learned years before as a girl at the High School:
"Quorum omnium fortissimi sunt Belgae," said Cæsar nearly twenty
centuries ago. "The bravest of all these are the Belgians."
Eugenia thought the same thing today and for the same reason
Cæsar did. "Because they are nearest to the Germans, who dwell
across the Rhine, with whom they do continually wage war."
CHAPTER IV
Plans for the Future
The moon shone down upon Belgium as serenely as upon any
unconquered land.
Two girls were walking slowly arm in arm along a stretch of country
road. There was no one else in sight at the time, yet they seemed
entirely unafraid. A quarter of a mile beyond them, however, a dim
light burned in the window of a small frame house. Near it was a
tumbled mass of brick and stone.
"We received our orders for work this afternoon, Eugenia dear,"
Barbara remarked. "They were sorry you were not with us. But you
are to come in to headquarters as soon as possible, when
arrangements will be made for you."
Unconsciously Barbara sighed and although it was too dark in the
moonlight to distinguish the expression on her face, her companion
paused for a moment.
"Are you disappointed in what they wish you to do, Barbara, child?"
Eugenia inquired more gently than she usually spoke. "You sound
rather forlorn and 'wee' as the Scotch sometimes say. Of course, I
know you are tired from the long trip into Brussels and coming here
to spend the night with me. It is lovely to have you for this quiet
walk, but I'm afraid you'll find a bed on the floor a pretty hard
resting place even for war times."
"Oh, I shan't mind. Besides, I brought over some more bed-clothes,"
the younger girl answered, although her attention was not really
fixed upon her reply.
Eugenia had guessed correctly in thinking Barbara was tired. Her
face was very small and white, so that her eyes appeared almost
unnaturally large and blue. Her only color was in her lips, which
drooped like a weary child's.
"Oh, yes, the work is all right. One can't expect an easy time of it
these days. Besides, I hope some day to prove to you, Eugenia, that
I did not come to Europe to nurse in the Red Cross just for the sake
of an adventure. Of course, I shall never dare hope to do anything
to compare with what you have done, or to be anything like you, but
——"
Barbara's speech was interrupted by her friend's hand being laid
firmly across her lips.
"I prefer your not saying things like that," she answered in a tone
that the other girl felt obliged to respect. It was not that Eugenia
was unduly modest. Only that she had never appeared to desire to
talk about her final experience in France. Indeed, the other three
girls had been provoked before this by her reticence. It was all very
well for Eugenia not to discuss before strangers her rescue and care
of Captain Castaigne under such extraordinary difficulties. But it was
tiresome of her never to be willing to relate the details of her
experience to her most intimate companions. Personally, Barbara
Meade intended to hear the whole thing some day from beginning to
end. Then she would be able to tell the story to the Countess
Amelie, who had become her own and Nona's devoted friend. For
Captain Castaigne had given only a brief account of the
circumstances to his mother. Actually he had been as reticent in the
matter as Eugenia. However, Barbara was not in the mood tonight to
demand other people's confessions.
"If you are tired, suppose we sit down for a while," Eugenia
suggested. The two girls found a tree near by that had been
uprooted by an underground explosion and lay face down upon the
earth with its arms outspread, like a defeated giant.
Unconsciously they both sighed with relief and then smiled half
humorously at each other.
"We are all to work at the same hospital in Brussels," Barbara went
on. "At least, Mildred and Nona and I have been chosen for the
same place. I don't know about you. Thank goodness, it is an
American hospital and supported by our money!"
"Don't be prejudiced," Eugenia remonstrated.
But Barbara shook her head impatiently. "How can one help being?
You are only pretending to yourself that you are neutral. If the
Germans had been conquered, perhaps I should feel equally sorry
for them. But to me Belgium is like a gallant boy who went out with
his head up and his lips smiling to do battle with a giant. The
courage of it is like a song!"
In silence Eugenia agreed.
Then Barbara leaned her curly brown head on her companion's arm.
"I have a piece of news for you, Gene," she added. "Really, I came
to you tonight to be the first to tell you. Who do you think arrived in
Brussels today to help with the American Relief work?" Barbara did
not wait for an answer to her question. "Dick Thornton!" she finished
with a sudden indrawing of her breath.
The older girl did not glance toward her companion. Her attention
seemed to be fixed upon a particularly effective June moon which
was just emerging from a cloud-like veil.
"That is tremendously good news, isn't it? And it is great of Dick to
insist on being useful in spite of his misfortune! But perhaps I am
not so surprised as you think I ought to be, Barbara. Nona half
confessed the possibility of his turning up to me several days ago.
She told me I was not to speak of this, however, to you, because
Dick might not be able to come and he did not wish—" Eugenia
hesitated a second—"he did not wish Mildred to be disappointed.
Now I am particularly glad you are all to be in Brussels. Perhaps you
may have a chance to see Dick nearly as often as you like."
"Yes, it will be awfully nice for Mildred and Nona and I am delighted
for them," Barbara interrupted, moving several feet away from her
friend. "But I do hope you will be with us, Eugenia, to associate with
me! I hate to be in the way. And I am afraid I will be, under the
circumstances."
The younger girl had lowered her voice to the purest confidential
tone. Then, although they were quite alone, she looked carefully
around before going on.
"Perhaps I haven't any right to say so, but I am almost sure there is
a bond between Nona Davis and Dick. I didn't dream of this when
we were in Paris together. But I know they have been writing each
other constantly ever since. Besides, if you had seen their meeting
today!"
She ceased talking, for Eugenia was shaking her head in doubt.
"But isn't Nona one of the prettiest girls you ever saw and the most
charming?" Barbara demanded argumentatively the next instant.
She seemed almost angry at the older girl's silent disagreement.
This time Eugenia inclined her head.
"I have no idea of disputing Nona's beauty or charm, or Dick
Thornton's either. He is a splendid American fellow. And if one of you
Red Cross girls must fall in love, certainly I should prefer you to fall
in love with Dick. However, at present I simply don't believe there is
an affair between Dick and Nona."
"But you'll see in time," Barbara persisted.
"Yes, I'll see in time," Eugenia concluded.
Then Barbara crept closer again.
"The moonlight, or something, makes me feel dismal," she confided.
"I don't know why, but the moon gives me the blues far more than it
ever makes me romantic. Sometimes I wonder if we will ever get
back home safely, all of us, without any illness or sorrow or
anything," Barbara ended vaguely.
Eugenia could be a remarkably comforting person when she liked.
She made no reply at the moment, only drew the younger girl
toward her.
"Now I have something to tell you, Barbara. It is good of you to wish
me to be in Brussels with you, but I'm really not much good as a
companion. You girls are ever so much happier without me, I feel
sure, or I wouldn't desert you."
"Desert us?" Barbara stiffened at once, forgetting the other subject
of their conversation.
"You don't mean, Eugenia Peabody, that you have decided to give up
the Red Cross work and go back home? You, of all of us! I simply
won't believe it. Why, I thought you were the most devoted, the
most——"
Eugenia laughed half-heartedly. "I didn't say I was going home,
Barbara," she protested. "But you are right in thinking I mean to
give up my Red Cross work, at least if I am allowed to resign. I don't
know why, but recently I don't seem to feel the same fondness for
nursing. I kind of dread a great many things about it."
Barbara laid her hand caressingly upon Eugenia's knee.
Really Eugenia was growing so surprisingly human these days that
one could scarcely recall the old Eugenia.
"Oh, that is just because you are tired. I know you have always
denied this, but you have never been exactly the same since your
siege with Captain Castaigne. The responsibility and the work were
too much for you. I don't think he was ever half grateful enough!
The idea of his joining his regiment without coming to say good-by
to you—just writing a letter! Promise me you will go quietly away
somewhere and rest for a few weeks, Eugenia. Then I know you'll
feel like getting back into harness again. Really, I need you to be
with us. I haven't any backbone unless you are around to make me
afraid of you."
Eugenia shook her head. "Perhaps I shall not be very far away and
we may be able to see each other now and then. I have been
thinking of a scheme for several days, almost ever since we came
into Belgium. You remember I told you I had a good deal of money,
but did not always know just how to spend it. Well, I have found a
way here. I am going to get a big house and I am going to fill it full
to overflowing with the Belgian babies and all the children who need
an old maid mother to look after them. And I think I found the very
house I need today. It is an old place that is supposed to be haunted
and is far away from everything else. But it is big and has an old
veranda. Perhaps I'll still be doing Red Cross work if I take care of
well babies as well as sick ones. Do you think I'll make a great
failure as a mother, Bab?" she ended.
Without replying Barbara's answer was yet sufficiently reassuring.
At the same time she was wondering if these past few months had
changed Eugenia as much as she appeared to be changed. But
perchance she had always been mistaken in her view of her.
Then both girls started suddenly to their feet. For the little French
girl, Nicolete, had come upon them unawares. She gave Barbara a
glance revealing but little affection. Then beckoning Eugenia
mysteriously aside she soon ran off again like a sprite in the
moonlight.
CHAPTER V
St. Gudula
Several weeks later Barbara Meade walked down the steps of a
house in Brussels out into one of the streets near the Palais de la
Nation. The house had once been a private residence, but since the
coming of war into the heart of Belgium had been turned into a
relief hospital by the American Red Cross Society.
Barbara walked slowly, looking at all the objects of interest along the
way. She wore a dark-blue taffeta suit and white blouse and a small
blue hat with a single white wing in it.
Evidently she was not in a hurry. Indeed, she behaved more like an
ordinary tourist than an overworked nurse. Yet a glance into
Barbara's face would have suggested that she was dreadfully fagged
and anxious to get away from the beaten track for a few hours. It
chanced to be her one afternoon of leisure in the week, so for the
time she had discarded her nurse's uniform. She was also trying to
forget the trouble surrounding her and to appreciate the beauty and
charm of Brussels.
Yet Barbara found it difficult to get into a mood of real enjoyment.
These past few weeks represented the hardest work she had yet
done, for the funds for the Belgian Relief work were getting painfully
low. Therefore, as there were still so many demands, the workers
could only try to do double duty.
Finally Barbara entered the church of St. Gudula, which happened to
be near at hand. It was a beautiful Gothic building, dedicated to the
patron saint of Brussels. Once inside, the girl strolled quietly about,
feeling herself already rested and calmed from the simple beauty of
the interior. The tall rounded pillars and sixteenth century stained
glass represented a new world of color and beauty. Although she
was not a Catholic, Barbara could not refrain from saying a short
prayer in the "Chapel of Notre-Dame-de-Deliverance" for the safety
of the Belgian people and their gallant king and queen. Barbara was
too loyal an American to believe that kings and queens were any
longer useful as the heads of governments. Nevertheless, as a noble
man and woman, King Albert and Queen Elizabeth of Belgium,
commanded her admiration and sympathy. Since the outbreak of the
war neither of them seem to have given thought to their royalty,
remembering only their common humanity with the people of their
land.
Already comforted by the few minutes of quiet, finally Barbara
slipped out of one of the side doors that chanced to be open.
Afterwards she stood looking about her in order to find out just
where she was.
The side street was almost entirely free from passers by. Therefore,
as Barbara desired to inquire her way to the nearest tram line, she
waited for a moment. At some distance down the street she could
see the figure of a man walking in her direction.
She did not look very closely or she might have discovered
something familiar in the quick stride and the graceful carriage of
the head and shoulders. The men of Brussels are rather more French
than Flemish in their appearance, yet this man did not resemble a
foreigner.
Indeed, he walked so much more rapidly than Barbara expected that
she was extremely startled when a voice said close beside her:
"Why, Barbara, this is good luck. To think I have not seen you since
the first afternoon of my arrival! I'm sorry you have been so
tremendously busy every time I have had a chance to run into the
hospital for a few moments. But Mildred and Nona have given me
news of you."
Dick Thornton had taken Barbara's hand and was looking searchingly
into her face. But after her first recognition of him she had dropped
her lids, so it was not possible to see her eyes.
"I have just been up to your hospital now, but could not get hold of
either Mildred or Nona. I am sorry. Nona had promised me, if she
could be spared, to spend the afternoon seeing sights. I have
investigated thirty destitute Belgian families since eight o'clock this
morning and reported their cases, so I feel rather in the need of
being cheered."
Barbara's chin quivered a little, although it was not perceptible to
her companion.
"I am dreadfully sorry too," she answered the next instant.
"Certainly you are deserving of Nona's society for a reward. And if I
had only known your plan you might have carried it out. It is my
afternoon of freedom, but I would very cheerfully have changed my
time with Nona."
"You are awfully kind, I am sure," Dick returned. But he scarcely
showed the gratitude at Barbara's suggestion that she expected.
He glanced up at the beautiful Gothic tower of the church near
them, remarking irritably, "I expect you are quite as much in need of
a rest as any one else. Really, Barbara, it is all very well to do the
best one can to help these unfortunate people, but there is no
especial point in killing yourself. You look wretchedly. You are not
trying to play at being the patron saint of Brussels, are you? Is that
why you haunt the church of Saint Gudula?"
Barbara smiled. "I am the farthest person from a saint in this world,"
she replied, wrinkling up her small nose with a faint return to her old
self. "Nona and Mildred and I have decided recently that we haven't
but one saint among us. And she is the last person I should ever
have awarded the crown at our first meeting. Moreover, I wouldn't
dare present it to her now, if she could see or hear me in the act.
She would probably destroy me utterly, because my saint is very
human and sometimes has a dreadful temper, besides a desire to
boss everybody else. I wonder if real saints ever had such traits of
character? Of course, you know I mean Eugenia! I am on my way
now to her Hotel des Enfants, if I can ever find the right street car.
She already is taking care of twelve children, and I have never seen
her nor her house since we separated. Gene has promised to send
some one to meet me at the end of the car line. Her house is a
deserted old place where a ghost is supposed to hold forth. But I am
assured the ghost has not turned up recently. It is nice to have met
you. Good-by." And Barbara was compelled to stop talking for lack of
breath after her long speech, as she held out her hand. Dick ignored
the outstretched hand. His face had assumed a charming, boyish
expression of pleading. Barbara was reminded of the first days of
their meeting in New York City.
"I say, Barbara, why can't I go along with you?" he demanded. "Of
course, I realize that for some reason or other you are down upon
me. I am not such a chump as not to understand you could have
seen me for a few minutes in these last few weeks if you had tried.
But Eugenia is friendly enough. I haven't seen her, but I had a
stunning note from her. Besides, as I sent her five of her twelve
Belgian babies, I think I've the right to find out if she is being good
to them. I am a kind of a godfather to the bunch. Let's stop by a
shop and get some stuffed dolls and whistles and sugar plums.
Some of the Belgian children I have discovered seemed to be
forgetting how to play."
Barbara had not answered. Indeed, Dick had not intended to give
her a chance. Nevertheless, her expression had changed to a
measure of its former brightness. It would be good fun to have Dick
on the afternoon's excursion! She had rather dreaded the journey
alone into a strange part of the countryside, one might so easily get
lost. Beside, Barbara knew in her heart of hearts that she had
absolutely no right for her unfriendly attitude toward Dick Thornton.
If he had chosen to treat her with less intimacy than in the
beginning of their acquaintance, that was his own affair. If he now
preferred Nona to her—well, he only showed a better judgment in
desiring the finer girl.
Barbara now put her hand in a friendly fashion on Dick's sleeve.
"I am awfully glad to have you come along and I am sure Gene will
be," she answered happily. "Lead on, Sir Knight, to the nearest
street car."
After an hour's ride into the country, through one of Belgium's
suburbs, Dick and Barbara arrived at a tumble-down shed. Eugenia
had carefully described this shed as their first destination.
Not far off they found Bibo waiting for them with a rickety old wagon
and an ancient horse. Money and Eugenia's determined character
had secured the forlorn equipage. For it was difficult to buy any kind
of horse or wagon in these war days.
However, the small driver, who was the boy Eugenia had rescued
some weeks before, drove with all the pomp of the king's coachman.
That is, he allowed the old horse to pick her way along a grass-
grown path for about a mile. Then he invited his two passengers to
get down, as there was no road up to the old house that a horse
and wagon could travel.
So Dick and Barbara found themselves for the first time in their
acquaintance wandering along a country lane together. Their
position was not very romantic, however. Barbara led the way along
the same narrow avenue that Eugenia had followed on the day of
her first visit to the supposedly deserted place.
Yet although Barbara almost ran along in her eagerness to arrive,
Dick noticed that she looked very thin. She was not the Barbara of
his first acquaintance; something had changed her. Well, one could
hardly go through the experiences of this war without changing,
even if one were only an outsider. And Dick Thornton glanced at his
own useless arm with a tightening of his lips. He probably owed his
life to the little girl ahead of him.
Eugenia did not at first see her guests approaching until they had
discovered her. She was in the front yard and the grass had been
cut, so that there was a broad cleared space. Moreover, every
window of the supposedly haunted house was thrown wide open, so
that the sun and air poured in.
It was as little like either a deserted or a haunted house as one
could humanly imagine. For there were eight or ten children at this
moment in the yard with Eugenia. She held a baby in her arms and a
small boy stood close beside her.
Barbara saw the little fellow at the same moment she recognized her
friend. Instantly she decided that he was the most exquisite child
she had ever seen in her life. The boy was like a small prince,
although he wore only the blue cotton overalls and light shirt such as
the other boys wore.
But he must have said something to Eugenia, for she glanced up and
then ran forward to meet her guests. The baby she dumped hastily
into her discarded chair.
"But I thought I was to be your guest of honor, Gene?" Barbara
protested a few moments later. "Never should I have allowed Dick to
come if I had dreamed he was to put me in the shade so
completely."
Eugenia laughed. Her new responsibilities did not appear to have
overburdened her.
"Come and meet my family," she insisted. "There was an old woman
who lived in a shoe, who had so many children she didn't know what
to do."
CHAPTER VI
The Locked Door
"But she seems to me a very unusual person to be a servant, Gene,"
Barbara remarked argumentatively. "Of course, I know she was
wearing a maid's apron and cap so that her hair was completely
hidden, and her dark glasses concealed her eyes. Still, I could see
very plainly the woman you call 'Louise' is not an everyday servant.
She spoke to Dick and me with perfect self-possession, although she
did seem nervous. But it is ridiculous to think one can hide a
personality under such a slight disguise."
Barbara spoke pettishly. She and Eugenia were wandering about the
big house together. They were looking over the arrangements
Eugenia had made for her recently acquired family. These were, of
course, of the most primitive kind. There were about eighteen army
cots in the bedrooms, some light coverings, and a few wooden
chairs. In the big front room downstairs long planks had been laid
across wooden supports. This formed a large and informal dining
room table. Yet by accident this same room contained a magnificent
Flemish oak sideboard that had been left in the house by the former
owners of the place.
However, Barbara and Eugenia were in Eugenia's own bedroom
when the present conversation started. They had already seen the
lower floor of the house, where Barbara had been introduced to
Eugenia's cook, who was a plain Flemish woman. But it was the
history of the housemaid, a woman of between forty and fifty, whose
identity Barbara was questioning.
In reply Eugenia gazed at her friend earnestly for a few moments
and then slowly shook her head.
"These are war times, Bab. I thought you and I had agreed long ago
to ask no unnecessary questions."
Eugenia had seated herself on the side of her cot bed, Barbara was
on a high wooden box, which served as a chair, near the window.
She did not reply at first, but this was merely because she was
thinking, not because she intended to consider Eugenia's suggestion.
She had one foot crossed under her, while the other swung in the
air. Her brow was wrinkled into a painfully heavy frown for so
miniature a person. Unconsciously Barbara pulled meditatively at a
brown curl that had escaped from the knot at the back of her head.
During her long study Eugenia smiled at her guest. She too could
not grow accustomed to considering Barbara as responsible a person
as the rest of the Red Cross girls. This was only because of her
appearance, for she had learned to have faith in her.
All of a sudden Barbara began talking again, just where she had left
off.
"It is all very well to preach, Gene, about not asking unnecessary
questions because we are living and working in war times. But you
know very well we never expected that point of view to apply to
asking questions of each other. We came abroad as strangers,
except that Mildred and I knew each other slightly, but since then we
have become friends. At least, we care a great deal about each
other's interests. Now I don't think for a minute we have the right to
keep secrets from one another. That is, unless they happen to be of
a kind one simply can't bear to tell." And at this Barbara hesitated
for an instant.
"But about this woman, this 'Louise', we were discussing. Eugenia,
you know perfectly well she isn't a real servant. I am dreadfully
afraid you are hiding some one and it may get you into serious
trouble," the younger girl continued, making no effort to hide her
anxiety. "Really, you ought to be careful, Gene. You came to Europe
to act as a Red Cross nurse, not to interfere with questions of
government. If you do, you may be put into prison, or something
else dreadful. Do you know I thought all along it was funny your
deciding so suddenly to give up your Red Cross work and then
knowing exactly where to find a house. Well, I might as well tell
you," Barbara now got off her stool and came over and put a hand
on either of her friend's shoulders, "I mean to find out what you are
trying to hide if I possibly can," she concluded.
Eugenia did not stir. But she let her own dark eyes rest gravely upon
Bab's blue ones.
"Please don't," she asked. "I suppose I might have guessed that you
would have discovered there is something unusual about my family.
But, Bab, I want you to promise me on your honor that you will not
mention your suspicion to any one—not to Nona, or Mildred, or Dick
Thornton. I am trying in a fashion to help some one who is in deep
trouble. As you have guessed, she is a woman, and that was her
little boy, Jan, whom you saw standing by me when you arrived. But
if questions are asked of you, Barbara, you know absolutely nothing
of this. I prefer to manage my own affairs."
Eugenia made this announcement in her haughtiest fashion.
However, her companion was not deceived. Eugenia simply meant
that if disaster followed her attempt to shield a prisoner, she alone
must bear the penalty.
Quietly for another moment, still with her hands on the older girl's
shoulders, Barbara continued to consider the situation.
"I won't make you any promises, Gene," she answered at last. "I
must decide what to do later. But I won't tell Nona, or Mildred, or
Dick, as I can't see any special point in confiding in them at present.
However, I am not willing to stand aside and let you run deliberately
into danger. It was all very well your taking care of Captain
Castaigne. He was desperately ill. Your finding him wounded on the
battlefield was so romantic. But this is quite a different affair. We
were under certain obligations to the Countess Amelie, while this
'Louise' and her 'Jan' are utter strangers. I think I'll go this instant
and tell the woman she has no right to make you undergo such
risks."
Again Eugenia did not stir, but this time neither did Barbara.
"You will do no such thing, my dear; you must let me manage my
life for myself," she declared quietly instead. "Of course, I am not
going to take any more chances than I must. Come now, let us go
downstairs and have tea. You and Dick were angels to have come on
such a long journey and you must be nearly famished. I have
managed to get a few supplies in Brussels and I have sent to Boston
for a great many more. So when you girls are able to visit me, we
can at least regale ourselves with a Boston Tea Party."
Eugenia put an arm across Barbara's shoulder as they moved toward
the door.
A few feet further on the younger girl stopped. "Are you very rich,
Eugenia Peabody?" she demanded. "Unless you are, it is perfectly
mad for you to have undertaken the expenses of this household.
Most of these children have not had anything to eat for a year and
must be nearly famished."
Eugenia nodded. "I suppose I am fairly wealthy, although I find it
hard to realize it, as I grew up such a poor girl."
"Then why—why, Eugenia (I have been simply dying to ask you this
ever since you told us you were rich)—why did you wear such old-
fashioned—if you will excuse me—such perfectly awful clothes?"
Barbara fairly shuddered, recalling how she and Nona and Mildred
had suffered over Eugenia's ancient Alpine hat.
But Eugenia only laughed. She had been sensitive enough over the
other girls' attitude toward her appearance when they first knew one
another. But Barbara's way of expressing things was too absurd.
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.
ebooknice.com