Algorithm
Algorithm
AND
Copyright CareerMonk Publications. All rights reserved. All rights reserved. No part of this book may be reproduced in any form or by any electronic or mechanical means, including information storage and retrieval systems, without written permission from the publisher or author
Acknowledgements
I would like to express my gratitude to many people who saw me through this book, to all those who provided support, talked things over, read, wrote, offered comments, allowed me to quote their remarks and assisted in the editing, proofreading and design. In particular, I would like to thank the following individuals. , for encouraging me when I was at . He is the first person who taught me and its by giving good books on them. [ . [ [ [ valuable suggestions. [ ], [ spending their valuable time in reviewing the book, suggestions and encouragement. , ] for , , . . . , ], [ , ] and ] for spending time in reviewing, testing code and for providing me the ], [ , ], ], for his encouragement during my stay at
the importance of
& [Founders of ], for approaching me for teaching Data Structures and Algorithms at their training centers. They are the primary reason for initiation of this book. , and for your help and suggestions. have contributed greatly to the quality of this book. I thank all of you
Last but not least, I would like to thank & [ [ [ ], my family during our studies. [ ,
of ], , ]& [
M-Tech, Founder of
A stone is broken by the last stroke. This does not mean that first stroke was useless. Success is a result of continuous daily effort. -Stand up, be bold, be strong. Take the whole responsibility on your own shoulders, and know that you are the creator of your own destiny. --
Preface
Dear Reader, Please Hold on! I know many people do not read preface. But I would like to strongly recommend reading preface of this book at least. This preface has from regular prefaces. Main objective of the book is not to give you the theorems and proofs about and . I have followed a pattern of improving the problem solutions with different complexities (for each problem, you observe multiple solutions with different improved complexities). Basically, its an enumeration of possible solutions. With this approach, even if we get a new question it gives us a way to think about all possible solutions. This book is very much useful for interview preparation, competitive exams preparation, campus preparations. As a if you read complete book with good understanding, I am sure you will challenge the interviewers and that is the objective of this book. If you read as an , you will give better lectures with easy go approach and as a result your students will feel proud for selecting Computer Science / Information Technology as their degree. This book is very much useful for the of and during their academic preparations. All the chapters of this book contain theory and their related problems as many as possible. There a total of approximately algorithmic puzzles and all of them are with solutions. If you read as a preparing for competition exams for Computer Science/Information Technology], the content of this book covers the topics in full details. While writing the book, an intense care has been taken to help students who are preparing for these kinds of exams. In all the chapters you will see more importance given to problems and analyzing them instead of concentrating more on theory. For each chapter, first you will see the basic required theory and then followed by problems. For many of the problems, solutions are provided with different complexities. We start with solution and slowly move towards the possible for that problem. For each problem we will try to understand how much time the algorithm is taking and how much memory the algorithm is taking. It is that, at least one complete reading of this book is required to get full understanding of all the topics. In the subsequent readings, you can directly go to any chapter and refer. Even though, enough readings were given for correcting the errors, due to human tendency there could be some minor typos in the book. If any such typos found, they will be updated at . I request you to constantly monitor this site for any corrections, new problems and solutions. Also, please provide your valuable suggestions at: . Wish you all the best. Have a nice reading. M-Tech, Founder of
Data Structures and Algorithms for GATE Data Structures and Algorithms Made Easy in Java Coding Interview Questions Peeling Design Patterns
Table of Contents
1. Introduction ----------------------------------------------------------------------- 9 2. Recursion and Backtracking ------------------------------------------------------33 3. Linked Lists -----------------------------------------------------------------------38 4. Stacks ------------------------------------------------------------------------------74 5. Queues ----------------------------------------------------------------------------96 6. Trees ----------------------------------------------------------------------------- 106 7. Priority Queue and Heaps ------------------------------------------------------ 175 8. Disjoint Sets ADT --------------------------------------------------------------- 193 9. Graph Algorithms -------------------------------------------------------------- 202 10. Sorting--------------------------------------------------------------------------- 246 11. Searching ------------------------------------------------------------------------ 269 12. Selection Algorithms [Medians]------------------------------------------------ 294 13. Symbol Tables------------------------------------------------------------------- 303 14. Hashing ------------------------------------------------------------------------- 305 15. String Algorithms --------------------------------------------------------------- 320 16. Algorithms Design Techniques ------------------------------------------------ 344 17. Greedy Algorithms ------------------------------------------------------------- 347 18. Divide and Conquer Algorithms ----------------------------------------------- 357 19. Dynamic Programming --------------------------------------------------------- 371 20. Complexity Classes ------------------------------------------------------------- 408 21. Miscellaneous Concepts -------------------------------------------------------- 415
Introduction
INTRODUCTION
Chapter-1
The objective of this chapter is to explain the importance of analysis of algorithms, their notations, relationships and solving as many problems as possible. We first concentrate on understanding the basic elements of algorithms, importance of analysis and then slowly move towards analyzing the algorithms with different notations and finally the problems. After completion of this chapter you should be able to find the complexity of any given algorithm (especially recursive functions).
1.1 Variables
Before going to the definition of variables, let us relate them to old mathematical equations. All of us have solved many mathematical equations since childhood. As an example, consider the below equation:
We dont have to worry about the use of above equation. The important thing that we need to understand is, the equation has some names ( and ) which hold values (data). That means, the ( and ) are the place holders for representing data. Similarly, in computer science we need something for holding data and are the facility for doing that.
1.1 Variables
Introduction
The number of bits allocated for each primitive data type depends on the programming languages, compiler and operating system. For the same primitive data type, different languages may use different sizes. Depending on the size of the data types the total available values (domain) will also changes. For example, may take bytes or bytes. If it takes bytes ( bits) then the total possible values are to + (-1). If it takes, bytes ( bits), then the possible values are between to (-1). Same is the case with remaining data types too.
10
Introduction
Commonly used ADTs : Linked Lists, Stacks, Queues, Priority Queues, Binary Trees, Dictionaries, Disjoint Sets (Union and Find), Hash Tables, Graphs, and many other. For example, stack uses LIFO (Last-In-First-Out) mechanism while storing the data in data structures. The last element inserted into the stack is the first element that gets deleted. Common operations of it are: creating the stack, pushing an element onto the stack, popping an element from stack, finding the current top of the stack, finding number of elements in the stack etc... While defining the ADTs do not care about implementation details. They come in to picture only when we want to use them. Different kinds of ADTs are suited to different kinds of applications, and some are highly specialized to specific tasks. By the end of this book, we will go through many of them and you will be in a position to relate the data structures to the kind of problems they solve.
11
Introduction
, since the number of statements varies with the programming language as well as the style of the individual programmer.
Ideal Solution? Let us assume that we expressed running time of given algorithm as a function of the input size
(i.e., ) and compare these different functions corresponding to running times. This kind of comparison is independent of machine time, programming style, etc...
For the above example, we can represent the cost of car and cost of cycle in terms of function and for a given function ignore the low order terms that are relatively insignificant (for large value of input size, ). As an example in the below case, , , and are the individual costs of some function and approximate it to . Since, is the highest rate of growth.
12
Introduction
D e c r e a s i n g
R a t e s O f G r o w t h
Introduction
For a given algorithm, we can represent best, worst and average cases in the form of expressions. As an example, let be the function which represents the given algorithm. , for worst case for best case Similarly, for average case too. The expression defines the inputs with which the algorithm takes the average running time (or memory).
Input Size,
Big-O Visualization
O O O is the set of functions with smaller or same order of growth as O etc.. For example, O includes 14
Introduction
we do not care for rate of
O , .
O , .
Big-O Examples
Example-1 Find upper bound for Solution: for all =O with c = 4 and Example-2 Find upper bound for Solution: for all =O with Example-3 Find upper bound for Solution: =O
and
and
Example-4 Find upper bound for Solution: for all =O with Example-5 Find upper bound for Solution: for all =O with and Example-6 Find upper bound for Solution: for all O with
and
and
No Uniqueness?
There are no unique set of values for and in proving the asymptotic bounds. Let us consider, For this function there are multiple and values possible. Solution1: Solution2: for all for all and and is a solution. is also a solution. O
15