Professional Documents
Culture Documents
INTROUDUCTION
DAA Algorithm
The word algorithm has been derived from the Persian author's name, Abu Ja 'far Mohammed ibn Musa al Khowarizmi (c. 825 A.D.), who has
written a textbook on Mathematics. The word is taken based on providing a special significance in computer science. The algorithm is
understood as a method that can be utilized by the computer as when required to provide solutions to a particular problem.
An algorithm can be defined as a finite set of steps, which has to be followed while carrying out a particular problem. It is nothing but a process
of executing actions step by step.
An algorithm is a distinct computational procedure that takes input as a set of values and results in the output as a set of values by solving the
problem. More precisely, an algorithm is correct, if, for each input instance, it gets the correct output and gets terminated.
An algorithm unravels the computational problems to output the desired result. An algorithm can be described by incorporating a natural
language such as English, Computer language, or a hardware language.
Characteristics of Algorithms
Input: It should externally supply zero or more quantities.
Output: It results in at least one quantity.
Definiteness: Each instruction should be clear and ambiguous.
Finiteness: An algorithm should terminate after executing a finite number of steps.
Effectiveness: Every instruction should be fundamental to be carried out, in principle, by a person using only pen and paper.
Feasible: It must be feasible enough to produce each instruction.
Flexibility: It must be flexible enough to carry out desired changes with no efforts.
Efficient: The term efficiency is measured in terms of time and space required by an algorithm to implement. Thus, an algorithm must ensure
that it takes little time and less memory space meeting the acceptable limit of development time.
Independent: An algorithm must be language independent, which means that it should mainly focus on the input and the procedure required to
derive the output instead of depending upon the language.
Advantages of an Algorithm
Effective Communication: Since it is written in a natural language like English, it becomes easy to understand the step-by-step delineation of a
solution to any particular problem.
Easy Debugging: A well-designed algorithm facilitates easy debugging to detect the logical errors that occurred inside the program.
Easy and Efficient Coding: An algorithm is nothing but a blueprint of a program that helps develop a program. Independent of Programming
Language: Since it is a language-independent, it can be easily coded by incorporating any high-level language.
Disadvantages of an Algorithm
Developing algorithms for complex problems would be time-consuming and difficult to understand. It
is a challenging task to understand complex logic through algorithms.
Pseudocode
Pseudocode refers to an informal high-level description of the operating principle of a computer program or other algorithm. It uses structural
conventions of a standard programming language intended for human reading rather than the machine reading.
Advantages of Pseudocode
Since it is similar to a programming language, it can be quickly transformed into the actual programming language than a flowchart. The
layman can easily understand it.
Easily modifiable as compared to the flowcharts.
Its implementation is beneficial for structured, designed elements. It
can easily detect an error before transforming it into a code.
Disadvantages of Pseudocode
Since it does not incorporate any standardized style or format, it can vary from one company to another.
Error possibility is higher while transforming into a code.
It may require a tool for extracting out the Pseudocode and facilitate drawing flowcharts. It
does not depict the design.
Difference between Algorithm and the Pseudocode
An algorithm is simply a problem-solving process, which is used not only in computer science to write a program but also in our day to day life.
It is nothing but a series of instructions to solve a problem or get to the problem's solution. It not only helps in simplifying the problem but also
to have a better understanding of it.
02:57/04:58 10 Sec
5.4M
114
HTML Tutorial
However, Pseudocode is a way of writing an algorithm. Programmers can use informal, simple language to write pseudocode without following
any strict syntax. It encompasses semi-mathematical statements.
Problem: Suppose there are 60 students in the class. How will you calculate the number of absentees in the class?
Pseudo Approach:
Initialize a variable called as Count to zero, absent to zero, total to 60 FOR
EACH Student PRESENT DO the following:
Increase the Count by One
Then Subtract Count from total and store the result in absent
Display the number of absent students Algorithmic
Approach:
Count <- 0, absent <- 0, total <- 60
REPEAT till all students counted
Count <- Count + 1 absent
<- total - Count
Print "Number absent is:" , absent
SL DAA IMPORTANT TOPIC VIDEO LINKS FAQ,S
NO
The Analysis Framework, https://youtu.be/7dz8Iaf_weM 1.What is Algorithm?
Asymptotic and Basic https://youtu.be/DwFAv_yEixY The name 'Algorithm' refers to the sequence of instruction
Efficiency Classes. that must be followed to clarify a problem.
The logical description of the instructions which may be
executed to perform an essential function.
Algorithms are usually generated independent of primary
languages, i.e., an algorithm can be achieved in more than
one programming language.
2) What is Asymptotic Notation?
A way to represents the behavior of functions in the limit or
without bounds. The notations are described in terms of
methods whose domains are the set of natural numbers N=
{0, 1, 2} 3.Asymptotic Analysis of algorithms (Growth of
function) Resources for an algorithm are usually expressed as
a function regarding input. Often this function is messy and
complicated to work. To study Function growth efficiently,
we reduce the function down to the important part.
Let f (n) = an2+bn+c
In this function, the n2 term dominates the function that is
when n gets sufficiently large.
Dominate terms are what we are interested in reducing a
function, in this; we ignore all constants and coefficient and
look at the highest order term concerning n.
4.Asymptotic notation: Asymptotic
analysis
It is a technique of representing limiting behavior. The
methodology has the applications across science. It can be
used to analyze the performance of an algorithm for some
large data set.
1. In computer science in the analysis of algorithms,
considering the performance of algorithms when applied to
very large input datasets he simplest example is a function ƒ
(n) = n2+3n, the term 3n becomes insignificant compared
2
to n when n is very large. The function "ƒ (n) is said to
2
be asymptotically equivalent to n as n → ∞", and here is
2
written symbolically as ƒ (n) ~ n . Asymptotic notations
are used to write fastest and slowest possible running time
for an algorithm. These are also referred to as 'best case' and
'worst case' scenarios respectively.
"In asymptotic notations, we derive the complexity
concerning the size of the input. (Example in terms of n)"
"These notations are important because without expanding
the cost of running the algorithm, we can estimate the
complexity of the algorithms."
5. Why is Asymptotic Notation Important?
1.T 1. Big-oh notation: Big-oh is the formal method of
expressing the upper bound of an algorithm's running time. It
is the measure of the longest amount of time. The function f
(n) = O (g (n)) [read as "f of n is big-oh of g of n"] if and only
if exist positive constant c and such that
f (n) ⩽ k.g (n)f(n)⩽k.g(n) for n>n0n>n0 in all case
Hence, function g (n) is an upper bound for function f (n), as g
(n) grows faster than f (n)
hey give simple characteristics of an algorithm's efficiency.
They allow the comparisons of the performances of various
algorithms.
Asymptotic Notations:
Asymptotic Notation is a way of comparing function that
ignores constant factors and small input sizes. Three
notations are used to calculate the running time complexity
of an algorithm:
For Example:
1. 3n+2=O(n) as 3n+2≤4n for all n≥2
2. 3n+3=O(n) as 3n+3≤4n for all n≥3
Hence, the complexity of f(n) can be represented as O (g (n))
2. Omega () Notation: The function f (n) = Ω (g (n)) [read as "f
of n is omega of g of n"] if and only if there exists positive
constant c and n0 such that
F (n) ≥ k* g (n) for all n, n≥ n0
For Example:
f (n) =8n2+2n-3≥8n2-3
=7n2+(n2-3)≥7n2 (g(n))
Thus, k1=7
Hence, the complexity of f (n) can be represented as Ω (g (n))
3. Theta (θ): The function f (n) = θ (g (n)) [read as "f is the
theta of g of n"] if and only if there exists positive constant k1,
k2 and k0 such that
k1 * g (n) ≤ f(n)≤ k2 g(n)for all n, n≥ n0
For Example:
3n+2= θ (n) as 3n+2≥3n and 3n+2≤ 4n, for n
k1=3,k2=4, and n0=2
Hence, the complexity of f (n) can be represented as θ (g(n)).
The Theta Notation is more precise than both the big-oh and
Omega notation. The function f (n) = θ (g (n)) if g(n) is both
an upper and lower bound.
6.What is the time complexity of
Algorithm?
The time complexity of an algorithm denoted the total time
needed by the program to run to completion. It is generally
expressed by using the big O notation.
7) What is NP-Complete?
NP-Complete problem is a problem in NP that is as difficult
as any other trouble in this class because any other dispute in
NP can be decreased to it in Polynomial-time.
8) Differentiate Time Efficiency and
Space Efficiency?
Time Efficiency measured by estimate the number of times the
essential algorithms functions are executed. Space
Efficiency is measured by calculating the number of additional
memory units consumed by the algorithm.
9) What is the Order of Algorithm?
The order of algorithm is standard documentation of an
algorithm that has been developed to represent a task that
bound the estimated time for algorithms. The order of an
algorithm is a method of defining its efficiency. It is commonly
referred to as O-notation.
10) What is Brute Force?
Input- Zero or more quantities are externally provided.
Output- At least one quantity is composed
Definiteness- Each instruction is simple and unambiguous
Finiteness- If we trace out the instructions of an algorithm,
then for all step the algorithm complete after a finite number
of steps
Effectiveness- Every instruction must be elementary.
DIVIDE-AND-CONQUER: https://youtu.be/T68vN1FNY4o 1.Which of the following algorithms is NOT a divide &
Introduction, Master theorem, https://youtu.be/E-QtwPi620I conquer algorithm by nature? (A) Euclidean algorithm
Multiplication of Large https://youtu.be/86CQq3pKSUw to compute the greatest common divisor
Integers and Strassen’s Matrix
Multiplication. The maximum (B) Heap Sort
subarray problem. (C) Cooley-Tukey fast Fourier transform
(D) Quick Sort
2. What does the program compute?
1.x + y using repeated subtraction
2.x mod y using repeated subtraction
3.the greatest common divisor of x and y
4.the least common multiple of x and y
Answer: (C)
3. Maximum Subarray Sum problem is to find the
subarray with maximum sum. For example, given an
array {12, -13, -5, 25, -20, 30, 10}, the maximum
subarray sum is 45.
The naive solution for this problem is to calculate
sum of all subarrays starting with every element and
return the maximum of all. We can solve this using
Divide and Conquer, what will be the worst case
time complexity using Divide and Conquer.
(A) O(n)
(B) O(nLogn)
(C) O(Logn)
(D) O(n^2)
Answer: (B)
4. Consider a situation where you don’t have
function to calculate power (pow() function in C) and
you need to calculate x^n where x can be any
number and n is a positive integer. What can be the
best possible time complexity of your power
function?
(A) O(n)
(B) O(nLogn)
(C) O(LogLogn)
(D) O(Logn)
Answer: (D)
5.What is Masters theorem in DAA?
Masters Theorem for divide and conquer is an analysis
theorem that can be used to determine a big-0 value for
recursive relation algorithms. It is used to find the time
required by the algorithm and represent it in asymptotic
notation form.
6. How do you use master's Theorem?
The master theorem is used in calculating the time complexity
of recurrence relations (divide and conquer algorithms) in a
simple and quick way.
7.The master theorem cannot be used if:
1.T(n) is not monotone. eg. T(n) = sin n. 2.f(n) is
not a polynomial. eg. f(n) = 2. n
3.a is not a constant. eg. a = 2n.
4.a < 1.
7.What are the three cases of Master Theorem? There
are 3 cases for the master theorem:
Case 1: d < log(a) [base b] => Time Complexity = O(n ^ log(a)
[base b])
Case 2: d = log(a) [base b] => Time Complexity = O((n ^ d) *
log(n) )
Case 3: d > log(a) [base b] => Time Complexity = O((n ^ d))
8.Strassen’s Matrix Multiplication
Algorithm
n this context, using Strassen’s Matrix multiplication algorithm,
the time consumption can be improved a little bit.
Strassen’s Matrix multiplication can be performed only
on square matrices where n is a power of 2. Order of both of
the matrices are n × n.
Divide X, Y and Z into four (n/2)×(n/2) matrices as
represented below −
Z=[IKJL]Z=[IJKL] X=[ACBD]X=[ABCD] and Y=[EGF
H]Y=[EFGH]
Using Strassen’s Algorithm compute the following −
M1:=(A+C)×(E+F)M1:=(A+C)×(E+F)
M2:=(B+D)×(G+H)M2:=(B+D)×(G+H)
M3:=(A−D)×(E+H)M3:=(A−D)×(E+H)
M4:=A×(F−H)M4:=A×(F−H)
M5:=(C+D)×(E)M5:=(C+D)×(E)
M6:=(A+B)×(H)M6:=(A+B)×(H)
M7:=D×(G−E)M7:=D×(G−E)
Then,
I:=M2+M3−M6−M7I:=M2+M3−M6−M7
J:=M4+M6J:=M4+M6
K:=M5+M7K:=M5+M7
L:=M1−M3−M4−M5L:=M1−M3−M4−M5
Analysis
T(n)={c7xT(n2)+dxn2ifn=1otherwiseT(n)={cifn=17xT(
n2)+dxn2otherwise where c and d are constants
Using this recurrence relation, we get
T(n)=O(nlog7)T(n)=O(nlog7)
Hence, the complexity of Strassen’s matrix multiplication
algorithm is O(nlog7)O(nlog7).
n this context, using Strassen’s Matrix multiplication algorithm,
the time consumption can be improved a little bit.
9.How to find the maximum number in a subarray?
Maximum Subarray Given an integer array nums, find the
contiguous subarray (containing at least one number) which has the
largest sum and return its sum. Input: [-2,1,-3,4,-1,2,1,-5,4], Output:
6 Explanation: [4,-1,2,1] has the largest sum = 6.
10.When do you add an element to a subarray?
The subarray must be contiguous so either you add the element of
index i, or you start a new sum. For ex: int [] A = {−2, 1, −3, 4, −1,
2, 1, −5, 4}; result will be 4, −1, 2, 1, with sum 6. But for this case,
int [] A = {−2, 1, −3, 4, −1, 2, 1, −5, 14}; result ll return 6 instead of
14. because we are not checking with last index.
11.When to use auxiliary space in a subarray?
This subarray is either empty (in which case its sum is zero) or
consists of one more element than the maximum subarray ending at
the previous index. The time complexity of above solution is O (n)
and auxiliary space used by the program is O (1). Above code
doesn’t handle the case when all elements of the array are negative.
12.How to maintain a positive sum in a subarray?
The idea is to maintain a maximum (positive-sum) subarray
“ending” at each index of the given array. This subarray is either
empty (in which case its sum is zero) or consists of one more
element than the maximum subarray ending at the previous index.
The algorithm can be implemented as follows in C++, Java, and
Python:
13.Print the Maximum Subarray Sum
Given an array arr[], the task is to find the elements
of a contiguous subarray of numbers which has the
largest sum.
Examples:
Input: arr = [-2, -3, 4, -1, -2, 1, 5, -3]
Output: [4, -1, -2, 1, 5] Explanation:
In the above input the maximum contiguous
subarray sum is 7 and the elements of the
subarray are [4, -1, -2, 1, 5]
Input: arr = [-2, -5, 6, -2, -3, 1, 5, -6]
Output: [6, -2, -3, 1, 5] Explanation:
In the above input the maximum contiguous
subarray sum is 7 and the elements of the
subarray are [6, -2, -3, 1, 5]
SPACE AND TIME TRADE- https://youtu.be/l7QXJ1Z8a8U 1.Input Enhancement in String Matching
OFFS: Input Enhancement in https://youtu.be/k7UpWkVvajM
String Matching. Matrix-chain https://youtu.be/prx1psByp7U
In this section, we see how the technique of input
multiplication. Longest https://youtu.be/NnD96abizww enhancement can be applied to the problem of string
common subsequenceAnalyze. https://youtu.be/hgA4xxlVvfQ
optimal binary search trees
matching. Recall that the problem of string matching
Analyze. requires finding an occurrence of a given string of m
characters called the pattern in a longer string of n
characters called the text. We discussed the brute-
force algorithm for this problem in Section 3.2: it
simply matches corresponding pairs of characters in
the pattern and the text left to right and, if a mismatch
occurs, shifts the pattern one position to the right for
the next trial. Since the maximum number of such
trials is n − m + 1 and, in the worst case, m
comparisons need to be made on each of them, the
worst-case efficiency of the brute-force algorithm is
in the O(nm) class. On average,
however, we should expect just a few comparisons
before a pattern’s shift, and for random
naturallanguage texts, the average-case efficiency
indeed turns out to be in O(n + m).
b)
d)
View Answer
Answer: c
Explanation: Preorder Traversal is 10, 4, 3, 5, 11, 12.
Inorder Traversal of Binary search tree is equal to
ascending order of the nodes of the Tree. Inorder
Traversal is 3, 4, 5, 10, 11, 12. The tree constructed using
Preorder and Inorder traversal is
GRAPH ALGORITHMS: https://youtu.be/Rv2RzVu9S9k Kruskal’s Algorithm-
Kruskal’sAlgorithm, Dijkstra’s https://youtu.be/poWB2UCuozA Kruskal’s Algorithm is a famous greedy algorithm.
Algorithm,An activityselection https://youtu.be/EjVHtpWkIho It is used for finding the Minimum Spanning Tree (MST) of a given
https://youtu.be/ivcbaIhrcsE graph.
problem,
To apply Kruskal’s algorithm, the given graph must be weighted,
connected and undirected.
Kruskal’s Algorithm Implementation-
Step-02: Take the edge with the lowest weight and use it to
connect the vertices of graph.
If adding an edge creates a cycle, then reject that edge and go
for the next least weight edge.
Step-03: Keep adding edges until all the vertices are connected
and a Minimum Spanning Tree (MST) is obtained.
Thumb Rule to Remember
The above steps may be reduced to the following thumb rule-
Simply draw all the vertices on the paper.
Connect these vertices using edges with minimum weights such
that no cycle gets formed.
Kruskal’s Algorithm Time Complexity-
Special Case-
If the edges are already sorted, then there is no need to
construct min heap.
So, deletion from min heap time is saved.
In this case, time complexity of Kruskal’s Algorithm = O(E + V)
PRACTICE PROBLEMS BASED ON KRUSKAL’S
ALGORITHM-
Construct the minimum spanning tree (MST) for the given graph
using Kruskal’s Algorithm-
Solution-
To construct MST using Kruskal’s Algorithm,
Simply draw all the vertices on the paper.
Connect these vertices using edges with minimum weights such
that no cycle gets formed.
Step-01:
Since all the vertices have been connected / included in the
MST, so we stop.
Weight of the MST
= Sum of all edge weights
= 10 + 25 + 22 + 12 + 16 + 14
= 99 units
BACKTRACKING& https://youtu.be/xFv_Hl4B83A 1.Placing n-queens so that no two queens attack each other is
BRANCH-AND-BOUND: called?
nqueens problem a) n-queen’s problem
b) 8-queen’s problem
c) Hamiltonian circuit problem
d) subset sum problem
Answer: a
Explanation: Placing n queens so that no two queens attack
each other is n-queens problem. If n=8, it is called as 8-
queens problem.
2.Where is the n-queens problem implemented?
carom
b) chess
c) ludo
d) cards
Answer: b
Explanation: N-queens problem occurs in chess. It is the problem of
placing n- queens in a n*n chess board.
3. In n-queen problem, how many values of n does not provide an
optimal solution? a) 1
b) 2
c) 3
d) 4
Answer: b
Explanation: N-queen problem does not provide an optimal
solution of only three values of n (i.e.) n=2,3.
4.Which of the following methods can be used to solve
nqueen’s problem?
a) greedy algorithm
b) divide and conquer
c) iterative improvement
d) backtracking
Answer: d
Explanation: Of the following given approaches, n-queens
problem can be solved using backtracking. It can also be
solved using branch and bound.
5.Of the following given options, which one of the following
is a correct option that provides an optimal solution for
4queens problem?
a) (3,1,4,2)
b) (2,3,1,4)
c) (4,3,2,1)
d) (4,2,3,1)
Answer: a
Explanation: Of the following given options for optimal
solutions of 4-queens problem, (3, 1, 4, 2) is the right
option.