Dijkstra's Algorithm and Negative Weights
Dijkstra's Algorithm and Negative Weights
Chapter-1. Introduction
What is Algorithm
Finite set of steps to solve a problem is call algorithm.
Analysing is a process of comparing two algorithms w.r.t time and space.
In computer science, the analysis of algorithms is the process of finding the computational
complexity of algorithms – the amount of time, storage, or other resources needed to execute them.
Initially the solution to problem is written in natural language known as algorithm then this
algorithm is converted into code.
If algorithm is correct then program should produce correct output on valid input otherwise it
should generate an appropriate error message.
An algorithm is said to be efficient when this function's values are small, or grow slowly compared
to a growth in the size of the input.
Different inputs of the same length may cause the algorithm to have different behaviour, so best,
worst and average case.
This document is property of RKDEMY and cannot be used, disclosed or duplicated without the prior written consent of RKDEMY pg.1- 1
Analysis of Algorithm Introduction
(i) Input:
The range of input for which algorithm work and there should be clear indication for the range of
inputs for which the algorithm may fail.
(ii) Output:
Algorithm reads input, processes it and produce at least one output.
(iii) Definiteness:
Each of the statement in the algorithm must be clear and precise. There should not be ambiguity in
any of the statement.
(iv) Finiteness:
Algorithm should be finite i.e there should not be infinite condition leading to a never-ending
procedure and hence never completing the task.
(v) Effectiveness:
It should produce the result as fast as possible or efficiently.
5. Loop Statement
a. While (condition) do
Do Some Work
end
b. For index Start to end do
Do some work
End
This document is property of RKDEMY and cannot be used, disclosed or duplicated without the prior written consent of RKDEMY pg.1- 2
Analysis of Algorithm Introduction
Algorithm Factorial(n)
// Description: Find factorial of given number
// Input: Number n whose factorial is to be computed.
// Output: Factorial of n = n × (n – 1) × …. × 2 × 1
If (n ==1) then
return 1
else
return n * Factorial(n – 1)
Performance Analysis
• Efficiency:
Efficiency of algorithm is it should take less space in memory and also require less time for
giving the output.
The various parameters required to be considered for the efficiency of an algorithm are:
1. Space Complexity
2. Time Complexity
1. Space Complexity
The amount of memory requires to solve given problem is called space complexity of the
algorithm.
This document is property of RKDEMY and cannot be used, disclosed or duplicated without the prior written consent of RKDEMY pg.1- 3
Analysis of Algorithm Introduction
Algorithm ADD_SCALAR(A,B)
// Description: Perform arithmetic addition of two numbers
// Input: Two scalar variables A and B
// Output: variable C, which holds the addition of A and B
C←A+B
return C
The addition of two scalar numbers required one extra memory location to hold the result. Thus
the space complexity of this algorithm is constant, hence S(n) = O(1).
Algorithm ADD_ARRAY(A, B)
// Description: Performa element-wise arithmetic addition of two arrays
// Input: Two number arrays A and B
// Output: Array C holding the element-wise sum of array A and B
for i ← 1 to n do
C[i] ← A[i] + B[i]
end
return C
Addition corresponding elements of two arrays, each of size n requires extra n memory locations
to hold the result. As input size n increases, required space to hold the result also grows in the linear order
of input. Thus, the space complexity of above code segment would be S(n) = O(n).
This document is property of RKDEMY and cannot be used, disclosed or duplicated without the prior written consent of RKDEMY pg.1- 4
Analysis of Algorithm Introduction
The addition of all array elements requires only one extra variable denoted as sum, this is independt
of array size.
So space complexity of algorithm is S(n)=O(1)
2. Time Complexity
The Time required by the algorithm to solve given problem is called complexity of the algorithm.
Time complexity is not measured in physical clock tricks, rather it is most frequent operation in
algorithm.
We use notation T(n) to symbolise time complexity
The sum of two scalar numbers requires one addition operation. Thus the time complexity of this
algotithm is constant, so T(n) = O(1).
This document is property of RKDEMY and cannot be used, disclosed or duplicated without the prior written consent of RKDEMY pg.1- 5
Analysis of Algorithm Introduction
As it can be observed from above code, addition array elements required iterating loop n times.
Variable i is initialized once, the relation between control variable i and n are checked n times, and i is
incremented n times. With the loop, addition and assignment operations are performed n time.
Thus, the total time of algorithm is measured as
T(n) = f(initialization) + n(comparison+ increment +addition + assignment)
= 1 + 4n
While doing efficiency analysis of the algorithm, we are interested in the order of complexity in term
of input size n.
So, all multiplicative and divisive constants should be dropped. Thus, for given algorithm T(n) = O(n).
The addition of all array elements requires n additions (we shall omit ṭhe number of comparisons,
assignment, initialization etc. to avoid the multiplicative or additive constants. A number of additions
depend on the size of the array. It grows in the linear order of imput size. Thus the time complexity of
above code is T(n) = O(n).
This document is property of RKDEMY and cannot be used, disclosed or duplicated without the prior written consent of RKDEMY pg.1- 6
Analysis of Algorithm Introduction
Growth Function
Growth functions are used to estimate the number of steps an algorithm uses as its input
grows.
Order of growth indicates how quickly the time required by algorithm grows with respect to
input size.
The largest number of steps needed to solve the given problem using an algorithm on input
of specified size is worst-case complexity.
Binary search
Logarithmic log n
Insert / delete element from binary search tree
Linear search
Merge sort
Binary search
n log n n log n
Quick sort
Heap sort
Selection sort
Bubble sort
Quadratic n2
Input 2D array
Find maximum element from 2D matrix
n3 Matrix multiplication
Cubic
Find power set of any set
These are widely used classes, there exist many other classes.
Algorithm having exponential or factorial running time are unacceptable for practical use.
This document is property of RKDEMY and cannot be used, disclosed or duplicated without the prior written consent of RKDEMY pg.1- 7
Analysis of Algorithm Introduction
Asymptotic Notation
Asymptotic notations are mathematical tool to find time and space complexity of an algorithm
without implementing it in a programming language.
It is way of describing cost of algorithm.
Asymptotic notation does analysis of algorithm independent of processor speed, ram, memory.
For example: In bubble sort, when the input array is already sorted, the time taken by the algorithm
is linear i.e., the best case.
But, when the input array is in reverse condition, the algorithm takes the maximum time (quadratic)
to sort the elements i.e., the worst case.
When the input array is neither sorted nor in reverse order, then it takes average time. These
durations are denoted using asymptotic notations.
➢ There are mainly three asymptotic notations:
• Big-O notation
• Omega notation
• Theta notation
1. Big oh
The notation is denoted by ‘O’ and pronounced as Big oh
It means running time of algorithm cannot be more than its
asymptotic upper bound.
f(n) = O(g(n))
f(n) <= c.g(n)
In this f(n) lies on or below c.g(n)
2. Big Omega
This notation is denoted by ‘Ω’ and pronounced as Big
omega
It defines lower bound for the algorithm.
It means running time of algorithm cannot be less than its
asymptotic lower bound.
f(n) = Ω(g(n))
f (n) >= c.g(n)
In this f (n) lies on or above c.g(n).
This document is property of RKDEMY and cannot be used, disclosed or duplicated without the prior written consent of RKDEMY pg.1- 8
Analysis of Algorithm Introduction
3. Big Theta
This notation is denoted by ‘𝜃’ and pronounced as Big
theta
It defines lower bound for the algorithm.
It means running time of algorithm cannot be less or
greater than its asymptotic tight bound.
f(n) = 𝜃(g(n))
c1.g(n) <= f(n) <= c2.g(n)
In this f(n) lies between c1.g(n) and c2.g(n)
Example: Represent the following function using Big oh, Omega and Theta Notations.
(i) (n) = 3n + 2 (ii) T(n) = 10n2 + 2n + 1
Solution:
(A) Big oh (upper bound)
(i) T(n) = 3n + 2
To Find upper bound of f(n), we have to find c and n0 such that 0 ≤ f(n) ≤ c . g(n) for all n ≥
n0
0 ≤ f(n) ≤ c . g (n)
0 ≤ 3n + 2 ≤ c . g (n)
0 ≤ 3n + 2 ≤ 3n + 2n, for all n ≥ 1 (there can be such infinite possibilities)
0 ≤ 3n + 2 ≤ 5n
So, c = 5 and g(n) = n, n0 = 1
This document is property of RKDEMY and cannot be used, disclosed or duplicated without the prior written consent of RKDEMY pg.1- 9
Analysis of Algorithm Introduction
This document is property of RKDEMY and cannot be used, disclosed or duplicated without the prior written consent of RKDEMY pg.1- 10
Analysis of Algorithm Introduction
4. Problem which can be solved theoretically and practically in reasonable amount of time
Problems which can be solved in polynomial time is known as P class problem (Sorting/
Searching), which take time like O(n), O(n2), O(n3).
E.g.,: finding maximum element in an array or to check whether a string is palindrome or not. So there
are many problems which can be solved in polynomial time.
Problem which can't be solved in polynomial time but can be verified in polynomial time like
TSP( travelling salesman problem) , su-do-ku
But NP problems are checkable in polynomial time means that given a solution of a problem, we can
check that whether the solution is correct or not in polynomial time.
This document is property of RKDEMY and cannot be used, disclosed or duplicated without the prior written consent of RKDEMY pg.1- 11
Analysis of Algorithm Introduction
P is subset of NP
Reducibility- If we can convert one instance of a problem A into problem B (NP problem) then it means
that A is reducible to B.
Now suppose we found that A is reducible to B, then it means that B is at least as hard as A.
NP Hard: Problems are slow to verify, slow to solve and can be reduced to any other problem.
NP-Complete -- The group of problems which are both in NP and NP-hard are known as NP-Complete
problem.
Now suppose we have a NP-Complete problem R and it is reducible to Q then Q is at least as hard as R
and since R is an NP-hard problem. Therefore Q will also be at least NP-hard, it may be NP-complete also.
NP Complete: Problems are also quick to verify, slow to solve and can be reduced to any other problem.
This document is property of RKDEMY and cannot be used, disclosed or duplicated without the prior written consent of RKDEMY pg.1- 12
Analysis of Algorithm Divide and Conquer Approach
Introduction
• The technique of diving large problems into smaller subproblems, solving subproblems and
combining them to get solution of original large problem.
• Divide and Conquer is a recursive problem-solving
approach which break a problem into smaller
subproblems.
1. Divide: This involves dividing the problem into some sub
problem.
2. Conquer: Sub problems are solved independently.
3. Combine: The Sub problem combine so that we will get
find problem solution.
Applications
Many computer science problems are effectively solved using divide and conquer.
• Finding exponential of the number
• Multiplying large numbers.
• Multiplying matrices.
• Sorting elements (Quick sort and Merge Sort )
• Searching elements from the list (Binary Search)
• Discreate Fourier Transform.
• Max-Min Problem.
This document is property of RKDEMY and cannot be used, disclosed or duplicated without the prior written consent of RKDEMY pg.1- 1
Analysis of Algorithm Divide and Conquer Approach
Master Method
➢ Time Complexity :-
n
T(n) = aT (b) + f(n)
Binary Search
0 1 2 3 4 5 6 7 8 9
Search 23 2 5 8 12 16 23 38 56 72 91
L=0 1 2 3 M=4 5 6 7 8 H=9
23 > 16
Take 2nd half
2 5 8 12 16 23 38 56 72 91
This document is property of RKDEMY and cannot be used, disclosed or duplicated without the prior written consent of RKDEMY pg.1- 2
Analysis of Algorithm Divide and Conquer Approach
Algorithm
Merge Sort
• Merge Sort Uses divide and Conquer approach.
• In Merge Sort, we divide array into two halves, sort the two halves recursively, and then merge the
sorted halves.
This document is property of RKDEMY and cannot be used, disclosed or duplicated without the prior written consent of RKDEMY pg.1- 3
Analysis of Algorithm Divide and Conquer Approach
This document is property of RKDEMY and cannot be used, disclosed or duplicated without the prior written consent of RKDEMY pg.1- 4
Analysis of Algorithm Divide and Conquer Approach
Algorithm MERGE_SORT(A,B)
// Description: Sort elements of array A using Merge sort
// Input: Array of size n, low ← 1 and high ← n
// Output: Sorted array B
if low < high then Recursively sort first sub list
mid ← floor (low + high) / 2
MERGE_SORT(A, low, mid) Recursively sort second sub list
MERGE_SORT(A, mid+1, high)
COMBINE(A, low, mid, high) // merge two sorted sublists
end
This document is property of RKDEMY and cannot be used, disclosed or duplicated without the prior written consent of RKDEMY pg.1- 5
Analysis of Algorithm Divide and Conquer Approach
Procedure COMBINE performs a two way merge to produce a sorted array of size n from two
sorted arrays of size n/2. The subroutine works as follow:
This document is property of RKDEMY and cannot be used, disclosed or duplicated without the prior written consent of RKDEMY pg.1- 6
Analysis of Algorithm Divide and Conquer Approach
Quick Sort
• It is divided and conquer based approach.
• It select one element as a pivot and moves pivot to correct location.
• Fixing the pivot to correct location divides the list into two sub list.
• Each sub lists is solved recursively.
Procedure:
- Scan array from left to right until an element greater than pivot is found.
- Scan array from right to left until an element equal or smaller than pivot is found.
✓ If low ≥ high, then exchange A[pivot] and A[high], which will split the list into two sub-
lists. Solve them recursively.
• It takes less number of multiplication compare to this traditional way of matrix multiplication.
This document is property of RKDEMY and cannot be used, disclosed or duplicated without the prior written consent of RKDEMY pg.1- 9
Analysis of Algorithm Greedy method Approach
Introduction
• Greedy Method find out the best method/option out of many present ways
• Greedy algorithm is optimization technique, it tries to find an optimal solution from the set of
feasible solutions.
• Greedy algorithm derive solution step by step, by looking at information available at current
moment. It does not look at future prospects.
• Decisions are completely locally optimal.
- The choice made under greedy solution procedure are irrevocable, means once we have selected
solution the local best solution it cannot be backtracked.
Algorithm GREEDY_APPROACH(L, n)
//Description: Solve the given problem using greedy approach.
//Input: L: List of possble choices, n: size of solution
//Output: Set Solution containing solution of given problem
Solution ∅
for i 1 to n do
Choice Select(L)
if (feasible(Choice ∪ Solution)) then
Solution Choice ∪ Solution
end
end
return Solution
This document is property of RKDEMY and cannot be used, disclosed or duplicated without the prior written consent of RKDEMY pg.1- 1
Analysis of Algorithm Greedy method Approach
Dijkstra's Algorithm
• It is a greedy algorithm that solves the single-source shortest path problem.
• Single-Source means that only one source is given, and we have to find the shortest path from the
source to all the nodes.
• Dijkstra's Algorithm maintains a set S of vertices whose final shortest - path weights from the
source s have already been determined.
Example:
Let's understand the working of Dijkstra's algorithm. Consider the below graph.
First, we have to consider any vertex as a source vertex. Suppose we consider vertex 0 as a source
vertex.
Here we assume that 0 as a source vertex, and distance to all the other vertices is infinity. Initially,
we do not know the distances. First, we will find out the vertices which are directly connected to the vertex
0. As we can observe in the above graph that two vertices are directly connected to vertex 0.
Let's assume that the vertex 0 is represented by 'x' and the vertex 1 is represented by 'y'. The distance
between the vertices can be calculated by using the below formula:
This document is property of RKDEMY and cannot be used, disclosed or duplicated without the prior written consent of RKDEMY pg.1- 2
Analysis of Algorithm Greedy method Approach
Therefore, we come to the conclusion that the formula for calculating the distance between the
vertices:
Therefore, the value of d(y) is 8. We replace the infinity value of vertices 1 and 4 with the values
4 and 8 respectively. Now, we have found the shortest path from the vertex 0 to 1 and 0 to 4. Therefore,
vertex 0 is selected. Now, we will compare all the vertices except the vertex 0. Since vertex 1 has the
lowest value, i.e., 4; therefore, vertex 1 is selected.
Since vertex 1 is selected, so we consider the path from 1 to 2, and 1 to 4. We will not consider the
path from 1 to 0 as the vertex 0 is already selected.
First, we calculate the distance between the vertex 1 and 2. Consider the vertex 1 as 'x', and the
vertex 2 as 'y'.
Since 15 is not less than 8, we will not update the value d(4) from 8 to 12.
This document is property of RKDEMY and cannot be used, disclosed or duplicated without the prior written consent of RKDEMY pg.1- 3
Analysis of Algorithm Greedy method Approach
Till now, two nodes have been selected, i.e., 0 and 1. Now we have to compare the nodes except
the node 0 and 1. The node 4 has the minimum distance, i.e., 8. Therefore, vertex 4 is selected.
Since vertex 4 is selected, so we will consider all the direct paths from the vertex 4. The direct paths
from vertex 4 are 4 to 0, 4 to 1, 4 to 8, and 4 to 5. Since the vertices 0 and 1 have already been selected so
we will not consider the vertices 0 and 1. We will consider only two vertices, i.e., 8 and 5.
First, we consider the vertex 8. First, we calculate the distance between the vertex 4 and 8. Consider
the vertex 4 as 'x', and the vertex 8 as 'y'.
Since 15 is less than the infinity so we update d(8) from infinity to 15.
Now, we consider the vertex 5. First, we calculate the distance between the vertex 4 and 5. Consider
the vertex 4 as 'x', and the vertex 5 as 'y'.
Till now, three nodes have been selected, i.e., 0, 1, and 4. Now we have to compare the nodes
except the nodes 0, 1 and 4. The node 5 has the minimum value, i.e., 9. Therefore, vertex 5 is selected.
Since the vertex 5 is selected, so we will consider all the direct paths from vertex 5. The direct paths
from vertex 5 are 5 to 8, and 5 to 6.
First, we consider the vertex 8. First, we calculate the distance between the vertex 5 and 8. Consider
the vertex 5 as 'x', and the vertex 8 as 'y'.
Since 24 is not less than 15 so we will not update the value d(8) from 15 to 24.
Now, we consider the vertex 6. First, we calculate the distance between the vertex 5 and 6. Consider
the vertex 5 as 'x', and the vertex 6 as 'y'.
This document is property of RKDEMY and cannot be used, disclosed or duplicated without the prior written consent of RKDEMY pg.1- 4
Analysis of Algorithm Greedy method Approach
Till now, nodes 0, 1, 4 and 5 have been selected. We will compare the nodes except the selected
nodes. The node 6 has the lowest value as compared to other nodes. Therefore, vertex 6 is selected.
Since vertex 6 is selected, we consider all the direct paths from vertex 6. The direct paths from
vertex 6 are 6 to 2, 6 to 3, and 6 to 7.
First, we consider the vertex 2. Consider the vertex 6 as 'x', and the vertex 2 as 'y'.
Since 15 is not less than 12, we will not update d(2) from 12 to 15
Now we consider the vertex 3. Consider the vertex 6 as 'x', and the vertex 3 as 'y'.
Now we consider the vertex 7. Consider the vertex 6 as 'x', and the vertex 7 as 'y'.
Till now, nodes 0, 1, 4, 5, and 6 have been selected. Now we have to compare all the unvisited
nodes, i.e., 2, 3, 7, and 8. Since node 2 has the minimum value, i.e., 12 among all the other unvisited nodes.
Therefore, node 2 is selected.
Since node 2 is selected, so we consider all the direct paths from node 2. The direct paths from
node 2 are 2 to 8, 2 to 6, and 2 to 3.
First, we consider the vertex 8. Consider the vertex 2 as 'x' and 8 as 'y'.
This document is property of RKDEMY and cannot be used, disclosed or duplicated without the prior written consent of RKDEMY pg.1- 5
Analysis of Algorithm Greedy method Approach
Now, we consider the vertex 6. Consider the vertex 2 as 'x' and 6 as 'y'.
Since 16 is not less than 11 so we will not update d(6) from 11 to 16.
Now, we consider the vertex 3. Consider the vertex 2 as 'x' and 3 as 'y'.
Till now, nodes 0, 1, 2, 4, 5, and 6 have been selected. We compare all the unvisited nodes, i.e., 3,
7, and 8. Among nodes 3, 7, and 8, node 8 has the minimum value. The nodes which are directly connected
to node 8 are 2, 4, and 5. Since all the directly connected nodes are selected so we will not consider any
node for the updation.
The unvisited nodes are 3 and 7. Among the nodes 3 and 7, node 3 has the minimum value, i.e., 19.
Therefore, the node 3 is selected. The nodes which are directly connected to the node 3 are 2, 6, and 7.
Since the nodes 2 and 6 have been selected so we will consider these two nodes.
Now, we consider the vertex 7. Consider the vertex 3 as 'x' and 7 as 'y'.
Since 28 is not less than 21, so we will not update d(7) from 28 to 21.
This document is property of RKDEMY and cannot be used, disclosed or duplicated without the prior written consent of RKDEMY pg.1- 6
Analysis of Algorithm Greedy method Approach
Vertex T Y X Z
S 10 5 00 00
Vertex T Y X Z
S-> y 8 - 14 7
Vertex T Y X Z
S-> y->t - - 9 7
Vertex T Y X Z
S-> y->t->z - - 9 -
- Weight from s to y is 5
- Weight from s to z is 7
- Weight from s to t is 8
- Weight from s to x is 9
This document is property of RKDEMY and cannot be used, disclosed or duplicated without the prior written consent of RKDEMY pg.1- 7
Analysis of Algorithm Greedy method Approach
Knapsack Problem
• The Greedy algorithm could be understood very well with a well-known problem referred to as
Knapsack problem.
• Let M is the capacity of knapsack i.e. knapsack can not hold item having collective weight more
than M.
• Knapsack problem is problem of filling knapsack using item in x such that it maximizes the profit
such that total weight item should not cross the knapsack capacity.
• 0/1 knapsack
• Fractional Knapsack
Example:
Solve following using 0/1 knapsack method.
Solution:
If items are selected according to decreasing order of profit to weight ratio using fractional
knapsack strategy, then algorithm always finds the optimal solution. First arrange items in decreasing order
of profit density. Items are labeled as X = (3, 1, 2, 4, 5), have profit V = (27, 18, 25, 10, 15) an weight W
= (4, 3, 5, 3, 6).
We shall select one by one item from above table. If the inclusion of an item does not cross the
knapsack capacity, then add it. Otherwise, break the current item and select only the portion of item
equivalent to remaining knapsack capacity. Select the profit accordingly. We should stop when knapsack
is full or all items are scanned.
Initialize, Weight of selected items, SW = 0, Profit of selected items, SP=0,
This document is property of RKDEMY and cannot be used, disclosed or duplicated without the prior written consent of RKDEMY pg.1- 8
Analysis of Algorithm Greedy method Approach
- Knapsack is full, no more items can be added to knapsack. Selected items are (3, 1, 2), which gives
the profit of 70.
Job Sequencing
- Schedule jobs out of set of N jobs on a single processor which maximizes profit as much as possible.
- Each job is taking unit time for execution and having some profit and deadline associated with it.
- Greedy approach produces an optimal result in fairly less time as each job takes same amount of time
- No Preemption :- if we start one job we should complete it without assigning any other
Job J1 J2 J3 J4
Profit 50 15 10 25
Deadline 2 1 2 1
This document is property of RKDEMY and cannot be used, disclosed or duplicated without the prior written consent of RKDEMY pg.1- 9
Analysis of Algorithm Greedy method Approach
SP← 0 //Sum is the profit earned
end
end
Example:
Let n = 4, (P1, P2, P3, P4)= (100, 10, 15, 27) and (d1, d2, d3, d4) = (2, 1, 2, 1). Find feasible solutions,
using job sequencing with deadlines.
Soln.:
Sort all jobs in descending order of profit.
So, P=(100, 27, 15, 10), J = (J1, J4, J3, J2) and D = (2, 1, 2, 1). We shall select one by one job from
the list of sorted jobs, and check if it satisfies the deadline. If so, schedule the job in the latest free slot. If
no such slot is found, skip the current job and process the next one.
Initially,
S
0 1 2 3 4
Profit of scheduled jobs, SP = 0
Iteration 1
Deadline for job J1 is 2. Slot 2(t = 1 to t = 2) is free, so schedule it in slot 2.
Solution set S = {J1}, and Profit SP = {100}
S J1
0 1 2 3 4
Iteration 2
Deadline for job J4 is 1. Slot 1(t = 0 to t = 1) is free, so schedule it in slot 1.
Solution set S = {J1, J4}, and Profit SP = {100, 27}
S J4 J1
0 1 2 3 4
Iteration 3
Job J3 is not feasible because first two slots are already occupied and if we schedule J3 any time
later t = 2, it cannot be finished before its deadline 2. So job J3 is discarded.
Solution set S = (J1, J4), and Profit SP = {100, 27}
This document is property of RKDEMY and cannot be used, disclosed or duplicated without the prior written consent of RKDEMY pg.1- 10
Analysis of Algorithm Greedy method Approach
Iteration 4
Job J2 is not feasible because first two slots are already occupied and if we schedule J2 any time
later t = 2, it cannot be finished before its deadline 1. So job J2 is discarded,
Solution set S = {J1, J4), and Profit SP= (100, 27) With the greedy approach, we will be able to
schedule two jobs (J1, J4), which gives a profit of 100 + 27 = 127 units..
Prims algorithm
Refer class notes
Kruskal algorithm
Refer class notes
This document is property of RKDEMY and cannot be used, disclosed or duplicated without the prior written consent of RKDEMY pg.1- 11
Analysis of Algorithm BackTracking And Branch and Bound
General Method
• Backtracking is a technique based on algorithm to solve problem.
• In backtracking problem, the algorithm tries to find a sequence path
to the solution which has some small checkpoints from where the
problem can backtrack if no feasible solution is found for the
problem.
• Solutions to many problem can be viewed as a making sequence of
decisions.
• Backtracking is an intelligent way of gradually building solution.
• Typically it is applied to problems like sudoku, crossword, 8-queen puzzels, chess and many others
• Backtracking builds the solutions incrementally. Partial solutions which do not satisfy the
constraint are abandon.
• Backtracking limits the search by eliminating the candidates that do not satisfy certain constraints.
4 Queens Problem
• 4 – Queens’ problem is to place 4 – queens on a 4 x 4 chessboard in such a
manner that no queens attack each other by being in the same row, column, or
diagonal.
After this first step, only the white squares are still available to place the three remaining queens. The
process of excluding some squares is what is called propagation.
The second step starts with the solver trying to place a second queen. It does so in the first available
This document is property of RKDEMY and cannot be used, disclosed or duplicated without the prior written consent of RKDEMY pg.1- 1
Analysis of Algorithm BackTracking And Branch and Bound
Now, we have a failure as there is no possibility to place a third queen in the third column: there simply
can not be a solution with this configuration. The solver has to backtrack!
First, the square with the red cross is removed because of the positive diagonal constraint. This leaves
only one possibility to place a queen in the fourth column.
This document is property of RKDEMY and cannot be used, disclosed or duplicated without the prior written consent of RKDEMY pg.1- 2
Analysis of Algorithm BackTracking And Branch and Bound
The “no two queen on the same row” constraint removes one more square in the third column, leaving
only one square to place the last remaining queen
8-Queen Problem
• Problem: - 8X8 chess board Arrange 8 queen in a way such that no two queen attack each other.
• Two queen are attacking each other if they are in same row, column or diagonal.
• 8 Queen Problem has 64c8= 4,42,61,65,368 different arrangements out of which only 12 are
fundamental solution.
1 2 3 4 5 6 7 8 Solution Vector
1 Q1
2 Q2 1 2 3 4 5 6 7 8
3 Q3 4 6 8 2 7 1 3 5
4 Q4
5 Q5
6 Q6
7 Q7
8 Q8
Sum of subsets
• Given set of positive integers, find the combination of numbers that sum to given value is M.
• Find subset whose sum of subset is M.
• Set (10,20,30,40)
• M=50 (sum)
❖ Boundary Function :
Q) n = 4 W = {2, 7, 8, 15} M = 17
This document is property of RKDEMY and cannot be used, disclosed or duplicated without the prior written consent of RKDEMY pg.1- 3
Analysis of Algorithm BackTracking And Branch and Bound
This document is property of RKDEMY and cannot be used, disclosed or duplicated without the prior written consent of RKDEMY pg.1- 4
Analysis of Algorithm BackTracking And Branch and Bound
x 1 1 0 0 1 0
1 2 3 4 5 6
∑ wi xi + wk+1 ≤ m
i=1
k n
∑ wi xi + ∑ wi > m
i=1 i=k+1
Graph Coloring
• Graph colouring is the problem of colouring vertices of a graph in such a way that no two
adjacent vertices of same color.
• We have given a chromatic number m which is the least number of colors needed to color graph.
1 2 3 4 5
R G R G B
M=5
R, G, B
Example:
This document is property of RKDEMY and cannot be used, disclosed or duplicated without the prior written consent of RKDEMY pg.1- 5
Analysis of Algorithm BackTracking And Branch and Bound
15 Puzzle problem
• In this puzzle solution of the 8 puzzle problem is discussed.
• Given a 3×3 board with 8 tiles (every tile has one number from 1 to
8) and one empty space.
• The objective is to place the numbers on tiles to match the final
configuration using the empty space.
• We can slide four adjacent (left, right, above, and below) tiles into
the empty space.
This document is property of RKDEMY and cannot be used, disclosed or duplicated without the prior written consent of RKDEMY pg.1- 6
Analysis of Algorithm BackTracking And Branch and Bound
This document is property of RKDEMY and cannot be used, disclosed or duplicated without the prior written consent of RKDEMY pg.1- 7
Analysis of Algorithm String Matching Algo
String matching
• String matching is core part in many text processing application
• Objective of string matching is to find pattern P from given set of text T.
• String matching is used in compilers and text editors.
Text T H O W A R E Y O U ?
Pattern P s=4 A R E
1 2 3
Pattern matching in Text T
In this example, pattern P = ARE is found in text T after four shifts.
Classical application of string matching algorithm is to find particular protein pattern in DNA
sequence.
This document is property of RKDEMY and cannot be used, disclosed or duplicated without the prior written consent of RKDEMY pg.1- 1
Analysis of Algorithm String Matching Algo
A N D
1 2 3
A N D
1 2 3
A N D
1 2 3
A N D
1 2 3
This document is property of RKDEMY and cannot be used, disclosed or duplicated without the prior written consent of RKDEMY pg.1- 2
Analysis of Algorithm String Matching Algo
Step 5 : T[5] ≠ P[3], advance text pointer and reset pattern pointer, i.e. t i ++, pj = 1
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
P L A N I N G A N D A N A L Y S I S
A N D
1 2 3
A N D
1 2 3
A N D
1 2 3
A N D
1 2 3
This document is property of RKDEMY and cannot be used, disclosed or duplicated without the prior written consent of RKDEMY pg.1- 3
Analysis of Algorithm String Matching Algo
A N D
1 2 3
A N D Match found
1 2 3
Algorithm NAIVE_STRING_MATCHING(T, P)
//T is the text string of length n
//P is the pattern of length m
for i ← 0 to n – m do
if P[l .... m] = = T[i + l ...... i + m] then
print “Match Found”
end
end
This document is property of RKDEMY and cannot be used, disclosed or duplicated without the prior written consent of RKDEMY pg.1- 4
Analysis of Algorithm String Matching Algo
3. m be the length of the pattern and n be the length of the text. Here
This document is property of RKDEMY and cannot be used, disclosed or duplicated without the prior written consent of RKDEMY pg.1- 5
Analysis of Algorithm String Matching Algo
This document is property of RKDEMY and cannot be used, disclosed or duplicated without the prior written consent of RKDEMY pg.1- 6
Analysis of Algorithm Dynamic Programming Approach
Introduction
• Dynamic Programming Approach is similar to divide and conquer in breaking down the problem
into smaller and yet smaller possible sub-problems. But unlike, divide and conquer, these sub-
problems are not solved independently. Rather, results of these smaller sub-problems are
remembered and used for similar or overlapping sub-problems.
• Dynamic programming is used where we have problems, which can be divided into similar sub-
problems, so that their results can be re-used.
• Dynamic programming is used where we have problems, which can be divided into similar sub-
problems, so that their results can be re-used.
• Dynamic programming can be used in both top-down and bottom-up manner.
Multistage Graph
This document is property of RKDEMY and cannot be used, disclosed or duplicated without the prior written consent of RKDEMY pg.1- 1
Analysis of Algorithm Dynamic Programming Approach
• Floyd-Warshall Algorithm is an algorithm for finding the shortest path between all the pairs of
vertices in a weighted graph.
• This algorithm works for both the directed and undirected weighted graphs. But, it does not work
for the graphs with negative cycles (where the sum of the edges in a cycle is negative).
This document is property of RKDEMY and cannot be used, disclosed or duplicated without the prior written consent of RKDEMY pg.1- 2
Analysis of Algorithm Dynamic Programming Approach
• It is problem of finding maximum length common sequence from given two strings A and B.
• A subsequence of a string is a new string generated from the original string with some characters
(can be none) deleted without changing the relative order of the remaining characters.
• For example, "ace" is a subsequence of "abcde"
• A common subsequence of two strings is a subsequence that is common to both strings.
This document is property of RKDEMY and cannot be used, disclosed or duplicated without the prior written consent of RKDEMY pg.1- 3
The greedy method in finding the shortest path within a graph involves selecting nodes in stages based on a local optimization criterion, typically choosing the edge with the smallest weight leading to an unvisited node at each step. The approach is iterative, as demonstrated by updating the shortest known distance to each node as the algorithm progresses. This method is effective in problems like Dijkstra's algorithm, where the cumulative cost is continuously compared, and node selections are adjusted to improve overall efficiency in pathfinding, minimizing total distance without fully exploring all possible routes .
A recursive approach to calculating the factorial of a number n is elegant in its simplicity, as it directly follows the mathematical definition of a factorial. The algorithm is easy to read and understand because it breaks the problem down into a base case (n = 1) and a recursive case (n * Factorial(n-1)). However, this simplicity comes at a cost in terms of performance due to the increased use of stack memory for each recursive call and potential stack overflow for large n. Additionally, each call adds extra overhead, which might make the iterative version more efficient despite being less intuitive .
Space complexity impacts algorithm design by dictating how much memory an algorithm needs to correctly execute processes as input increases. An algorithm with high space complexity can lead to inefficient use of memory, potentially slowing down performance when the system runs out of resources or when memory needs to be frequently reallocated. Efficient algorithms strive to minimize space complexity to sustain performance and scalability. For instance, algorithms that operate with constant space complexity O(1), like scalar variable addition, require minimal memory allocation, which is desirable for handling large input sizes without performance degradation .
The divide and conquer approach improves efficiency by reducing the number of comparisons needed to find the minimum and maximum elements in an array. Traditionally, this requires n-1 comparisons, where n is the number of elements. Using the divide and conquer method, the algorithm splits the array into two subarrays recursively, treating each subarray as a separate problem. This method effectively reduces the number of comparisons by dividing the work and significantly limits redundant checks, ultimately yielding a more efficient solution compared to checking each element directly .
Partitioning in quicksort enhances performance by isolating elements around a pivot, dividing the array into lesser and greater sub-arrays, which are then sorted independently. This reduces the problem size in each recursive step, with an average case time complexity of O(n log n). However, potential drawbacks include poor performance on already sorted arrays or when poor pivot choices lead to unbalanced partitions, resulting in O(n^2) complexity. Such scenarios require strategies like random pivot selection or insertion sort for small sub-arrays to maintain efficiency .
The variable space component affects an algorithm's space complexity by determining the amount of space that fluctuates based on the program execution, such as the space required for dynamic data structures like linked lists or the number of loop iterations. As an algorithm processes more data, the space required by these components can increase, impacting memory utilization and potentially causing performance issues such as excessive memory usage or heap fragmentation, especially in environments with limited resources or when handling large datasets .
In the quicksort algorithm, the pivot plays a central role in the divide and conquer paradigm by determining the point around which the array is partitioned. By selecting a pivot, the algorithm rearranges elements so that those less than the pivot come before it and those greater come after it. This pivot division enables quicksort to recursively sort the sub-arrays on either side of the pivot independently, breaking down the problem into smaller, more manageable parts. This method efficiently sorts the entire array with an average time complexity of O(n log n), contributing to its status as a highly efficient sorting method .
Recursive methods present several challenges and considerations in algorithm design, such as increased memory usage due to call stack growth, the risk of stack overflow for large input sizes, and possible inefficiency due to repeated calculations unless optimized with techniques like memoization. Designers must also consider readability versus performance trade-offs, as recursive solutions are often more intuitive but can be less efficient compared to their iterative counterparts. Each recursive call involves overhead costs that might accumulate significantly in terms of both time and memory, necessitating careful evaluation of their suitability for large-scale problems .
Growth functions in time complexity analysis are used to predict how the runtime of an algorithm will scale with increasing input size. By examining the growth rate, big-O notation provides a high-level understanding of an algorithm's efficiency, highlighting potential bottlenecks and inefficiencies in design. This predictive power enables developers to estimate resource requirements and choose appropriate algorithms for specific tasks, especially those involving large-scale data, ensuring optimal performance across different environments .
Time complexity allows developers to predict an algorithm's efficiency and scalability by measuring how the time required to complete an algorithm grows as the input size increases. This plays a critical role in choosing between algorithms; for example, an algorithm with time complexity T(n) = O(n) might be preferable for large datasets compared to one with T(n) = O(n^2), which grows quadratically and thus performs worse as inputs grow. By comparing the big-O notation of time complexity, developers can select algorithms that offer the best performance trade-offs for given constraints and resources .