Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
40 views12 pages

AnsKey - Data Structures - Final Exam Fall 2024

The document is a final term exam for Data Structures and Algorithms at the National University of Computer and Emerging Sciences, covering various topics such as linked lists, expression conversion, binary trees, AVL trees, and graph algorithms. It consists of multiple questions requiring C++ code implementations, algorithm applications, and theoretical explanations. The exam is structured with a total of 100 marks and includes 13 questions to be attempted within a 3-hour time frame.

Uploaded by

f2204048
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
40 views12 pages

AnsKey - Data Structures - Final Exam Fall 2024

The document is a final term exam for Data Structures and Algorithms at the National University of Computer and Emerging Sciences, covering various topics such as linked lists, expression conversion, binary trees, AVL trees, and graph algorithms. It consists of multiple questions requiring C++ code implementations, algorithm applications, and theoretical explanations. The exam is structured with a total of 100 marks and includes 13 questions to be attempted within a 3-hour time frame.

Uploaded by

f2204048
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

National University of Computer and Emerging Sciences

Chiniot-Faisalabad Campus
Data Structures (CS2001), Final Term Exam
Data Structures and Algorithms Total Time (Hrs): 3
(CS2002), Applied Programming Total Marks: 100
(CS4002) Total Questions: 13
Date: January 2nd 2025
Course Instructor(s)
Mr. Muhammad Shahbaz, Mr. Muhammad
Yousaf, Dr. Shamsa Abid, Ms. Ayesha Liaqat

___________ __________ _____________________


Roll No Section Student Signature

Vetted by: Signature: .

Attempt all the questions.


Note: No extra sheets are allowed to the students.
CLO # 1:
Q1: [6 marks]
You are asked to implement a delete operation in a singly linked list such that you are provided with
the only memory address of node to be deleted (and not the head of the linked list in any case you
can’t use it). Write a C++ code to remove the specified node while ensuring the linked list remains
connected.
Each node contains 3 attributes: SongID (integer), SongTitle (string) and next pointer!
Initial List: 101 -> 102 -> 103 -> 104 -> 105 -> 106…. N (each number representing SongID)
Node to delete: Address of the node with SongID = 104, stored in node * ptr.
Expected Result: 101 -> 102 -> 103 -> 105 -> 106… N

Fall-2024 Department of Computer Science Page 1 of 2


National University of Computer and Emerging Sciences
Chiniot-Faisalabad Campus

CLO # 1:
Q2: [5+5=10 marks]
a) Consider the usual algorithm to convert an infix expression to a postfix expression. Suppose
that you have read 10 input characters during a conversion and stack now contains these
symbols:
/
+
(
*

Now, consider that you read and process the 11th symbol of the input. Considering the
above-mentioned stack state and draw the updated states for all the cases mentioned below
separately where the 11th symbol is:
1. A number { 5 }:
2. A left parenthesis { ( }:
3. A right parenthesis { ) }:
4. A minus sign { - }:
5. A division sign { / }:

1. 2. 3. 4. 5.
*
/
(-/ +
+(/ (
+*( *
*(
*

b) Convert the given infix expression into a postfix expression using a stack. Ensure that your
solution handles precedence and associativity of operators correctly. Only write final solution
here and rough work aside.
Input: (((A + B) * C - D) / (E * F - G)) + ((H + I) * J - K)

AB+C*D-EF*G-/HI+J*K-+

Fall-2024 Department of Computer Science Page 2 of 2


National University of Computer and Emerging Sciences
Chiniot-Faisalabad Campus

CLO # 3:
Q3: [6+6=12 marks]
a) Complete the following function code in C++ using recursion to check if the given binary tree
is a valid BST or not. Fill in the blanks with appropriate parameters for checking the validity of
BST tree.
Input Example: Binary tree:
10
/ \
5 15
/\
3 12
Output Example: false
Note: min and max parameters represent the minimum and maximum value of the long data
type that it can hold.
bool isValidBST(TreeNode* node, long min, long max)
{
if (node == nullptr)
{return true;}
if (node->val <= min || node->val >= max)
{return false;}
return isValidBST( node->left, min, , node->val )) &&
isValidBST (node->right , node->val,, max ) ;
}
b) Write down the preorder, postorder and inorder traversals of the following BST.

Preorder:
8,3,1,6,4,7,10,14,13
Postorder:
1,4,7,6,3,13,14,10,8
Inorder:
1,3,4,6,7,8,10,13,14

Fall-2024 Department of Computer Science Page 3 of 2


National University of Computer and Emerging Sciences
Chiniot-Faisalabad Campus

CLO # 3:
Q4: [4+4=8 marks]
a) Predict the output of the following code.
#include <iostream>
using namespace std;
int countOccurrences(int n, int x) {
if (n == 0) return 0;
// n/10 reduces the number by one digit. In C++, the result is automatically truncated to an integer.
return (n % 10 == x) + countOccurrences(n / 10, x);
}
int main() {
cout << countOccurrences(51515, 5);
return 0;

b) Predict the output of the following code.


stackType<int> stack; case 2:
queueType<int> queue; queue.addQueue(x);
int x; break;
Suppose the input is: case 3:
15 28 14 22 64 -999 if (!queue.isEmptyQueue())
Show what is written by the following segment of {cout << "Queue Element = " <<
code: queue.front()
stack.push(0); << endl;
queue.addQueue(0); queue.deleteQueue();}
cin >> x; else
while (x != -999) cout << "Sorry, the queue is empty." <<
{switch (x % 4) endl;
{case 0: stack.push(x); break;} //end switch
break; cin >> x;} //end while
case 1: cout << "Stack Elements: ";
if (!stack.isEmptyStack()) while (!stack.isEmptyStack())
{cout << "Stack Element = " << stack.top() {cout << stack.top() << " ";
<< endl; stack.pop();}
stack.pop();} cout << endl;
else cout << "Queue Elements: ";
cout << "Sorry, the stack is empty." << endl; while (!queue.isEmptyQueue()){
break; cout << queue.front() << " ";
queue.deleteQueue();}
cout << endl;

Fall-2024 Department of Computer Science Page 4 of 2


National University of Computer and Emerging Sciences
Chiniot-Faisalabad Campus

Queue Element = 0
Stack Elements: 64 28 0
Queue Elements: 14 22

CLO # 1:
Q5: [10 marks]
You are given an empty AVL tree. Insert 20, 35, 45, 18, 15, 25, 22, 26 one by one. After each
insertion, draw the tree and show any required rotations (LL, RR, LR, RL). Once insertions are done,
delete 25 and 22, redrawing the tree after each deletion and showing rotations if needed. Ensure
the tree remains balanced at every step.

Fall-2024 Department of Computer Science Page 5 of 2


National University of Computer and Emerging Sciences
Chiniot-Faisalabad Campus

CLO # 1:
Q6: [10 marks]
Suppose you are designing a navigation system that finds the shortest path between two locations in
a city. Using the provided graph (representing locations as nodes and road distances as edge
weights), apply Dijkstra's algorithm to determine the shortest path and total distance using table
method. Show step-by-step updates to the distance table and the final path. Note: Starting point is
“a”.

112

112

178

CLO # 3:
Q7: [10 marks]
Write a C++ program to implement a graph using an adjacency matrix. The program should:
1. Accept the number of vertices and edges from the user.
2. Allow the user to input the edges (as pairs of vertices).

Fall-2024 Department of Computer Science Page 6 of 2


National University of Computer and Emerging Sciences
Chiniot-Faisalabad Campus

3. Display the adjacency list for the graph.


4. Check if a cycle exists in the graph when a specific node is given as input.
5. Calculate and display the in-degree of the given node.

#include <iostream> bool detectCycle(int startNode) {


#include <queue> bool* visited = new bool[vertices]();
using namespace std; bool* recursionStack = new bool[vertices]();

class Graph { bool result = detectCycleUtil(startNode, visited,


private: recursionStack);
int vertices;
int** adjList; delete[] visited;
delete[] recursionStack;
public:
Graph(int v) { return result;
vertices = v; }
adjList = new int*[vertices];
for (int i = 0; i < vertices; i++) { int calculateInDegree(int node) {
adjList[i] = new int[vertices](); // Initialize adjacency int inDegree = 0;
matrix with zeros for (int i = 0; i < vertices; i++) {
} if (adjList[i][node]) {
} inDegree++;
}
~Graph() { }
for (int i = 0; i < vertices; i++) { return inDegree;
delete[] adjList[i]; }
} };
delete[] adjList;
} int main() {
int vertices, edges;
void addEdge(int u, int v) { cout << "Enter the number of vertices: ";
adjList[u][v] = 1; cin >> vertices;
}
cout << "Enter the number of edges: ";
void displayAdjList() { cin >> edges;
for (int i = 0; i < vertices; i++) {
cout << "Vertex " << i << ":"; Graph graph(vertices);
for (int j = 0; j < vertices; j++) {
if (adjList[i][j]) { cout << "Enter the edges (u v):" << endl;
cout << " -> " << j; for (int i = 0; i < edges; i++) {
} int u, v;
} cin >> u >> v;
cout << endl; graph.addEdge(u, v);
} }
}
cout << "\nAdjacency List:\n";
bool detectCycleUtil(int node, bool* visited, bool* graph.displayAdjList();
recursionStack) {
visited[node] = true; int node;
recursionStack[node] = true; cout << "\nEnter a node to check for a cycle and calculate
in-degree: ";
for (int neighbor = 0; neighbor < vertices; neighbor++) { cin >> node;
if (adjList[node][neighbor]) {
if (!visited[neighbor] && detectCycleUtil(neighbor, if (graph.detectCycle(node)) {
visited, recursionStack)) { cout << "A cycle exists starting from node " << node <<
return true; ".\n";
} else if (recursionStack[neighbor]) { } else {
return true; cout << "No cycle exists starting from node " << node <<
} ".\n";
} }
}
CLO # 1: int inDegree = graph.calculateInDegree(node);
recursionStack[node] = false; cout << "The in-degree of node " << node << " is: " <<
return false; inDegree << endl;
} return 0;
Fall-2024 Department of Computer Science Page 7 of 2
National University of Computer and Emerging Sciences
Chiniot-Faisalabad Campus

Q8: [2+7 = 9 marks]


a) For PercolateUp_Min(A,i) write the C++ code to initialize the parent node against input node
‘i’ based on whether the input node is a left or right child of its parent.

Considering the first element index starts at 1


if (i % 2 == 0) { // If i is even i.e. left child
parent = i / 2;
} else { // If i is odd i.e. right child
parent = (i - 1) / 2;
}
Alternate Solution: Considering the first element index starts at 1
parent = i / 2; // integer division handles both left and right child cases

Alternate Solution: Considering the first element index starts at 0


parent = (i - 1) / 2; // integer division handles both left and right child cases

b) You are organizing a programming contest with scores from multiple participants. You want
to quickly retrieve the top-scoring participant after each score entry. To efficiently support
this, decide whether to use a max-heap or min-heap. Build the heap for the given sequence
of scores: 150, 80, 40, 30, 10, 70, 110, 100, 20, 90 using the buildheap algorithm. (You may
show all swaps occurring in one heapify call by adding a slash on old value and putting the
new value beside. Then you may make a neat new updated heap diagram after the cutting
process.)

Fall-2024 Department of Computer Science Page 8 of 2


National University of Computer and Emerging Sciences
Chiniot-Faisalabad Campus

Fall-2024 Department of Computer Science Page 9 of 2


National University of Computer and Emerging Sciences
Chiniot-Faisalabad Campus

CLO # 3:
Q9: [2 marks]
You are tasked with designing a leaderboard system for an online gaming platform that tracks the
top scores among all players. If a max-heap is used to maintain the leaderboard efficiently, propose
a strategy to handle situations when there is a tie between multiple players with the same score.
How can such scores for the players be inserted and retrieved from the heap? How does your
solution affect the run time cost of insertion and retrieval?
To handle ties between multiple players with the same score, we maintain a linked list at each
max-heap node. If a new player’s score needs to be added to the max-heap and the same score
already exists in the heap, we insert the new score at the head of the linked list.
The cost of max-heap insertion with linked list is O(lg(n)) because linked list insertion is
constant O(1).
The cost of max-heap retrieval (top score) with linked list is O(t) where t is the number of
tied scores in the list.

CLO # 4:
Q10: [2 marks]
Identify and correct the bugs in the following Insert function for MINHEAP:
Insert(A, val )
1 heap_size ← heap_size-1
2 A[heap_size] ← val
3 PercolateDown_Min(A,heap_size[A])

Insert(A, val )
1 heap_size ← heap_size+1
2 A[heap_size] ← val
3 PercolateUp_Min(A,heap_size[A])

CLO # 1:
Q11: [8 marks]
Consider M = 10, h1 (k) = k%10.
Table already contains keys: 46, 15, 20, 37, 23 Next we want to insert 25
Linear Probing Function: h(k,i) = (h1 (k) + i) % M
Quadratic Probing: h(k,i) = (h1 (k) + 2i + i^2 )% M
Double hashing: hash(k, i) = ( hash1(k) + i * hash2(k)) % M

Fall-2024 Department of Computer Science Page 10 of 2


National University of Computer and Emerging Sciences
Chiniot-Faisalabad Campus

Index Linear Quadratic Double Hashing Double hashing


h2 (k) = 1+(k%7) h2 (k) = 1+(k%9)
0 20 20 20 20
1 25
2
3 23 23 23 23
4
5 15 15 15 15
6 46 46 46 46
7 37 37 37 37
8 25 25
9

Where will 25 go in the above table for each of the hashing technique? Add 25 in the correct
position if available.
Use the table below to calculate hash indexes against probes.
Which technique gives the fastest insertion and how many probes?

Probe Linear Quadratic Double Hashing Double hashing


i h(k) = (h1 (k) + i) % h(k) = (h1 (k) + 2i + i^2 )% h2 (k) = 1+(k%7) h2 (k) = 1+(k%9)
M M
1+(25%7)=5 1+(25%9)=8
0 (5+0)%10=5 (5+ 2x0 + 0^2)%10=5 (5+ 0x5)%10=5 (5+ 0x8)%10=5
1 (5+1)%10=6 (5+ 2x1 + 1^2)%10=8 (5+ 1x5)%10=0 (5+ 1x8)%10=3
2 (5+2)%10=7 (5+ 2x8)%10=1
3 (5+3)%10=8 No insertion
Index cycles back

Quadratic hashing gives the fastest insertion and is successful after one collision and one probe.

CLO # 3:
Q12: [3 marks]
Propose a hashing technique for the case where we have to store books in a library and there is a
frequent need to add more books every month so the storage requirement keeps growing. Also, we
must ensure that overflow never occurs. We must guarantee insertion and retrieval. We must use
the best hashing technique that offers the best runtime efficiency among linear, quadratic, double
hashing, and separate chaining. Justify your choice.

Fall-2024 Department of Computer Science Page 11 of 2


National University of Computer and Emerging Sciences
Chiniot-Faisalabad Campus

Separate chaining is a suitable hashing technique. The linked lists enable dynamic growth
and handle collisions effectively. Adding new books doesn’t cause overflow because of
linked lists and insertion is guaranteed.

CLO # 2:
Q13: [4+4+2=10 marks]
a) Referring to Question No.1, Write the time complexity in the form of big O notation to
remove the duplicate values from a given singly linked list of size ‘N’.
Ans: O(N2)

b) Evaluate the efficiency of a hash table using linear probing and compare it with quadratic
probing in terms of advantages, disadvantages. runtimes for worst-case and best-case
insertion, deletion, and search. Express runtimes in big O notation.
Ans:
Linear probing is simple to implement but suffers from primary clustering. Quadratic probing
solves primary clustering but suffers from secondary clustering. The best case insertion
deletion and search is O(1) and worst case is O(n) for both techniques.

c) Provide the best and worst case run time analysis of insert and delete operations in a heap.
You may use either a min-heap or max-heap example to explain your answer.
Ans:
Heap insertion best O(1) and worst O(log(n))
Heap deletion (delete-min or delete-max) best O(1) and worst O(log(n))

Fall-2024 Department of Computer Science Page 12 of 2

You might also like