DS Final Exam Solution
DS Final Exam Solution
Q1: [2+3=5]
Consider a function findTopPlayers which receives a list of N players with in a tournament and returns
top 3 players based on their scores.
void sort(Player** playersList, int N) {
int largest;
for (int j = 0; j < N - 1; j++) {
largest = j;
for (int i = j + 1; i < N; i++) {
if (playersList[i]->getScore() > playersList[largest]->getScore())
largest = i;
}
swap(playersList[j], playersList[largest]);
}
}
sort(playersList, N);
Solution:
largest = j; 𝑁
largest = i; 𝑁(𝑁 + 1)
2
swap(playersList[j], playersList[largest]); 𝑁
topPlayersList[i] = playersList[i]; 3
3𝑁(𝑁 + 1)
𝑇(𝑁) = + 3𝑁 + 6
2
𝑇(𝑁) = 𝑂(𝑁 2 )
(b) Devise a better solution for this problem (and write its pseudocode) to improve the running time of this
algorithm. What will be the time complexity of your improved algorithm?
Another solution:
void sort(Player** playersList, int N, int m) {
int largest;
for (int j = 0; j < m; j++) {
largest = j;
for (int i = j + 1; i < N; i++) {
if (playersList[i]->getScore() > playersList[largest]->getScore())
largest = i;
}
swap(playersList[j], playersList[largest]);
}
}
sort(playersList, N, 3);
Given a string containing only lowercase letters and spaces, remove pairs of matching characters. This
matching starts from the end of the string. For example,
Input: “assassin”
Output: “in“
Input: “pacific ocean”
Output: “pcf oen“
Input: “an assassin sins”
Output: “an“
Remember that the matching starts from the end of the string. So, for input string “sadness”, the output
must be “sadne” and not “adnes”.
a) Write a C++ implementation for the function removePairs to solve the above mentioned problem.
You’re allowed to use only two stacks and a constant number of variables. The minimum program
structure is shown below
Solution:
#include <iostream>
#include <stack>
#include <string>
using namespace std;
if (!matched) {
stack2.push(C);
topOfStack2 = C;
}
}
string result;
while (!stack2.empty()) {
char C = stack2.top(); stack2.pop();
result.push_back(C);
}
return result;
}
int main() {
return 0;
}
Solution: 𝑂(𝑁 2 )
c) Show the dry run of your algorithm with your name as the input string and write the final output of
your algorithm. (Use your complete official name registered in FLEX at FAST-NU)
Q3: [2]
Three agents were working on a mission when they came across a secret message. They decided to deliver
this message to their boss but they can’t deliver the message as it is because it’s very sensitive information.
They decided to encrypt it and then send it to their boss. All of the three agents tried to encode it and came
up with the following Huffman codes:
a 15 00 11 01
m 8 10 01 10
space 12 01 10 00
Q4: [4+1+(2+3)=10]
a. It is possible to determine the shortest distance (or the least effort / lowest cost) between a start node
and any other node in a graph. The idea of the algorithm is to continuously calculate the shortest distance
beginning from a starting point, and to exclude longer distances when making an update. FINDPATH
function shown below calculates the shortest path from a given source vertex towards the destination.
Given the pseudocode shown above, and the graph shown in Fig.1, perform the following tasks
Solution:
Adjacency Matrix
A B C D E F
A 0 1 1 1 0 0
B 1 0 1 1 1 0
C 1 1 0 1 1 1
D 1 1 1 0 1 1
E 0 1 1 1 0 1
F 0 0 1 1 1 0
Cost 0 ∞ ∞ ∞ ∞ ∞
Q A B C D E F
1. After execution of line 7, the condition is true, so the Vertex ‘A’ with smallest distance value is
removed from the Q. All the adjacent vertices of A are explored one by one and checked for the smallest
distance available. So, after exploring all the adjacent vertices of vertex A, the overall values of smallest
distance, and the previous vertex to be visited are as follows
Cost 3 5 9 ∞ ∞
Q B C D E F
The adjacent vertices of B still not removed from the Q are C, D and E. The cost of moving from B to C
is 6, the current cost of C is 5. Therefore, the condition at line 12 is false. The cost of moving from B to D
is 7 which is less than the previous calculated distance. Therefore, the cost of the path is updated. The cots
of moving from B to E is 10 which is smaller than ∞. Therefore, the cost of the path for vertex E is
updated
Cost 5 7 10 ∞
Q C D E F
3. Vertex C will be removed from the Q as it has the smallest distance value. The neighboring vertices of
C are D, E, and F. The updated table and the status if Q is as follows
Cost 7 10 13
Q D E F
4. Now, D will be removed from the Q and explored for its adjacent vertices that are still in Q. The
resulting table and the status of Q is as follows
5. Vertex E will be removed from the Q and the only adjacent neighbor still part of the Q is F. No value
will be updated so the resulting Q and table is shown below
Cost 9
Q F
6. Vertex F will be removed from the Q and the resulting table and empty Q is shown
Cost
Q
ii. Fill the following table, with NODES and total final cost
Solution:
Solution: No, we can’t do that because if add one more edge in a Maximum Spanning Tree, it will not
remain a tree anymore.
c. Mr. X has just shifted in his brand new house. The floor plan for the ground floor is shown in Fig 2. Mr.
X wants to give a tour of his new home to an old friend. The doors within the rooms are represented by
the alphabets for simplicity. And the integers in the rooms are cost of moving from one door to another
door. This means, in room 2 the cost of moving from door B to door W is 2, from door B to door D is
2, and from door B to door F is also 2. Similarly, in room 3 the cost of moving from door F to door G
is 6, from door G to door K is 6 and from door F to door K is also 6.
Solution:
B 2 F
2
2 2 6
2 6
D
4 6
A 2 K G
2
4 4
W 3
3 4 4
5 5
S 4 J
5
C
Solution:
Kruskal’s Algorithm
2
B F
2
2
D
4
A 2 K G
W 4 3
3 4
S J
C
There are three tree traversal methods in-order, pre-order and post-order. Given the iterative and recursive
code (Q5-TreeTraversals.cpp) provided answer the following questions
a. Write down specifications of your system i.e. CPU capacity, RAM, Cache (if applicable) and virtual
memory size [ The specification will directly impact the values in part b]
b. With different input sizes mentioned, find the elapse time required for in-order, preorder and post-order
traversal using recursive solution and iterative solution, and fill the following table
Solution:
Table 1: Comparative analysis
Recursive Solution (Time in nano secs) Iterative Solution (Time in nano secs)
Input Size
In-order Preorder Post-order In-order Preorder Post-order
10 382 152 166 2804 1203 708
50 599 392 395 4825 1654 1559
500 2855 2271 2273 3788 3563 5673
c. What is the efficiency in terms of Big Oh notation for each algorithm (recursive and iterative)?
d. What trend do you observe in table 1? Which version (recursive/iterative) in general grows faster? How
can you justify difference in computational time? Write crisp and clear statements. Ambiguous
statements won’t earn you any credit.
Solution: Both versions grow at the same rate because complexity of both of them is 𝑂(𝑛) but iterative
version is taking more time as it’s doing some extra computation.
Q6: [(2+3+2)+2+1=10]
Coalesced hashing is a technique for implementing a hash table. It's an open addressing technique which
means that all keys are stored in the array itself. However, as opposed to other open addressing techniques,
it also uses nodes with next-pointers to form collision chains. Coalesced hashing, also called coalesced
chaining, is a strategy of collision resolution in a hash table that forms a hybrid of separate chaining and
It uses the concept of Open Addressing(linear probing) to find first empty place for colliding element and
the concept of Separate Chaining to link the colliding elements to each other through pointers. Inside the
hash table, each node has three fields, h(key): The value of hash function for a key, Data: The key itself,
Next: The link to the next colliding elements.
Modify the Q6-hashingLinearProbing.cpp to perform the following operations for Coalesced hashing and
the following functions
a. INSERT(key): The insert Operation inserts the key according to the hash value of that key if that hash
value in the table is empty otherwise the key is inserted in first empty place found after applying
QUADRATIC PROBING.
b. SEARCH(key): Returns True if key is present, otherwise return False.
#include<iostream>
using namespace std;
//Hashnode class
class HashNode
{
public:
V value;
K key;
HashNode *next;
//Constructor of hashnode
HashNode(K key, V value)
{
this->value = value;
this->key = key;
}
};
//HashMap *next;
public:
HashMap()
{
//Initial capacity of hash array
capacity = 10;
size = 0;
}
// This implements hash function to find index
// for a key
int hashCode(K key)
{
return key % capacity;
}
oldHash = hashIndex;
probe++;
key = key + (probe * probe);
hashIndex = hashCode(key);
cout << "\nProbe =" << probe << "," << "HashIndex = " <<
hashIndex << endl;
}
arr[hashIndex] = temp;
if (flag)
previous->next = arr[hashIndex];
}
// Reduce size
size--;
return temp->value;
}
hashIndex++;
hashIndex %= capacity;
probe++;
key = key + (probe*probe);
cout<< "key="<< key << "Probe="<< probe <<endl;
hashIndex = hashCode(key);
}
//Search Key
bool search(int key)
{
// Apply hash function to find index for given key
int hashIndex = hashCode(key);
int counter = 0;
int probe = 0;
//finding the node with given key
while (arr[hashIndex] != NULL)
{
//int counter = 0;
if (counter++ > capacity) //to avoid infinite loop
return false;
//if node found return its value
if (arr[hashIndex]->key == key)
return true;
h->insertNode(1, 1);
//h->display();
h->insertNode(2, 26);
h->insertNode(3, 13);
h->display();
h->insertNode(2, 39);
h->insertNode(2, 93);
h->insertNode(4, 87);
h->display();
/*h->display();
h->insertNode(3, 33);
h->insertNode(2, 60);
system("pause");
return 0;
}
c. What is the worst case complexity analysis for insertion and searching in hash table using coalesced
hashing?
Solution: 𝑂(𝑁).
Q7: [3+4=7]
Solution:
-1
4
2 1
10
3
-1
1 -1
2 7 11
1 6 9 1 12
0 0
0
8
0
Solution:
2 1
10
3
1 -1
2 7 11
1 6 9 1 12
0 0
0
8
0
0 1
10
2
0 -1 -1
1 0 3 7 11
6 9 1 12
0
0
8
0
Here we will look for the tallest grandchild of the root node. RL rotation will be performed resulting in the
following balanced AVL Tree.
1
1 10
4
1 -1
0 9 11
2 6
0
12
8 0
1 3
0
0 0