Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 21

1. A] What is an Algorithm?

Write the properties of the


Algorithm.
A finite set of instruction that specifies a sequence of operation is to be carried out in
order to solve a specific problem or class of problems is called an Algorithm.

Properties of Algorithm:
 It should terminate after a finite time.
 It should produce at least one output.
 It should take zero or more input.
 It should be deterministic means giving the same output for the same input
case.
 Every step in the algorithm must be effective i.e. every step should do some
work.

 Clear and Unambiguous: The algorithm should be unambiguous. Each of its


steps should be clear in all aspects and must lead to only one meaning.
 Well-Defined Inputs: If an algorithm says to take inputs, it should be well-
defined inputs. It may or may not take input.
 Well-Defined Outputs: The algorithm must clearly define what output will be
yielded and it should be well-defined as well. It should produce at least 1
output.
 Finite-ness: The algorithm must be finite, i.e. it should terminate after a finite
time.
 Feasible: The algorithm must be simple, generic, and practical, such that it can
be executed with the available resources. It must not contain some future
technology or anything.
 Language Independent: The Algorithm designed must be language-
independent, i.e. it must be just plain instructions that can be implemented in
any language, and yet the output will be the same, as expected.
 Input: An algorithm has zero or more inputs. Each that contains a fundamental
operator must accept zero or more inputs.
 Output: An algorithm produces at least one output. Every instruction that
contains a fundamental operator must accept zero or more inputs.
 Definiteness: All instructions in an algorithm must be unambiguous, precise,
and easy to interpret. By referring to any of the instructions in an algorithm one
can clearly understand what is to be done. Every fundamental operator in
instruction must be defined without any ambiguity.
 Finiteness: An algorithm must terminate after a finite number of steps in all test
cases. Every instruction which contains a fundamental operator must be
terminated within a finite amount of time. Infinite loops or recursive functions
without base conditions do not possess finiteness.
 Effectiveness: An algorithm must be developed by using very basic, simple, and
feasible operations so that one can trace it out by using just paper and pencil.
1. B] What is a Binary tree? Explain the types of Binary tree
A binary tree is a hierarchical data structure composed of nodes, where each node has at most
two children, referred to as the left child and the right child. The topmost node of the tree is
called the root node. Each child node can, in turn, have its own left and right children, forming
subtrees.

1. Full Binary Tree


A Binary Tree is a full binary tree if every node has 0 or 2 children. The following
are examples of a full binary tree. We can also say a full binary tree is a binary tree
in which all nodes except leaf nodes have two children.
A full Binary tree is a special type of binary tree in which every parent node/internal
node has either two or no children. It is also known as a proper binary tree.

Full Binary Tree

2. Degenerate (or pathological) tree


A Tree where every internal node has one child. Such trees are performance-wise
same as linked list. A degenerate or pathological tree is a tree having a single child
either left or right.

Degenerate (or pathological) tree


3. Skewed Binary Tree
A skewed binary tree is a pathological/degenerate tree in which the tree is either
dominated by the left nodes or the right nodes. Thus, there are two types of
skewed binary tree: left-skewed binary tree and right-skewed binary tree.

Skewed Binary Tree

4. Perfect Binary Tree


A Binary tree is a Perfect Binary Tree in which all the internal nodes have
two children and all leaf nodes are at the same level.
The following are examples of Perfect Binary Trees.
A perfect binary tree is a type of binary tree in which every internal node has
exactly two child nodes and all the leaf nodes are at the same level.

Perfect Binary Tree

In a Perfect Binary Tree, the number of leaf nodes is the number of internal
nodes plus 1
L = I + 1 Where L = Number of leaf nodes, I = Number of internal nodes.
A Perfect Binary Tree of height h (where the height of the binary tree is the
number of edges in the longest path from the root node to any leaf node in
the tree, height of root node is 0) has 2 h+1 – 1 node.
An example of a Perfect binary tree is ancestors in the family. Keep a person
at root, parents as children, parents of parents as their children.

5. Balanced Binary Tree


A binary tree is balanced if the height of the tree is O(Log n) where n is the
number of nodes. For Example, the AVL tree maintains O(Log n) height by
making sure that the difference between the heights of the left and right
subtrees is at most 1. Red-Black trees maintain O(Log n) height by making
sure that the number of Black nodes on every root to leaf paths is the same
and that there are no adjacent red nodes. Balanced Binary Search trees are
performance-wise good as they provide O(log n) time for search, insert and
delete.

Example of Balanced and Unbalanced Binary Tree

It is a type of binary tree in which the difference between the height of the left
and the right subtree for each node is either 0 or 1. In the figure above, the
root node having a value 0 is unbalanced with a depth of 2 units.

1. C] Explain the concept of i) sets ii) disjoint

i] Sets:-
Sets, in the context of data structures and algorithms, refer to a fundamental abstract
data type that represents a collection of unique elements with no specific order. The
set data structure is designed to store elements such that each element occurs only
once within the set. Sets are widely used in various algorithms and applications due
to their ability to efficiently handle unique collections of data and perform set
operations.
Key Characteristics of Sets in Data Structures and Algorithms:

1. Uniqueness: Sets contain only unique elements. If an element is added to a set and
it already exists in the set, the set structure ensures that only one instance of the
element is stored.
2. No Specific Order: Unlike sequences or lists, sets do not impose any specific order
on the elements they contain. The order of elements within a set is arbitrary and
does not affect the set itself.
3. Membership Testing: Sets support efficient membership testing, which allows for
determining whether a given element belongs to the set or not. This operation is
typically performed in constant time (1)O(1), making sets suitable for quickly
checking the presence of elements.
4. Set Operations: Sets support various operations for performing set manipulations
and comparisons. Some of the common set operations include:
 Union: Combining the elements of two sets to form a new set containing all
unique elements from both sets.
 Intersection: Finding the common elements between two sets to form a new
set.
 Difference: Obtaining the elements that are present in one set but not in
another set.
 Subset: Checking if one set is a subset of another set.
 Superset: Checking if one set contains all the elements of another set.
5. Dynamic Size: Sets can dynamically resize to accommodate a varying number of
elements. As elements are added or removed, the size of the set adjusts accordingly
to maintain efficiency in terms of memory usage and performance.

Applications of Sets in Data Structures and Algorithms:

 Data Deduplication: Sets are used to remove duplicate elements from data
collections efficiently.
 Database Systems: Sets are utilized to represent relationships and ensure data
integrity in database management systems.
 Graph Algorithms: Sets are employed in graph algorithms to represent sets of
vertices, edges, or other graph components.
 Text Processing: Sets are used to perform operations such as finding unique words
in a document or determining common elements in multiple documents.

ii] Disjoint:-

the concept of disjoint primarily refers to sets or data structures that do not share
any common elements. Disjoint sets play a crucial role in various algorithms and data
structures, especially when dealing with relationships between elements, identifying
connectivity in graphs, or managing collections of elements efficiently.

Here's an explanation of the concept of disjoint in DAA:

1. Disjoint Sets: Disjoint sets refer to sets or collections of elements in which no


element belongs to more than one set at a time. In other words, each element is part
of one and only one set, and there are no overlapping elements between sets.
2. Applications:
 Union-Find Data Structure: Disjoint sets are often managed and
manipulated using a data structure called the union-find data structure. This
data structure efficiently supports operations such as finding the set to which
an element belongs and merging two disjoint sets into one.
 Graph Algorithms: Disjoint sets are extensively used in graph algorithms to
determine connectivity between vertices, identify connected components, and
detect cycles within graphs. For example, disjoint sets are essential in
algorithms like Kruskal's algorithm for finding minimum spanning trees and in
detecting cycles in graphs.
 Dynamic Equivalence Relations: Disjoint sets can represent equivalence
relations, where elements are considered equivalent if they belong to the
same set. This concept is applied in various algorithms and scenarios where
equivalence relationships need to be maintained dynamically.
3. Operations:
 MakeSet: Creates a new set with a single element.
 Union: Merges two sets into one by combining their elements.
 Find: Determines which set a given element belongs to and returns the
representative element of the set.
4. Efficient Management of Relationships: Disjoint sets allow for the efficient
management of relationships between elements, particularly in scenarios where
connectivity, disjointness, or equivalence relationships need to be determined or
maintained dynamically.

2. A] Write down the algorithm of Merge Sort

2. B] Evaluate the Following Example using Quick Sort

44 33 11 55 77 90 40 60 99 22 88

1. 44 33 11 55 77 90 40 60 99 22 88

Let 44 be the Pivot element and scanning done from right to left
Comparing 44 to the right-side elements, and if right-side elements
are smaller than 44, then swap it. As 22 is smaller than 44 so swap them.

22 33 11 55 77 90 40 60 99 44 88

Now comparing 44 to the left side element and the element must be greater than
44 then swap them. As 55 are greater than 44 so swap them.

22 33 11 44 77 90 40 60 99 55 88

Recursively, repeating steps 1 & steps 2 until we get two lists one left from pivot
element 44 & one right from pivot element.

22 33 11 40 77 90 44 60 99 55 88

Swap with 77:

22 33 11 40 44 90 77 60 99 55 88

Now, the element on the right side and left side are greater than and smaller
than 44 respectively.

Now we get two sorted lists:

And these sublists are sorted under the same process as above done.

These two sorted sublists side by side.


2. C] Determine the concept of Strassen's Matrix Multiplication

3. A] Explain Prim's Algorithm with an appropriate Example.


4. Prim's Algorithm is a greedy algorithm that is used to find the minimum
spanning tree from a graph. Prim's algorithm finds the subset of edges that
includes every vertex of the graph such that the sum of the weights of the
edges can be minimized.
5. Prim's algorithm starts with the single node and explores all the adjacent
nodes with all the connecting edges at every step. The edges with the minimal
weights causing no cycles in the graph got selected.

the prim's algorithm work


Prim's algorithm is a greedy algorithm that starts from one vertex and continue to
add the edges with the smallest weight until the goal is reached. The steps to
implement the prim's algorithm are given as follows -

o First, we have to initialize an MST with the randomly chosen vertex.


o Now, we have to find all the edges that connect the tree in the above step
with the new vertices. From the edges found, select the minimum edge and
add it to the tree.
o Repeat step 2 until the minimum spanning tree is formed.

The applications of prim's algorithm are -


o Prim's algorithm can be used in network designing.
o It can be used to make network cycles.
o It can also be used to lay down electrical wiring cables.

Example of prim's algorithm


Now, let's see the working of prim's algorithm using an example. It will be easier to
understand the prim's algorithm using an example.

Suppose, a weighted graph is -

Step 1 - First, we have to choose a vertex from the above graph. Let's choose B.

Step 2 - Now, we have to choose and add the shortest edge from vertex B. There are
two edges from vertex B that are B to C with weight 10 and edge B to D with weight
4. Among the edges, the edge BD has the minimum weight. So, add it to the MST.
Step 3 - Now, again, choose the edge with the minimum weight among all the other
edges. In this case, the edges DE and CD are such edges. Add them to MST and
explore the adjacent of C, i.e., E and A. So, select the edge DE and add it to the MST.

Step 4 - Now, select the edge CD, and add it to the MST.
Step 5 - Now, choose the edge CA. Here, we cannot select the edge CE as it would
create a cycle to the graph. So, choose the edge CA and add it to the MST.

So, the graph produced in step 5 is the minimum spanning tree of the given graph.
The cost of the MST is given below -

Cost of MST = 4 + 2 + 1 + 3 = 10 units.

Algorithm
1. Step 1: Select a starting vertex
2. Step 2: Repeat Steps 3 and 4 until there are fringe vertices
3. Step 3: Select an edge 'e' connecting the tree vertex and fringe vertex that has minim
um weight
4. Step 4: Add the selected edge and the vertex to the minimum spanning tree T
5. [END OF LOOP]
6. Step 5: EXIT

Complexity of Prim's algorithm


Now, let's see the time complexity of Prim's algorithm. The running time of the
prim's algorithm depends upon using the data structure for the graph and the
ordering of edges. Below table shows some choices -

Data structure used for the minimum edge weight Time Complexity

Adjacency matrix, linear searching O(|V|2)

Adjacency list and binary heap O(|E| log |V|)

Adjacency list and Fibonacci heap O(|E|+ |V| log |V|)

o Time Complexity
Prim's algorithm can be simply implemented by using the adjacency matrix or
adjacency list graph representation, and to add the edge with the minimum weight
requires the linearly searching of an array of weights. It requires O(|V| 2) running time.
It can be improved further by using the implementation of heap to find the minimum
weight edges in the inner loop of the algorithm.

The time complexity of the prim's algorithm is O(E logV) or O(V logV), where E is the
no. of edges, and V is the no. of vertices.

3] B] Explain Kruskal's Algorithm with a suitable Example.


Kruskal's Algorithm is a popular greedy algorithm used to find the minimum
spanning tree (MST) of a connected, undirected graph. The minimum spanning tree
is a subset of the edges of a graph that forms a tree, connecting all the vertices
together with the minimum possible total edge weight.

Here's how Kruskal's Algorithm works:

1. Initialize: Begin with all vertices being isolated, forming single-vertex trees.
2. Sort Edges: Sort all the edges of the graph in non-decreasing order of their weights.
3. Iterate through Edges: Starting from the edge with the smallest weight, iterate
through each edge.
4. Check for Cycle: For each edge, check if adding it to the spanning tree creates a
cycle. If adding the edge does not create a cycle, include it in the MST.
5. Union-Find Data Structure: Use a union-find data structure to efficiently determine
whether adding an edge creates a cycle. This data structure maintains disjoint sets of
vertices and efficiently merges them while checking for connectivity.
6. Repeat: Repeat steps 4 and 5 until the MST contains V - 1 edges, where V is the
number of vertices in the graph.

Example of Kruskal's algorithm


Now, let's see the working of Kruskal's algorithm using an example. It will be easier
to understand Kruskal's algorithm using an example.

Suppose a weighted graph is -

ADVERTISEMENT
ADVERTISEMENT
The weight of the edges of the above graph is given in the below table -

Edge AB AC AD AE BC CD DE

Weight 1 7 10 5 3 4 2

Now, sort the edges given above in the ascending order of their weights.

Edge AB DE BC CD AE AC AD

Weight 1 2 3 4 5 7 10

Now, let's start constructing the minimum spanning tree.

Step 1 - First, add the edge AB with weight 1 to the MST.


Step 2 - Add the edge DE with weight 2 to the MST as it is not creating the cycle.

Step 3 - Add the edge BC with weight 3 to the MST, as it is not creating any cycle or
loop.
Step 4 - Now, pick the edge CD with weight 4 to the MST, as it is not forming the
cycle.

ADVERTISEMENT

Step 5 - After that, pick the edge AE with weight 5. Including this edge will create
the cycle, so discard it.

Step 6 - Pick the edge AC with weight 7. Including this edge will create the cycle, so
discard it.

Step 7 - Pick the edge AD with weight 10. Including this edge will also create the
cycle, so discard it.

So, the final minimum spanning tree obtained from the given weighted graph by
using Kruskal's algorithm is -

The cost of the MST is = AB + DE + BC + CD = 1 + 2 + 3 + 4 = 10.


ADVERTISEMENT
ADVERTISEMENT

Now, the number of edges in the above tree equals the number of vertices minus 1.
So, the algorithm stops here.

Algorithm
1. Step 1: Create a forest F in such a way that every vertex of the graph is a separate tre
e.
2. Step 2: Create a set E that contains all the edges of the graph.
3. Step 3: Repeat Steps 4 and 5 while E is NOT EMPTY and F is not spanning
4. Step 4: Remove an edge from E with minimum weight
5. Step 5: IF the edge obtained in Step 4 connects two different trees, then add it to the
forest F
6. (for combining two trees into one tree).
7. ELSE
8. Discard the edge
9. Step 6: END

Complexity of Kruskal's algorithm


Now, let's see the time complexity of Kruskal's algorithm.

Time Complexity:-
The time complexity of Kruskal's algorithm is O(E logE) or O(V logV), where E
is the no. of edges, and V is the no. of vertices.

6. C] Explain the concept of Huffman code with a suitable


Example.
Huffman Coding is a greedy technique to obtain an optimal solution
to a problem. The Huffman coding is generally used for lossless data
compression mechanisms. Sometimes, it is also called data
compression encoding. It makes sure that there is no ambiguity while
decoding the output bitstream.
Huffman Coding Algorithm
The Huffman coding algorithm, as already discussed, follows the greedy
design approach to arrive at an optimal solution. It uses a Huffman tree to
encode and decode the data. A Huffman tree is created using the following
steps:

1. Create a leaf node for each character of the text.


2. Arrange all the nodes in the increasing order of their frequency.
3. Considering the first two nodes have the minimum frequency.
-Create an internal node.
-The frequency of this internal node is the sum of the frequency of
the previous two nodes.
-Make the first and second nodes the left and right children
respectively of the newly created node.
4. Repeat steps 2 and 3 until all the nodes form a tree. The tree thus
obtained is a Huffman tree.

After the Huffman tree is created, each character is assigned a unique


code. For decoding, the same Huffman tree is traversed.

4] A] Explain the concept of the Flow Shop Scheduling algorithm.


Flow Shop Scheduling is a problem in operations research and scheduling theory
that deals with scheduling a series of tasks or jobs that need to be processed
through a set of machines or workstations in a specific sequence. The goal is to
minimize the total completion time, makespan, or other objective functions while
adhering to certain constraints.

In the Flow Shop Scheduling problem, each job consists of multiple operations that
must be performed sequentially, with each operation requiring processing on one of
the available machines. The objective is to find the optimal sequence of jobs and
operations to minimize the total completion time or another performance metric.

The problem is called "flow shop" because the jobs flow through the machines in a
fixed order, with each machine performing a specific operation on the job before
passing it to the next machine. Here are the key components and concepts
associated with the Flow Shop Scheduling algorithm:

1. Jobs: A set of tasks or jobs that need to be processed through the machines. Each
job consists of multiple operations that must be performed in a specific sequence.
2. Machines: A set of machines or workstations available to process the jobs. Each
machine is capable of performing specific operations, and jobs must be scheduled in
a way that minimizes idle time and maximizes machine utilization.
3. Processing Time: The time required to complete each operation of a job on a
specific machine. The processing times are usually predetermined and known in
advance.
4. Sequence: The sequence in which jobs are scheduled to be processed through the
machines. The goal is to find the optimal sequence that minimizes the total
completion time or makespan.
5. Objective Function: The performance metric used to evaluate the quality of the
scheduling solution. Common objective functions include minimizing the total
completion time, minimizing the maximum completion time (makespan), minimizing
the total flow time, or minimizing the total tardiness.
6. Constraints: Constraints may include precedence constraints (certain operations
must be completed before others can start), resource constraints (limited availability
of machines or workers), and job release times (jobs cannot start processing before a
certain time).

Flow Shop Scheduling algorithms can be classified into several categories, including
exact algorithms, heuristic algorithms, and metaheuristic algorithms. Some common
algorithms and techniques used to solve Flow Shop Scheduling problems include
Johnson's algorithm, Palmer's algorithm, Genetic algorithms, Simulated Annealing,
Tabu Search, and Ant Colony Optimization.

4] B] Explain the concept of Matrix Chain Multiplication.

4. C] Consider the 0/1 knapsack problem having weights and


profits are:

Weights: \{3, 4, 6, 5\}


Profits: \{2, 3, 1, 4\}

The weight of the knapsack is 8 kg. Solve the problem using


dynamic programming

5] A] Explain the concept of the spanning Tree with a suitable


Example.
5] B] Write down the Algorithm for BFS.

BFS algorithm
In this article, we will discuss the BFS algorithm in the data structure. Breadth-first
search is a graph traversal algorithm that starts traversing the graph from the root
node and explores all the neighboring nodes. Then, it selects the nearest node and
explores all the unexplored nodes. While using BFS for traversal, any node in the
graph can be considered as the root node.

There are many ways to traverse the graph, but among them, BFS is the most
commonly used approach. It is a recursive algorithm to search all the vertices of a
tree or graph data structure. BFS puts every vertex of the graph into two categories -
visited and non-visited. It selects a single node in a graph and, after that, visits all the
nodes adjacent to the selected node.

Applications of BFS algorithm


The applications of breadth-first-algorithm are given as follows -

o BFS can be used to find the neighboring locations from a given source location.
o In a peer-to-peer network, BFS algorithm can be used as a traversal method to find
all the neighboring nodes. Most torrent clients, such as BitTorrent, uTorrent, etc.
employ this process to find "seeds" and "peers" in the network.
o BFS can be used in web crawlers to create web page indexes. It is one of the main
algorithms that can be used to index web pages. It starts traversing from the source
page and follows the links associated with the page. Here, every web page is
considered as a node in the graph.
o BFS is used to determine the shortest path and minimum spanning tree.
o BFS is also used in Cheney's technique to duplicate the garbage collection.
o It can be used in ford-Fulkerson method to compute the maximum flow in a flow
network.

Algorithm
The steps involved in the BFS algorithm to explore a graph are given as follows -

Step 1: SET STATUS = 1 (ready state) for each node in G


Step 2: Enqueue the starting node A and set its STATUS = 2 (waiting state)

Step 3: Repeat Steps 4 and 5 until QUEUE is empty

Step 4: Dequeue a node N. Process it and set its STATUS = 3 (processed state).

Step 5: Enqueue all the neighbours of N that are in the ready state (whose STATUS =
1) and set

their STATUS = 2

(waiting state)

[END OF LOOP]

Step 6: EXIT

5. C] Explain the concept of the N-queen Problem.


The N-Queens problem is a classic problem in computer science and
combinatorial optimization that involves placing N chess queens on an
N×N chessboard so that no two queens threaten each other. In chess, a
queen can attack any piece that lies in the same row, column, or diagonal
as itself. Therefore, the goal of the N-Queens problem is to arrange the
queens on the chessboard such that no two queens can attack each other.

The problem is named after the chess piece "queen," which is the most
powerful piece on the chessboard. The problem statement is as follows:

Given an N×N chessboard, place N queens on the board such that no two
queens threaten each other. This means that no two queens can share the
same row, column, or diagonal.

Key Concepts and Challenges:

1. Constraint Satisfaction Problem: The N-Queens problem is a constraint


satisfaction problem, where the primary goal is to find a valid arrangement
of queens that satisfies the constraints (no two queens can attack each
other).
2. Recursion and Backtracking: One of the common approaches to solving
the N-Queens problem is through recursion and backtracking. The idea is
to recursively explore all possible configurations of queens on the
chessboard while ensuring that the placement is valid and does not violate
any constraints.
3. Branch and Bound: Another approach to solving the N-Queens problem
involves using the branch and bound technique. This method involves
exploring the search space of possible solutions using heuristics to
efficiently prune branches of the search tree that cannot lead to a valid
solution.
4. Symmetry and Redundancy: Due to the symmetrical nature of the
chessboard and the placement of queens, certain solutions may be
redundant or equivalent. Techniques such as symmetry breaking can help
reduce the search space and improve the efficiency of the algorithm.
5. Optimization and Performance: As the size of the chessboard (N)
increases, the complexity of the problem grows exponentially. Therefore,
optimizing algorithms and heuristics are crucial for solving larger instances
of the N-Queens problem efficiently.

The N-Queens problem is not only of theoretical interest but also has
practical applications in various fields, including artificial intelligence,
constraint programming, and optimization. It serves as a benchmark
problem for evaluating and comparing different algorithms and techniques
for solving constraint satisfaction problems. Additionally, it demonstrates
the importance of problem-solving skills and algorithmic techniques in
computer science and mathematics.

You might also like