DAA - I UNIT
DAA - I UNIT
2 marks:
1. What is an Algorithm? What are the criteria for writing an algorithm?
An algorithm is a sequence of unambiguous instructions for solving a problem, i.e., for obtaining a
required output for any legitimate input in a finite amount of time.
The criteria for writing an algorithms:
• Input: Each algorithm should have zero or more inputs and it should work for a range of inputs
• Output: the algorithm should produce correct result. It should produce atleast one output
• Definiteness: Each instruction should be clear and unambiguous
• Effectiveness: The instructions should be simple and should transform the given input to the
desired o/p.
• Finiteness: The algorithm should terminate after a finite sequence of instructions.
2. What are the methods of specifying an algorithm?
• Natural language
• Pseudocode
• Flowchart
3. List the steps of Algorithm design and analysis process.
c) Stack
It is a list in which insertions and deletions can be done only at the end. This end is called the top.
The structure operates in the “last-in-first-out” (LIFO) fashion.
d) Queue
It is a list from which elements are deleted from one end of the structure, called the front (this
operation is called dequeue), and new elements are added to the other end, called the rear (this
operation is called enqueue).
e) Graph
A graph is a collection of points called vertices, some of which are connected by line segments
called edges. Some of the graph problems are graph traversal, shortest path algorithm, topological
sort, traveling salesman problem and the graph-coloring problem and so on.
f) Tree
A tree is a non-linear and hierarchical data structure where the elements are arranged in a tree-like
structure. In a tree, the topmost node is called the root node. Each node contains some data, and data
can be of any type. A tree with no more than two children is known as a binary tree.
b) Undirected graph
A graph in which edges do not have any direction. That is the nodes are unordered pairs in the definition
of every edge.
c) Adjacency matrix
The adjacency matrix of a graph with n vertices is an n × n boolean matrix with
one row and one column for each of the graph’s vertices, in which the element in
the i th row and the j th column is equal to 1 if there is an edge from the i th vertex
to the j th vertex, and equal to 0 if there is no such edge.
d) Adjacency lists
The adjacency lists of a graph or a digraph is a collection of linked lists, one for
each vertex, that contain all the vertices adjacent to the list's vertex (i.e., all the
vertices connected to it by an edge). Usually, such lists start with a header
identifying a vertex for which the list is compiled.
e) Weighted graph
A weighted graph is a graph with numbers assigned to its edges. These numbers are called weights
or costs.
f) Path
A path is a type of open walk where neither edges nor vertices are allowed to repeat. There is a
possibility that only the starting vertex and ending vertex are the same in a path. In an open walk,
the length of the walk must be more than 0.
g) Cycle
A closed path in the graph theory is also known as a Cycle. A cycle is a type of closed walk where
neither edges nor vertices are allowed to repeat. There is a possibility that only the starting vertex
and ending vertex are the same in a cycle.
• The inner loop executes n times for each of the m outer loop iterations.
• This results in a total of m * n iterations for the combination of both loops.
• Therefore, the overall time complexity is O(m * n), indicating that the algorithm's running time
grows proportionally to the product of m and n.
• If m=n, then O(m * n) becomes O(n * n), which simplifies to O(n2).
18. What is Big O notation? Give an example.
A function t(n) is said to be in O(g(n)), denoted t(n) ∈ O(g(n)), if t(n) is bounded above by some
constant multiple of g(n) for all large n, i.e., if there exist some positive constant c and some
nonnegative integer n0 such that
t(n) ≤ cg(n) for all n ≥ n0.
where t(n) and g(n) are nonnegative functions defined on the set of natural numbers.
Example : Prove the assertion 3n + 2 and n.
Let f(n) = 3n +2 and g(n) = n
f(n) ≤ c.g(n) Let c = 4 Then, 3n + 2 ≤ 4n
Let n = 3 3.3 + 2 ≤ 4.3
∴ f(n) = Ο(g(n))
19. What is Big Omega notation? Give an example.
A function t(n) is said to be in Ω(g(n)), denoted t(n) ∈ Ω(g(n)), if t(n) is bounded below by some
positive constant multiple of g(n) for all large n, i.e., if there exist some positive constant c and
some nonnegative integer n0 such that
t (n) ≥ cg(n) for all n ≥ n0.
where t(n) and g(n) are nonnegative functions defined on the set of natural numbers.
Example : Let f(n) = 3n +2 and g(n) = n
f(n) ≥ c.g(n) Let c = 1 Then, 3n + 2 ≥ 1.n
Let n = 1 3.1 + 2 ≥ 1
∴ f(n) = Ω(g(n))
20. Define Big Theta notation. Give an example.
A function t(n) is said to be in Θ(g(n)), denoted t(n) ∈ Θ(g(n)), if t(n) is bounded both above and
below by some positive constant multiples of g(n) for all large n, i.e., if there exist some positive
constants c1 and c2 and some nonnegative integer n0 such that
c2g(n) ≤ t (n) ≤ c1g(n) for all n ≥ n0.
where t(n) and g(n) are nonnegative functions defined on the set of natural numbers.
Example : Let f(n) = 3n +2 and g(n) = n
f(n) ≤ c1.g(n) Let c1 = 4 Then, 3n + 2 ≤ 4.n
Let n = 3 3.3 + 2 ≤ 4.3
f(n) ≥ c2.g(n) Let c2 = 1 Then, 3n + 2 ≥ 1.n
Let n = 1 3.1 + 2 ≥ 1.1
∴ f(n) = Θ(g(n))
21. Define Little Oh notation. Give an example.
Let f (n) and g(n) be functions that map positive integers to positive real numbers. Given two
functions f(n) and g(n), we say that f(n) is o(g(n)) if for any positive constant c, there exists a
positive constant n₀ such that:
0 ≤ f(n) < c • g(n) for all n ≥ n₀
Example : Given f(n) = 2n + 3 and g(n) = n2, to show that f(n) = o(g(n)), we need to find constants
c > 0 and n₀ > 0 such that 0 ≤ 2n + 3 < c • n2 for all n ≥ n₀.
In this case, let’s choose c=1 and n₀ = 4 : 0 ≤ 2n + 3 < 1 • n2
Thus, f(n) = 2n + 3 is o(n2)
2. Explain Euclid Algorithm with example to find the GCD of two numbers.
Computing the greatest common divisor of two integers, denoted as gcd(m,n), defined as the largest
integer that divides both m and n evenly, i.e., with a remainder of zero.
Step 1 : If n = 0, return the value of m as the answer and stop; otherwise, proceed to Step 2.
Step 2 : Divide m by n and assign the value of the remainder to r.
Step 3 : Assign the value of n to m and the value of r to n. Go to Step 1.
ALGORITHM Euclid(m, n)
//Computes gcd(m, n) by Euclid’s algorithm
//Input: Two nonnegative, not-both-zero integers m and n
//Output: Greatest common divisor of m and n
while n = 0 do
r ← m mod n
m←n
n←r
return m
Ex: gcd(60, 24) can be computed as follows:
gcd(60,24) = gcd (24, 60 mod 24)
gcd(24,12) = gcd (12, 24 mod 12)
gcd(12, 0)
gcd = 12
3. Explain Consecutive integer checking methods to find the GCD of two numbers.
Consecutive integer checking algorithm for computing gcd(m, n)
Step 1 : Assign the value of min{m, n} to t.
Step 2 : Divide m by t. If the remainder of this division is 0, go to Step 3; otherwise, go to Step 4.
Step 3 : Divide n by t. If the remainder of this division is 0, return the value of t as the answer and
stop; otherwise, proceed to Step 4.
Step 4 : Decrease the value of t by 1. Go to Step 2.
Ex: For the numbers 60 and 24, the algorithm will try first 24, then 23, and so on, until it reaches
12, where it stops.
Unlike Euclid’s algorithm, this algorithm, in the form presented, does not work correctly when one
of its input numbers is zero. This example illustrates why it is so important to specify the set of an
algorithm’s inputs explicitly and carefully.
6. Explain following
a. Graph problem
A graph can be thought of as a collection of points called vertices, some of which are connected by
line segments called edges. Some of the graph problems are graph traversal, shortest path algorithm,
topological sort, traveling salesman problem and the graph-coloring problem and so on.
b. Combinatorial problems
These are problems that ask, explicitly or implicitly, to find a combinatorial object—such as a
permutation, a combination, or a subset—that satisfies certain constraints. A desired combinatorial
object may also be required to have some additional property such as a maximum value or a
minimum cost. The traveling salesman problem and the graph coloring problem are examples of
combinatorial problems.
c. Geometrical problems
Geometric algorithms deal with geometric objects such as points, lines, and polygons. Geometric
algorithms are used in computer graphics, robotics, and tomography. The closest-pair problem and
the convex-hull problem are comes under this category.
(ii) Linked List : Sequence of zero or more elements called nodes each containing two kinds of
information: some data and one or more links called pointers to other nodes of the linked list.
In singly linked list, each node except the last one contains a single pointer to the next element.
In doubly linked list, every node except the first and the last contains pointers to both its successor
and its predecessor.
(iii) Stacks : It is a list in which insertions and deletions can be done only at the end. This end is
called the top. The structure operates in the “last-in-first-out” (LIFO) fashion.
(iv) Queue : It is a list from which elements are deleted from one end of the structure , called the
front(this operation is called dequeue), and new elements are added to the other end, called the rear
(this operation is called enqueue). A queue operates in the “first-in-first-out” (FIFO) fashion.
Non-Linear DS:
(v) Graph : A collection points in the plane called “vertices” or “nodes”, which are connected by
line segments called edges. a graph G=<V,E>is defined by a pair of two sets: a finite set V of items
called vertices and a set E of pairs of these items called edges.
A graph is called “undirected” if every edge in it is undirected. A graph whose every edge is
directed is called directed.
(vi) Trees : A tree is a non-linear and hierarchical data structure where the elements are arranged in
a tree-like structure. In a tree, the topmost node is called the root node. Each node contains some
data, and data can be of any type. A tree with no more than two children is known as a binary tree.
(vii) Sets : A set is an unordered collection of distinct items called elements of the set. It can be
defined under collection of items:
(a) Universal set
(b) Subset
(c) Bit vector: Representation of subset using binary division
Eg : U = {1,2,3,4,5,6,7}
S = {2,4,6}
Bit vector = 0 1 0 1 0 1 0
(viii) Dictionaries: In computing, the operations we need to perform for a set or a multiset most
often are searching for a given item, adding a new item, and deleting an item from the collection. A
data structure that implements these three operations is called the dictionary.
There are quite a few ways a dictionary can be implemented. They range from an unsophisticated
use of arrays (sorted or not) to much more sophisticated techniques such as hashing and balanced
search trees.
8. Write a note on Graph data structure.
A collection points in the plane called “vertices” or “nodes”, which are connected by line segments
called edges. a graph G=<V,E>is defined by a pair of two sets: a finite set V of items called vertices
and a set E of pairs of these items called edges.
A graph is called “undirected” if every edge in it is undirected. A graph whose every edge is
directed is called directed. Directed graphs are also called digraphs. A graph with weights is called
a weighted graph.
If a pair of vertices (u, v) is not the same as the pair (v, u), we say that the edge (u, v) is directed
from the vertex u, called the edge's tail, to the vertex v, called the edge's head.
A graph with every pair of its vertices connected by an
edge is called complete. A graph with relatively few
possible edges missing is called dense. A graph with
few edges relative to the number of its vertices is called
sparse.
12. Write an algorithm find the sum of n numbers also calculate its space and time complexity.
ALGORITHM SumOfNNumbers(A,n)
//Addition of n numbers
//Input: Array A of n numbers
//Output: Sum of the elements in A
sum ← 0
for i ← 0 to n-1 do
sum ← sum + A[i]
return sum
The time complexity is O(n), where n is the number of elements. Each element n the array is added
to the sum exactly once.
The space complexity is O(1) since the algorithm uses a constant amount of extra space (the sum
variable) regardless of the size of the input array.
14.Explain Worst case, Best case and average case with example.
Worst-case : The worst-case efficiency of an algorithm is its efficiency for the worst-case input of
size n, which is an input (or inputs) of size n for which the algorithm runs the longest among all
possible inputs of that size.
Eg: For sequential search, the worst case is when there are no matching elements or the first
matching element happens to be the last one on the list.
Cworst(n) = n
Best-case : The best-case efficiency of an algorithm is its efficiency for the best-case input of size
n, which is an input of size n for which the algorithm runs the fastest among all possible inputs of
that size.
For example, the best-case inputs for sequential search are lists of size n with their first element
equal to a search key.
Cbest(n) = 1
Average Case : Average-case efficiency of an algorithm is its efficiency for the “random” input. To
analyze the algorithm’s average-case-efficiency, we must make some assumptions about possible
inputs of size n.
Eg: Consider again sequential search. The average case is when the key element is present in the
exact middle of the array.
Cavg(n) = (n+1) / 2
15.Write an algorithm to perform sequential search and also calculate its Worst case, Best
case and average case complexity.
ALGORITHM SequentialSearch(A[0..n − 1], K)
//Searches for a given value in a given array by sequential search
//Input: An array A[0..n − 1] and a search key K
//Output: The index of the first element in A that matches K
// or −1 if there are no matching elements
A[n] ← K
i←0
while A[i] ≠ K do
i←i+1
if i < n return i
else return −1
Best case : If key element K matches with the first element.
Cbest(n) = 1
Worst case : When there are no matching elements or the first matching element happens to be the
last one on the list.
Cworst(n) = n
Average case : If the key element is present in the exact middle of the array.
Cavg(n) = (n+1) / 2
19.Explain asymptotic notations Big O, Big Ω and Big θ that are used to compare the order of
growth of an algorithm with example.
Refer Q.No. 16, 17, 18
c) 1/2n(n-1) ∈ Θ (n2)
Let f(n)= ½ (n(n-1)) and g(n)=n2. We want to show that f(n) is in Θ(n²).
To prove this, we need to find positive constants c1, c2, and n0 such that c₁.g(n) ≤ f(n) ≤ c2.g(n) for
all n ≥ no
Lower Bound:
Start with the inequality c₁.n² ≤ ½ (n(n-1))
Set c1 = 1/4 and no = 1
Now, for all n ≥ 1: 1/4 n² ≤ ½(n(n-1))
Upper Bound:
Start with the inequality ½(n(n-1)) ≤ c2.n²
Set c2 = 1 and no = 1
Now, for all n ≥ 1: ½(n(n-1)) ≤ n²
Therefore, ½(n(n-1)) belongs to Θ (n²) with c1 = 1/4, c2 = 1, and no = 1.
20. Write an algorithm to Checking for Unique elements in an array and also perform
mathematical analysis.
Analysis:
o Parameter to be considered is n (size of input).
o Since the innermost loop contains a single operation (the comparison of two elements), we should
consider it as the algorithm’s basic operation.
o The number of element comparisons depends not only on n but also on whether there are equal
elements in the array and, if there are, which array positions they occupy. We will limit our
investigation to the worst case only. An inspection of the innermost loop reveals that there are two
kinds of worst-case inputs:
➢ arrays with no equal elements
➢ arrays in which the last two elements are the only pair of equal elements.
o Here, one comparison is made for each repetition of the innermost loop, i.e., for each value of the
loop variable j between its limits i + 1 and n − 1; This is repeated for each value of the outer loop,
i.e., for each value of the loop variable i between its limits 0 and n − 2.
Accordingly, we get
21. Write an algorithm to perform matrix multiplication and also perform mathematical
analysis.
ALGORITHM MatrixMultiplication(A[0..n − 1, 0..n − 1], B[0..n − 1, 0..n − 1])
//Multiplies two square matrices of order n by the definition-based algorithm
//Input: Two n × n matrices A and B
//Output: Matrix C = AB
for i ←0 to n – 1 do
for j ←0 to n – 1 do
C[i, j ] ← 0.0
for k←0 to n − 1 do
C[i, j ] ← C[i, j ] + A[i, k] * B[k, j]
return C
Analysis:
o Parameter to be considered is n (size of input).
o There are two arithmetical operations in the innermost loop here: multiplication and addition. We
consider multiplication as the basic operation.
o Let M(n) be the sum for the total number of multiplications executed by the algorithm.
o There is just one multiplication executed on each repetition of the algorithm’s innermost loop,
which is governed by the variable k ranging from the lower bound 0 to the upper bound n − 1.
22. Write a non-recursive algorithm to Count the number of bits in a number. And also
perform mathematical analysis.
ALGORITHM Binary(n)
//Input: A positive decimal integer n
//Output: The number of binary digits in n’s binary representation
count ←1
while n > 1 do
count ← count + 1
n← [n / 2]
return count
Analysis:
o The most frequently executed operation here is not inside the while loop but rather the
comparison n > 1 that determines whether the loop’s body will be executed.
o Loop variable takes on only a few values between its lower and upper limits; therefore, we have
to use an alternative way of computing the number of times the loop is executed. Since the value of
n is about halved on each repetition of the loop, the answer should be about log2n.
o The exact formula for the number of times the comparison n>1 will be executed is actually
[log2 n] + 1
23. List the steps for analyzing the time efficiency of recursive algorithm.
General Plan for Analyzing Time Efficiency of Recursive Algorithms
(i) Decide on a parameter (or parameters) indicating an input's size.
(ii) Identify the algorithm's basic operation.
(iii) Check whether the number of times the basic operation is executed can vary on different inputs
of the same size; if it can, the worst-case, average-case, and best-case efficiencies must be
investigated separately.
(iv) Set up a recurrence relation, with an appropriate initial condition, for the number of times the
basic operation is executed.
(v) Solve the recurrence or at least ascertain the order of growth of its solution.
Analysis:
25, Write an algorithm to perform Towers of Hanoi using recursion and also perform
mathematical analysis.
The problem has an elegant recursive solution,
T(n) = ∑𝑛−1 𝑖
𝑖=0 ∑𝑗=0 𝑂(1)
The double summation represents the two nested loops. The inner loop runs from 0 to 'i', and the
outer loop runs from 0 to 'n-1'. The constant time operation is (1) for each element assignment.
Simplifying the expression:
T(n) = ∑𝑛−1
𝑖=0 (𝑖 + 1). 𝑂(1)
T(n) = 𝑂(∑𝑛−1
𝑖=0 (𝑖 + 1))
T(n) = O (𝑛(𝑛+1)
2
)
Therfore, the time complexity is O(n2).
27. Solve the following recurrence relation.
a) x(n) = x(n-1) + 5 for n >1 , x(1) =0
b) x(n) = 3x(n-1) for n > 1 , x(1)=4
c) x(n) = x(n-1) + n for n>1 , x(0)=0
Analysis:
The algorithm has a single loop that iterates from 2 to n.
Inside the loop, there are constant-time operations (addition and assignments) that do not depend on
the input size.
The loop runs n - 1 times (from 2 to n).
Time Complexity:
Let's denote the time complexity as T(n). The time complexity is determined by the loop, which
iterates n - 1 times.
T(n) = O(n)
Therefore, the time complexity of the given Fibonacci algorithm is linear, denoted by O(n).