DSA Paper Solution
DSA Paper Solution
(Management)
IT – 12 : DATA STRUCTURES AND ALGORITHMS
(2024 Pattern) (Semester – I)
Solution
NOTE:
1. Please don’t give marks if in place of an algorithm, a student has written the Python
code.
2. Please don’t give marks if a student has used the library function of Python directly. We
are expecting them to write the logic of the predefined function.
Q.1 a) Write an algorithm to generate fibonacci series upto 5 numbers using array elements.
[6 marks]
Ans 1 a)
Fibo(A,5):
STEP 1: Start
STEP 5: For I 2 to 5 do
Next I
STEP 6: For I 0 to 5 do
Print A[I]
Next I
STEP 7: Stop
If a student have written the algorithm and given an example for the same, allot 6 marks.
Q.1 c) Write an algorithm to insert elements at the last position of the list.
Ans 1 c) To insert an element at the end of the list, first we have to find the length of the list and then
we can perform the append operation.
STEP 1: Start
STEP 4: For I 0 to n do
Read A[I]
Print A[I]
Next I
STEP 8: Stop
If a student have written the algorithm first and given an example for the same, allot 6 marks.
If only append function is written or a Python code is written then NO MARKS.
Ans 1 d) Sparse Matrix: A sparse matrix is a special case of a matrix in which the number of zero
elements is much higher than the number of non-zero elements. As a rule of thumb, if 2/3 of the total
elements in a matrix are zeros, it can be called a sparse matrix. Using a sparse matrix representation
— where only the non-zero values are stored — the space used for representing data and the time for
scanning the matrix are reduced significantly.
Example:
00304
00570
00000
02600
Representing a sparse matrix by a 2D array leads to wastage of lots of memory as zeroes in the
matrix are of no use in most of the cases. So, instead of storing zeroes with non-zero elements, we
only store non-zero elements. This means storing non-zero elements with triples- (Row, Column,
value).
Sparse Matrix Representations can be done in many ways following are two common
representations:
1. Array representation
2. Linked list representation
Unlike the array representation, a node in the linked list representation consists of four fields. The
four fields of the linked list are given as follows -
o Row - It represents the index of the row where the non-zero element is located.
o Column - It represents the index of the column where the non-zero element is located.
o Value - It is the value of the non-zero element that is located at the index (row, column).
o Next node - It stores the address of the next node.
The node structure of the linked list representation of the sparse matrix is shown in the below image -
If the student has explained the 3-Tuple form of the sparse matrix then you can allot full 4
marks, otherwise give step marking.
Q. 2 a) Write an algorithm to print sum of alternate node elements in a doubly linked list. [6 marks]
Ans 2 a) Consider that the doubly linked list is already being created. For example,
STEP 1: Start
STEP 2: Declare curr as a marker and sum as an integer
STEP 3: Set sum 0
STEP 4: Set curr head
STEP 5: While(curr < > NULL) [curr not equal to NULL, to traverse up to the last node of the
list]
Set sum sum + curr. info
Set curr (curr.Next).Next
[ End of While Loop]
STEP 6: Print sum
STEP 7: Stop
Student must be assigned step marking.
Q. 2 b) Differentiate between a Doubly Linked List and a Circular Linked List. [4 marks]
Ans 2 b)
Sr. Doubly Linked List Circular Linked List
No.
1 It is a bi-directional list. It is a unidirectional list.
2 The node consists of 3 fields: The node consists of 2 fields:
1. Back: Address of Previous Node 1. Info: Information about a Node
2. Info: Information about a Node 2. Next: Address of Next Node
3. Next: Address of Next Node
3 It can be traversed in both the directions. It can be traversed in one direction only.
The Next field of last node contains NULL. The Next field of last node contains the
4
address of the first node.
Q.2 c) Write an algorithm to reverse the single linked list elements. [6 marks]
Ans 2 c) Consider that the single linked list is already being created.
The algorithm:
Reverse( ):
STEP 1: Start
STEP 2: Declare head, curr, temp, trail as markers
[Check whether the linklist is empty. If it is empty, then print appropriate message.]
STEP 3: If head == NULL
Print ― Link list is empty‖
Goto Step 10
STEP 4: Else
Set curr head
[Traverse the linked list to reach to the end.]
STEP 5: While (curr < > NULL) [ curr not equal to NULL]
Set curr curr.Next
[End of While loop]
STEP 6: Set temp curr
STEP 7: While(curr < > head)
Set trail head
While(trail.Next < > curr)
Set trail trail. Next
[End of Inner While Loop]
Set curr.Next trail
Set curr trail
[End of Outer While Loop]
STEP 8: Set curr. Next NULL
STEP 9: Set head temp
STEP 10: Stop
Student must be assigned step marking.
Q.2 d) Write an algorithm to delete a node from the beginning in singly linked list. [4 marks]
Ans 2 c) Consider that the single linked list is already being created.
STEP 1: Start
STEP 2: Declare head, temp, trail as markers
STEP 3: [Check whether the linklist is empty. If it is empty, then print appropriate message.]
STEP 3: If head == NULL
Print ― Link list is empty‖
Goto Step
STEP 4: Else
STEP 5: Set Temp head
STEP 6: Set head head. Next
STEP 7: Delete Temp
STEP 8: Stop
Q. 3 a) Write an algorithm to perform all operations of Queue using Linked List. (Insert, Delete,
Peek and Traverse) [6 marks]
Ans 3 a)
Insertion operation on a linked queue is known as Enqueue. The Node structure will be as that
of a singly linked list. At the start of the insert operation, both Front and Rear will be NULL.
Enqueue() :
STEP 1: Start
STEP 2: Declare Front, Rear, New as markers and val as an integer
STEP 3: Allocate memory space for a New node
STEP 4: Set New. info val
STEP 5: Set New. Next NULL
[Checking the underflow condition. If the Queue is empty then the New node becomes the first
node of the linked queue and both Front and Rear points to New
Deletion operation on a Linked Queue is known as Dequeue. The deletion is done with respect to
Front and hence, Rear will remain fixed and we will move the Front.
Dequeue():
STEP 1: Start
STEP 2: Declare Front, Rear, Temp as markers
STEP 3: If (Front == NULL AND Rear == NULL)
Print ― Queue Underflow‖
Goto Step 5
STEP 4: Else
Print Front. Info is deleted
Set Temp Front
[If there is only a single node, then after deleting it, we have to bring both Front and Rear to NULL]
If (Front == Rear)
Set Front Rear NULL
Else
Set Front Front. Next
STEP 5: Stop
Peek():
STEP 1: Start
STEP 2: Declare Front, Rear as markers
STEP 3: If (Front == NULL AND Rear == NULL)
Print ― Queue Underflow‖
Goto Step 4
Else
Print ―The first element in the queue is ", Front. Info
STEP 4: Stop
Traverse():
We have to check whether the Queue is empty or not. If it is empty then Print an appropriate
message else, traverse from Front to Rear.
STEP 1: Start
STEP 2: Declare Front, Rear and curr as markers
STEP 3: If (Front == NULL AND Rear == NULL)
Print ― Queue Underflow‖
Goto Step 5
STEP 4: Else
Set curr Front
While(curr < > NULL)
Print curr. Info
Set curr curr. Next
[End of While Loop]
STEP 5: Stop
1. Expression Evaluation and Conversion: There are three types of expression that you use
in programming, they are:
a. Infix (Operand1 – Operator – Operand2): A + B
b. Prefix (Operator – Operand1 – Operand2): +AB
c. Postfix(Operand1 – Operand2 – Operator): AB+
Stack is used to evaluate and convert prefix, postfix & infix expressions.
2. Syntax Parsing : Since many programming languages are context-free languages, the stack
is used for syntax parsing by many compilers.
3. Backtracking : Backtracking is a recursive algorithm mechanism that is used to solve
optimization problems. It is also used in Game playing, finding paths, exhaustive searching.
4. Parenthesis Checking: Stack in data structures is used to check if the parentheses like ( ), {
} are valid or not in programming while matching opening and closing brackets are balanced or
not. So it stores all these parentheses in the stack and controls the flow of the program.
For e.g ((a + b) * (c + d)) is valid but {{a+b})) *(b+d}] is not valid.
5. String Reversal: Another exciting application of stack is string reversal. Each character of
a string gets stored in the stack. The string's first character is held at the bottom of the stack,
and the last character of the string is held at the top of the stack, resulting in a reversed string
after performing the pop operation.
6. Function Call: Whenever you call one function from another function in programming, the
reference of calling function stores in the stack. When the function call is terminated, the
program control moves back to the function call with the help of references stored in the stack.
So stack plays an important role when you call a function from another function.
7. Recursion
8. Used in "undo" mechanism in text editor.
9. Memory Management: Memory management is an essential feature of the operating
system, so the stack is heavily used to manage memory.
If the students have written half of it, then give them 2 marks. If the full list is provided without
the theory, you can give 3 to 4 marks based on the content written.
Q. 3 c) Convert the given infix expression to postfix expression.
A + B * (C – D) / (E – F) [6 marks]
Ans 3 c)
Input Stack Postfix Sequence
A A
+ + A
B + AB
* +* AB
( +*( AB
C +*( ABC
- +*(- ABC
D +*(- ABCD
Since there is a closing ― ) ―, it will pop the ― – ―
operator from stack and add it to the Postfix Sequence.
) +* ABCD -
Next there is a ― / ― operator, which has same priority
with ― * ― operator. So we will pop the ― * ― operator
from the stack and add it to the Postfix Sequence. And
the push ― / ― operator onto the stack.
/ +/ ABCD - *
( +/( ABCD - *
E +/( ABCD - *E
- +/(- ABCD - *E
F +/(- ABCD - *EF
Since there is a closing ― ) ―, it will pop the ― – ―
operator from stack and add it to the Postfix Sequence.
) +/ ABCD - *EF -
Now since the end of input is reached, pop the
remaining operators from the stack in LIFO style and
add it to the Postfix Sequence.
End of Empty
ABCD - *EF - / +
input Stack
You can give students step marking. If they have solved the expression till ABCD – correctly, then
give 3 marks.
Q. 3 d) Explain advantages of Queue over Stack. [4 marks]
Ans 3 d) Advantages of Queue
1. Simplicity and Predictability: Queues operate on a simple and predictable First In, First
Out (FIFO) principle, which is easy to implement and understand.
2. Fairness: By processing elements in the order they arrive, queues ensure fairness in
systems like scheduling processes in an operating system or managing customers in
service industries.
4. Asynchronous Data Handling: Queues are excellent for handling data from
asynchronous processes, such as buffering inputs in I/O operations, where data can arrive
at any time and needs to be processed in the correct order.
Q. 4 a) Create an AVL tree by inserting the values 48, 72, 36, 8, 79, 22, 84, 66. [6 marks]
Ans 4 a) AVL is a balanced Binary Search Tree, where every node contains an extra parameter,
called Balance Factor, where,
72 BF = 0
48 BF = 0
BF = 0 36 72 BF = 0
48 BF = 1
BF = 1 36 72 BF = 0
BF = 0 8
Since 79 > 48, it will be added to the right of 48.
48 BF = 0
BF = 1 36 72 BF = -1
BF = 0 8 79 BF = 0
48 BF = 1
BF = 2 36 72 BF = -1
BF = -1 8 79 BF = 0
BF = 0 22
A node has been inserted into the right subtree of the left subtree. This makes 36 an
unbalanced node. Hence we have to perform left-right rotation(LR). We first perform the left
rotation on the left subtree of 36. This makes 8, the left subtree of 22.
48 BF = 1
BF = 2 36 72 BF = -1
BF = 1 22 79 BF = 0
BF = 0 8
We shall now right-rotate the tree, making 22 the new root node of this subtree. 36 now
becomes the right subtree of its own left subtree.
48 BF = 1
BF = 0 22 72 BF = -1
BF = 0 8 36 79 BF = 0
BF = 0
48 BF = -1
BF = 0 22 72 BF = -2
BF = 0 8 36 79 BF = -1
BF = 0
84 BF = 0
Here, after insertion of 84, node 72 has become unbalanced. So, we perform LL rotation, on
node 72, by which, node 79 will become the parent of 72 which will move to the left of 79 and
84 will become the right child.
48 BF = 0
BF = 0 22 79 BF = 0
BF = 0 8 36 72 84 BF = 0
BF = 0
Since 66 > 48, it will be added to the right of 48.
48 BF = -1
BF = 0 22 79 BF = 1
BF = 0 8 36 72 84 BF = 0
BF = 0 BF = 1
66 BF = 0
Please give step marking. The students must take 1 value at a time, place it properly depending on
the conditions and also mention the type of rotation performed. If the students have drawn the final
tree without the steps give 1 mark.
Q. 4 b) Draw a Binary Tree from the given traversal and print its preorder traversal. [4 marks]
Post-order: 4, 5, 2, 6, 3, 1
In-order: 4, 2, 5, 1, 3, 6
Ans 4 b) There are two rules to create a tree form the given post-order and in-order sequence:
Rule 1: Check the postorder sequence from Right to Left. It will give the root of the tree.
Rule 2: Check the position of the selected node from post-order. It will give the left and
right sub-trees.
Since the rightmost number in the post-order sequence is 1, hence the root of the Binary
Tree will be 1.
1 (Root)
In the in-order sequence, values 4,2,5 is at the left side and values 3, 6 are in the right side.
1 (Root)
4, 2, 5 3, 6
Next value in the post-order sequence is 3. So, it will be connected to the right of node 1. And
after checking the in-order sequence, we found that 6 is to the right of 3. So the Binary Tree
will be:
1 (Root)
4, 2, 5 3
Next value in the post-order sequence is 6, which is already been added to the Binary Tree.
Next values in the post-order sequence is 2. And after checking the in-order sequence, we
found that 4 is to the left of 2 and 5 is to the right of 2. So the Binary Tree will be:
1 (Root)
2 3
4 5 6
If the students have drawn the final tree without the steps and the pre-order traversal, give 1 mark.
Ans 4 c) For performing BFS on the given graph, a queue is used where the sequence of vertices are
inserted and depending upon the adjacent vertices, a vertex is added to the final BFS sequence. At the
start queue is empty. We perform the operations, till the queue becomes empty.
Now insert the adjacent vertices of ‗a‘ in the Queue and set their status = 2.
Once all adjacent vertices of ‗a‘ in is the Queue, remove vertex ‗a‘ from the Queue, set its status = 3
(Processed) and update the BFS sequence.
Now bring all the adjacent vertices of ‗c‘ in the queue and set their status = 2
The adjacent vertices of ‗c‘ are a, d, f. ‗a‘ is processed and ‗d‘ is already in Queue, so we will add ‗f‘
in the queue.
The adjacent vertices of ‗d‘ are a, c, b. ‗a‘ and ‗c‘ is processed hence ‗b‘ will be inserted in Queue
The adjacent vertices of ‗e‘ are a, f, b. ‗a‘ is processed and ‗f‘ and ‗b‘ are already in the Queue.
The adjacent vertices of ‗f‘ are c, e, b. ‗c‘ and ‗e‘ are processed and ‗b‘ is already in the Queue.
Since both the adjacent vertices of ‗b‘ i.e., ‗e‘ and ‗f‘ are processed, add vertex ‗b‘ to BFS sequence
and Queue becomes empty again, and front and rear is assigned -1.
BFS = {a, c, d, e, f, b}, status of ‘b’ = 3, front = -1, rear = -1 Queue = { } empty.
In this question, it is expected that the students draw the Queue, every time a vertex is inserted in or
deleted from a Queue. Also check the sequence of alphabets, inserted in the Queue.
Q. 4 d) Construct step-by-step Binary Search Tree for the following data: [4 marks]
Ans 4 d) Since the first value in the given sequence is 12, hence it will be taken as the Root of the
Binary Search Tree.
12 (Root)
10
10 17
10 17
14
10 17
14
15
9 => Since 9 < 12, it will move to the left of 12.
Since 9 < 10, it will move to the left of 10.
12
10 17
9 14
15
11 => Since 11 < 12, it will move to the left of 12.
Since 11 > 10, it will move to the right of 10.
12
10 17
9 11 14
15
19 => Since 19 > 12, it will move to the right of 12.
10 17
9 11 14 19
15
22 => Since 22 > 12, it will move to the right of 12.
Since 22 > 17, it will move to the right of 17.
Since 22 > 19, it will move to the right of 19.
12
10 17
9 11 14 19
15 22
10 17
9 11 14 19
15 22
20
10 17
9 11 14 19
6 15 22
20
If the students don‘t draw the tree stepwise, don‘t give any marks. 1 mark for the final tree without
steps. Give step marking.
Ans 5 a) Since Binary Search method only works on a sorted array, first we have to sort the entire
array and then perform the search.
We can use any sorting mechanism to 1st sort the entire array. Let the given sequence be array A.
88 12 14 26 31 41 53 58 71
0 1 2 3 4 5 6 7 8
88 12 14 26 31 41 53 58 71
0 1 2 3 4 5 6 7 8
88 12 14 26 31 41 53 58 71
0 1 2 3 4 5 6 7 8
88 12 14 26 31 41 53 58 71
0 1 2 3 4 5 6 7 8
88 12 14 26 31 41 53 58 71
0 0 2 3 4 5 6 7 8
12 88 14 26 31 41 53 58 71
0 1 2 3 4 5 6 7 8
12 14 26 88 31 41 53 58 71
0 1 2 3 4 5 6 7 8
low = mid + 1, 4 + 1 = 5
53 58 71 88
5 6 7 8
If a student directly writes the sorted array and then perform the algorithm correctly…4 marks.
SCENARIO 1:
There is a small company of 100 employees, each employer is assigned and EMP_ID in the range 0 –
99.
To store the records in an array, each employee‘s EMP_ID acts as an index into the array, where the
employee‘s record will be stored.
In this case we can directly access the record of any employee, once we know his EMP_ID.
SCENARIO 2:
Let us assume that the same company uses a 5-digit EMP_ID, as the primary key.
We need an array of size, 100,000 of which only 100 elements will be used.
SOLUTION:
We can use the last 2 digits of the key to identify each employee. E.g., The employee with EMP_ID
88464, will be stored at the index 64. Similarly, the employee with EMP_ID 12456 can be stored at
the index 56.
Here the elements are not stored according to the value of the key. Here we need a way to convert a 5-
digit key number to a 2-digit array index.
We need a function which will do the transformation. This function is known as a HASH
FUNCTION, and the array in which it will store the key value is called a HASH TABLE.
HASH TABLE is a data structure in which keys are mapped to array position by a hash function.
Hence a value stored in the hash table can be searched in O(1) time using a hash function.
In a hash table, an element with key ‗k‘ is stored at index h(k) and not ‗k‘.
A hash function ‗h‘ is used to calculate the index at which the element with key ‗k‘ will be stored.
Thus the process of mapping the keys to appropriate locations or indices in a hash table is known as
HASHING.
When two or more keys map to the same memory location, a COLLISION is said to occur.
A hash function is simply a Mathematical formula which when applied to a key, produces an integer
which can be used as an index for the key in the hash table.
The main aim of a hash function is that the elements should be relatively, randomly, and universally
distributed. It produces a unique set of integers within some suitable range.
Hash functions are used to reduce the number of collisions.
A good hash function can only minimize the number of collisions by spreading the elements
uniformly throughout the array.
1. Division Method
2. Multiplication Method
4. Folding Method
1. Division Method: It is the most simple method of hashing an integer ‘k’. It can be given as :
h( k ) = k % M…where ‘M’ can be any value.
Generally, we choose ‘M’ to be a large prime number. Because it increases the likelihood
that the keys are mapped with uniformity in the output range of values.
e.g., Calculate the hash values of the keys 2345 and 1267.
Let M = 97
h (2345) = 2345 % 97 = 17
h (1267) = 1267 % 97 = 06
2. Multiplication Method: The steps involved in the multiplication method are as follows:
Step 1: Choose a constant ‗A‘ such that 0 < A < 1.
Step 2: Multiply the key ‗k‘ by ‗A‘.
Step 3: Extract the fraction part of ‗kA‘.
Step 4: Multiply the result of Step 3 by ‗m‘ and take the floor.
hash function, h(k) = [ m * (kA mod 1) ], where kA mod 1 gives the fractional part of kA
and m is the size of hash table.
In this method same ‘x’ bits must be chosen for all keys.
e.g., Calculate the hash values of the keys 2345 and 1267. The hash table has 100 locations.
Note that since hash table has 100 locations, the indices vary from 0 to 99. This means only 2
digits are needed to map the key to a location in the hash table. So x = 2.
k1 = 2345 = 23452 = 5499025, h(k1) = 49 (2nd and 3rd bit from left are chosen).
k2 = 1267 = 12672 = 16,05,289, h(k2) = 60 (2nd and 3rd bit from left are chosen).
If any two methods are discussed with the theory, then please give at least 75% marks.
5 4 2 3 6 10 8 11 7
0 1 2 3 4 5 6 7 8
P
Now, select an element from Right to Left, which is smaller than 5. It is 3. Swap 5 and 3.
3 4 2 5 6 10 8 11 7
0 1 2 3 4 5 6 7 8
P
Now, select an element from Left to Right, which is larger than 5. There are no elements. Hence we
can say that ‗5‘ has reached to its required location and here we will divide the array in 3 parts.
3 4 2 5 6 10 8 11 7
0 1 2 3 4 5 6 7 8
P
For Part 1, we will again select the 1st element as pivot, and select an element from Right to Left,
which is smaller than 3. It is 2. Swap 2 and 3.
2 3 4 5 6 10 8 11 7
0 2 1 3 4 5 6 7 8
P
Now, select an element from Left to Right, which is larger than 3. It is 4. Swap 4 and 3.
2 3 4 5 6 10 8 11 7
0 1 2 3 4 5 6 7 8
P
For Part 3, we will select the element at location ‗4‘ as Pivot, i.e., 6.
2 3 4 5
6 10 8 11 7
0 1 2 3
4 5 6 7 8
P
Select an element from Right to Left, which is smaller than 6. There is none. So the array is now:
2 3 4 5 6 10 8 11 7
0 1 2 3 4 5 6 7 8
P
Part 4
For Part 4, we will select the element at location ‗5‘ as Pivot, i.e., 10. From Right to Left, select an
element less than 10. It is 7, so swap 7 and 10.
2 3 4 5 6 7
11 10 8
0 1 2 3 4 7 85 6
P
Now, select an element from Left to Right, which is larger than 10. It is 11, so swap 11 and 10.
2 3 4 5 6 7 8 10 11
0 1 2 3 4 5 6 7 8
P
We can see now, the array has been sorted. The final array is,
2 3 4 5 6 7 8 10 11
0 1 2 3 4 5 6 7 8
Give step marking.
Ans 5 d) Heap: A Heap is a complete binary tree with elements at every node being either less,
greater than or equal to the element at its left and the right child. All the levels of the tree except the
last level are completely filled.
1. Min Heap
2. Max Heap
Therefore, Min Heap stores the minimum value at the root of the heap. Min Heap is used to
maintain the minimum element in a collection of data.
For example…
4 => 4
5 => 4
2=> 4
5 4
6=> 2
5 4
3=>
2 Since 3 is less than 5, we perform heapify and swap 5 and 3.
5 4
6 3
2 .
3 4
6 5
1=> 2
3 4
3 2
6 5 4
Therefore, Max Heap stores the maximum value at the root of the heap.
For example…
4 => 4
2=> 5
4 2
6=> 5 Since 6 is the largest value, we will perform heapify twice, and
swap 6 with 4 and then 6 with 5
4 2
5 6
6 2 5 2
4 4
3 => 6
5 2
4 3
1=> 6
5 2
4 3 1