DSA Assignment Shreya
DSA Assignment Shreya
DSA Assignment Shreya
CAP2001
School of Engineering and Sciences
Department of Computer Science and Engineering
Submitted By:
Student Name Shreya Prakash
Roll No 220160212091
Programme BCA
Section B, T4
Department Computer Science and Engineering
Session/Semester 2023-24/3rd Semester
Submitted To:
Faculty Name Ms. Sapna Sharma
G D Goenka University
Gurgaon, Haryana
Q1. What do you mean by Searching? Explain Sequential search and Binary search with
help of example.
Ans. Searching is the process of finding a particular item or value in a collection of data. It's a
common operation in computer science and is used in various applications such as databases,
information retrieval, and algorithms. There are different searching algorithms, and two common
ones are sequential search and binary search.
Sequential Search:
• Definition: Sequential search, also known as linear search, is a simple searching algorithm
that iterates through each element in a collection until it finds the target value or reaches
the end of the collection.
• Example: Let's consider an array of integers: [3, 1, 4, 7, 2, 8, 5]. Suppose we want to search
for the value 7.
Array: [3, 1, 4, 7, 2, 8, 5]
Index: 0 1 2 3 4 5 6
Q2. Define Linked List. What are the types of linked lists? What are the ways of
implementing linked list? State the advantages of circular lists over doubly linked list.
Ans. A linked list is a data structure used for organizing and storing a sequence of elements. Unlike
arrays, elements in a linked list are not stored in contiguous memory locations; instead, each
element points to the next one, forming a chain-like structure. The basic building block of a linked
list is a node, which contains data and a reference (or link) to the next node in the sequence.
There are several types of linked lists, with the main distinctions being in the way nodes are
connected. The common types include:
• Singly Linked List: Each node points to the next node in the sequence.
• Doubly Linked List: Each node has references to both the next and the previous nodes in
the sequence.
• Circular Linked List: In a circular linked list, the last node points back to the first node,
forming a circle.
Linked lists can be implemented using various programming languages, and the choice of
implementation may depend on the language and the specific requirements. The main ways to
implement linked lists include:
• Node-based Implementation: Define a node structure that contains data and a reference
to the next (and possibly previous) node.
• Class-based Implementation: In object-oriented languages like Java or Python, you can
define a class for the linked list, where each instance of the class represents a node.
• Dynamic Memory Allocation (C): In languages like C, nodes can be dynamically
allocated using pointers.
Circular linked lists have some advantages over doubly linked lists in certain scenarios:
However, it's essential to note that the choice between circular and doubly linked lists depends on
the specific requirements of the application, and each has its own set of advantages and trade-offs.
Q3. What do you mean by Link list? Write an algorithm to insert and delete a node in Singly
Linked List.
Ans. A linked list is a linear data structure consisting of a sequence of elements where each element
points to the next element in the sequence. The basic building block of a linked list is a node, which
contains data and a reference (or link) to the next node in the sequence.
a. Set the new node's next pointer to the next node of the current node.
b. Set the next pointer of the current node to the new node.
Delete(Node, Position)
a. Set the head of the list to the next node of the current head.
a. Set the next pointer of the current node to the next node of the next node.
Pseudocode:
Node Structure:
Node:
data
next
2. If position is 0:
3. Else:
DeleteNode(head, position):
2. If position is 0:
a. Set temp to head.
3. Else:
ii. If current is null or current.next is null, return an error (position out of bounds).
This pseudocode assumes a zero-based index for the positions, and it performs error checking to
handle cases such as an empty list or attempting to insert/delete at an out-of-bounds position.
Additionally, it dynamically allocates and frees memory for nodes as needed.
Program:
#include <stdio.h>
#include <stdlib.h>
// Node structure
struct Node {
int data;
};
current = current->next;
printf("NULL\n");
newNode->data = newData;
newNode->next = head;
head = newNode;
return head;
// Function to delete a node with a given key from the linked list
head = current->next;
free(current);
return head;
}
// Search for the key to be deleted, keeping track of the previous node
prev = current;
current = current->next;
if (current == NULL) {
return head;
prev->next = current->next;
free(current);
return head;
// Main function
int main() {
printList(head);
return 0;
Q4. What do you mean by Searching? Write a C program for Linear Search and binary
search. Write their time complexity.
Ans. Searching is the process of finding a particular item or value in a collection of data. It involves
examining the elements of a data structure and determining if a particular element matches the
target value. Searching is a fundamental operation in computer science and is used in various
algorithms and applications.
Linear Search: Linear search, also known as sequential search, is a simple searching algorithm
that examines each element in a collection one by one until the target element is found or the end
of the collection is reached.
Input:
#include <stdio.h>
if (arr[i] == key) {
int main() {
int n, key;
scanf("%d", &n);
scanf("%d", &arr[i]);
scanf("%d", &key);
if (result != -1) {
} else {
return 0;
Output:
1 4 7 9 10 13 16 18 23 25
The time complexity of linear search is O(n), where 'n' is the number of elements in the array. In
the worst case, the algorithm may need to iterate through all elements to find the target.
Binary Search: Binary search is a more efficient searching algorithm that works on sorted arrays.
It repeatedly divides the search interval in half.
Input:
#include <stdio.h>
if (arr[mid] == key) {
} else {
int main() {
int n, key;
scanf("%d", &n);
scanf("%d", &arr[i]);
scanf("%d", &key);
} else {
return 0;
Output:
1 2 3 5 6 8 10 13 16 18
The time complexity of binary search is O(log n), where 'n' is the number of elements in the array.
This is because, in each step, the search space is halved, leading to a more efficient search
compared to linear search.
Q5. Define:
Ans.
1. Graph: A graph is a collection of nodes (or vertices) and edges that connect pairs of nodes.
Graphs are widely used to represent relationships between entities. The edges may be
directed or undirected, and they may have weights.
2. Weighted Graph: A weighted graph is a type of graph in which each edge is assigned a
numerical value or weight. This weight represents some quantitative measure of the
relationship between the nodes connected by the edge. Weighted graphs are used when the
connections between nodes have associated costs, distances, or other numerical values.
3. Directed Graph: A directed graph (or digraph) is a graph in which edges have a direction,
meaning they are ordered pairs. If there is a directed edge from node A to node B, it doesn't
imply the existence of an edge from B to A unless explicitly defined. Directed graphs are
useful for representing relationships with a sense of direction, such as dependencies or
flows.
4. Undirected Graph: An undirected graph is a graph in which edges do not have a direction.
The edges are unordered pairs, meaning that if there is an edge between node A and node
B, it implies an edge between B and A. Undirected graphs are used to represent symmetric
relationships.
5. Indegree and Outdegree of a Graph:
• Indegree: For a directed graph, the indegree of a node is the number of incoming edges to
that node. It represents how many edges are directed towards the node.
• Outdegree: For a directed graph, the outdegree of a node is the number of outgoing edges
from that node. It represents how many edges are directed away from the node.
6. Adjacency Matrix: An adjacency matrix is a two-dimensional array used to represent a
finite graph. The rows and columns of the matrix correspond to the vertices of the graph,
and the presence or absence of an edge between two vertices is indicated by the values in
the matrix. For an undirected graph, the matrix is symmetric, and for a directed graph, it
may not be symmetric. The matrix may also contain weights if it's a weighted graph. An
entry A[i][j] is usually 1 if there is an edge between vertices i and j, and 0 otherwise. If it's
a weighted graph, A[i][j] may represent the weight of the edge.
Q6. What is sorting? What do you mean by internal and external sorting? List the different
types of sorting techniques. Write their times complexity.
Ans. Sorting is the process of arranging elements in a specific order, typically in ascending or
descending order based on some criteria. It is a fundamental operation in computer science and
finds applications in various areas, such as searching, data analysis, and information retrieval.
• Internal Sorting: Internal sorting refers to sorting the entire data set in the main memory
(RAM). It assumes that the entire data set fits into the computer's memory.
• External Sorting: External sorting is used when the data set is too large to fit entirely into
the main memory. It involves dividing the data into smaller chunks, sorting each chunk
internally, and then merging the sorted chunks.
1. Bubble Sort:
Time Complexity:
• Worst Case: O(n^2)
• Best Case: O(n) (when the list is already sorted)
2. Selection Sort:
Time Complexity:
3. Insertion Sort:
Time Complexity:
4. Merge Sort:
Time Complexity:
5. Quick Sort:
Time Complexity:
6. Heap Sort:
Time Complexity:
7. Radix Sort:
Time Complexity:
8. Counting Sort:
Time Complexity:
9. Bucket Sort:
Time Complexity:
Q7. Define an AVL tree. Obtain an AVL tree by inserting one integer at a time in the
following sequence: 50, 55, 60, 15, 10, 40, 20, 45, 30, 47, 70, 80. Show all the steps.
Ans. An AVL tree (Adelson-Velsky and Landis tree) is a self-balancing binary search tree. In an
AVL tree, the heights of the two child subtrees of any node differ by at most one, ensuring that the
tree remains balanced. If, at any time during an insertion or a deletion operation, the AVL property
is violated, rotations are performed to restore balance.
Here are the steps to obtain an AVL tree by inserting one integer at a time in the following
sequence: 50, 55, 60, 15, 10, 40, 20, 45, 30, 47, 70, 80.
Steps:
1. 50
/
2. 55
/
3. 60
(Right Rotation at node 50)
4. 55
/ \
50 60
/
5. 15
/
6. 10
(Right Rotation at node 50)
7. 55
/ \
15 60
/ \
10 50
(Similarly add the rest of the integers)
Now, the AVL tree is balanced after inserting all the integers in the given sequence. Each node's
balance factor (the height difference between the left and right subtrees) is either -1, 0, or 1,
ensuring that the tree remains balanced.
Q8. Define binary search tree. Draw the binary search tree that is created if the following
numbers are inserted in the tree in the given order: Kavita, Helan, Reena, Sonam, Amir,
Ranbir, Salman, Abhishek.
Ans. A Binary Search Tree (BST) is a binary tree data structure in which each node has at most
two child nodes, referred to as the left child and the right child. The key (value) of nodes in the left
subtree is less than the key of the root, and the key of nodes in the right subtree is greater than the
key of the root. This ordering property extends to all nodes in the tree, making it an efficient data
structure for searching, insertion, and deletion operations.
BST for the given names: Kavita, Helan, Reena, Sonam, Amir, Ranbir, Salman, Abhishek.
Kavita
/ \
Helan Reena
/ \
Amir Sonam
/ / \
Abhishek Ranbir Salman
Q10. What are the two types of Complexities? Explain them. Explain the concept of Big O
and Big Omega and Theta.
Ans. In the context of algorithm analysis, two types of complexities are often discussed: time
complexity and space complexity.
• Time Complexity:
Time complexity is a measure of the amount of time an algorithm takes to complete concerning
the input size. It provides an estimation of the running time of an algorithm as a function of the
size of the input.
Time complexity is often expressed using Big O notation, which represents the upper bound or
worst-case scenario of an algorithm's running time. It provides an asymptotic upper bound on the
growth rate of the running time concerning the input size.
• Space Complexity:
Space complexity is a measure of the amount of memory space an algorithm needs to complete
concerning the input size. It quantifies the amount of memory space required by an algorithm
during its execution.
Similar to time complexity, space complexity is also often expressed using Big O notation,
representing the upper bound or worst-case scenario of the space requirements.
Concepts of Big O, Big Omega, and Theta:
• Big O (O):
Big O notation describes the upper bound or worst-case scenario of an algorithm's time or space
complexity. It represents the maximum amount of resources an algorithm may consume
concerning the input size.
For example, if an algorithm has a time complexity of O(f(n)), it means that the running time of
the algorithm grows at most proportionally to the function f(n).
• Big Omega (Ω):
Big Omega notation describes the lower bound or best-case scenario of an algorithm's time or
space complexity. It represents the minimum amount of resources an algorithm requires
concerning the input size.
If an algorithm has a time complexity of Ω(f(n)), it means that the running time of the algorithm
grows at least proportionally to the function f(n).
• Theta (Θ):
Theta notation represents both the upper and lower bounds of an algorithm's time or space
complexity. It provides a tight asymptotic bound, indicating that the running time or space
requirements of the algorithm grow at the same rate as the function f(n).
If an algorithm has a time complexity of Θ(f(n)), it means that the running time of the algorithm
grows at the same rate as the function f(n), both in the worst and best cases.
➢ Big O provides an upper bound, Big Omega provides a lower bound, and Theta provides a
tight bound on the growth rate of an algorithm's time or space complexity. These notations
are essential for analyzing and comparing the efficiency of different algorithms.
Q11. What is Queue? Why is it known as FIFO? Write an algorithm to insert and delete an
element from a simple Queue.
Ans. A queue is a linear data structure that follows the First-In-First-Out (FIFO) principle. In a
queue, elements are added at the rear (enqueue operation), and elements are removed from the
front (dequeue operation). The element that has been in the queue the longest is the first one to be
removed.
FIFO Principle: The FIFO (First-In-First-Out) principle means that the element that is added first
to the queue is the one that will be removed first. It mimics the behavior of a physical queue or
line, where the first person to join the line is the first one to be served.
Algorithm to Insert and Delete an Element from a Simple Queue:
Queue: a linear data structure with operations enqueue and dequeue.
Pseudocode:
Queue:
- Initialize front and rear pointers to -1.
Enqueue(element):
1. if (rear == MAX_SIZE - 1)
return "Queue Overflow"
2. else if (front == -1 && rear == -1)
front = rear = 0
3. else
rear = rear + 1
4. queue[rear] = element
5. return "Element enqueued successfully"
Dequeue():
1. if (front == -1)
return "Queue Underflow"
2. else if (front == rear)
front = rear = -1
3. else
element = queue[front]
front = front + 1
4. return element
In this pseudocode, MAX_SIZE is the maximum size of the queue. The enqueue operation adds
an element at the rear, and the dequeue operation removes an element from the front. The front
and rear pointers are adjusted accordingly.
Q12. Explain Breadth First Search traversal and Depth First Search traversal of Graph
using an example.
Ans. Example Graph:
Consider the following undirected graph:
A -- B
| |
C -- D -- E
Q13. What is Circular Linked List? State the advantages and disadvantages of Circular Link
List Over Doubly Linked List and Singly Linked List. Also write advantages of Linked List
over an Array.
Ans. A circular linked list is a variation of a linked list in which the last node of the list points back
to the first node, forming a loop or circle. In a circular linked list, there is no NULL at the end;
instead, the last node points back to the first node.
Advantages of Circular Linked List:
• Efficient Operations on Both Ends: Since the last node points to the first node, operations
like insertion and deletion at both ends (front and rear) are more efficient compared to a
singly linked list.
• Traversal from Any Node: It's easy to traverse the entire list starting from any node, as
there is no NULL indicating the end of the list.
Disadvantages of Circular Linked List:
• Complexity: The implementation of a circular linked list is more complex than that of a
singly linked list, especially in handling edge cases and avoiding infinite loops.
• Memory Overhead: The extra link from the last node to the first node introduces
additional memory overhead.
Advantages of Circular Linked List Over Doubly Linked List:
• Space Efficiency: Circular linked lists can be more space-efficient than doubly linked lists
because they only need one pointer to the next node instead of two.
• Traversal in Both Directions: Circular linked lists can be traversed in both forward and
backward directions efficiently.
Disadvantage of Circular Linked List Over Doubly Linked List:
• Complexity of Operations: Operations like insertion and deletion are more complex in
circular linked lists compared to doubly linked lists due to the need to update the next
pointer of the previous node and the previous pointer of the next node.
Advantages of Circular Linked List Over Singly Linked List:
• Efficient Operations at Both Ends: Similar to the advantage over doubly linked lists,
circular linked lists support efficient operations at both ends.
• Traversal from Any Node: Traversing the circular linked list from any node is more
straightforward compared to a singly linked list.
Advantage of Linked List Over an Array:
• Dynamic Size: Linked lists can easily grow or shrink in size during program execution,
whereas arrays have a fixed size determined during their declaration.
• Efficient Insertion and Deletion: Insertion and deletion operations in a linked list can be
more efficient than in an array, especially for large datasets, as they involve changing
pointers rather than shifting elements.
• No Wasted Memory: Linked lists use memory efficiently by allocating memory only
when needed. In contrast, arrays may have unused allocated space.
• Ease of Implementation: Implementing certain data structures and algorithms can be
simpler with linked lists compared to arrays.
However, it's essential to note that the choice between linked lists and arrays depends on the
specific requirements of the application, as each has its own advantages and disadvantages.
A
/ \
B---C
Here, a '1' in the matrix indicates the presence of an edge between the corresponding vertices, and
'0' indicates no edge.
Pros:
• Easy to implement and understand.
• Suitable for dense graphs (graphs with many edges).
Cons:
• Consumes more space for sparse graphs.
• Inefficient for graphs with a large number of vertices and few edges.
2. Adjacency List:
In an adjacency list, each vertex maintains a list of its neighboring vertices. This can be
implemented using an array of lists or a hash table.
Example:
Consider the same undirected graph:
A
/ \
B---C
A: B, C
B: A, C
C: A, B
3. Incidence Matrix:
An incidence matrix is used to represent a graph in which both vertices and edges are represented
as rows and columns. It is often used in bipartite graphs.
Example:
Consider the bipartite graph:
A---B
\ /
C
A B C
A 1 1 0
B 1 1 0
C 0 0 1
Here, '1' in the matrix indicates that the corresponding vertex is incident to the corresponding edge.
4. Edge List:
In an edge list, the graph is represented as a list of edges, where each edge is represented by a pair
of vertices.
Example:
For the graph:
A
/ \
B---C