Week 1 Chapter 1: Introduction - Programming Overview Chapter 2: Algorithms Analysis Chapter 3: Approach To Solve Algorithm Design Problems Chapter 4: Abstract Data Type & JAVA Collectio
Trang 2Problem Solving in Data Structures & Algorithms Using JAVA
First Edition
By Hemant Jain
Trang 3in the case of very brief quotations embodied in critical reviews and certain other non-commercial uses permitted by copyright law
Trang 4I would like to express profound gratitude to my guide/ my friend Naveen Kaushik for his
invaluable encouragement, supervision and useful suggestion throughout this book writing work.His support and continuous guidance enable me to complete my work successfully
Last but not least, I am thankful to Anil Berry and Others who helped me directly or indirectly incompleting this book
Hemant Jain
Trang 8
PROBLEMS IN STACK
PROS AND CONS OF ARRAY AND LINKED LIST IMPLEMENTATION OF STACK.USES OF STACK
Trang 11OO DESIGN FOR A MCDONALDS SHOP
OBJECT ORIENTED DESIGN FOR A RESTAURANTOBJECT ORIENTED DESIGN FOR A LIBRARY SYSTEMSUGGEST A SHORTEST PATH
EXERCISE
APPENDIX
APPENDIX A
Trang 12CHAPTER 0: HOW TO USE THIS BOOK
Trang 13This book is about usage of data structures and algorithms in computer programming Datastructures are the ways in which data is arranged in computers memory Algorithms are set ofinstructions to solve some problem by manipulating these data structures
Designing an efficient algorithm to solve a computer science problem is a skill of Computerprogrammer This is the skill which tech companies like Google, Amazon, Microsoft, Facebookand many others are looking for in an interview Once we are comfortable with a programminglanguage, the next step is to learn how to write efficient algorithms
This book assumes that you are a JAVA language developer You are not an expert in JAVAlanguage, but you are well familiar with concepts of references, functions, arrays and recursion
At the start of this book, we will be revising the JAVA language fundamentals that will be usedthroughout this book We will be looking into some of the problems in arrays and recursion too
Then in the coming chapter we will be looking into Complexity Analysis Followed by thevarious data structures and their algorithms Will look into a Linked-List, Stack, Queue, Trees,Heap, Hash-Table and Graphs We will also be looking into Sorting, Searching techniques
And we will be looking into algorithm analysis of various algorithm techniques, we will belooking into Brute-Force algorithms, Greedy algorithms, Divide and Conquer algorithms,
Dynamic Programming, Reduction and Back-Tracking
In the end, we will be looking into System Design that will give a systematic approach to solvethe design problems in an Interview
Trang 14
Given the limited time you have before your next interview, it is important to have a solid
preparation plan The preparation plan depends upon the time and which companies you areplanning to target Below are the three-preparation plan for 1 Month, 3 Month and 5 Month
durations
1 Month Preparation Plans
Below is a list of topics and approximate time user need to take to finish these topics These arethe most important chapters that must to be prepared before appearing for an interview
This plan should be used when you have a small time before an interview These chapters cover90% of data structures and algorithm interview questions In this plan since we are reading aboutthe various ADT and JAVA collections in chapter 4 so we can use these datatype easily withoutknowing the internal details how they are implemented
Chapter 24 is for system design, you must read this chapter if you are three or more years ofexperienced Anyway, reading this chapter will give the reader a broader perspective of variousdesigns
Week 1
Chapter 1: Introduction - Programming Overview
Chapter 2: Algorithms Analysis Chapter 3: Approach To Solve Algorithm Design Problems
Chapter 4: Abstract Data Type & JAVA Collections
You will get a basic understanding of how to find complexity of a solution You will know how to handle new problems You will read about a variety of datatypes and their uses.
Week 2
Chapter 5: Searching Chapter 6: Sorting Chapter 14: String Algorithms
Searching, Sorting and String algorithm consists
of a major portion of the interviews.
Week 3
Chapter 7: Linked List Chapter 8: Stack Chapter 9: Queue
Linked list, Stack and Queue are one of the favorites in an interview.
Week 4
Chapter 10: Tree Chapter 23: Interview Strategy Chapter 24: System Design
This portion you will read about Trees and System Design You are good to go for interviews Best of luck.
3 Month Preparation Plan
This plan should be used when you have some time to prepare for an interview This preparationplan includes nearly everything in this book except various algorithm techniques Algorithmproblems that are based on dynamic programming divide & conquer etc Which are asked in vary
Trang 15interview with them you can park these topics for some time and focus on the rest of the topics
Again, same thing here with system design problems, the more experience you are, the moreimportant this chapter becomes However, if you are a fresher from college, then also you shouldread this chapter
Week 1
Programming Overview Chapter 2: Algorithms Analysis Chapter 3: Approach To Solve Algorithm Design Problems Chapter 4: Abstract Data Type &
Chapter 1: Introduction -JAVA Collections
You will get a basic understanding of how to find complexity of a solution You will know how to handle new problems You will read about a variety of datatypes and their uses.
Week 2 &
Week 3
Chapter 5: Searching Chapter 6: Sorting Chapter 14: String Algorithms
Linked list, Stack and Queue are one of the favorites in an interview.
Week 6 &
Week 7
Chapter 10: Tree Chapter 11: Heap
This portion you will read about trees and heap data structures.
Week 8 &
Week 9
Chapter 12: Hash-Table Chapter 13: Graphs
Hash-Table is used throughout this book in various places, but now it’s time to understand how Hash-Table are actually implemented Graphs are used to propose a solution many real life problems.
Chapter 24: System Design
Interview strategy and system design chapter are the final chapters of this course.
Week 11 &
At this time, you need to revise all the chapters that we have seen in this book.
Whatever is left needs to be completed and the exercise that may be left needing to be solved in this period of time.
5 Month Preparation Plan
In this preparation plan is made on top of 3-month plan In this plan, the students should look foralgorithm design chapters In addition, in the rest of the time they need to practice more and morefrom www.topcoder.com and other resources If you are targeting google, Facebook, etc., Then it
is highly recommended to join topcoder and practice as much as possible
Chapter 1: Introduction - Programming
Trang 16Week 2
Overview Chapter 2: Algorithms Analysis Chapter 3: Approach To Solve Algorithm Design Problems Chapter 4: Abstract Data Type & JAVA Collections
You will get a basic understanding of how to find complexity of a solution You will know how to handle new problems You will read about a variety of datatypes and their uses.
Week 3, Week
4 &
Week 5
Chapter 5: Searching Chapter 6: Sorting Chapter 14: String Algorithms
Searching, sorting and string algorithm consists of a major portion of the interviews Week 6, Week
7 &
Week 8
Chapter 7: Linked List Chapter 8: Stack Chapter 9: Queue
Linked list, Stack and Queue are one of the favorites in an interview.
Week 9 &
Week 10
Chapter 10: Tree Chapter 11: Heap
This portion you will read about trees and priority queue.
Week 11 &
Week 12
Chapter 12: Hash-Table Chapter 13: Graphs
Hash-Table is used throughout this book in various places, but now it’s time to
understand how Hash-Table are actually implemented.
Graphs are used to propose a solution many real life problems.
Chapter 16: Brute Force Chapter 17: Greedy Algorithm Chapter 18: Divide-And-Conquer, Decrease-And-Conquer
Chapter 19: Dynamic Programming Chapter 20: Backtracking And Branch- And-Bound
Chapter 21: Complexity Theory And Np Completeness
These chapters contain various algorithms types and their usage Once the user is familiar with most of this algorithm Then the next step is to start solving topcoder
Interview strategy and system design chapter are the final chapters of this course.
Trang 17
These are few preparation plans that can be followed to complete this book there by preparing forthe interview It is highly recommended that the user should read the problem statement first, then
he should try to solve the problems by himself and then only he should look into the solution tofind the approach of the book Practicing more and more problems will increase your thinkingcapacity and you will be able to handle new problems in an interview System design is a topicthat is not asked much from a fresher from college, but as you gain experience its importanceincrease We will recommend practicing all the problems given in this book, then solve more andmore problems from online resources like www.topcoder.com, www.careercup.com,
www.geekforgeek.com etc
Trang 18PROGRAMMING OVERVIEW
Trang 19This chapter emphasizes on brush up of the fundamentals of the JAVA Programming language Itwill talk about variables, references, classes, loops, recursion, arrays etc We assume that thereader is familiar with the syntax of the JAVA programming language and knows the basics ofObject-Orientation
Trang 20
It is tradition to discuss a HelloWorld program in the start which will print the phrase “Hello,World!” to the output screen So let us start discussing it This is a small program but it containsmany common features of all the JAVA programs
1. This program begins with “public class HelloWorld”:
a. A class is the basic unit of encapsulation Keyword class is used to create a new
class in our case class HelloWorld is created The class name is same as the name ofthe file, which will contain this class Therefore, in our case the name of the file isHelloWorld.java A class contains data and methods
b. The keyword public is an access specifier, which sets the accessibility of classes A
public class can be accessed from any class within the JAVA program
2. Next are the comments, which are for readability of the program and are ignored by thecompiler
Trang 21
4. System.out.println(“Hello, World!”) is a system provided method which will print “Hello,World! ” to the standard output
Trang 22
An Object is an entity with state and behavior A baby, a cat, a dog, a bulb etc are all examples
of objects A baby has properties & states (name, hungry, crying, sleeping etc.) and behaviors(feed, play, etc.) Another example a bulb have two states (on, off) and the two behaviors (turn
on, turn off)
Software objects are just like real world objects They have state in the form of member
variables called fields (isOn) and they expose behavior in the form of member functions called methods (turn on, turn off).
Trang 23
"Variables" are simply storage locations for data For every variable, some memory is allocated.The size of this memory depends on the type of the variable
Example 1.2:
public class variableExample {
public static void main(String[] args ) {
Trang 24The various types of variable are defined as Data Types There are two varieties of data typesavailable in JAVA:
1. Primitive/ Basic Data Types
2. Reference Data Types
Trang 25
Example 1.3: Program demonstrating range of Primitive data type
public class MinMaxValueTest {
public static void main(String args []) {
byte maxByte = Byte.MAX_VALUE;
byte minByte = Byte.MIN_VALUE;
short maxShort = Short.MAX_VALUE;
short minShort = Short.MIN_VALUE;
int maxInteger = Integer.MAX_VALUE;
int minInteger = Integer.MIN_VALUE;
long maxLong = Long.MAX_VALUE;
long minLong = Long.MIN_VALUE;
float maxFloat = Float.MAX_VALUE;
float minFloat = Float.MIN_VALUE;
double maxDouble = Double.MAX_VALUE;
double minDouble = Double.MIN_VALUE;
System.out.println( "Range of byte :: " + minByte + " to " + maxByte);
System.out.println( "Range of short :: " + minShort + " to " + maxShort);
Trang 26System.out.println(" Range of integer :: "+ minInteger + " to " +maxIntege); System.out.println( "Range of long :: " + minLong + " to " + maxLong); System.out.println( "Range of float :: " + minFloat + " to " + maxFloat); System.out.println( "Range of double :: " + minDouble + " to " + maxDouble); }
Trang 27Arguments can be passed from one method to other using parameters All the basic data typeswhen passed as parameters are by the passed-by-value That means a separate copy is createdinside the called method and the variable in the calling method remains unchanged
Trang 28Reference variables are used to store memory address of classes as well as arrays Any variableother them 8 primitive data types are reference data type
Parameter passing of a reference variable is done by copying the address of the variable Thismethod is called pass-by-reference Since the object is not copied, it is shared, the changes done
Trang 29If you need to change the value of the parameter inside the method, then you should use call byreference JAVA language by default passes by value Therefore, to make it happen, you need topass the address of a variable and changing the value of the variable using this address inside thecalled method
Points to remember:
1. Call by reference is implemented indirectly by passing the address of an instance of class
or array to the function
Trang 31
There are three types of methods Class Methods, Instance Methods and Constructors By default,all the methods are instance methods
5. The special keyword “this” is valid only inside instance methods (and invalid inside classmethods ) as “this“ refers to the current instance
Constructor: It is a special kind of method, which is invoked over objects when they are created.
Constructor methods have the same name as the class Constructor method is used to initialize thevarious fields of the object For the class that does not have constructors, JAVA language providesdefault constructors for them
Trang 32
Access modifiers are used to set the visibility level to the class, variables and methods JAVAprovide four types access modifiers: default, public, protected, private
Trang 33Objects define their interface as the interaction with the outside world For example, in the bulbcase switch is the interface between you and the bulb You press the button turn on and the bulbstart glowing
Example 1.7:
public inte rface BulbInterface {
public void turnOn();
public void turnOff();
Trang 34
These are the various relationships that exist between two classes:
Dependency: Objects of one class use objects of another class temporarily When a class creates
an instance of another class inside its member method and use it and when the method exits, thenthe instance of the other class is deleted
Trang 36
An abstract method is a method which does not have a definition Such methods are declared withabstract keyword
A class which has at least one abstract method need to be declared as abstract We cannot createobjects of an abstract class (A class which does not have any abstract method can also be
public class Circle e xte nds Shape {
private double radius ;
Trang 37public class ShapeDemo {
public static void main(String[] args ) {
double width = 2, length = 3;
Shape rectangle = ne w Rectangle( width , length );
System.out.println( "Rectangle width: " + width + " and length: " + length
+ " Area: " + rectangle area()
+ " Perimeter: " + rectangle perimeter());
double radius = 10;
Shape circle = ne w Circle( radius );
System.out.println( "Circle radius: " + radius
+ " Area: " + circle area()
Trang 38+ " Perimeter: " + circle perimeter());
Trang 39
Example 1.12:
public class LinkedList {
private static class Node {
private int value ;
private Node next ;
Trang 40private int value ;
private Node lChild ;
private Node rChild ;
// Nested Class Node other fields and methods }