DAA by Tech Move - Merged
DAA by Tech Move - Merged
Thank You!
Need of Algorithm
➢ To understand the basic idea of the problem.
➢ To find an approach to solve the problem.
➢ To improve the efficiency of existing techniques.
➢ To understand the basic principles of designing the algorithms.
➢ To compare the performance of the algorithm with respect to other techniques.
➢ It is the best method of description without describing the implementation detail.
➢ A good design can produce a good solution.
➢ To understand the flow of the problem.
➢ To measure the behavior (or performance) of the methods in all cases (best cases,
worst cases, average cases)
➢ With the help of an algorithm, we can also identify the resources (memory, input-
output) cycles required by the algorithm.
➢ With the help of algorithm, we convert art into a science.
Analysis of Algorithm
The analysis is a process of estimating the efficiency of an algorithm. There are two
fundamental parameters based on which we can analysis the algorithm:
Space Complexity:- The space complexity can be understood as the amount of space
required by an algorithm to run to completion.
Time Complexity:- Time complexity is a function of input size n that refers to the
amount of time needed by an algorithm to run to completion.
Types of Algorithm Analysis
➢ Best case:- Define the input for which algorithm takes less time or minimum time. In
the best case calculate the lower bound of an algorithm.
✓ Example:- In the linear search when search data is present at the first location of large
data then the best case occurs.
➢ Worst Case:- Define the input for which algorithm takes a long time or maximum
time. In the worst calculate the upper bound of an algorithm.
✓ Example: In the linear search when search data is not present at all then the worst case
occurs.
➢ Average case:- In the average case take all random inputs and calculate the
computation time for all inputs.
And then we divide it by the total number of inputs.
➢ Sorting algorithms:- Bubble Sort, insertion sort, and many more. These algorithms
are used to sort the data in a particular format.
➢ Searching algorithms:- Linear search, binary search, etc. These algorithms are
used in finding a value or record that the user demands.
➢ Graph Algorithms:- It is used to find the solutions of problems like finding the
shortest path between cities, real-life problems like traveling salesman problems.
Advantages & Disadvantages of Algorithm
Advantages of Algorithms:-
➢ It is easy to understand.
➢ An algorithm is a step-wise representation of a solution to a given problem.
➢ Language Independent- It is not dependent on any programming language, so it can easily
be understood by anyone.
➢ Debug / Error Finding- Every step is independent / in a flow so it will be easy to spot and fix
the error.
➢ Sub-Problems- It is written in a flow so now the programmer can divide the tasks which
makes them easier to code.
Disadvantages of Algorithms:-
➢ Writing an algorithm takes a long time so it is time-consuming.
➢ Understanding complex logic through algorithms can be very difficult.
➢ Branching and Looping statements are difficult to show in Algorithms(imp).
Time Complexity
Time Complexity:- The time complexity of an algorithm is the total amount of time
required by an algorithm to complete its execution.
Examples 1 :-
Examples 2:-
int sum(int A[], int n)
{
int sum = 0, i;
for(i = 0; i < n; i++)
sum = sum + A[i];
return sum;
}
Remark:- If the amount of time required by an algorithm is increased with the increase of
input value then that time complexity is said to be Linear Time Complexity.
Logarithmic Complexity:- It imposes a complexity of O(log(N)). It undergoes the execution
of the order of log(N) steps. To perform operations on N elements, it often takes the
logarithmic base as 2.
Cubic Complexity: It imposes a complexity of O(n3). For N input data size, it executes the
order of N3 steps on N elements to solve a given problem.
Example 1:-
int square(int a)
{
return a*a;
}
Remark:- If any algorithm requires a fixed amount of space for all input values then that
space complexity is said to be Constant Space Complexity.
Example 2:-
int sum(int A[ ], int n)
{
int sum = 0, i;
for(i = 0; i < n; i++)
sum = sum + A[i];
return sum;
}
'n*2' bytes of memory to store array variable 'a[ ]'
2 bytes of memory for integer parameter 'n'
4 bytes of memory for local integer variables 'sum' and 'i' (2 bytes each)
2 bytes of memory for return value.
Remark:- If the amount of space required by an algorithm is increased with the increase
of input value, then that space complexity is said to be Linear Space Complexity.
Asymptotic Notation
Asymptotic Notation:- Asymptotic notation of an algorithm is a mathematical
representation of its complexity.
Input Data
Majorly, we use THREE types of Asymptotic Notations and those are as follows...
➢ Big - Oh (O)
➢ Big - Omega (Ω)
➢ Big - Theta (Θ)
Big - Oh Notation (O):- Big - Oh notation is used to define the upper bound of an algorithm
in terms of Time Complexity. That means Big - Oh notation always indicates the maximum
time required by an algorithm for all input values. That means Big - Oh notation describes
the worst case of an algorithm time complexity.
• Master Method
• Recursion Tree Method
➢ Substitution Method
➢ Iteration Method
➢ Recursion Tree Method
➢ Master Method
Master Theorem
Master’s Theorem is a popular method for solving the recurrence relations.
Case-02:
If a = bk and
➢ If p < -1, then T(n) = θ (nlogba)
➢ If p = -1, then T(n) = θ (nlogba.log2n)
➢ If p > -1, then T(n) = θ (nlogba.logp+1n)
Here, a >= 1, b > 1, k >= 0 and p is a real number.
Case-03:
If a < bk and
➢ If p < 0, then T(n) = O (nk)
➢ If p >= 0, then T(n) = θ (nklogpn)
Problem-01: Solve the following recurrence relation using Master’s theorem-
T(n) = 3T(n/2) + n2
Solution:- We compare the given recurrence relation with T(n) = aT(n/b) + θ (nklogpn).
Then, we have-
a=3
b=2
k=2
p=0
Now, a = 3 and bk = 22 = 4.
Clearly, a < bk. Here, a >= 1, b > 1, k >= 0 and p
So, we follow case-03. is a real number.
Since p = 0, so we have-
T(n) = θ (nklogpn)
T(n) = θ (n2log0n)
Thus,
T(n) = θ (n2)
Problem-02: Solve the following recurrence relation using Master’s theorem-
T(n) = 2T(n/2) + nlogn
Solution:- We compare the given recurrence relation with T(n) = aT(n/b) + θ (n klogpn).
Then, we have- a=2
b=2
k=1
p=1
Now, a = 2 and bk = 21 = 2.
Clearly, a = bk.
Here, a >= 1, b > 1, k >= 0 and p
So, we follow case-02. is a real number.
Since p = 1, so we have-
T(n) = θ (nlogba.logp+1n)
T(n) = θ (nlog22.log1+1n)
Thus,
T(n) = θ (nlog2n)
Problem-03: Solve the following recurrence relation using Master’s theorem-
T(n) = 2T(n/4) + n0.51
Solution:- We compare the given recurrence relation with T(n) = aT(n/b) + θ (n klogpn).
Then, we have- a=2
b=4
k = 0.51
p=0
Now, a = 2 and bk = 40.51 = 2.0279.
Clearly, a < bk.
Here, a >= 1, b > 1, k >= 0 and p
So, we follow case-03. is a real number.
Since p = 0, so we have-
T(n) = θ (nklogpn)
T(n) = θ (n0.51log0n)
Thus,
T(n) = θ (√n)
Problem-05: Solve the following recurrence relation using Master’s theorem-
T(n) = 8T(n/4) – n2logn
Solution:-
➢ The given recurrence relation does not correspond to the general form of Master’s
theorem.
➢ So, it cannot be solved using Master’s theorem.
Now, a = 3 and bk = 31 = 3.
Clearly, a = bk.
Since p = 0, so we have-
T(n) = θ (nlogba.logp+1n)
T(n) = θ (nlog33.log0+1n)
T(n) = θ (n1.log1n)
Thus,
T(n) = θ (nlogn)
Recursion Tree Method
➢ Like Master’s Theorem Recursion Tree is another method for solving the recurrence
relations.
➢ A recursion tree is a tree where each node represents the cost of a certain recursive
sub-problem.
➢ We sum up the values in each node to get the cost of the entire algorithm.
Problem-01: Solve the following recurrence relation using recursion tree method-
T(n) = 2T(n/2) + n
Solution:
Step-06: Add costs of all the levels of the recursion tree and simplify the expression so obtained in terms of
asymptotic notation-
= n x log2n + θ (n)
= nlog2n + θ (n)
= θ (nlog2n)
Problem-02: Solve the following recurrence relation using recursion tree method-
T(n) = 2T(n/2) + c.n
Solution:
B-Tree Property
All leaf nodes must be at same level.
Every node in a B-Tree contains at most m children.
e
The root nodes must have at least 2 nodes.
v
Every node in a B-Tree except the root node and the leaf node contain
o
All the key values in a node must be in Ascending Order.
M
Examples
c h
Te
B-Tree of Order 4 contains a maximum of 3 key values in a node and maximum of 4
children for a node.
Operation on a B-Tree
Searching
Insertion
Deletion
the function
If both are not matched, then check whether search element is smaller
Examples
Construct a B-Tree of Order 3 by inserting numbers from 1 to 10.
Insert-1
Insert-2
Insert-3
Insert-4
Insert-5
Insert-6
Insert-7
Insert-8
ve
M o
c h
e
Insert-9
Insert-10
T
Red-Black Tree Data Structure
Red Black Tree is a Binary Search Tree in which every node is colored
In all the paths of the tree, there should be same number of BLACK
colored nodes.
Examples
ve
o
M
c h
Every Red Black Tree is a binary search tree but every Binary Search Tree
Recolor
Rotation
If tree is Empty then insert the newNode as Root node with color Black
If tree is not Empty then insert the newNode as leaf node with color Red.
sibling of newNode.
If it is colored Black or NULL then make suitable Rotation and Recolor it.
Examples
ve
o
M
c h
Te
Delete operation in Red-Black Tree
Every deletion operation, we need to check with the Red-Black Tree properties.
in BST.
Reference: www.btechsmartclass.com
Merge Sort Algorithm
It divides the problem into sub problems and solves them individually.
It then combines the results of sub problems to get the solution of the
original problem.
e
Step by Step Process
ov
h M
e c
T
Insertion sort Algorithm
step 1: start
return
mid= (left+right)/2
step 4: Stop
Examples
6, 2, 11, 7, 5, 4
ve
M o
c h
Te Final sorted list
Merge sort uses additional memory for left and right sub arrays.
Select the first element of the list (i.e., Element at first position in the
list).
Compare the selected element with all the other elements in the list.
Repeat the same procedure with element in the next position in the list
e
till the entire list is sorted.
ov
M
for(j=i+1; j<size; j++){
h
temp=list[i];
list[i]=list[j];
c
list[j]=temp;
e
}
T Examples
Select the first position element in the list, compare it with all other
elements in the list and when ever we found a smaller element then the
Iteration-01
Iteration-02
Select the second position element in the list, compare it with all other
elements in the list and when ever we found a smaller element then the
Iteration-03
Select the 3rd position element in the list, compare it with all other
elements in the list and when ever we found a smaller element then the
Iteration-04
Iteration-05
Iteration-06
ve
List after 6th Iteration:-
o
M
h
Iteration-07
c
List after 7th Iteration:-
Bubble sort uses two loops- inner loop and outer loop.
Best CaseO(n)
k
li e temp, i, n.
unsorted portion to sorted portion until all the elements are sorted in
the list.
Assume that first element in the list is in sorted portion and all the
Take first element from the unsorted portion and insert that element
Repeat the above process until all the elements from the unsorted
key = A [ i ];
M
j = i - 1;
Here,
h
i = variable to traverse the array A
A [ j+1 ] = A [ j ];
c
be inserted into the sorted sub-array
e
array
}
T
Examples
e
v
o
M
h
c
e Final sorted list
Best Case n
Average Case n2
Worst Case n2
used.
Important Notes
Insertion sort is not a very efficient algorithm when data sets are large.
ve
M o
Selection sort algorithm consists of two nested loops.
h
Owing to the two nested loops, it has O(n2) time complexity.
c
Best Case n2
Average Case n2
e
Worst Case n2
used.
T
It performs all computation in the original array and no other array is
RADIX_SORT(A, d)
// A is an array to be sorted
for i ← 1 to k do
end
Examples
Sort following sequence of data using radix sort: 165,958, 635, 694,
480, 637, 598
The largest element in list is 958, and its width is 3. So radix sort
algorithm needs to perform three scans on each digit from LSD to MSD.
ve
Time complexity Analysis
M o
h
Best O(n+k)
c
Worst O(n+k)
Average O(n+k)
e
Space complexity Analysis
T
O(max)
Heap Sort Algorithm
Heapsort is an in-place comparison based sorting algorithm.
It is similar to the selection sort where we first find the minimum
element and place the minimum element at the beginning.
Heapsort is not stable algorithm.
e
heap. Start from the first index of the non-leaf node whose index is
given by n/2 – 1. Heapify uses recursion
v
heapify(array)
o
Root = array[0]
if(Root != Largest)
M
Swap(Root, Largest)
c h
Te Heap Data Structure
It is a complete binary tree data structure.
Except for the last level, all levels are entirely filled.
There are two types of heap tree.
Max Heap:
In a max heap, the value of the parent element is greater than its child
node.
The largest element is at the root.
Max heap is used in heap sort.
Min Heap:
In min-heap, the value of the parent element is less than its child node.
The smallest element is at the root.
Min heap is used in a priority queue.
Examples
Sort given data using heap sort: 17, 32, 45, 76, 40, 13, 55, 30, 7, 11
> Sorting
STAGE 1: Build max heap
Here, number of elements n = 10, so i = ceil(n/2) – 1 = ceil(10/2) – i = 4
Step 2 : For node having index i=4, check if it satisfies the max heap
property. Here node 4 has value 76, which is greater than both of its child,
Step 3 : Check if the 3rd node satisfies the max heap property.
Step 4 : Check if the 2nd node satisfies the max heap property.
Step 5: Check if the 1st node satisfies the max heap property.
All node satisfies the max heap property, so this is the desired max-heap.
STAGE 2: Sorting
ve
o
In each iteration, the value of the 1st node will be swapped with the last
M
the largest element at the end of the unsorted list.
Step 1 : Swap A[1] with A[10], and heapify the tree again.
c h
Te
Step 2 : Swap A[1] with A[9], and heapify the tree again.
Step 3 : Swap A[1] with A[8], and heapify the tree again.
Step 4 : Swap A[1] with A[7], and heapify the tree again.
Step 5 : Swap A[1] with A[6], and heapify the tree again.
Step 6 : Swap A[1] with A[5], and heapify the tree again.
Step 7 : Swap A[1] with A[4], and heapify the tree again.
Step 8 : Swap A[1] with A[3], and heapify the tree again
Step 9 : Swap A[1] with A[2], and heapify the tree again.
Worst O(nlog n)
Average O(nlog n)
Space complexity Analysis
O(1)
Quick Sort Algorithm
St ep by Step Algorithm
Consider the first element of the list as pivot
Define two variables i and j. Set i and j to first and last elements of the
list respectively.
Examples
Consider the following elements have to be sorted in ascending order -
Step -01:
Left and Loc (pivot) points to the first element of the array.
Step -02:
Since loc points at left, so algorithm starts from right and move towards
left.
As a[loc] < a[right], so algorithm moves right one position towards left as-
Step -03:
Since loc points at left, so algorithm starts from right and move towards
left.
As a[loc] > a[right], so algorithm swaps a[loc] and a[right] and loc points at
right as-
Now,
e
loc, left and right points at the same element.
v
The pivot element 25 is placed in its final position.
o
All elements to the right side of element 25 are greater than it.
All elements to the left side of element 25 are smaller than it.
h M
e c
T
Similar Solve........................
Worst O(n2)
Average O(n*log n)
S pace complexity Analysis
O(log n)
Binomial Heap
A Binomial Heap is a collection of Binomial trees.
Binomial Heap is used to implement priority queues.
It is an extension of Binary Heap that provides faster union or merge
operation together with other operations provided by Binary Heap.
Order-0
Order-2
ve
Order-3
An n nodes should have at most 1 + log2^n binomial trees, here log2 is
o
the binary logarithm.
M
h
c
e
T
>>>>>>Represent trees using left-child, right sibling pointers.
Parent of X
Key
D g e ree of X
Binomial Tree
A Binomial Tree is a unique structure tree which follows the following properties:
A Binomial Tree of order 0 has exactly 1 node.
e
trees of order k-1 and making one as leftmost child or other.
ov
h M
e c
T
Binomial-Tree Property
It has exactly 2k nodes.
It has a depth or height of k.
There are exactly kCi nodes at depth(height) i, for i=0, 1, 2, .....k-1, k.
The root of tree has degree k and children of root are themselves are
follows -
Inserting a node
Decreasing a key
Deleting a node
When we create a new binomial heap, it simply takes O(1) time because
creating a heap will create the head of the heap in which no elements
are attached.
tree satisfies the min-heap property. It means that the root node
:
Case 3 If degree[x] = degree[next x] ≠ degree[sibling[next x]] and
key[x] < key[next x] then remove [next x] from root and attached to x.
and key[x] > key[next x] then remove x from root and attached to [next x].
e
v
o
M
h
c
e
T
heap only with the element to be inserted, and then merging it with the
original heap.
Due to the merging, the single insertion in a heap takes O(logn) time.
Insert-1 5
e
v
o
M
h
c
e
T
Extracting the minimum key Operation in
Binomial Heap
value.
value.
So, we have to compare the key value of the root node of all the
binomial trees.
Let's see an example of extracting the minimum key from the heap.
12, 7, and 15 are the key values of the root node in the above heap in
which 7 is minimum; therefore, remove node 7 from the tree
The degree of node 1 2 and node 25 is B0, and the degree of node 15 is
B2. so use the Merging/Union Operation.
The above heap is the final heap after extracting the minimum key.
Once the value of the key is decreased, it might be smaller than its
'
parent s key that results in the violation of min-heap property.
If such case occurs after decreasing the key, then exchange the
property is satisfied.
After decreasing the key, the min-heap property of the above heap is
violated.
Now, compare 7 wits its parent 30, as it is lesser than the parent, swap
7 with 30, and after swapping, the heap will be -
Swap the element 7 with its parent 8, after swapping the heap will be -
Now, the min-heap property of the above heap is satisfied. So, the
above heap is the final heap after decreasing a key.
Operation).
Now, swap the negative infinity with its root node in order to maintain
the min-heap property.
Now, again swap the negative infinity with its root node.
Extract the minimum key from the heap. Since the minimum key in the
above heap is -infinity so we will extract this key, and the heap would be :
e
v
o
M
h
c
e
T
The final heap after deleting the node 41.
''
The space complexity of a binomial heap with n elements is O(n).
Fibonacci Heap
A fibonacci heap is a data structure that consists of a collection of
trees.
which follow min heap or max heap property.
In a fibonacci heap, a node can have more than two children or no
children at all.
It has more efficient heap operations than that supported by the
binomial and binary heaps.
e
All the trees in the Fibonacci Heap are rooted but not ordered.
ov
h M
Remark:-
e c
x , Degree[x],
P[ ] Mark[x],
T
Left[x], Right[x], Child[x]
e
Example:- We will perform an extract-min operation on the heap below.
ov
h M
e c
T
Delete the min node, add all its child nodes to the root list and set the
min-pointer to the next root in the root list.
The maximum degree in the tree is 3. Create an array of size 4 and map
degree of the next roots with the array.
ve
o
h M
c
The final heap is.
e
T
Decrease-Key:-
Select the node to be decreased, x, and change its value to the new
value k.
If the parent of x, y, is not null and the key of parent is greater than that
of the k then call Cut(x) and Cascading-Cut(y) subsequently.
If the key of x is smaller than the key of min, then mark x as min.
Cut:-
R emove x from the current position and add it to the root list.
If x is marked, then mark it as false.
Cascading-Cut:-
Cut part: Since 24 ≠ nill and 15 < its parent, cut it and add it to the
root list.
Example: Decreasing 35 to 5
Cut part: Since 26 ≠ nill and 5<its parent, cut it and add it to the root list.
Cascading-Cut.
Cut(26): Cut 26 and add it to the root list and mark it as false.
Cascading-Cut(24):
ve
o
h M
e c
D
T
eleting a Node operation on Fibonacci Heap
This process makes use of decrease-key and extract-min operations.
The following steps are followed for deleting a node.
Let k be the node to be deleted
e
Spell Cheker:
v
o
Spell checking is a three-step process. First, look for that word in a
M
Auto-complete:
h
and the Internet. It provides a simple way to find an alternative word to complete
c
It provides an alphabetical filter of entries by the key of the node.
e
We trace pointers only to get the node that represents the string entered
by the user.
T
Browser history:
It is also used to complete the URL in the browser. The browser keeps a
Each node (except the root) can store one letter of the alphabet.
A trie representation for the bell, bear, bore, bat, ball, stop, stock, and stack.
e
v
o
M
h
c
e
T
A dv anta g s
e of Trie Data Structure
It can be insert faster and search the string than hash tables and binary
search trees.
Di s dv
a anta g s e of Trie Data Structure
Combine: Put together the solutions of the subproblems to get the solution
ve
M o
c h
Te
If we expand out two more recursive steps, it looks like this:
Searching Algorithms
If the element is present in the list, then the process is called successful,
and the process returns the location of that element; otherwise, the search
is called unsuccessful.
we start from one end and check every element of the list until the
ve
Else, return not found.
M o
h
Linear Search Algorithm
e c
Best Case O(1)
LinearSearch(array, key)
T
Worst Case O(n)
if item == value
in a sorted array.
portion of an array.
Iterative Method
Recursive Method
The recursive method follows the divide and conquer approach.
Set two pointers low and high at the lowest and the highest positions
respectively.
Find the middle element mid of the array ie. arr[(low + high)/2] = 6
ve
o
Repeat steps 3 to 6 until low meets high.
h M
c
x = 4 is found.
Te
Time Comple xities
Best case complexity: O(1)
Conve x Hull
Polygon is called convex polygon if the angle between any of its two
j
ad acent edges is always less than 1 80. Otherwise, it is called a
concave polygon.
e
(a)Concave polygon (b) Convex polygon (c) Complex polygon
v
Given a set of points in the plane. the convex hull of the set is the
o
smallest convex polygon that contains all the points of it.
h M
e c
T Process to find Conve
’
convex hull s vertices. Lines AB and BA should be added to the solution
set.
Find the point C that is the farthest away from line AB.
Calculate the convex hull of the points on the line AC s right and left ’
sides. Remove line AB from the original solution set and replace it with
AC and CB.
Process the points on the right side of line BA in the same way.
Find the convex hull of the points on the left and right of the line
connecting the two farthest points of that specific convex hull
recursively.
Find the convex hull for a given set of points using divide and conquer approach.
Find left most and rightmost points from the set P and label them as A
and B. Label all the points on the right of AB as S1 and all the points on
the right of BA as S 2.
FindHull(X1, A, C)
FindHull(X2, C, B)
Now we will explore the points in S2, on the right-hand side of the line
BA
FindHull(S2 ,B, A)
e
But X1 set is empty, so call to FindHull (X1, B, F) returns
v
FindHull (X2, F, A)
h M
e c
= {A
T
Solution = Solution
Conventional Approach
e
C11 = S1 + S4 – S5 + S7
C1 2 = S3 + S5
C 21 = S2 + S4
C 22 = S1 + S3 – S2 + S6
Where,
h
S1 = (A11 + A22) * (B11 + B22)
T
S 4 = A22 * (B21 – B11)
C1 2 = S3 + S5
Solution:
let,
ve
o
S 7 = (A12 – A22) x (B21 + B22)
h M
e c
T
Greedy Algorithms
The greedy method is one of the strategies like Divide and conquer used
F or example, suppose we want to find the longest path in the graph below
e
M
ov
h
Our problem is to find the largest path. And, the optimal solution at the
c
Finally the weight of an only child of 3 is 1. This gives us our final result
e
20 + 3 + 1 = 24.
T
However, it is not the optimal solution. There is another path that carries
more weight (20 + 2 + 10 = 32).
Spanning Tree
A spanning tree is a subset of an undirected Graph that has all the vertices
connected by minimum number of edges.
If all the vertices are connected in a graph, then there exists at least one
spanning tree. In a graph, there may exist more than one spanning tree.
Properties:
A spanning tree does not have any cycle.
Any vertex can be reached from any other vertex.
Prim’s Algorithm
P rim’s Algorithm is a famous greedy algorithm.
It is used for finding the Minimum Spanning Tree (MST) of a given graph.
To apply Prim’s algorithm, the given graph must be weighted, connected
and undirected.
e
The vertex connecting to the edge having least weight is usually
selected.
Step-02:
o
ind all the edges that connect the tree to new vertices.
v
F
Find the least weight edge among those edges and include it in the
existing tree.
If including that edge creates a cycle, then reject that edge and look for
the next least weight edge.
M
h
Step-03:
c
Keep repeating step-02 until all the vertices are included and Minimum
Spanning Tree (MST) is obtained.
C
e
PRACTICE PROBLEMS BASED ON PRIM’S ALGORITHM
T
onstruct the minimum spanning tree (MST) for the given graph using
Prim’s Algorithm-
S tep:2
S tep:3
S tep:4
S tep:5
S tep:6
e
S
ince all the vertices have been included in the MST, so we stop.
M
ov
h
=S
5 + 22 + 12 + 16 + 14
c
= 10 + 2
e
= 99 units
T
Time Complexities
Worst case time complexity of Prim’s Algorithm is-
O(
O(E + VlogV) using Fibonacci heap
If adjacency list is used to represent the graph, then using breadth first search,
= O( E + V) x O(logV)
= O(( E + V)logV)
= O( ElogV)
given graph-
Solution:
=1+4+2+ 6 + 3 + 10
=2 6 units
Kruskal’s Algorithm
K ruskal’s Algorithm is a famous greedy algorithm.
It is used for finding the Minimum Spanning Tree (MST) of a given graph.
To apply Kruskal’s Algorithm, the given graph must be weighted,
connected and undirected.
e
ov
S ort all the edges from low weight to high weight.
S tep-02:
Take the edge with the lowest weight and use it to connect the vertices
M
of graph.
h
If adding an edge creates a cycle, then reject that edge and go for the
next least weight edge.
c
S tep-03:
e
Keep adding edges until all the vertices are connected and a Minimum
T
Spanning Tree (MST) is obtained.
Kruskal’s Algorithm-
Step:2
Step:3
Step:4
e
M
ov
Step:5
ch
Te
Step:6
Step:7
S ince all the vertices have been connected / included in the MST, so we stop.
= 10 + 2 5 + 22 + 12 + 16 + 14
= 99 units
Time Complexities
Worst case time complexity of Kruskal’s Algorithm
= O(ElogV) or O(ElogE)
Dijkstra’s Algorithm
Dijkstra's algorithm allows us to find the shortest path between any two
vertices of a graph.
Dijkstra algorithm is a single-source shortest path algorithm.
Here, single-source means that only one source is given, and we have to
find the shortest path from the source to all the nodes.
e
ov
Dijkstra's Algorithm works on the basis that any subpath B -> D of the
shortest path A -> D between vertices A and D is also the shortest path
between vertices B and D.
M
ch
Te
PRACTICE PROBLEMS BASED ON DIJKSTRA’S ALGORITHM
It is easier to start with an example and then think about the algorithm.
C hoose a starting vertex and assign infinity path values to all other devices
If the path length of the adjacent vertex is lesser than new path length, don't
update it
e
After each iteration, we pick the unvisited vertex with the least path length.
So we choose 5 before 7
M
ov
c h
Te
Notice how the rightmost vertex has its path length updated twice
Time Complexities
Time Complexity: O(E Log V)
9
F E
2 6
14 11
C
D
9
10
A 15
7
o r e
S u c D estination
A B C D E F
0 ∞ ∞ ∞ ∞ ∞
A->B 7 9 ∞ ∞ 14
e
A,B,C 7 9 22 ∞ 14
A,B,C,F 7 9 20 ∞ 11
ov
A,B,C,F,D 7 9 20 20 11
A,B,C,F,D,E 7 9 20 20 11
M
h
A,B,C,F,D,E 7 9 20 20 11
c
F nali solution:
Te
9
F E
11
C
D
9
A
7
B A B C
-8
10
0 ∞ ∞
A C AC 10 5
5 ACB 10 5
10
10
B B
10 -8 10 -8
A C A A C
5
5 5
2
Every edge relax time: (V-1)+1
e
M
ov
ch
Te
Time Complexities
Best Case ComplexityO(E)
Space Complexities
S pace Complexity: O(V)
ch
e
To find the shortest path of the above graph, the first step is note down all
T
the edges which are given below:
(A, B), (A, C), (A, D), (B, E), (C, E), (D, C), (D, F), (E, F), (C, B)
The source vertex as 'A'; therefore, the distance value at vertex A is 0 and
the distance value at all the other vertices as infinity.
S ince the graph has six vertices so it will have five iterations.
First iteration
Consider the edge (A, B). Denote vertex 'A' as 'u' and vertex 'B' as 'v'. Now
use the relaxing formula:
d(u) = 0
d(v) = ∞
c(u , v) = 6
d(v) = 0 + 6 = 6
Consider the edge (A, C). Denote vertex 'A' as 'u' and vertex 'C' as 'v'. Now
use the relaxing formula:
d(u) = 0
d(v) = ∞
c(u , v) = 4
d(v) = 0 + 4 = 4
Second iteration
In the second iteration, we again check all the edges. The first edge is (A, B).
Since (0 + 6) is greater than 1 so there would be no updation in the vertex B.
The next edge is (A, C). Since (0 + 4) is greater than 3 so there would be no
updation in the vertex C.
The next edge is (B, E). Since (1 - 1) equals to 0 which is less than 5 so
update:
= 1 - 1 = 0
The next edge is (C, E). Since (3 + 3) equals to 6 which is greater than 5 so
there would be no updation in the vertex E.
e
The next edge is (E, F). Since (5 + 3) equals to 8 which is greater than 4 so
there would be no updation in the vertex F.
ov
The next edge is (C, B). Since (3 - 2) equals to 1` so there would be no
updation in the vertex B.
M
ch
Third iteration
Te
We will perform the same steps as we did in the previous iterations. We will
observe that there will be no updation in the distance of vertices.
A: 0
B: 1
C: 3
D: 5
E: 0
F: 3
The bellman ford algorithm does not produce a correct answer if the sum of
the edges of a cycle is negative.
Knapsack Problem
A knapsack (kind of shoulder bag) with limited weight capacity.
Few items each having some weight and value.
The problem states
The value or profit obtained by putting the items into the knapsack is
maximum
And the weight limit of the knapsack does not exceed.
Ex amples:
Item Weight Value
e
ov
1 18 2 5
2 15 24
C apacity 20Kg
3 10 1 5
M
Greedy About value:
Greedy About Weight:
h
25+2/15*24 = 28.2 15+10/15*24 = 31
c
Greedy About Both Weight and Value:
e
Item Weight Value V/W
T
1 18 2 5 1.3
2 15 24 1.6
3 10 1 5 1.5
Time Complexity
The main time taking step is the sorting of all items in decreasing order of
their value / weight ratio
If the items are already arranged in the required order, then while loop
takes O(n) time
The average time complexity of Quick Sort is O(nlogn)
Therefore, total time taken including the sort is O(nlogn).
KNAPSACK PROBLEM
For the given set of items and knapsack capacity = 60 kg, find the optimal
solution for the fractional knapsack problem making use of greedy approach.
1 5 3 0
2 10 40
3 1 5 4 5
4 22 77
5 2 5 90
OR
Find the optimal solution for the fractional knapsack problem making use of
greedy approach. Consider-
n = 5
w = 60 kg
(w1, w2, w3, w4, w5) = (5, 10, 15, 22, 25)
(b1, b2, b3, b4, b5) = (30, 40, 45, 77, 90)
Solution-
e
S tep-02: Sort all the items in decreasing order of their value / weight ratio-
I1 I2 I5 I4 I3
o
(6) (4) (3.6) (3.5) (3)
S tep-03: Start filling the knapsack by putting the items into it one by one.
v
M
c h
Now
K
Te
napsack weight left to be filled is 20 kg but item-4 has a weight of 22 kg
Since in fractional knapsack problem, even the fraction of any item can be
taken
So, knapsack will contain the following items-
= 160 + (20/22) x 77
= 160 + 70
= 230 units
Dynamic Programming
optimization problems.
5
A A
8
10
50 7
A A A
2
12
A A
100
The five steps used in dynamic programming to solve the optimization problem
e
We will find the optimal solution to these sub-problems.
v
o
Storing the results of these sub-problems.
M
Finally, we will calculate the result of the complex problem.
certain properties
h
c
Overlapping subproblems: The overlapping problems are those that
e
Optimal substructure: The optimal substructure is a substructure that
T
can be obtained by the combination of all the optimal solution of
subproblems.
Consider
Draw a table say T with ‘ ’ (n+1) number of rows and (w+1) number of
columns .
Fill all the boxes of 0th row and 0th column with zeroes as shown-
Start filling the table row wise top to bottom from left to right .
Here, T(i , j) = maximum value of the selected items if we can take items
1 to i and have weight restrictions of j
Then, value of the last box represents the maximum possible value
To identify the items that must be put into the knapsack to obtain that
maximum profit
stored in the entry immediately above it, mark the row label of that
entry
After all the entries are scanned, the marked labels represent the
P R CTICE ROBLEM B SE ON
A P A D 0/1 K N S CK
AP A
ROBLEM P
For the given set of items and knapsack capacity = 5 kg, find the optimal
solution for the 0/1 knapsack problem making use of dynamic programming
approach.
Item Weight Value
1 2 3
2 3 4
3 4 5
4 5 6
OR
Find the optimal solution for the 0/1 knapsack problem making use of
n = 4
w = 5 kg
v
o
Solution-
M
h
Given
Knapsack capacity (w) = 5 k
Number of items (n) = 4
c
Step-01
e ‘ ’ (n+1) = 4 + 1 = 5 number of rows and (w+1) = 5 + 1
T
Draw a table say T with
= 6 number of columns
Fill all the boxes of 0th row and 0th column with 0.
Step-02:
Start filling the table row wise top to bottom from left to right using the
formula -
Finding T(1,1)-
We have
i=
j=
(value)i = (value)1 =
(weight)i = (weight)1 = 2
T 1,1
T(1,1) = 0
Finding T(1,2)-
We have
i=
j=
(value)i = (value)1 =
(weight)i = (weight)1 = 2
T 1,2
T(1,2) = 3
Finding T(1,3)-
We have
i=
j=
(value)i = (value)1 =
(weight)i = (weight)1 = 2
T 1,
T(1,3) = 3
Finding T(1,4)-
We have
i=
j=
(value)i = (value)1 =
(weight)i = (weight)1 = 2
T 1,
T(1,4) = 3
Finding T(1,5)-
We have
i=
j=
(value)i = (value)1 =
(weight)i = (weight)1 = 2
T 1,5
T(1,5) = 3
e
Finding T(2,1)-
We have
= v
o
i
j=
(value)i = (value)2 =
M
(weight)i = (weight)2 = 3
T 2,1
c
e
Similarly, compute all the entries.
T
After all the entries are computed and filled in the table, we get the following
table -
The last entry represents the maximum possible value that can be put into
the knapsack
So, maximum possible value that can be put into the knapsack = 7.
Thus, items that must be put into the knapsack to obtain the maximum value 7
algorithm is used to find all pair shortest path problem from a given
weighted graph .
F dW h
loy ars all Algorit h m
It computes the shortest path between every pair of vertices of the given
graph.
approach.
Time Complexity
Floyd Warshall Algorithm consists of three loops over all the nodes
operations
It is extremely simple
It is easy to implement.
A P A D D A A
LGORITHM- A
o
Pr blem - Consider the following directed weighted graph-
Using Floyd Warshall Algorithm, find the shortest path distance between every
pair of vertices.
Solution-
Step-01
Remove all the self loops and parallel edges (keeping the lowest weight
edge) from the graph
In the given graph, there are neither self edges nor parallel edges.
Step-02
given weights
that edge
Step-03 :
The last matrix D 4 represents the shortest path distance between every pair of
vertices.
Remember
In the above problem, there are 4 vertices in the given graph
So, there will be total 4 matrices of order 4 x 4 in the solution excluding the
B h
e
acktracking Algorit m
The Brute force approach tries out all the possible solutions and
M
chooses the desired/best solutions.
h
suitable, then backtrack and try other solutions. Thus, recursion is used
in this approach.
c
This approach is used to solve problems that have multiple solutions. If
eS S T
T tate pace ree
A space state tree is a tree representing all the possible states (solution
or nonsolution ) of the problem from the root as an initial state to the leaf
as a terminal state.
3,1,2
3,2,1
3
2,3,1
1 2
2,1,3
1,3,2
3 e
v 1 2
k
c
a
o
tr
k
c
a
B
M
h 3
c
1,2,
3,2 3,1
e
1, 2,
T
Application
N-queen proble
Sum of subset proble
Graph colorin
Hamiliton cycle
G hC rap oloring
Such that no two ad acent vertices of it are assigned the same color. j
Graph Coloring is also called as Vertex Coloring.
Such a graph is called as a Properly colored graph.
Assignmen
Chromatic Number
Chromatic Number is the minimum number of colors required to
properly color any graph.
1. Cycle Graph
In a cycle graph, all the vertices are of degree 2
number =2
If number of vertices in cycle graph is odd, then its chromatic
number = 3.
2. Planar Graphs
A Planar is a graph that can be drawn in a plane such that none of its
3. Complete Graphs
A complete graph is a graph in which every two distinct vertices are
vertex
4. Bipartite Graphs
Graphs consists of two sets of vertices X and Y
A Bipartite
set.
5. Tree
A Tree is a special type of connected graph in which there are no
circuits
Problem-01 :
Solution: Minimum number of colors used to color the given graph are 2
Therefore, Chromatic Number of the given graph = 2
Problem-02 :
Solution: Minimum number of colors used to color the given graph are 3
Therefore, Chromatic Number of the given graph = 3.
Problem-0 3:
Solution: Minimum number of colors used to color the given graph are 4
Therefore, Chromatic Number of the given graph = 4
Problem-0 4:
Solution: Minimum number of colors used to color the given graph are 3
Therefore, Chromatic Number of the given graph = 3.
Problem-05 :
Solution: Minimum number of colors required to color the given graph are 3
Therefore, Chromatic Number of the given graph = 3.
N - Queens Problems v
e
o
N - Queens problem is to place n - queens in such a manner on an n x n
M
chessboard that no queens attack each other by being in the same row,
column or diagonal .
It can be seen that for n =1, the problem has a trivial solution.
No solution exists for n =2 and n =3.
h
c
The n- queen problem must follow the following rules
e
There must be at least one queen in each row
T
There must be at least one queen in each diagonal.
Example :
The implicit tree for 4 - queen problem for a solution (2, 4, 1, 3) is as follows:
Hamiltonian Cycle
A Hamiltonian graph is the directed or undirected graph containing a
Hamiltonian cycle.
The Hamiltonian cycle is the cycle that traverses all the vertices of the
given graph G exactly once and then ends at the starting vertex.
Practice-Problems-Based-On- Hamiltonian-Graph
Solution: Firstly, we start our search with vertex 'a.' this vertex 'a' becomes the
root of our implicit tree.
e
v
Next, we select 'c' adjacent to 'b.'
o
M
h
c
e
T
Next, we select 'd' adjacent to 'c.'
Next, we select vertex 'f' adjacent to 'e.' The vertex adjacent to 'f' is d and e, but
they have already visited. Thus, we get the dead end, and we backtrack one
From backtracking, the vertex ad acent to e is b, c, d, and f from which vertex j ' '
'f' has already been checked, and b, c, d have already visited.
Now, adjacent to c is 'e' and adjacent to 'e' is 'f' and adjacent to 'f' is 'd' and
adjacent to 'd' is 'a.' Here, we get the Hamiltonian Cycle as all the vertex other
Example
from one, then two, then three, and so on for the required sum.
Include: Here include means that we are selecting the element from the
array .
Exclude: Here, exclude means that we are rejecting the element from the
array .
Example
0
a =0
a =1 0
b =1
10
b =1 b =1
20
30 10
c=1
c=1 =1
=0 c 50
....................
c
c =0 Similar next step
60
30 40 10
d =1
d =0 d =1 d =0 d =1 d =0
70
30 80 40 50 10
a =1 b =0 c =0 d =1
a =0 b =1 c =1 d =0
It is similar to the backtracking since it also uses the state space tree.
elements one by one, starting from the root. Note that the root contains
no element.
problems.
Examples:
S
6
3
B
6
A
3
2
E
2
7
D
C
4 1
5
S
6
B
3 9
12
A 12
D E S
10 5
6
C 10
D
S
9 7
8 7
G E B A
For a given set {A, B, C, D}, the state space tree will be constructed as follows :
He has to come back to the city from where he starts his journey.
What is the shortest possible route that the salesman must follow to
e
If salesman starting city is A, then a TSP tour in the graph is
v -
A → B → D → Co → A
= 10 + 25 + 30 + 15
M
= 80 units
h
c
e
Traveling Salesperson problem using
Step-01 :
Row Reduction-
This will create an entry 0 in that row, thus reducing that row.
‘ ’
Column Reduction-
This will create an entry 0 in that column, thus reducing that column.
‘ ’
Now, we calculate the cost of node-1 by adding all the reduction elements.
Cost(1)
= 4 + 5 + 6 + 2 + 1
= 18
Set M[B,A] = ∞
Cost(2)
= 18 + (13 + 5) + 0
= 36
Set M[C,A] = ∞
Cost(3)
= 18 + 0 + 7
= 25
Set M[D,A] = ∞
Cost(4)
= 18 + 5 + 3
= 26
Thus, we have
( ) = 36 (for Path A → B
Cost 2
Step-03:
Set M[B,A] = ∞
Cost(5)
= 25 + (13 + 8) + ∞
= ∞
Set M[D,A] = ∞
Cost(6)
= 25 + 0 + 0
= 25
Thus, we have
( ) = (for Path A → C → B
Cost 5 ∞
Step-04:
Set M[B,A] = ∞
Cost(7)
= 25 + 0 + 0
= 25
Thus
36
B 25 2 6 D
C
∞
25
D
B
25
e
v
o
M
h
c
e
T