100% found this document useful (2 votes)
27 views

Data Structures & Algorithms using Kotlin, Second Edition Hemant Jain - Own the complete ebook with all chapters in PDF format

Data

Uploaded by

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

Data Structures & Algorithms using Kotlin, Second Edition Hemant Jain - Own the complete ebook with all chapters in PDF format

Data

Uploaded by

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

Read Anytime Anywhere Easy Ebook Downloads at ebookmeta.

com

Data Structures & Algorithms using Kotlin, Second


Edition Hemant Jain

https://ebookmeta.com/product/data-structures-algorithms-
using-kotlin-second-edition-hemant-jain/

OR CLICK HERE

DOWLOAD EBOOK

Visit and Get More Ebook Downloads Instantly at https://ebookmeta.com


Recommended digital products (PDF, EPUB, MOBI) that
you can download immediately if you are interested.

Problem Solving in Data Structures Algorithms Using C 2nd


Edition Hemant Jain

https://ebookmeta.com/product/problem-solving-in-data-structures-
algorithms-using-c-2nd-edition-hemant-jain/

ebookmeta.com

A Common Sense Guide to Data Structures and Algorithms


Second Edition Jay Wengrow

https://ebookmeta.com/product/a-common-sense-guide-to-data-structures-
and-algorithms-second-edition-jay-wengrow/

ebookmeta.com

Data Structures & Algorithms in Python John Canning

https://ebookmeta.com/product/data-structures-algorithms-in-python-
john-canning/

ebookmeta.com

Working with Dynamical Systems: A Toolbox for Scientists


and Engineers (Series in Computational Biophysics) 1st
Edition Len Pismen
https://ebookmeta.com/product/working-with-dynamical-systems-a-
toolbox-for-scientists-and-engineers-series-in-computational-
biophysics-1st-edition-len-pismen/
ebookmeta.com
Apostles of Transformation Anthology of Muslim Women
Trailblazers in India Akhtarul Wasey Juhi Gupta Eds

https://ebookmeta.com/product/apostles-of-transformation-anthology-of-
muslim-women-trailblazers-in-india-akhtarul-wasey-juhi-gupta-eds/

ebookmeta.com

Find Your Way Home (Small Town Dreams #1) 1st Edition
Jackie Ashenden

https://ebookmeta.com/product/find-your-way-home-small-town-
dreams-1-1st-edition-jackie-ashenden/

ebookmeta.com

MrExcel 2022 Boosting Excel 6th Edition Bill Jelen

https://ebookmeta.com/product/mrexcel-2022-boosting-excel-6th-edition-
bill-jelen-2/

ebookmeta.com

India–Africa Partnerships for Food Security and Capacity


Building : South–South Cooperation 1st Edition Renu Modi

https://ebookmeta.com/product/india-africa-partnerships-for-food-
security-and-capacity-building-south-south-cooperation-1st-edition-
renu-modi/
ebookmeta.com

Epicurus and the Singularity of Death 1st Edition David B.


Suits

https://ebookmeta.com/product/epicurus-and-the-singularity-of-
death-1st-edition-david-b-suits/

ebookmeta.com
Digitalization and Analytics for Smart Plant Performance
Theory and Applications 1st Edition Frank (Xin X.) Zhu

https://ebookmeta.com/product/digitalization-and-analytics-for-smart-
plant-performance-theory-and-applications-1st-edition-frank-xin-x-zhu/

ebookmeta.com
Data Structures &
Algorithms using
Kotlin
Second Edition

By Hemant Jain

Подписывайся на топовый канал по Kotlin:

https://t.me/KotlinSenior
Data Structures & Algorithms using Kotlin
Hemant Jain

Copyright © Hemant Jain, 2022. All Right Reserved.

Hemant Jain asserts the moral right to be identified as the author of this work.

All rights reserved. No part of this publication may be reproduced, stored in or


introduced into a retrieval system, or transmitted, in any form, or by any means
(electrical, mechanical, photocopying, recording or otherwise) without the prior written
permission of the author, except in the case of very brief quotations embodied in
critical reviews and certain other non-commercial uses permitted by copyright law. Any
person who does any unauthorised act in relation to this publication may be liable to
criminal prosecution and civil claims for damages.
ACKNOWLEDGMENT

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

What this book is about


This book will take you through basic to advanced data structures and algorithms. Data structures
define how data is arranged in memory for fast and efficient access. An algorithm is a finite set of
unambiguous instructions to solve problems by manipulating various data structures.

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.

Who should take this course ?


If you’re planning to pursue a career in the Kotlin language, get better at it and apply for a job, this
book is best for you. If you can put a reasonable amount of time into this book by reading various
concepts and solving the various problems on data structures, you can become an expert in data
structures and algorithms.

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 properties of an algorithm are:


1. It takes zero or more inputs.
2. It should produce one or more output.
3. It should be Deterministic. It produces the same output if the same input is provided again.
4. It should be Correct. It should be correct and able to process all the given inputs and provide the
correct output.
5. It should Terminate in a finite time.
6. It should be Efficient. The algorithm should be efficient in solving 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.

There are two types of Complexity:


1. First is Time-Complexity, how much time is required by an algorithm to produce output for an
input of size ‘n’.
Time-Complexity is represented by function T(n) - time required versus the input size n.
2. Second is Space-Complexity, how much RAM or memory that an algorithm is going to
consume to produce output for an input of size ‘n’.
Space-Complexity is represented by function S(n) - memory used versus the input size n.

Asymptotic Analysis or Asymptotic Notations


Calculating the running time of any algorithm in mathematical units of computation is known as
Asymptotic Analysis. The efficiency of algorithms is calculated using asymptotic analysis, independent
of the given data set or programming language.

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

Example : n^2 + n = O(n^2)

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)

Find relationship of f(n) = nc and g(n) = cn


f(n) = Ω(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).

Example: n^3 + n^2 + n = Ɵ(n^3)


Example: n^2 + n = Ɵ(n^2)
Find relationship of f(n) = 2n^2 + n and g(n) = n^2
f(n) = O(g(n))
f(n) = Ɵ(g(n))
f(n) = Ω(g(n))

Complexity analysis of algorithms


The complexity of an algorithm are analysed in three categories:
➢ Worst-Case Complexity: The worst-case complexity represents the maximum number of steps
required to execute an algorithm. It provides us with the upper bound of an algorithm. Usually, we
use this complexity to judge algorithm performance.
➢ Best-Case Complexity:The best-case complexity represents the minimum number of steps
required to execute an algorithm. It provides us with the lower bound of an algorithm.
➢ Average-Case Complexity:The average-case complexity represents the average number of steps
required to execute an algorithm. We take the average of the steps executed in all the cases to
calculate average-case complexity.

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.

Constant Time, O(1)


An algorithm is said to run in constant time if the output is produced in constant time, regardless of the
input size.

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.

Linear Time, O(n)


An algorithm is said to run in linear time if the execution time of the algorithm is directly proportional to
the input size.

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)

Logarithmic Time, O(log(n))


An algorithm is said to run in logarithmic time if the execution time of the algorithm is proportional to
the logarithm of the input size. In each step of an algorithm, a significant portion (e.g. half portion) of
the input is pruned/rejected out without traversing it.

An example is the Binary search algorithm. We will read about this algorithm in this book.

n.log(n) Time, O(n.log(n))


An algorithm is said to run in n*log(n) time if the execution time of an algorithm is proportional to the
product of input size and logarithm of the input size. In these algorithms, each time the input is divided
into half (or some proportion) and each portion is processed independently.

Examples are Merge-Sort, Quick-Sort (average case), Heap-Sort etc.

5
Chapter 1: Algorithms Analysis Growth of functions

Quadratic Time, O(n^2)


An algorithm is said to run in quadratic time if the execution time of an algorithm is proportional to the
square of the input size. In these algorithms, each element is compared with all the other elements.
Examples are Bubble-Sort, Selection-Sort, Insertion-Sort

Exponential Time O(2^n)


In these algorithms, all possible subsets of elements of input data are generated. Its common example
is the power set.

Factorial Time O(n!)


In these algorithms, all possible permutations of the elements of input data are generated. Finding
permutations is a common example of factorial time.

A list of commonly occurring algorithm Time Complexity in increasing order:


Name Notation
Constant O(1)
Logarithmic O(log(n))
Linear O(n)
N.Log(N) O(n.log(n))
Quadratic O(n^2)
Polynomial O(n^c) c is a constant & c>1
Exponential O(c^m) c is a constant & c>1
Factorial O(n!)
N-Power-N O(n^n)

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:

Function Growth Rate (Approximate)


N O(1) O(log(n)) O(n) O(n.log(n)) O(n^2) O(n^3) O(2^n)

10 1 3 10 30 102 103 103


102 1 6 102 6x102 104 106 1030
103 1 9 103 9x103 106 109 10300
104 1 13 104 13x104 108 1012 103000
105 1 16 105 16x105 1010 1015 1030000
106 1 19 106 19x106 1012 1018 10300000

6
Chapter 1: Algorithms Analysis Deriving an Algorithm's Runtime Function

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

Time Complexity Examples


Example 1.1: Single loop
fun fun1(n: Int): Int {
var m = 0
for (i in 0 until n) {
m += 1
}
return m
}

// Testing code.
fun main() {
println("N = 100, Number of instructions O(n):: " + fun1(100))
}

Output:
N = 100, Number of instructions in O(n)::100

Time Complexity: O(n), single loop takes linear time.

7
Chapter 1: Algorithms Analysis Time Complexity Examples

Example 1.2: Nested loops


fun fun2(n: Int): Int {
var m = 0
for (i in 0 until n) {
for (j in 0 until n) {
m += 1
}
}
return m
}

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

Example 1.3: Triple nested loops


fun fun3(n: Int): Int {
var m = 0
for (i in 0 until n) {
for (j 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^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.

Example 1.4: Triple nested loops


fun fun4(n: Int): Int {
var m = 0
for (i in 0 until n) {
for (j in i until n) {
for (k in j+1 until n) {
m += 1
}
}

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)

Example 1.5: Arithmetic Progression


fun fun5(n: Int): Int {
var m = 0
for (i in 0 until n) {
for (j in 0 until i) {
m += 1
}
}
return m
}

// 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).

Example 1.6: Arithmetic Progression


fun fun6(n: Int): Int {
var m = 0
for (i in 0 until n) {
for (j in i downTo 0) {
m += 1
}
}
return m
}

// 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).

Example 1.7: Nested loops / Geometric Progression


fun fun7(n: Int): Int {
var m = 0
var i = n
while (i > 0) {
var j = 0
while (j < i) {
m += 1
j++
}
i /= 2
}
return m
}

// 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)

Example 1.8: Geometric Progression


fun fun8(n: Int): Int {
var m = 0
var i = 1
while (i <= n) {
var j = 0
while (j <= i) {
m += 1
j++
}
i *= 2
}
return m
}

// 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)

Example 1.9: Double the iteration variable


fun fun9(n: Int): Int {
var m = 0
var i = 1
while (i < n) {
m += 1
i = i * 2
}
return m
}

// 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))

Example 1.10: Half the iteration variable


fun fun10(n: Int): Int {
var m = 0
var i = n
while (i > 0) {
m += 1
i = i / 2
}
return m
}

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

The initial value of i is n. In each iteration, the value of “i” is halved.


So the value of i after k iterations will be n/2^k.

11
Chapter 1: Algorithms Analysis Time Complexity Examples

At the time of exit, n/ 2^k = 1


n = 2^k // At the time of exit.
log(2^k) = log(n) // Taking log both sides.
k = log(n)
Time Complexity: O(log(n))

Example 1.11: Consecutive Statements


fun fun11(n: Int): Int {
var m = 0
for (i in 0 until n) {
for (j in 0 until n) {
m += 1
}
}

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)

Example 1.13: Multiple loops in O(n)


fun fun13(n: Int): Int {
var m = 0
var i = 0
var j = 0
while (i < n) {
while (j < n) {
m += 1
j++
}
i++
}
return m
}

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

Three important properties of the recursive algorithm are:


1. A recursive algorithm must have a termination condition.
2. A recursive algorithm must change its state, and shift state towards the termination condition.
3. A recursive algorithm must be capable of calling 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.

Example 1. 14: Factorial Calculation.


fun factorial(i:Int):Int {
// Termination Condition
if (i <= 1) {
return 1
}
// Body, Recursive Expansion
return i * factorial(i - 1)
}

// Testing code.
fun main() {
println("Factorial:" + factorial(5))
}

Output:
Factorial:120

Analysis: We calculate factorial(i) as i*factorial(i-1) recursively.

Function F(n) calls F(n-1)


T(n) = T(n-1) + 1
T(n-1) = T(n-2) + 1
T(n-2) = T(n-3) + 1
T(n) = T(n-1) + 1 = (T(n-2) + 1) + 1 = T(n-2) + 2 = (T(n-3) + 1) + 2 = T(n-3) + 3
Similarly, for kth term T(n) = T(n-k) + k
for base case (n-k) = 1 or n – 1 = k
T(n) = T(1) + n -1 = n
Time Complexity is O(n)

Print Base 16 Integers


Problem: Given an integer in decimal form, print its hexadecimal form. Use recursion to solve the
problem.

Example 1.15: Generic print to some specific base method.


fun printInt(numberInput:Int, base:Int) {
var conversion = "0123456789ABCDEF"
var number = numberInput
var digit = conversion[number % base]

number = number / base


if (number != 0) {
printInt(number, base)
}
print(digit)
}

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.

Time Complexity is O(n), Where n is the number of 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

towerOfHanoi(num - 1, src, temp, dst)


println("Move " + num + " disk from peg " + src + " to peg " + dst)
towerOfHanoi(num - 1, temp, dst, src)
}

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

Greatest Common D ivisor (GCD)


Problem: Find the greatest common divisor of two numbers using recursion.

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
}

return fibonacci(n-1) + fibonacci(n-2)


}

// Testing code.
fun main() {
println(fibonacci(10));
}

Output:
55

Analysis: Recurrence Relation: T(n) = 1 + T(n-1) + T(n-2)


T(n) = 1 + 2T(n-1) // Approximately
T(n) = 1 + 2T(n-1)
T(n-1) = 1 + 2T(n-2)
T(n-2) = 1 + 2T(n-3)
T(n) = 1 + 2( 1 + 2T(n-2)) = 1 + 2 + 4T(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 is O(2^n), ignoring the constants.

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

Complexities from Recurrence Relation


Example 1.19: Find complexity of the function with the following recurrence relation.
T(n) =
{T (n−1 1)+1if n=0if n> 0
Solution:
T(n) = T(n-1) + 1
T(n-1) = T(n-2) + 1
T(n-2) = T(n-3) + 1
T(n) = ( T(n-2) + 1) + 1 = T(n-2) + 2 = (T(n-3) + 1) + 2 = T(n-3) + 3
T(n) = T(n-k) + k
base case when T(0) = 1, n-k = 0 => n = k
T(n) = T(0) + n = 1 + n
Time Complexity is O(n)

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

T(n) = T(n-k) + klog(n)


base case when T(0) = 1, n-k = 0 => n = k
T(n) = T(0) + n*log(n) = 1 + n.log(n)
Time Complexity is O(n.log(n))

Recurrence Relation Time-Complexity


T(n) = T(n-1) + 1 O(n)
T(n) = T(n-1) + n O(n^2)
T(n) = T(n-1) + log(n) O(n.log(n))
T(n) = T(n-c) + 1 , c is a constant O(n) , complicity is not changed by c.
T(n) = T(n-c) + b , c is a constant and b is a polynomial O(n*b), generalised above 4 cases.

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

T(n) = 2 ( 2 T(n/22) + (n/2) ) + n = 22 T(n/22) + 2n


T(n) = 22 ( 2 T(n/23) + (n/22) ) + 2n = 23T(n/23) + 3n
T(n) = 2^k.T(n/2^k) + kn
base case when n = 2^k,
k = log(n)
T(n) = n*T(1) + k*n
T(n) = n + k*n = n + n*log(n)
Time Complexity is O(n.log(n))

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.

It is possible to determine an asymptotic tight bound in these three cases:


logba-ε logba
Case 1: When f(n) = O(n ) and constant Є > 1, then the final time complexity is T(n) = O(n )

Case 2: When f(n) = Θ(n


logba.
logkn) and constant k ≥ 0, then the final time complexity is

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))

Master theorem flow diagram

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)

Example 1.29: T(n) = 2 T(n/2) + n^2


Solution: In this example, a is equal to 2 and b is also equal to 2. So, logba = log22 = 1
Which means, f(n) = n^2 = Ω(nlog22 + 1). That means case 3 is applied and T(n) = Θ(f(n)).
So, its final time complexity will be T(n) = Θ(n^2)

Example 1.30: T(n) = 4 T(n/2) + n^2


Solution: In this example, a is equal to 4 and b is equal to 2. So, logba = log24 = 2.
Which means, f(n) = n^2 = Θ(nlog24log0n). That means case 2 is applied and T(n) = Θ(nlog24log0+1n).
So, its final time complexity will be T(n) = Θ(n^2 * log n)

Example 1.31: T(n) = T(n/2) + 2n


Solution: In this example, a is equal to 1 and b is equal to 2. So, logba = log21 = 0
Which means, f(n) = 2n = Ω(nlog21 + 1). That means case 3 is applied and T(n) = Θ(f(n)).
So, its final time complexity will be T(n)= Θ(n)

Example 1.32: T (n) = 16T (n/4) + n


Solution: In this example, a is equal to 16 and b is equal to 4. So, logba = log416 = 2.
Which means, f(n) = n = O(nlog416 - 1). That means case 1 is applied and T(n) = Θ(nlog416).
So, its final time complexity will be T(n)= Θ(n^2)

Example 1.33: T (n) = 2T (n/2) + n log n


Solution: In this example, a is equal to 2 and b is also equal to 2. So, logba = log22 = 1
Which means, f(n) = n.log(n) = Θ(nlog22log1n ). That means case 2 is applied and T(n) = Θ(nlog22log1+1n).
So, its final time complexity will be T(n) = Θ(n log2(n))

Example 1.34: T(n) = 2 T(n/4) + n0.5


Solution: In this example, a is equal to 2 and b is equal to 4. So, logba = log42 = 0.5
Which means, f(n) = n0.5= Θ(nlog42log0n). That means case 2 is applied and T(n) = Θ(nlog42log0+1n).
So, its final time complexity will be T(n) = Θ(n0.5 log(n))

22
Chapter 1: Algorithms Analysis Master Theorem

Example 1.35: T(n) = 2 T(n/4) + n0.49


Solution: In this example, a is equal to 2 and b is equal to 4. So, logba = log42 = 0.5
Which means, f(n) = n0.49 = O(nlog42 – 0.01). That means case 1 is applied and T(n) = Θ(nlog42).
So its final time complexity will be T(n) = Θ(n0.5)

Example 1.36: T (n) = 3T (n/3) + √ n


Solution: In this example, a is equal to 3 and b is also equal to 3. So, logba = log33 = 1
Which means, f(n) = n = O(nlog33 - 1/2). That means case 1 is applied and T(n) = Θ(f(n))
So, its final time complexity will be T(n) = Θ(n)

Example 1.37: T (n) = 3T (n/3) + n/2


Solution: In this example, a is equal to 3 and b is also equal to 3. So, logba = log33 = 1
Which means, f(n) = n = Θ(nlog33log0n). That means case 2 is applied and T(n) = Θ(nlog33log0+1n)
So, final time complexity will be T(n) = Θ(n.log(n))

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.

Five steps for solving algorithm design questions are:


1. Constraints
2. Ideas Generation
3. Complexities analysis
4. Coding
5. Testing

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.

The basic guideline for the Constraints for an array of numbers:


1. How many numbers of elements are there in an array?
2. What is the range of value in each element? What is the min and max value?
3. What is the kind of data in each element? Is it an integer or a floating point?
4. Does the array contain unique data or not?

24
Chapter 2: Approach to Solve Problems Constraints

The basic guideline for the Constraints for an array of strings:


1. How many total numbers of elements are there in the array?
2. What is the length of each string? What is the min and max length?
3. Does the array contain unique data or not?

The basic guideline for the Constraints for a Graph


1. How many nodes are there in the graph?
2. How many edges are there in the graph?
3. Is it a weighted graph? What is the range of weights?
4. Does the graph have directed edges, or undirected edges?
5. Does the graph have a loop?
6. Does the graph have a negative sum loop?
7. Are there any self-loops in the graph?

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.

Try to simplify the task at hand


Let’s look into the following problem: Husbands and wives are standing at random in a line. Husbands
have been numbered, H1, H2, H3 and so on. Wives have been numbered, W1, W2, W3 and so on.
You need to arrange them so that H1 will stand first, followed by W1, then H2 followed by W2 and so
on.

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.

Try a few examples


In the above problem, if you try the above problem with an example of three husband-wife pairs then
you can get the same formula as shown in the previous section. Using more examples will also assist
in solving the problem.

Think of a suitable data-structure


It’s simple to figure out which data structure would be more appropriate for some specific problems.
Throughout this book, we will see a variety of data structures. We must determine which data structure
would best meet our requirements.

Problem 1: If we want to find the minimum and maximum of a given sequence.


Analysis: The heap is most likely the data structure we’re searching for.

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.

Following are some test cases to check:


• Normal test cases: These are the positive test cases, which contain the most common
scenario, and the emphasis is on the functioning of the code’s base logic.
For example, if we are solving some problems for a linked list, then this test may contain, what
happens when a linked list with three or four nodes is given as input. Before declaring the code
complete, you should always think about these test cases.
• Edge cases: These are the test cases, which are used to test the boundaries of the code.
Edge cases can help to make your code more robust. We must add checks in the code to
handle edge cases.
For example, we can generate edge cases with the same linked list algorithm to see how the
code reacts when an empty list or only one node liar is passed.

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.

Let’s look at these questions one by one.


Question 1: What is the kind of data? Are they integers?
Answer: Yes, they are integers.

Question 2: How much data are we going to sort?


Answer: Maybe thousands.

Question 3: What exactly is this data about?


Answer: They store a person’s age

Question 4: What kind of data structure is used to hold this data?


Answer: Data are given in the form of a list

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

Abstract Data Type (ADT)


An abstract data type (ADT) is a logical description of the data and its operations. An ADT is known as
a user’s point of view of data. An ADT is concerned about the possible values of data and interfaces
exposed by it. An ADT is not concerned about the actual implementation of the data structure.

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

Kotlin Collection Framework


Kotlin programming language provides a Kotlin Collection Framework, which is a set of high quality,
high-performance & reusable data structures and algorithms.

The following advantages of using a Kotlin collection framework:


1. Programmers do not have to implement basic data structures and algorithms repeatedly. Thereby,
it prevents the reinvention of the wheel. Thus, the programmer can devote more effort to business
logic
2. The Kotlin Collection Framework code is a well-tested, high quality, high-performance code. Using
them increases the quality of the programs.
3. Development cost is reduced as basic data structures and algorithms are implemented in the
Collections framework.
4. Easy to review and understand programs written by other developers, as most Kotlin developers
use the Collection framework. In addition, the collection framework is well documented.

Array
Arrays are the simplest data structures that store items of the same data type.

Array ADT Operations


Below is the API of an array:
1. Adds an element at the kth position. Value can be stored in an array at the kth position in O(1)
constant time. We just need to store value at arr[k].
2. Reading the value stored at the kth position. Accessing the value stored at some index in the array
is also O(1) constant time. We just need to read the value stored at arr[k].
3. Substitution of value stored in kth position with a new value.
4. Time complexity: O(1) constant time.

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.

ArrayList implementation in Kotlin Collections


ArrayList<E> in Kotlin Collections is a data structure that implements the List<E> interface, which
means that it can have duplicate elements in it. ArrayList is an implementation of a dynamic array that
can grow or shrink as needed. (Internally the array is used when it is full, a bigger array is allocated
and the old array values are copied to it.)

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())

al.removeAt(al.size - 1) // last element of array is removed.


println("Array : $al")

al.removeLast() // last element of array is removed.


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
Exploring the Variety of Random
Documents with Different Content
The full-grown Manatee is from ten to twelve feet in length. Its long
body terminates in a thin, wide, shovel-shaped, fibrous, horizontal
tail, proportionally broader, but resembling somewhat that of the
Beaver. The fore-limbs, or flippers, have diminutive flat nails. The
skin of the body can be compared only to that of the Elephant, not
in colour alone, but also in its coarse, wrinkly texture, and widely-
scattered, delicate, but long hairs. Its deep-set, minute eye is
surrounded by skin wrinkles. As in the preceding genera, the muzzle
is peculiar—a kind of half-moon-shaped swelling above, with deep
crossing wrinkles set with short stiff bristles. Beneath this there
projects a mass of hard gum, covered with a roughened horny plate.
The lower jaw also has a gum plate, underhung by a bristle-clad
lower lip. The nostrils are two semi-lunar, valve-like slits, at the apex
of the muzzle. When the mouth is opened, the marginal inner
cheeks are seen to be hair-covered, and the hard, horny palate to be
very conspicuous above and below. This remarkable muzzle and
mouth are specially adapted to the animal’s mode of feeding. Steller
long ago remarked that the Rhytina’s muzzle was exceedingly
prehensile; but in a live Manatee exhibited at the London Zoological
Gardens, Professor Garrod observed and has recorded the
remarkable manner and use of this lip-structure. In grasping its
food, the bristly-clad outer angles of the upper lip at first diverge,
and then approximate like a pair of pincers, holding the object firmly,
which is then drawn inwards by a backward movement of the lips.
The horny pads again on the closing of the mouth further bruise the
vegetable matter. In 1866, the Zoological Society sent Mr. Clarence
Bartlett to Surinam, to bring home a young Manatee. This suckling,
christened “Patcheley,” had been obtained when quite a baby by the
Indians, and duly transferred to a lakelet, where he had his freedom.
Although fishy in form and fondness for the water, he had
nevertheless to receive daily a good quantum of Cow’s milk from a
bottle. He soon got fond of the “black Jack,” as well as of his keeper.
Mr. Bartlett, as wet nurse, had a difficulty in training his charge.
Loosely attired, he waded about and coaxed his pet to the water’s
edge, where, after a stolen suck or two, he permitted himself to be
raised partly on his knees, and then sucked away might and main till
the bottle was dry. His appetite satisfied, he seemed in high glee,
tumbled and rolled about a while, then got quieter, retired to the
pool, and slept lazily near the surface. At times his disposition was
more rollicking, and Master Patcheley would overturn his nurse into
the mud, where the two spluttered and floundered for possession of
the bottle. Clusius recounts how a pet “Mato” was kept by a Spanish
Governor for twenty-six years; it came at call to the side of the lake
to be fed, and would even allow boys to mount on its back while it
harmlessly swam about. For long the pursuit of the Manatee has
been a favourite amusement with the natives. One instance is
related of Indians on the Mosquito shore spearing it from canoes,
when the animal darted off as he felt the weapon, dragging the
canoe after it round and round the bight until exhausted. Mr. Alfred
R. Wallace says the natives of the Amazon capture them alive, in
strong nets, at the mouth of the streams, and afterwards kill them
by thrusting wooden plugs up their nostrils. The Manatee has no
milk-teeth, though when young there are two rudimentary incisors in
each jaw, which afterwards become covered in. Canines are entirely
absent, and the molars vary in number from nine to eleven in the
upper and lower jaw on each side. Those in the upper series are
three-rooted, in the lower series two-rooted; all the molars are
broad, square-crowned, and with transverse ridging or cusp
structure like that of the Hippopotamus or partly like that of
Mastodon. The molar series are never simultaneously in place and
use, those in front dropping out and making room for those behind.
FOSSIL SIRENIA.—The HALITHERIUM is the name given to certain fossil
remains which have been found in the Miocene strata of Germany
and various other parts of Europe. These remains show that there
may have been several species, but all are truly of a Sirenian
character. The fossil remains were intermediate, though possibly
most closely allied to the Manatee, some of them being slightly
larger than this animal. The dentition is unusually interesting,
inasmuch as there appear to have been vertical successors;
anteriorly there are simple, cylindrical premolars, and posteriorly
larger, complex molars, while the somewhat bent-down upper jaw
bore tusk-like appendages. But the most peculiar and interesting
point in connection with the Halitheria, is that they were provided
with rudiments of a hind limb, a thigh-bone some few inches in
length having been found by the late Professor Kaup, though
curiously enough no further vestige of it has since turned up.
Judging from the almost complete skeletons obtained, and from
comparison with what we know of other Sirenia, the Halitherium
must have closely resembled the living Manatee, and possibly have
lived in the lagoons and brackish waters of mid-Europe and
elsewhere, for in the Eocene and Miocene times these regions, now
high and dry, formed watery areas in communication with the ocean.
Besides the foregoing, within the last few years our knowledge of
Sirenoids has been considerably augmented by the discovery of
other fossil remains indicating several new genera. Prorastomus is
founded by Owen on a skull from West Indian (doubtful) Tertiary
strata. Crassitherium is applied by Van Beneden to vertebræ, and
part of a skull from deposits near Antwerp. Felsinotherium, (with but
5–5
molar teeth) is a form described by Capellini, from Pliocene beds
5–5
in Bologna. Pachyacanthus, found in strata in the neighbourhood of
Vienna, Brandt supposed a Cetacean, but Van Beneden regards it as
a Sirenian. The Rhytiodus, of Lartet, is based on some fossil teeth
bearing resemblances to those of the Dugong. Lastly comes (in the
cast of a brain), the still more remarkable Eotherium of Owen, from
the nummulitic Eocene of Egypt. Some of these fossils are of intense
interest, for example, Prorastomus, the Tapir-like dentition of which
is—Incisors, 3–3; canines, 1–1; premolars, 5–5; molars, 3–3 = 48. Very
3–3 1–1 5–5 3–3
interesting also are Pachyacanthus, with possibly but six neck
vertebræ, like the Manatee; and Halitherium, with its hind limb
bones, and which also, along with Felsinotherium, foreshadows the
molar pattern of Hippopotamus. Thus, taking these facts into
consideration, together with many other structural peculiarities,
Elephant-like and otherwise, and notwithstanding that the Sirenia
are aquatic and Whale-like, their structural relationship with the
Proboscidea and Ungulata is not so far-fetched as at first sight might
seem. But the gap is not yet bridged, and until that is done the
order Sirenia must be retained.

JAMES MURIE.

MOUNTED SKELETON OF HALITHERIUM, IN THE HEIDELBERG UNIVERSITY


MUSEUM.
SKELETON OF INDIAN ELEPHANT.

ORDER PROBOSCIDEA (ELEPHANTS).


Order Proboscidea—Antiquity of the Elephant—Referred to in the Bible—
Mentioned in the Apocrypha—War Elephants—Their Accoutrements—
Hannibal’s Elephants—Elephants amongst the Romans—Skull—
Dentition—Vertebræ—Odd Delusion about its Legs—Proboscis—
Species—THE INDIAN ELEPHANT—Size—Range—Habits—Various Modes of
Capture—Keddah—Used as a Labourer or Nurse—Sagacity—White
Elephants—THE AFRICAN ELEPHANT—Characteristics—Range—Habits and
Haunts—Hunting—Pitfalls—Aggageers Chasing—Elephant-Shooting—
How the Natives Cut it up—FOSSIL ELEPHANTS AND THEIR ALLIES—Absurd
Stories—MAMMOTH—How it was first Found—Story of the Fourth or
Benkendorf’s Discovery—Range—MASTODON—DINOTHERIUM.

THE Elephants, Horses, Rhinoceroses, Tapirs, Coneys, Pigs, and


Hippopotami, were all grouped together by the older naturalists
under the order of Pachyderms,[256] or thick-skinned animals
provided with hoofs, but not furnished with a complex stomach for
rumination, or chewing of the cud. They are now divided into three
different orders—the Proboscidea, Hyracoidea, and Ungulata—which
we shall define and describe each in its proper place.
The order Proboscidea, or animals possessed of a proboscis, or
trunk, consists of two living species, the Indian and African Elephant,
and two extinct genera known as Dinotherium and Mastodon. The
Elephant, from its large size and its singular sagacity, attracted the
attention of man in the earliest times, and was always looked upon
with feelings of awe and reverence. At the present time the African
savage, in the region of the Congo, compasses its death with the
mysterious aid of the medicine-man, according to Mr. Winwood
Reade, as well as by the ordinary means of hunting. The animal, in
early times, was used both for purposes of war and peace, and
figures, at the present time, alike in the gorgeous retinues of Indian
princes, and ministers to the more humble and more useful services
of the husbandman. The ivory furnished by its tusks was known in
the remotest antiquity. The first undoubted mention of the Elephant
in the Bible relates to the use of ivory, which certainly was employed
by the ancient Greeks, Assyrians, and Egyptians early in their history.
King Solomon had a throne of ivory, which was obtained through
the Phœnician traders probably from Africa. “For the king had at sea
a navy of Tharshish (Cilicia) with the navy of Hiram; once in three
years came the navy of Tharshish, bringing gold, and silver, ivory,
and apes, and peacocks” (1 Kings x. 22). Elephants are also
mentioned in 2 Chron. ix. 21; and at considerable length in the first
and second books of Maccabees, where their use in war is described
(1 Macc. vi. 28–30; 43–46).
The Elephants were used in war also by the Indian nations, and
were looked upon as most formidable engines in battle. By the aid of
these huge creatures, to a large extent, they conquered and held
possession of the region of Central Asia west of the Indus.
It appears that the relative force of Elephants in a great army
corps was one to each chariot of war, with three horsemen and five
archers, the latter being perched on the Elephant’s back within a
houdah of a defensible nature, denominated a castle, the whole
forming what was termed a patti, or squad, comprising altogether
not more than eleven men, with the drivers or attendants. This
shows that in India, which furnished Elephants and the manner of
arming them, only four or five archers, with or without the mahout,
or driver, were told off to each animal; consequently, when the
successors of Alexander introduced them in their wars in Syria,
Greece, and Italy, they were not encumbered with more than one or
two additional persons before a charge. Indeed, considerable trouble
appears to have been taken that a war Elephant should not be
nearly as heavily laden as one simply used for carrying burdens;
therefore the number of thirty-two soldiers given in Maccabees as
seated upon each Elephant must somehow or other be a mistake.
These Elephants were well trained, and taught to hold out one of
their hind legs horizontally, when it was necessary to mount them in
a hurry. They appeared to take considerable delight and satisfaction
in the gaudy trappings with which they were usually decorated. In
some cases, Elephants have proved more dangerous to the army in
whose ranks they were serving than to the enemy, by being
suddenly confronted with objects previously unobserved. On such
occasions they turn in haste, and spread terror and death into their
own ranks. Careful, judicious, and long-continued training was the
only remedy against these sudden surprises.
African Elephants probably were never so well trained and
subdued as the Indian; nevertheless, they were used by the
Carthaginians in the first Punic War (264–241 B.C.) with much
success, and to the discomfiture of the Romans. In the second Punic
War (218–216 B.C.) Hannibal performed the most astounding and
remarkable feats of crossing the Pyrenees, making his way through
Gaul, crossing the Alps with thirty-seven Elephants, and defeating
the Romans at the Ticinus. Most of the Elephants, however, died
shortly afterwards from the excessive coldness of the weather and
the fatigue they had undergone. Various accounts are given in
Roman history regarding the manner in which the Elephants crossed
the Rhone. One story goes that they were assembled together on
the bank, and the fiercest of them being provoked by his keeper,
pursued him as he swam across the water, to which he had run for
refuge, and that the rest of the herd followed. There is, however,
more reason to believe that they were conveyed across on rafts. It is
said that one raft two hundred feet long and fifty broad was
extended from the bank to the river, and was then secured higher up
by several strong cables to the bank, that it might not be carried
down by the stream. The soldiers then covered it over with earth, so
that the animals might tread upon it without fear, as on solid ground.
Another raft one hundred feet long, and of the same breadth as the
other, was joined to this first. The Elephants were driven along the
stationary raft as along a road, and then, the females leading the
way, passed on to the other raft, which was fastened to it by
lashings. This, on being cut, was drawn by boats to the opposite
shore. The Elephants gave no signs whatever of alarm, while they
were driven along as it were on a continuous bridge; but a few
became infuriated when the raft was let loose, and fell into the river,
finding their way, however, safely to the shore.
The trappings and armour of a war Elephant have been described
by the author of the “Ayeen Akbery” as follows:—“Five plates of iron,
each one cubit long and four fingers broad, are joined together by
rings, and fastened round the ears of the Elephant by four chains,
each an ell in length; and betwixt these another chain passes over
the head, and is secured beneath; and across it are four iron spikes,
with ratasses and iron knobs. There are other chains with iron spikes
and knobs, hung under the throat and over the breasts, and others
fastened to the trunk; these are for ornament and to frighten
Horses. Pakher is a kind of steel armour that covers the body of the
Elephant; there are other pieces of it for the head and proboscis.”

SECTION OF SKULL OF INDIAN ELEPHANT.


s, Air Sinuses; n, Nostrils; b, Brain; m, Molar; t, Tusk.

History informs us that when Timour, or Tamerlane, attacked the


dominions of the Sultan Mahmoud (A.D. 1399), the Elephants, of
which the latter had a considerable number, caused great terror and
alarm; and that the preparations made by Timour to overcome the
Elephants were of the most extraordinary nature, for not only did he
surround his camp with a deep ditch and bucklers, but also had
Buffaloes tied together round the ramparts, with huge brambles on
their heads, which were to be set on fire at the approach of the
Elephants. The forces of the Sultan, besides the Elephants, consisted
of a large number of horse and foot soldiers armed with swords and
poisoned daggers. Attendant upon the Elephants were men armed
with fire, melted pitch, and other horrid missiles, to be hurled at the
invaders. The Elephants also, besides being armed, were decorated
with all sorts of articles, such as cymbals and bells, and other
objects likely to create a noise and confusion. Notwithstanding all
this terrific display, Timour’s forces fought with great courage,
actually defeating the Sultan’s forces, and putting the Elephants to
flight, the unfortunate creatures undergoing severe usage to their
trunks by the swordsmen, who appeared soon to find out the more
vulnerable parts. It is said that the trunks of many of the Elephants
were left scattered on the battle-field, having been severed by the
sword. The belief in the invincibility of the Elephants was then for
ever gone; and it is even said of Timour’s grandson, then quite a
boy, that he himself wounded an Elephant, and drove it in as a
captive to his grandfather’s camp.
We are told that in ancient times the number of Elephants
annually brought from Africa to Rome, to be trained for the cruel
and disgusting practice of fighting in the theatre, was very great. It
is said of Pompey that, at the dedication of his theatre, no less than
five hundred Lions, eighteen Elephants, and a number of armed
men, were all at one time in the circus. In the second consulate of
Pompey (54 B.C.) Elephants were opposed, in the circus, to Getulian
archers; and, according to Pliny, this exhibition was characterised by
some uncommon circumstances. One of the Elephants, although
furious from a wound, is recorded to have seized upon the shields of
his adversaries, and to have thrown them in the air with a peculiar
movement, doubtless the effect of training, which caused the shields
to whirl round before their fall. It is also stated that an Elephant,
having been killed by a thrust of a javelin through the eye, the
others rushed forward in a general charge to save him, and that on
their coming with terrific force against the iron railings, the latter
gave way, and several of the spectators were either injured or killed.
On another occasion, when some Elephants, with other wild animals,
were fighting together in the arena, the spectators so
compassionated the unfortunate creatures, who were raising their
trunks to heaven and roaring piteously, as if imploring aid of the
gods, that they rose from their seats, and, disregarding Pompey’s
presence, demanded that the Elephants might be spared. The
destruction of Elephants in sport by the Romans, as well as the
increased demands of the ivory trade, have caused the African
Elephants to disappear from those regions of Northern Africa which
they once inhabited. In the days of the Carthaginians, the animal
was found north of the Sahara, where at present it is unknown.
The skull of the Elephant is remarkable for its great size, and the
comparatively small cavity occupied by the brain. The latter is small
in comparison to the size of the animal, in bulk not much exceeding
that of man. Although the bones of the skull are so large, they are
not solid, their interior being occupied by hollows divided from each
other by thin partitions, by which means the skull is rendered lighter
than might be supposed; and altogether it forms a beautiful instance
of a provision for increasing the surface for attachment of muscles,
without being too great a burden to its possessor. The skull of the
Indian Elephant is of a much more pyramidal and less shapely form
than that of the African.
The dentition in the Elephants presents several points of
considerable interest. In the Indian species, the males alone have
well-developed incisors; while both sexes of the African species are
provided with them. These—more commonly known as tusks—grow
to an enormous size, sometimes reaching the weight of from a
hundred and fifty to two hundred pounds. There are no lower
incisors, and only two of the molar teeth are to be seen at each side
of the jaw at one time. There are six of these in each side, or four-
and-twenty in all, in the lifetime of the Elephant, and these present a
gradual increase in size as they successively appear. These teeth
move forward into their working place in the jaw in regular
succession, from behind forwards, each being pushed out by its
successor as it gradually becomes worn away. The teeth are worn
away, not merely by the food on which the animal lives, but also by
the particles of sand and grit entangled in the roots of the herbs torn
up for food, and their wear is compensated by the growth and
development of the succeeding teeth. In a state of captivity,
however, where the food is much more free from extraneous
substances than in a state of nature, the teeth are not worn away
fast enough to make room for the development of the successors,
and it therefore frequently happens that the tooth is deformed by a
piling over of the plates of which it is composed.

SIDE VIEW OF MOLAR TOOTH OF INDIAN ELEPHANT.


A, Upper; B, Lower.

The molar or grinding-teeth of the Elephant are for the most part
buried in the socket, and present little more than a surface for
mastication above the gum. Each is composed of a number of
transverse perpendicular plates, built up of a body of dentine,
covered by a layer of enamel, and this again by a layer of cement,
which fills the interspaces of the plates, and binds together the
divisions into one solid mass. Each of these enamel plates, however,
in the perfect tooth is united at the base. When these plates of
enamel—which stand out in the transverse plates on account of their
superior hardness, and cause the grinding surface to be uneven—are
worn out, the animal either dies of indigestion, or more often
becomes weak, and falls a prey to wild beasts.
LAST LOWER TOOTH OF LAST LOWER TOOTH OF
AFRICAN ELEPHANT. INDIAN ELEPHANT.

The difference between the grinders of the Indian and African


Elephants is well defined. In the former, the transverse ridges of
enamel are narrower, more undulating, and more numerous than in
the African, in which latter species the ridges are less parallel, and
enclose lozenge-shaped spaces. The cervical vertebræ form a short
and stiff series, allowing but a limited motion of the head from side
to side, a more extended action being rendered unnecessary by the
flexibility of the trunk. With regard to the dorsal vertebræ, they
appear to vary in number in both species. In the African species the
number varies from twenty to twenty-one, and in the Indian species
from nineteen to twenty. As might be expected, the limbs of the
Elephant are massive and powerful. In ancient times it was a
popular delusion that the legs of an Elephant possessed no joints;
and even now people are to be found who believe that the
Elephant’s joints move in a contrary direction to that of other
quadrupeds. Shakspere evidently enjoyed the popular belief. In
Troilus and Cressida, Ulysses, speaking of the stiff demeanour of
Ajax towards Achilles, says:—

“The Elephant hath joints, but none for courtesy,


His legs are legs for necessity, not for flexure.”

And so in Chapman’s drama (1605) of All Fools we read:—

“I hope you are no Elephant, you have joints.”


These ideas originated from the peculiar gait of the Elephant.
The shape of the Elephant is so familiar to every one that it is
only necessary to remark that the ponderous body, clad in a thick
and almost hairless skin, has the fore-quarters higher than the
hinder parts, and that the thigh in the hind leg is long and straight
when the animal is standing. The knee is visible below the body, and
bends so as to bring the foot in the rear. On comparing an Elephant
and a Carnivore, and their skeletons as well, the arrangement of the
joints of the hind quarters will be noticed to be different. In fact, the
bend of the Elephant’s knee gives the gait of the huge creature an
appearance unlike that of any other animal. It stands on the ends of
its five toes, each of which is terminated by comparatively small
hoofs, and the heel-bone is a little distance from the ground.
Beneath comes the wonderful cushion, composed of membranes,
fat, nerves, and blood-vessels, besides muscles, which constitutes
the sole of the foot. The fore-foot is larger than the hind one, and as
the creature does not require to climb, or to lift its fore-limb very
high, there is no collar-bone. In the young there is more hair on the
body than might have been expected, and they have a set of milk
teeth.
The brain is greatly convoluted on the surface, but the little
brain, or cerebellum, is not covered by the brain proper.
TRUNK OR PROBOSCIS OF ELEPHANT.
A, Muscles and Tendons; B, Transverse Section.

The trunk or proboscis of the Elephant, from which the name of


the order to which this animal belongs is derived, is certainly a
remarkable and wonderful organ. It is really a prolongation of the
nose, of a sub-conical form, consisting of two tubes divided by a
septum. At the extremity on the upper side, above the opening of
the nostrils, is a lengthened process to be looked upon in the light of
a finger; beneath this finger is a tubercle, opposable to it, and
acting, so to speak, as a thumb. With this organ, which is nearly
eight feet in length, of considerable stoutness, and extreme
sensibility, the Elephant is enabled to uproot or shake trees, lift a
cannon, or pick up a pin. By its aid, food and water are carried to
the mouth, and when necessary, it can be converted into a syringe
or a shower-bath. The length of the organ does away with the
necessity of a long neck, a short and muscular neck being absolutely
required for the support of the enormous head and tusks.
The principal characters of the Indian species, as compared with
the African, are the small ears, concave forehead, small eye, lighter
colour, and the possession of four instead of three nails or hoofs on
the hind foot. There is also a very remarkable difference in the
teeth, those of the Indian species being built up of a series of plates
much more numerous and more closely packed together than in the
African species.
THE INDIAN ELEPHANT.[257]—There are but two living species of
Elephant—the Indian (Elephas indicus) and the African (Elephas
africanus), although some naturalists have considered the Elephant
of Sumatra and Ceylon to be a distinct species, and Schlegel has
separated it from both the Indian and African, and defined it as E.
sumatrensis. It has been, however, shown by Dr. Falconer and
others, that although certain differences are to be noticed, they are
not of sufficient value to create a new species; but they are still of
sufficient importance to form a variety.
In size, notwithstanding the differences of opinion to be found
between certain writers on this subject, some saying that the Indian
and others that the African Elephant is the larger, it seems perfectly
clear that there cannot be much difference between the two species,
and that the maximum height is about eleven feet.
The Indian Elephant (where the progress of civilisation has not
interfered with it) is found over the greater part of the forest lands
of India, Ceylon, Burmah, Siam, Cochin-China, the Malay Peninsula,
and Sumatra; but it is doubtful whether it is indigenous to any of the
other islands of the Eastern Archipelago. Unlike the African species,
to a certain extent, it appears to have a partiality for coolness and
shade; indeed, Sir J. Emerson Tennent says that “although found
generally in warm and sunny climates it is a mistake to suppose that
the Elephant is partial either to heat or to light. In Ceylon, the
mountain tops, and not the sultry valleys, are its favourite resort. In
Oovah, where the elevated plains are often crisp with the morning
frost, and on Pedura-talla-galla, at the height of upwards of eight
thousand feet, they are found in herds, whilst the hunter may search
for them without success in the hot jungles of the low country.”
In some parts of the country Elephants are exceedingly
destructive to crops of grain. And in various parts of India,
notwithstanding the care and trouble taken to watch the crops, they
do much injury. When the rice approaches maturity it is necessary to
place watchers throughout the night in places which they frequent.
Stages are erected on posts twelve or fourteen feet high, and on one
side of the stage a small shed is made for the watchmen, two of
whom always mount the same stage. One feeds a fire kept
constantly burning on the open part, while the other in his turn is
allowed to sleep, and when any Elephants come into the field, he is
awakened and both join in shouting and making all the noise they
can with sticks and drums.
The food of the Elephant appears to be considerably varied, and
chosen by the animal with no small amount of daintiness; sweet-
tasting fruits, seeds, and blossoms he has the greatest partiality for,
and in their selection much destruction is occasioned by a herd of
these huge animals. Tennent says that in Ceylon, where the food of
the Elephant is most abundant, the animal never appears to be in a
hurry to eat; but amuses himself with playing with the leaves,
shaking the trees, tearing the bark, and now and then pausing to
eat, altogether taking the whole affair in a very leisurely sort of way.
He is especially fond of the fruit of the palmyra palm, and never fails
to make his appearance in the districts where these trees grow when
the fruit begins to fall to the ground. Although the amount of food
consumed by Elephants in their wild state is very large, there is
reason to believe that many stories told of their extraordinary eating
capabilities are much exaggerated. It by no means follows that
because an Elephant in a tame state will eat so much bread, turnips,
hay, &c., that it consumes the same quantity of its natural food in a
wild state. The Elephants are believed to drink nightly in very hot
weather, but in cool weather only every third or fourth day, and for
this purpose they travel long distances to their watering-places, even
as far as ten or twenty miles, refreshing themselves by a bath and a
drink at the same time when they reach their destination.
Various modes are used for catching Elephants; but the usual
practice is to drive them into what is termed a keddah. The keddah
is a large area surrounded by a broad ditch, and towards the
entrance is a similar construction to the main body, but smaller,
acting as a sort of funnel, into which the Elephants enter when
driven from the jungle, and which assists in getting them into the
keddah itself.
On discovering a large herd of Elephants, a body of men, often
numbering six or eight thousand, are collected to surround them,
carrying all sorts of instruments likely to create a noise, such as
firearms, drums, trumpets, &c., Elephants being exceedingly alarmed
by any unusual noises. By this means they are gradually driven into
the keddah, sometimes from a distance of thirty or forty miles, which
frequently occupies some days. When the Elephants find themselves
fairly entrapped, they become violent and use their utmost
endeavours to break down the barriers.
INDIAN ELEPHANT.

LARGER IMAGE

Formerly, it was the practice to starve these captured Elephants


into submission; now, however, by means of two tame ones, trained
for the purpose, they can be captured without injury, one by one,
and afterwards bound to a tree. To accomplish this the trained
animals are sent into the enclosure, and on a wild Elephant being
singled out, the two trained ones place themselves one on each side,
and attract its attention while the attendants are occupied in binding
its legs, which having been satisfactorily accomplished, the captive is
dragged to a tree and fastened firmly, where it remains until reduced
to submission and obedience by kindness and good feeding.
“The vast jungles in the south-eastern portion of the Mysore
territory are infested with herds of wild Elephants, whose
depredations on the adjacent lands have retarded agriculture to a
serious extent. A project was set on foot by Mr. G. P. Sanderson, a
young and energetic officer in the service of the Mysore
Government, to convert these Elephants to some use by capturing
and taming them. Mr. Sanderson’s design was to drive a herd into a
strongly embanked channel leading out of the Houhole river, escape
being cut off at one end by it deep ditch, and the other opening on
the river, guarded by Elephant chains supported by strong posts. On
the 9th June, 1874, the Elephants being reported in the
neighbourhood, a large party of natives, led by Mr. Sanderson and
two other ardent sportsmen, hurried to the spot, and quietly drove
the animals towards the channel. The leading Elephant being pushed
from behind by his companions, tumbled over the bank, and the
latter soon followed. This having been effected, the embankment
was quickly strengthened, large fires lighted at intervals along it, and
watchers placed for the night. The next point was to move the
Elephants into a still smaller enclosure, which was prepared close by.
It was funnel-shaped at the mouth, and formed of trunks of trees,
firmly fixed in the ground, the snare being disguised by branches
and brushwood. Over the neck of the funnel, so to speak, a drop
formed of two large cocoa-nut trees lashed together was suspended
by a rope, to be severed at a stroke when the Elephants were all in.
The herd, terrified by firebrands, rockets, and guns, were driven
towards the keddah, and led by a troublesome tusker, who had long
kept the others at bay, marched majestically one by one through the
gate. After a short pause, owing to a stand being made by a few of
the most refractory, the last of the herd went in with a rush, closely
followed by a frantic native waving a firebrand. An officer sitting
ready on a branch of a tree now cut the rope, and the drop fell amid
loud cheers, thus capturing the rich prize of fifty-three Elephants,
which were brought out one by one with the assistance of tame
Elephants. The latter advance in a body and gradually cut one off
from the herd. While amusing it, and distracting its attention, its legs
are warily tied by trained men. After this no difficulty is encountered.
The capture described included twelve valuable tuskers, and its
value was estimated at over £4,000.”[258]
Indian Elephants are also sometimes captured by means of
pitfalls formed in a similar manner to those used in Africa. There is,
however, one great objection to this mode of capture, which is, that
the animal is rendered very liable, from the heavy fall it sustains, of
being seriously hurt, and indeed injuries thus received have often
proved fatal.
Another way of catching these animals in some districts of India
is by means of the lasso. Two trained females are procured for the
purpose; these are provided with a long rope which is fastened to
their girdle, and then coiled on their backs. Its end forms a noose,
which a man, who sits on the back of the trained female, throws
round the neck of the wild Elephant; the tame one then walks away
until the captured one is almost strangled. In the meantime, the
people, assisted by another tame female, endeavour to fasten ropes
to his legs, and he is dragged to a place where there are trees, to
which he is fastened until he becomes tame. The Elephants caught
in this manner are usually small, and the majority, for some reason
or other, die, probably from the rough usage they have undergone.
Elephant shooting, especially in Ceylon, was considered to be the
acme of sport; but from the number that were wantonly destroyed,
an order was issued by the Governor prohibiting their destruction.
The Elephant is invaluable as a labourer; its assistance in road-
making, bridge-building, ploughing, piling logs, lifting weights, and
other similar operations, is of the utmost service. Even as a nurse for
young children, its services, we are told, are sometimes required. An
Indian officer relates that he has seen the wife of a mahout (for the
followers often take their families with them to camp), give a baby in
charge of an Elephant, while she went on some business, and has
been highly amused in observing the sagacity and care of the
unwieldy nurse. The child, which, like most children, did not like to
be at rest in one position, would, as soon as left to itself, begin
crawling about, in which exercise it would probably get among the
legs of the animal, or entangled in the branches of the trees on
which he was feeding, when the Elephant would in the most tender
manner disengage his charge, either by lifting it out of the way with
his trunk, or by removing the impediments to its free progress. If the
child had crawled to such a distance as to verge upon the limits of
his range (for the animal was chained by the leg to a peg driven in
the ground), he would stretch out his trunk and lift it back as gently
as possible to the spot whence it had started.

ELEPHANT IN THE ZOOLOGICAL GARDENS, LONDON.


(From a Photograph by Symmons and Co., Chancery Lane, expressly taken for this work.)

LARGER IMAGE

Endless other stories are told of the sagacity of this noble animal,
some of them, however, probably not ungarnished with considerable
exaggeration. However, this creature does undoubtedly possess a
most wonderful amount of intelligence, and it is believed that the
Indian species, both in sagacity and docility, surpasses the African.
The White Elephants, held in reverence in Siam, and extremely
rare, are not distinct from the rest; they are merely albinoes, or
white varieties, and are to be viewed in the same light as white
Blackbirds or white Sparrows.
THE AFRICAN ELEPHANT[259] is distinguished at once from the Indian
species by the great size of its ears, its larger eye, convex forehead,
darker colour of its skin, and by possessing only three instead of four
nails or hoofs in the hind foot. It is indigenous to Africa, being found
south of the Sahara as far as Cape Colony, and from the Indian
Ocean to the Atlantic. It formerly lived north of the Sahara, and in
the Pleistocene age of geologists was found in Europe, in Italy, and
in Spain, to which points it probably crossed at the time when the
submerged barriers between Sicily and Africa, and Gibraltar and
Africa, were above the level of the water.
Unlike the Indian species, both the males and the females are
provided with tusks. The African differs also considerably in his
habits, for while the Indian enjoys coolness and shade, the African is
more or less exposed to the burning sun.
According to Sir Samuel Baker, “in Africa the country being
generally more open than in Ceylon, the Elephant remains
throughout the day either beneath a solitary tree, or exposed to the
sun in the vast prairies, where the thick grass attains a height of
from nine to twelve feet. The general food of the African Elephant
consists of the foliage of trees, especially of mimosas. Many of the
mimosas are flat-headed, about thirty feet high, and the richer
portion of the foliage confined to the crown. Thus, the Elephant, not
being able to reach to so great a height, must overturn the tree to
procure the coveted food. The destruction caused by a herd of
Elephants in a mimosa forest is extraordinary, and I have seen trees
uprooted of so large a size that I am convinced no single Elephant
could have overturned them. I have measured trees four feet six
inches in circumference, and about thirty feet high, uprooted by
Elephants. The natives have assured me that they mutually assist
each other, and that several engage together in the work of
overturning a large tree. None of the mimosas have tap roots; thus
the powerful tusks of the Elephants applied as crowbars at the roots,
while others pull at the branches with their trunks, will effect the
destruction of a tree so large as to appear invulnerable.”
The following account by Gordon Cumming, which, on some
points as to the habits and haunts of the African Elephant does not
agree with that of Sir Samuel Baker, may be explained by the
different nature of the country hunted by him:—“The Elephant is
widely diffused through the vast forests, and is met with in herds of
various numbers. The male is much larger than the female. He is
provided with two enormous tusks. These are long, tapering, and
beautifully arched; their length averages from six to eight feet, and
they weigh from sixty to a hundred pounds each. In the vicinity of
the Equator the Elephants attain to a larger size than to the
southward; and I am in possession of a pair of tusks of the African
bull Elephant, the larger of which measures ten feet nine inches in
length, and weighs one hundred and seventy-three pounds.
“Old bull Elephants are found singly or in pairs, or consorting
together in small herds, varying from six to twenty individuals. The
younger bulls remain for many years in the company of their
mothers, and these are met together in large herds of from twenty
to a hundred individuals. The food of the Elephant consists of the
branches, leaves, and roots of the trees, and also of a variety of
bulbs, of the situation of which he is advised by his exquisite sense
of smell. To obtain these he turns up the ground with his tusks, and
whole acres may be seen thus ploughed up. Elephants consume an
immense quantity of food, and pass the greater part of the day and
night in feeding. Like the Whale in the ocean, the Elephant on land
is acquainted with, and roams over, wide and extensive tracts. He is
extremely particular in always frequenting the freshest and most
verdant districts of the forests, and when one district is parched and
barren, he will forsake it for years and wander to great distances in
quest of better pasture.”
AFRICAN ELEPHANT.

LARGER IMAGE

“The Elephant entertains an extraordinary horror of man, and a


child can put a hundred of them to flight by passing at a quarter of a
mile to windward; and when thus disturbed they go a long way
before they halt. It is surprising how soon these sagacious animals
are aware of the presence of a hunter in their domains. When one
troop has been attacked, all the other Elephants frequenting the
district are aware of the fact within two or three days, when they all
forsake it, and migrate to distant parts, leaving the hunter no
alternative but to inspan his wagons, and remove to fresh ground.
“This constitutes one of the greatest difficulties which a skilful
Elephant-hunter encounters. Even in the most remote parts, which
may be reckoned the head-quarters of the Elephant, it is only
occasionally, and with inconceivable toil and hardship, that the eye
of the hunter is cheered by the sight of one. Owing to habits
peculiar to himself, the Elephant is more inaccessible and much more
rarely seen than any other game quadruped, excepting certain rare
Antelopes. They choose for their resort the most lonely and secluded
depths of the forest, generally at a very great distance from the
rivers and fountains at which they drink. In dry and warm weather
they visit these waters nightly; but in cool and cloudy weather they
drink only once every third or fourth day. About sundown the
Elephant leaves his distant midday haunt, and commences his march
towards the fountain, which is probably from twelve to twenty miles
distant. This he generally reaches between the hours of nine and
midnight, when, having slaked his thirst and cooled his body by
spouting large volumes of water over his back with his trunk, he
resumes the path to his forest solitudes. Having reached a secluded
spot, I have remarked that full-grown bulls lie down on their
broadsides about the hour of midnight and sleep for a few hours.
The spot which they usually select is an ant-hill, and they lie around
it with their backs resting against it. These hills, formed by the white
Ants, are from thirty to forty feet in diameter at their base. The mark
of the under tusk is always deeply imprinted in the ground, proving
that they lie upon their sides. I never remarked that females had
thus lain down, and it is only in the more secluded districts that the
bulls adopt this practice; for I observed that, in districts where the
Elephants were liable to frequent disturbance, they took repose
standing on their legs beneath some shady tree. Having slept, they
then proceed to feed extensively. Spreading out from one another,
and proceeding in a zigzag course, they smash and destroy all the
finest trees in the forest which happen to lie in their course. The
number of goodly trees which a herd of bull Elephants will thus
destroy is utterly incredible. They are extremely capricious, and on
coming to a group of five or six trees they break down, not
unfrequently, the whole of them, when, having perhaps only tasted
one or two small branches, they pass on and continue their wanton
work of destruction. I have repeatedly ridden through forests where
the trees thus broken down lay so thick across one another that it
was almost impossible to ride through the district; and it is in
situations such as these that attacking the Elephant is attended with
most danger. During the night they will feed in open plains and
thickly-wooded districts, but as day dawns, they retire to the densest
covers within reach, which nine times in ten are composed of the
impracticable wait-a-bit thorns; and here they remain drawn up in a
compact herd during the heat of the day. In remote districts,
however, and in cool weather, I have known herds to continue
pasturing throughout the whole day.”
The African Elephant is not now hunted for domestic purposes,
but for the sake of the flesh and of the ivory; and its death is a
grand affair for the natives, since it affords opportunity not merely
for a feast, but for obtaining fat for internal and external uses. There
are various methods of killing them. Pitfalls are most common, and
are generally placed in the neighbourhood of a drinking-place, the
natives showing great skill in felling trees, so as to turn the
Elephants into them. According to Sir Samuel Baker, “the pits are
usually about twelve feet long, and three feet broad, by nine deep;
these are artfully made, decreasing towards the bottom to the
breadth of a foot. The general Elephant route to the drinking-places
being blocked up, the animals are diverted by a treacherous path
towards the water, the route intersected by numerous pits, all of
which are carefully concealed by sticks and straw, the latter being
usually strewn with Elephants’ dung, to create a natural effect.
Should an Elephant during the night fall through the deceitful
surface, his foot becomes jammed in the bottom of the narrow
grave, and he labours shoulder-deep, with two feet in the pitfall so
fixed that extrication is impossible. Should one animal be thus
caught, a sudden panic seizes the rest of the herd, and in their hasty
retreat one or more are generally victims to the numerous pits in the
vicinity. Once helpless in the pit, they are easily killed with lances.”

AGGAGEERS HUNTING AN ELEPHANT.

The same author also relates that sometimes the Elephant-


hunters, or aggageers, of the Hamram tribe, use swords for killing
Elephants. They follow the tracks of the animal, “so as to arrive at
their game between the hours of 10 and 12 A.M., at which time it is
either asleep or extremely listless, and easy to approach. Should
they discover the animal asleep, one of the hunters would creep
stealthily towards the head, and with one blow sever the trunk while
stretched upon the ground; in which case the Elephant would start
upon his feet, while the hunters escaped in the confusion of the
moment. The trunk severed would cause a loss of blood sufficient to
insure the death of the Elephant within about an hour. On the other
hand, should the animal be awake upon their arrival, it would be
impossible to approach the trunk. In such a case, they would creep
up from behind, and give a tremendous cut at the back sinew of the
hind leg, about a foot above the heel. Such a blow would disable the
Elephant at once, and would render comparatively easy a second cut
to the remaining leg. These were the methods adopted by poor
hunters, until by the sale of ivory they could purchase Horses for the
higher branch of the art. Provided with Horses, the party of hunters
should not exceed four. They start before daybreak, and ride slowly
throughout the country in search of Elephants, generally keeping
along the course of a river until they come upon the tracks where a
herd, or a single Elephant, may have drunk during the night. When
once upon the track, they follow fast towards the retreating game.
The Elephants may be twenty miles distant, but it matters little to
the aggageers. At length they discover them, and the hunt begins.
The first step is to single out the bull with the largest tusks; this is
the commencement of the fight. After a short hunt, the Elephant
turns upon his pursuers, who scatter and fly from his headlong
charge until he gives up the pursuit; he at length turns to bay when
again pressed by the hunters. It is the duty of one man in particular
to ride up close to the head of the Elephant, and thus to absorb its
attention upon himself. This insures a desperate charge. The
greatest coolness and dexterity are then required by the hunter,
who, now the hunted, must so adapt the speed of his Horse to the
pace of the Elephant that the enraged beast gains in the race, until
it almost reaches the tail of the Horse. In this manner the race
continues. In the meantime, two hunters gallop up behind the
Elephant, unseen by the animal, whose attention is completely
directed to the Horse almost within his grasp. With extreme agility,
when close to the heels of the Elephant, one of the hunters, while at
full speed, springs to the ground with his drawn sword, as his
companion seizes the bridle, and with one dexterous two-handed
blow he severs the back sinew. He immediately jumps out of the
way, and remounts his Horse; but if the blow is successful, the
Elephant is hamstrung, and, as it cannot run rapidly on three legs, is
easily killed.”
The Fans in the neighbourhood of the Gaboon settlements,
according to Mr. Winwood Reade, are in the habit of employing the
same mode of capturing Elephants as the natives of India, namely,
by enticing them within an enclosure or fence of posts and rails,
where they are afterwards killed with cross-bows, spears, and trade-
guns.
Elephant shooting, although not unattended by danger, appears
to be on the whole accomplished with considerable success, five or
six Elephants having been killed occasionally in a very short space of
time by one man; and many are the tales of hair-breadth escapes
related to us by Gordon Cumming, Tennent, Baker, and others. But it
appears the forehead-shot, so much in favour in shooting Indian
Elephants, does not answer with the African species, the form of the
head and the position of the tusks preventing the bullet from
reaching the brain.
“The only successful forehead-shot,” says Sir S. Baker, “that I
made at an African Elephant was shortly after my arrival in the
Abyssinian territory, on the Settite River; this was in thick, thorny
jungle, and an Elephant from the herd charged with such good
intention that, had she not been stopped, she must have caught one
of the party. When within about five yards of the muzzle of my rifle,
I killed her dead by a forehead-shot with a hardened bullet, and we
subsequently recovered the bullet in the vertebræ of the neck! This
extraordinary penetration led me to suppose that I should always
succeed as I had done in Ceylon, and I have frequently stood the
charge of an African Elephant until close upon me, determined to
give the forehead-shot a fair trial, but I have always failed, except in
the instance now mentioned. It must be borne in mind that the
Elephant was a female, with a head far inferior in size and solidity to
that of the male. The temple-shot, and that behind the ear, are
equally fatal in Africa as in Ceylon, provided the hunter can approach
within ten or twelve yards; but altogether the hunting is far more
difficult, as the character of the country does not admit of an
approach sufficiently close to guarantee a successful shot. In the
forests of Ceylon, an Elephant can be stalked to within a few paces,
and the shot is seldom fired at a greater distance than ten yards.
Thus accuracy of aim is insured; but in the open ground of Africa an
Elephant can seldom be approached within fifty yards, and should he
charge the hunter escape is most difficult. I never found African
Elephants in good jungle, except once, and on that occasion I shot
five quite as quickly as we should kill them in Ceylon.”
Gordon Cumming gives us the following information as to how
the natives cut up an Elephant for food and other purposes. “The
rough outer skin is first removed, in large sheets, from the side
which lies uppermost. Several coats of an under skin are then met
with. This skin is of a tough and pliant nature, and is used by the
natives for making water-bags, in which they convey supplies of
water from the nearest ‘vley,’ or fountain (which is often ten miles
distant), to the Elephants. They remove this inner skin with caution,
taking care not to cut it with the assegai; and it is formed into
water-bags by gathering the corners and edges, and transfixing the
whole on a pointed wand. The flesh is then removed in enormous
sheets from the ribs, when the hatchets come into play, with which
they chop through, and remove individually, each colossal rib. The
bowels are thus laid bare; and in the removal of these the leading
men take a lively interest and active part, for it is throughout and
around the intestines that the fat of the Elephant is mainly found.
“There are few things which a Bechuana prizes so highly as fat of
any description. They will go an amazing distance for a small portion
of it. They use it principally in cooking their sun-dried biltong, and
they also eat it with their corn. The fat of the Elephant lies in
extensive layers and sheets in his inside, and the quantity which is
obtained from a full-grown bull, in high condition, is very great.
Before it can be obtained, the greater part of the intestines must be
removed. To accomplish this, several men eventually enter the
immense cavity of his inside, where they continue mining away with
their assegais, and handing the fat to their comrades outside until all
is bare. While this is transpiring with the sides and intestines, other
parties are equally active in removing the skin and flesh from the
remaining parts of the carcass.
“The natives have a horrid practice on these occasions of
besmearing their bodies, from the crown of the head to the sole of
the foot, with the black and clotted gore; and in this anointing they
assist one another, each man taking up the fill of both his hands,
and spreading it over the back and shoulders of his friend.
Throughout the entire proceeding, an incessant and deafening
clamour of many voices and confused sounds is maintained, and
violent jostling and wrestling are practised by every man, elbowing
the breasts and faces of his fellows, all slippery with gore, as he
endeavours to force his way to the flesh through the dense
intervening ranks, while the sharp and ready assegai gleams in every
hand. The angry voices and gory appearances of these naked
savages, combined with their excited and frantic gestures and
glistening arms, presented an effect so wild and striking that, when I
first beheld the scene, I contemplated it in the momentary
expectation of beholding one-half of the gathering turn their
weapons against the other.
“The trunk and feet of the Elephant are considered a great
delicacy, and are baked in holes in the earth, which have been
heated by fires burnt in them. The flesh of the Elephant is then cut
into strips, varying from six to twenty feet, and about two inches in
breadth and thickness. It is then placed on poles, and allowed to dry
in the sun for two or three days, after which it is packed into
bundles, each man carrying off his share to his wife and family.”

You might also like