DSA QB-Answers
DSA QB-Answers
Page No. 1
UNIT -1
1 Marks
1. Define data structure.
Ans:- "A data structure is a way to organize and store data in a computer so
that it can be efficiently accessed, modified, and manipulated."
Page No. 2
5. Trees
6. Graphs
Long Answers
1. Illustrate binary search with example
Page No. 3
Ans:- Binary search is a highly efficient algorithm for finding an element in a
sorted array. It works by repeatedly dividing the search interval in half and
comparing the target value to the middle element of the array. Here's a detailed
illustration of how binary search works with an example.
Algorithm:
Example:
Suppose we have a sorted array and we want to find the position of element 23
in the following array:
2,5,8,12,16,23,38,45,56,72
1. Initialization:
o Set two pointers: low at the beginning (index 0) and high at the
end (index 9) of the array.
o Calculate the middle index: mid = (low + high) / 2. For
integer division, mid = (0 + 9) / 2 = 4.
2. First Comparison:
o Compare the middle element array[4] = 16 with the target
value 23.
o Since 23 is greater than 16, narrow the search to the right half of
the array. Update low to mid + 1 = 5.
3. Second Comparison:
o Calculate the new middle index: mid = (5 + 9) / 2 = 7.
o Compare the middle element array[7] = 45 with 23.
Page No. 4
oSince 23 is less than 45, narrow the search to the left half of the
current subarray. Update high to mid - 1 = 6.
4. Third Comparison:
o Calculate the new middle index: mid = (5 + 6) / 2 = 5.
o Compare the middle element array[5] = 23 with 23.
o Since 23 equals 23, we have found the target value at index 5.
Time Complexity:
Advantages:
Binary search is much faster than linear search for large datasets.
It is straightforward to implement.
Disadvantages:
Binary search requires the array to be sorted. If the array is not sorted, it
must be sorted first, which takes O(nlogn) time.
1. Starting from the first element, compare the current element with the next
element.
2. If the current element is greater than the next element, swap them.
3. Move to the next element and repeat the process for the rest of the list.
4. Repeat steps 1-3 for the entire list until no swaps are needed, which
means the list is sorted.
Example:
Page No. 5
5,1,4,2,8
Pass-by-Pass Explanation:
Initial Array:
5,1,4,2,8
First Pass:
Second Pass:
Third Pass:
Since no swaps were made in the third pass, the algorithm stops, and the array is
sorted.
Page No. 6
3. Explain Linear search with an example
Ans:-
It works by sequentially checking each element of a list until the
target value is found or the list ends. Here’s a detailed explanation of the linear
search algorithm with an example.
Example:
Suppose we have the following array and we want to find the index of element
7:
3,5,2,9,7,8
Step-by-Step Explanation:
Page No. 7
o They are equal, so return the index of this element, which is 4.
Time Complexity:
Space Complexity:
Advantages:
Disadvantages:
Initial List:
65,70,75,80,85,60,55,50,45
Page No. 8
Step 1: First Pass (Finding the minimum and swapping)
Page No. 9
Step 7: Seventh Pass
Unsorted list: 85
The last element is already in place.
Sorted List:
45,50,55,60,65,70,75,80,85
Here's a step-by-step explanation of how Insertion Sort works with the given list
of values:
Initial List:
3,10,4,2,8,6,5,1
Page No. 10
Step 1: First Iteration
Page No. 11
Step 7: Seventh Iteration
Sorted List:
1,2,3,4,5,6,8,10
UNIT-2
1 Marks
1. Give the algorithm for the creation of node struct for a
single Linked list
Ans:- Algorithm:
Page No. 12
2. Include two members in the structure:
o An integer data to store the value of the node.
o A pointer next of type struct Node* to point to the next node
in the list
Ans:- - HEAD pointer: A pointer that points to the first node of a linked
list.
- NULL pointer: A special pointer that does not point to any valid memory
location, indicating the end of the linked list.
This allocates memory for a new Node structure and returns a pointer to it,
which is then assigned to the newNode variable.
4. Data are pushed to stack and pop from stack in the following order
push(10), Push(20), Pop(), Push(10), Push(20), Pop(), Pop(),Pop(),
Push(20) pop() Show what are element will be in the stack at end of
all operation.
Ans:-
Page No. 13
5. Push(20): Stack = [10, 10, 20]
Page No. 14
5. Return "Element pushed successfully".
Ans:- Here are three applications of Linked Lists in one line each:
1. Dynamic memory allocation in systems like malloc() and free().
Ans:- Linked Lists offer efficient insertion and deletion of elements at any
position, and dynamic memory allocation, making them more flexible and
memory-efficient than Arrays.
Ans:- A Circular Linked List is a type of linked list where the last node
points back to the first node, forming a circular structure, and there is no
distinct beginning or end.
10. Write the output for stack using linked list :Push (10)
,Push (20) ,Push (30) ,display(),Peek() , Pop() , Peek() , Pop()
, Peek ()
Ans:-
i) Push(10):
Stack: 10
ii) Push(20):
Stack: 10, 20
iii) Push(30):
iv) Display():
Page No. 15
10, 20, 30
v) Peek():
30
vi) Pop():
Stack: 10, 20
Returned: 30
vii) Peek():
20
viii) Pop():
Stack: 10
Returned: 20
ix) Peek():
10
LONG Answer
Page No. 16
o Create a new node.
o Set the new node's next pointer to the next pointer of the given
node.
o Set the given node's next pointer to the new node.
Deletion Algorithm
a) Delete by Key:
o Start from the head node.
o If the head node itself holds the key, update the head to the next
node.
o Traverse the list to find the node before the node to be deleted.
o Update the next pointer of the previous node to skip the node to
be deleted.
b) Delete at a Given Position:
o If the position is 0, update the head to the next node.
o Traverse the list to find the node before the node to be deleted.
o Update the next pointer of the previous node to skip the node to
be deleted.
1. Structure: Each node contains a data field, a pointer to the next node,
and a pointer to the previous node.
2. Traversal: Can traverse in both forward and backward directions.
3. Memory: Requires more memory per node due to the extra previous
pointer.
4. Use Case: Suitable for applications requiring bidirectional traversal, like
undo-redo functionality in applications.
1. Structure: Similar to a single linked list, but the last node points back to
the first node, forming a circle.
2. Traversal: Can traverse starting from any node and eventually return to
the same node, forming a loop.
3. Memory: Uses the same amount of memory as a single linked list.
4. Use Case: Useful for applications requiring circular traversal, like round-
robin scheduling and buffering applications.
Page No. 17
2. Write routines to pop and push onto a stack using array implementation
Ans:- A stack is a data structure that follows the Last In, First Out (LIFO)
principle. Using an array to implement a stack involves managing an array
and a top pointer that indicates the position of the top element of the stack.
Push Routine:
4. Assign the new element to the top index of the array (arr[top] = element).
5. Return success.
Pop Routine:
Here's implementation:
#define MAX_SIZE 10
int arr[MAX_SIZE];
if (top == MAX_SIZE - 1) {
Page No. 18
printf("Stack is full\n");
return;
arr[++top] = element;
int pop() {
if (top == -1) {
printf("Stack is empty\n");
return -1;
return arr[top--];
These routines can be used to push and pop elements onto/from the stack
using an array implementation.
Arrays:
Page No. 19
- Arrays are suitable for situations where data is fixed, and fast access is
crucial.
Linked Lists:
- Elements are stored in nodes, each containing data and a reference (link)
to the next node
- Linked lists are suitable for situations where data is dynamic, and frequent
insertions/deletions are expected.
2. If the list is empty (head = NULL), set newNode as the head and tail.
3. Otherwise:
Page No. 20
1. If the list is empty (head = NULL), return an error.
2. Otherwise:
- Set the tail's previous node as the new tail (tail = tail->prev).
Note: In both algorithms, it's important to update the previous and next pointers of the
adjacent nodes to maintain the integrity of the doubly linked list
Ans:- A stack is a data structure that follows the Last-In-First-Out (LIFO) principle,
meaning the last element added to the stack is the first one to be removed. A stack can
be implemented using a linked list, where each node represents an element in the stack.
3. Set the head to the next node in the list (head = head->next).
Page No. 21
6. Return the removed element.
UNIT -3
1 Marks
1) List the Queue operations.
Ans:- Here are the basic Queue operations:
Page No. 22
3. Scheduling
4. Resource Allocation
5. Cryptography
4) What is input restricted deque?
Ans:-An input-restricted deque is a deque (double-ended queue) that
only allows insertions at one end, but allows deletions at both ends.
5) What causes the underflow of stack? How could it be avoided?
LONG Answer
1) Discuss the Queue implementation using arrays
Ans:- A queue is a data structure that follows the First-In-First-Out (FIFO)
principle, meaning that the first element added to the queue is the first one
to be removed. A queue can be thought of as a line of people waiting for
something, where the person who arrives first is served first.
Queue implementation using arrays:
Array-based Queue
Page No. 23
- A queue can be implemented using a fixed-size array.
- The array size is fixed, and the queue can become full if the array is
completely utilized.
- Two indices, front, and rear, are used to keep track of the queue's state.
Operations:
1. Enqueue (add element):
- Check if the queue is full (rear == size - 1).
- If full, return the error or resize the array.
- Otherwise, add the element at the rear index and increment the rear.
2. Dequeue (remove element):
- Check if the queue is empty (front == rear).
- If empty, return error.
- Otherwise, remove the element at the front index and increment front.
3. Front (get front element):
- Return the element at the front index.
4. Rear (get rear element):
- Return the element at the rear index.
5. IsEmpty:
- Check if front == rear.
6. IsFull:
- Check if rear == size - 1.
Page No. 24
Enqueue operations:
1. Enqueue 5: queue[0] = 5; rear = 1;
2. Enqueue 8: queue[1] = 8; rear = 2;
3. Enqueue 2: queue[2] = 2; rear = 3;
Dequeue operations:
1. Dequeue: element = queue[0]; front = 1;
- The element 5 is removed, and the front index is incremented.
Array Queue Advantages:
- Efficient use of memory (fixed size).
- Fast enqueue and dequeue operations (O(1)).
Array Queue Disadvantages:
- Fixed-size limits the queue capacity.
- Resizing the array can be costly.
Overall, array-based queues are suitable for situations where the maximum
queue size is known and memory efficiency is important. However, they
may not be ideal for scenarios where the queue size needs to dynamically
grow or shrink.
2) Explain the algorithm for evaluating postfix expressions using a stack
for the below expression. 2 5 3 6 + * * 5 / 2 –
Ans:- The algorithm for evaluating postfix expressions using a stack is as
follows:
1. Create an empty stack.
2. Scan the expression from left to right.
3. For each token (operand or operator):
- If the token is an operand, push it onto the stack.
- If the token is an operator, pop the required number of operands from
the stack, perform the operation, and push the result back onto the stack.
Page No. 25
4. When the end of the expression is reached, the final result is the top
element on the stack.
3) Elaborate in detail about the double ended queue and their various
operations with suitable examples.
Ans:- A double-ended queue (deque) is a data structure that allows adding and
removing elements from both the beginning and the end of the queue. It is a versatile
data structure that combines the benefits of both stacks and queues.
Operations on a Deque:
Page No. 26
1. Add to the front (enque_front): Adds an element to the beginning of the deque.
Example:
Deque: []
Add 5 to the front: [5]
Add 3 to the front: [3, 5]
2. Add to the rear (enque_rear): Adds an element to the end of the deque.
Example:
Deque: []
Add 5 to the rear: [5]
Add 3 to the rear: [5, 3]
3. Remove from the front (deque_front): Removes the element from the beginning of
the deque.
Example:
Deque: [3, 5]
Remove from the front: [5]
4. Remove from the rear (deque_rear): Removes the element from the end of the deque.
Example:
Deque: [5, 3]
Remove from the rear: [5]
5. Peek at the front (front): Returns the element at the beginning of the deque without
removing it.
Example:
Deque: [3, 5]
Peek at the front: 3
6. Peek at the rear (rear): Returns the element at the end of the deque without removing
it.
Example:
Deque: [5, 3]
Peek at the rear: 3
Page No. 27
7. IsEmpty: Checks if the deque is empty.
Example:
Deque: []
IsEmpty: True
8. Size: Returns the number of elements in the deque.
Example:
Deque: [5, 3]
Size: 2
Implementing a Deque:
A deque can be implemented using a dynamic array or a linked list. The dynamic array
implementation is more efficient for small to medium-sized deques, while the linked list
implementation is more suitable for large deques.
4. Dequeue: Remove element from the front of the array (front index) and increment
front.
5. Check for overflow (array full) and underflow (array empty) conditions.
Front(f) rear(r)
Page No. 28
4. Dequeue: Remove the node at the front of the list (front pointer) and update front.
5. No need to worry about overflow, as linked lists can dynamically grow.
Both implementations have their pros and cons:
Array Implementation:
- Efficient use of memory
- Fast indexing and access
- Limited size
Linked List Implementation:
- Dynamic size
- Efficient insertion and deletion
- Slower access and traversal
Choose the implementation based on your specific use case and requirements!
Unit-4
1 Marks
1) What is Traversal and its types?
Ans:- Traversal: Visiting each node in a data structure.
Types of Traversal:
1. Linear Traversal
2. Pre-Order Traversal
3. In-Order Traversal
4. Post-Order Traversal
Page No. 29
- Heap property ensures highest priority elements are at the top.
- Efficient insertion and extraction of highest (or lowest) priority element.
4) What is Heapify?
Ans:- Heapify is a process of rearranging the elements of a heap to maintain the
heap property.
It involves:
- Comparing a node with its children
- Swapping the node with its largest (or smallest) child if necessary
- Repeating the process until the heap property is restored
Page No. 30
The height is 3, since the longest path from the root (1) to a leaf (4 or 5) has 3 edges.
2. Pre-Order Traversal: Visit the root node, then the left subtree, and finally the right
subtree.
3. Post-Order Traversal: Visit the left subtree, then the right subtree, and finally the root
node.
LONG Answer
1) What is Heap? Illustrate the Min Heap and Max Heap with example
Ans:- A heap is a specialized tree-based data structure that satisfies the heap property. It
is a complete binary tree, meaning every level of the tree is fully filled except possibly
the last level, which is filled from left to right.
There are two types of heaps:
1. Min Heap: In a min heap, each parent node is less than or equal to its child nodes. The
smallest element is at the root.
Example of Min Heap:
4
/ \
6 2
/\ /\
Page No. 31
8 95 1
In this example, the smallest element (1) is at the root, and each parent node is less than
or equal to its child nodes.
2. Max Heap: In a max heap, each parent node is greater than or equal to its child nodes.
The largest element is at the root.
Example of Max Heap:
9
/ \
7 5
/\ /\
3 18 2
In this example, the largest element (9) is at the root, and each parent node is greater
than or equal to its child nodes.
Heaps are used in various algorithms, such as heap sort, priority queues, and graph
algorithms. They provide efficient insertion, deletion, and extraction of the minimum or
maximum element.
Page No. 32
Example:
4
/\
2 6
/\ \
1 3 5
Inorder traversal: 1, 2, 3, 4, 5, 6
2. Preorder Traversal (Root-Left-Right):
- Visit the root node.
- Visit the left subtree.
- Visit the right subtree.
Example: 4
/\
2 6
/\ \
1 3 5
Preorder traversal: 4, 2, 1, 3, 6, 5
3. Postorder Traversal (Left-Right-Root):
- Visit the left subtree.
- Visit the right subtree.
- Visit the root node.
Example:
4
/\
2 6
/\ \
Page No. 33
1 3 5
Postorder traversal: 1, 3, 2, 5, 6, 4
These tree traversal methods are essential in various applications, such as:
- Searching for a specific node or value.
- Inserting or deleting nodes while maintaining tree balance.
- Traversing trees in databases or file systems.
- Evaluating expressions in programming languages.
- Compiling code and generating syntax trees.
3) Illustrate the construction of heaps and its operations with a suitable
example.
Ans:- A heap is a specialized tree-based data structure that satisfies the heap
property:
- For a max heap, the parent node is greater than or equal to its child nodes.
- For a min heap, the parent node is less than or equal to its child nodes.
Let's consider a max heap example:
Suppose we have a list of numbers: [5, 3, 8, 2, 9, 1]
Construction:
1. Start with an empty heap.
2. Insert the first element (5) as the root node.
3. Insert the next element (3) as a child of the root node (5).
4. Insert the next element (8) as a child of the root node (5).
5. Continue inserting the remaining elements (2, 9, 1) in the same manner.
The resulting heap looks like this:
9
/ \
8 5
/ \ \
3 2 1
Operations:
Page No. 34
1. Insert: Insert a new element (6) into the heap.
a. Add the new element as a leaf node.
b. Compare the new element with its parent node. If it's greater, swap them.
c. Repeat step b until the heap property is satisfied.
9
/ \
8 6
/ \ / \
3 2 5 1
Page No. 35
Ans:- Heap Sort is a popular sorting algorithm that uses a heap data structure to
sort an array of elements. Here's a step-by-step explanation of the Heap Sort algorithm
with examples:
Step 1: Build a Max Heap
- Start with an unsorted array: [5, 3, 8, 2, 9, 1]
- Build a max heap by repeatedly inserting elements into the heap:
9
/ \
8 5
/ \ \
3 2 1
Step 2: Heapify the Array
- Starting from the last non-leaf node (8), heapify the array by swapping elements to
maintain the max heap property:
9
/ \
5 8
/ \ \
3 2 1
Step 3: Extract Maximum Element
- Extract the maximum element (9) from the heap and place it at the end of the array:
8
/ \
5 3
/ \ \
2 1 9
Step 4: Repeat Heapify and Extract
- Repeat steps 2 and 3 until the heap is empty:
8
/ \
Page No. 36
5 3
/ \ \
2 1
5
/ \
3 2
/ \
1 8
3
/ \
2 1
/
5
2
/
1
/
3
1
/
2
1
Step 5: Sorted Array
- The final sorted array is: [1, 2, 3, 5, 8, 9]
Page No. 37
UNIT-5
1 Marks
1) Define Hash function.
Ans:- A hash function is a mathematical function that takes a variable-
length input (such as a string or an integer) and returns a fixed-length
output (known as a hash value or digest). The output of a hash function is
unique to the input and is designed to be collision-resistant, meaning that it
is unlikely to produce the same output for different inputs.
2) List any two applications of Hashing
Ans:- Two applications of hashing are:
1. Data Integrity: Ensuring data has not been tampered with or corrupted.
2. Password Storage: Storing passwords securely to prevent unauthorized access.
3) Create an undirected graph and its adjacency matrix for the following
specification of a graph G. V(G)=1,2,3,4 E(G)={
(1,2),(1,3),(3,3),(3,4),(4,1) }
Ans:- Here is the adjacency matrix for the graph G:
1 2 3 4
|--- | - | - | --| -- |
1 |0|1|1|1|
2 |1|0|0|0|
3 |1|0|2|1|
4 |1|0|1|0|
Page No. 38
2. The hash key is the ASCII value:
- Hash key = 49
So, the hash key for the string "1" is 49.
Cyclic Graph:
- A graph that contains at least one cycle (a path that starts and ends at the same vertex, passing
through at least one edge more than once).
Acyclic Graph:
- A graph where every path is a simple path (no repeated edges or vertices).
- Example: A -> B -> C (this graph does not have any cycles)
In summary, if a graph has a cycle, it's cyclic. If it doesn't have any cycles, it's acyclic.
(OR)
Page No. 39
Ans:-
Definition of Collision:
A collision occurs when two or more elements in a hash table hash to the same index
or slot.
Two methods to handle collision:
1. Separate Chaining
2. Open Addressing
Long Answers
1) Define Graph Data Structure. Discuss the most common
ways to represent a graph.
3_) Describe in detail about the following representations
of a graph. i) Adjacency Matrix ii) Adjacency List
Page No. 40
Ans:-
Page No. 41
Page No. 42
4_) Given input {4371, 1323, 6173, 4199,4344, 9679, 1989} and a hash function h(x) =x
mod 10. Prepare the resulting for the following:
1. Open hash table.
2. Open addressing hash table using linear probing.
3. Open addressing hah table using quadratic probing.
Page No. 43
Page No. 44
5_) Examine topological sorting of a graph G with suitable example
Page No. 45
Page No. 46
7_)
Page No. 47
Ans:-
Page No. 48
8_)
Ans:-
Page No. 49