0% found this document useful (0 votes)
13 views26 pages

CS-21001 (DS) - CS End Nov 2024

The document outlines the structure and requirements for the Autumn End Semester Examination-2024 for B.Tech students in Data Structures. It includes a question paper format with two sections, detailing various programming and theoretical questions related to data structures, including linked lists, binary trees, heaps, and sorting algorithms. Additionally, it provides solutions and explanations for specific problems, emphasizing time complexity and algorithm efficiency.

Uploaded by

Adyasha Mohanty
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)
13 views26 pages

CS-21001 (DS) - CS End Nov 2024

The document outlines the structure and requirements for the Autumn End Semester Examination-2024 for B.Tech students in Data Structures. It includes a question paper format with two sections, detailing various programming and theoretical questions related to data structures, including linked lists, binary trees, heaps, and sorting algorithms. Additionally, it provides solutions and explanations for specific problems, emphasizing time complexity and algorithm efficiency.

Uploaded by

Adyasha Mohanty
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/ 26

SOLUTION AUTUMN END SEMESTER EXAMINATION-2024

3rd Semester, B.Tech (Programme)


DATA STRUCTURES
CS21001/IT21002/CC21002/CM21002/ CS2001 (Back)
(For 2023 Admitted Batches)
Time: 2 Hours 30 Minutes Full Marks: 50
Answer any FIVE questions.
Question paper consists of two SECTIONS i.e. A and B.
Section A is compulsory.
Attempt any Four question from Sections B.
The figures in the margin indicate full marks.
Candidates are required to give their answers in their own words as far as practicable
and all parts of a question should be answered at one place only.

SECTION-A (Learning levels 1)


1. Answer the following questions. Mark
(a) A single linked list contains n nodes. What is the time complexity of reversing this list in- 1
place?
Solution:
The time Complexity is O(n).
Explanation:
Steps for Reversing the Linked List In-Place:
1. Initialize three pointers:
a. prev to NULL (since the new tail of the list will point to NULL).
b. current to the head of the list.
c. next to temporarily hold the next node in the list as we change the
pointers.
2. Traverse through the list and reverse the next pointers:
a. For each node, set its next pointer to the prev node.
b. Move the prev pointer to the current node.
c. Move the current pointer to the next node (which is stored temporarily
in next).
3. Continue until the current pointer reaches NULL.
Time Complexity:
We visit each node exactly once, and for each node, we perform constant time operations
(changing pointers).
Therefore, the time complexity of reversing the list is O(n), where n is the number of
nodes in the list.

(b) Write a recursive C function to print all the elements present in a single linked list in 1
reverse order.
Solution:
// Recursive function to print the linked list in reverse order
void printReverse(struct Node* head) {
if (head == NULL) {
return; // Base case: if the list is empty, do nothing
}
// Recursive call to go to the next node
printReverse(head->next);
KIIT-DU/2024/SOT/Autumn End Semester Examination-2024
// Print the current node's data after the recursion
printf("%d ", head->data);
}

(c) Construct a binary tree from the following sequence of tree traversal: 1
In-order traversal =dbfeagcljhk
Post-order traversal =dfebgljkhca
Solution:

(d) While converting an infix expression: 6 + 5 * (8 * 5 - 9) to its postfix equivalent using 1


stack, what will be the maximum number of symbols that appear in the stack at one point
of time?

(e) In a max-heap of size n, what is the time complexity of extracting the maximum element 1
and then inserting a new element?
Solution:
Time Complexity:
• Extracting the maximum element: O(log n)
• Inserting a new element: O(log n)
Thus, the total time complexity for extracting the maximum element and then inserting a
new element is O(log n) + O(log n) = O(log n).
Conclusion:
Both operations — extracting the maximum element and inserting a new element — have
a time complexity of O(log n) in a max-heap of size n.
KIIT-DU/2024/SOT/Autumn End Semester Examination-2024
(f) Suppose the depth of a fully complete binary tree is 6. If the level of the tree is starting 1
from 0, how many nodes will be there in the tree?
Solution:
Given the depth d=6
Total nodes=26+1−1=27−1=128−1=127
(g) Write a modified bubble sort function whose time complexity is O (n) when it is applied 1
to an already sorted array. (n is the number of elements in the array)
Solution:
void bubbleSort(int arr[], int n)
{
int i, j;
int swapped; // A flag to check if a swap was made
// Traverse through all array elements
for (i = 0; i < n - 1; i++)
{
swapped = 0;

for (j = 0; j < n - i - 1; j++)


{
if (arr[j] > arr[j + 1])
{
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
swapped = 1;
}
}

if(swapped == 0)
{
break;
}
}
}
1
What is the time complexity of the following code:
(h)
int num = 1, counter= N;
while (counter> 0) {
num =num* i;
counter= counter/2;
}
Solution:
Time Complexity:
The while loop executes O(log2(N)) iterations, and the operations inside the loop (num = num ×
i and counter=counter/2) take constant time O(1).
Thus, the overall time complexity is: O(log2N)

(i) Consider the following function applied to a single linked list with odd no. of nodes : 1
struct node * fun ( )
{
struct node *p, *q;
p=q=start;// start points to the first node of the list
while(q!=NULL && q->next!=NULL)
KIIT-DU/2024/SOT/Autumn End Semester Examination-2024
{
q=q->next->next;
p=p->next;
}
return p;
}
The code will return _______ node of the list.
(A) Last node
(B) Node before the last node
(C) Middle node
(D) None of options
Solution:
The code will return the middle node of the list.
Correct Option: (C) Middle node

(j) Suppose the key values {63, 22, 50, 23, 49, 57, 81} are stored in a hash table using the 1
hash function: H(k)=K%7. Linear probing is used to resolve collision if present. After
inserting the key values, the content of the hash table at index 4, 5, 6, and 7 are_______.
Solution:
Content at Indices 4, 5, 6, and 7:
Index 4: 49
Index 5: 57
Index 6: 81
Index 7: Not part of the table (since table size is 7).
Thus, the content at indices 4, 5, and 6 is 49, 57, and 81, respectively. Index 7 is out of bounds.

Explanation:

Hash Function and Linear Probing


Hash Function:
H(k)=k%7
This function maps a key kk to an index in the hash table of size 7.
Collision Resolution:
If a collision occurs (i.e., two keys map to the same index), linear probing is used, which checks
the next available slot sequentially.

KIIT-DU/2024/SOT/Autumn End Semester Examination-2024


SECTION-B (Learning levels 2, 3, 4, 5 and 6)
2. Write a C function of complexity O (log n) to count the number of elements present in a [5]
sorted array between values X and Y. The elements, to be counted, are greater than X
(a)
and smaller than Y. X and Y are user inputs and may not be present in the array.
Example-1:
Input:
A[]= {7,11,13, 15, 18, 20, 21, 25, 37, 41, 49}
X=15, Y=49
Output: 6
Example-2:
Input:
A[]= {7,11,13, 15, 18, 20, 21, 25, 37, 41, 49}
X=17, Y=47
Output: 6
Scheme of Evaluation: Step marks can be given based on the partial correctness of the
answer.
Solution:
#include <stdio.h>
// Function to perform binary search and return the first index greater than `value`
int findFirstGreater(int A[], int n, int value) {
int low = 0, high = n - 1, result = n;
while (low <= high) {
int mid = low + (high - low) / 2;
if (A[mid] > value) {
result = mid;
high = mid - 1;
} else {
low = mid + 1;
}
KIIT-DU/2024/SOT/Autumn End Semester Examination-2024
}
return result;
}
// Function to perform binary search and return the first index greater than or equal to
`value`
int findFirstGreaterEqual(int A[], int n, int value) {
int low = 0, high = n - 1, result = n;
while (low <= high) {
int mid = low + (high - low) / 2;
if (A[mid] >= value) {
result = mid;
high = mid - 1;
} else {
low = mid + 1;
}
}
return result;
}
// Function to count elements in the range (X, Y)
int countElementsInRange(int A[], int n, int X, int Y) {
int left = findFirstGreater(A, n, X);
int right = findFirstGreaterEqual(A, n, Y);
return (right - left);
}
// Main Function
int main() {
int A[] = {7, 11, 13, 15, 18, 20, 21, 25, 37, 41, 49};
int n = sizeof(A) / sizeof(A[0]);
int X, Y;
// Input X and Y
printf("Enter X and Y: ");
scanf("%d %d", &X, &Y);
// Calculate the count
int count = countElementsInRange(A, n, X, Y);
printf("Number of elements between %d and %d: %d\n", X, Y, count);
return 0;
}

(b) Consider an array a[10]={10,74,19,80,27,93,33,5,12,24} [5]


Perform insertion sort on the given array. Consider the case when a[8]=12, has to be
inserted to its appropriate position in the sorted subset of the array {a[0],a[1]….a[7]}.
Mention the values of elements of the array at each step while reaching to the mentioned
KIIT-DU/2024/SOT/Autumn End Semester Examination-2024
stage while performing insertion sort. Write down C function for insertion sort to sort an
array in ascending order. Write the time complexity of insertion sort algorithm.
Scheme of Evaluation: Step marks can be given based on the partial correctness of the
answer.
Solution:
Insertion Sort Steps:
Given array:
a[10]={10,74,19,80,27,93,33,5,12,24}
We perform insertion sort until a[8]=12 is placed in its correct position within the sorted
subset.

// Function to perform insertion sort


void insertionSort(int arr[], int n)
{
for (int i = 1; i < n; i++)
{
int key = arr[i];
int j = i - 1;
// Move elements that are greater than key to one position ahead
while (j >= 0 && arr[j] > key)
{
arr[j + 1] = arr[j];
j--;
}
arr[j + 1] = key;
}
}

Time Complexity of Insertion Sort:


Best Case (Already Sorted): O(n)
Worst Case (Reverse Order): O(n2)
Average Case: O(n2)
3. You are given an array of integers, and your task is to find the maximum sub-array sum. [5]
A sub-array is defined as a contiguous subset of the array. Write a C function to find the
(a)
maximum sub-array sum efficiently.
Example:
Input Array: [-2, 1, -3, 4, -1, 2, 1, -5, 4]
Output: 6 (The maximum sub-array is [4, -1, 2, 1], and their sum is 6)
Note:
Your program should be able to handle both positive and negative numbers in the array.
The maximum sub-array sum is the sum of elements in a sub-array such that the sum is
as large as possible.
KIIT-DU/2024/SOT/Autumn End Semester Examination-2024
Scheme of Evaluation: Step marks can be given based on the partial correctness of the
answer.
Solution:
#include <stdio.h>
// Function to find the maximum sub-array sum
int maxSubArraySum(int arr[], int n)
{
int current_sum = arr[0]; // Initialize the current sum to the first element
int max_sum = arr[0]; // Initialize the maximum sum to the first element

for (int i = 1; i < n; i++) {


// Update current_sum by either starting a new sub-array or extending the current
sub-array
current_sum = (arr[i] > current_sum + arr[i]) ? arr[i] : current_sum + arr[i];

// Update max_sum if the current_sum is greater than the max_sum


if (current_sum > max_sum) {
max_sum = current_sum;
}
}
return max_sum;
}
int main() {
// Example input array
int arr[] = {-2, 1, -3, 4, -1, 2, 1, -5, 4};
int n = sizeof(arr) / sizeof(arr[0]);

// Call the function to find the maximum sub-array sum


int result = maxSubArraySum(arr, n);

// Output the result


printf("Maximum sub-array sum: %d\n", result);

return 0;
}
(b) What is the difference between a single linked list and double linked list representation? [5]
Write a C function to rotate a double linked list anti-clockwise by k nodes, where k is a
given positive integer and smaller than the number of nodes in linked list.. For example,
if the given linked list is A->B->C->D->E->F and k is 3, the list should be modified to
D->E->F->A->B->C.
Scheme of Evaluation: Step marks can be given based on the partial correctness of the
answer.
Solution:

A single linked list and a double linked list are both types of linked list data structures,
but they differ in how they store and access elements. Here's a comparison of the node
structure of the two:

1. Node Structure:

• Single Linked List:


o Each node contains two parts:
1. Data: The value or data stored in the node.
2. Next: A reference (or pointer) to the next node in the list.
o It only points forward to the next node.

KIIT-DU/2024/SOT/Autumn End Semester Examination-2024


· Double Linked List:

• Each node contains three parts:


1. Data: The value or data stored in the node.
2. Next: A reference (or pointer) to the next node.
3. Prev: A reference (or pointer) to the previous node.
• It has references to both the next and the previous nodes.

To rotate a doubly linked list anti-clockwise by k nodes, we need to do the following:

Approach:

1. Find the length of the doubly linked list.


2. Normalize k to ensure it's within the bounds of the list (i.e., k = k % length).
3. Traverse the list to find the new head and tail after the rotation.
4. Rearrange the pointers:
i. The node at position k becomes the new head.
ii. The node just before the new head becomes the new tail.
iii. The old tail's next pointer should point to the old head, and the old head's
previous pointer should point to the old tail.

void rotate (struct Node** head, int k) {


if (*head == NULL || k == 0) return;
// Find the length of the doubly linked list
struct Node* temp = *head;
int length = 1;
while (temp->next != NULL) {
temp = temp->next;
length++;
}
// If k is greater than or equal to length, take modulo
k = k % length;
if (k == 0) return;
// Find the k-th node
struct Node* kthNode = *head;
for (int i = 1; i < k; i++) {
kthNode = kthNode->next;
}
// kth node will become the new head
struct Node* newHead = kthNode->next;
struct Node* newTail = kthNode;
// Make the old tail point to the old head
temp->next = *head;
(*head)->prev = temp;
// Update the next and prev pointers
*head = newHead;
newHead->prev = NULL;
newTail->next = NULL;
}
4. Write a non-recursive C function to traverse a binary search tree in postorder. Define a [5]
stack ADT to be used in the function.
(a)
Scheme of Evaluation: Step marks can be given based on the partial correctness of the
answer.
Solution:
// Non-recursive function for postorder traversal of a BST
void postOrderTraversal(struct Node* root) {
if (root == NULL) return;
KIIT-DU/2024/SOT/Autumn End Semester Examination-2024
struct Stack* stack = createStack(100); // Create stack with capacity 100
struct Node* prev = NULL; // Track previously visited node
struct Node* curr = root;

while (!isEmpty(stack) || curr != NULL) {


// Traverse the leftmost path and push nodes to stack
while (curr != NULL) {
push(stack, curr);
curr = curr->left;
}

// Peek the top node from the stack


curr = stack->arr[stack->top];

// If the right child is NULL or already visited, process the current node
if (curr->right == NULL || curr->right == prev) {
printf("%d ", curr->data); // Process the current node
pop(stack); // Pop the node
prev = curr; // Set prev to the current node
curr = NULL; // Move to the next node
} else {
// Otherwise, move to the right child
curr = curr->right;
}
}

free(stack->arr);
free(stack);
}

Stack ADT:
The stack is implemented using an array of pointers to Node structures.
The stack provides basic operations: push(), pop(), and isEmpty().

(b) Write a C function to construct a complete binary tree (using linked list) from a given [5]
level order traversal sequence of the tree.
Eg. :
Input: A B C D E F G H I H
Output:

Scheme of Evaluation: Step marks can be given based on the partial correctness of the
answer.
Solution:
#include <stdio.h>
#include <stdlib.h>

// Definition of a Binary Tree Node


struct TreeNode {
int data;
KIIT-DU/2024/SOT/Autumn End Semester Examination-2024
struct TreeNode* left;
struct TreeNode* right;
};

// A simple queue node for helping with level order traversal


struct QueueNode {
struct TreeNode* treeNode;
struct QueueNode* next;
};

// Queue structure to manage queue of tree nodes


struct Queue {
struct QueueNode* front;
struct QueueNode* rear;
};

// Function to create a new tree node


struct TreeNode* createNode(int data) {
struct TreeNode* newNode = (struct TreeNode*)malloc(sizeof(struct TreeNode));
newNode->data = data;
newNode->left = newNode->right = NULL;
return newNode;
}

// Function to create an empty queue


struct Queue* createQueue() {
struct Queue* queue = (struct Queue*)malloc(sizeof(struct Queue));
queue->front = queue->rear = NULL;
return queue;
}

// Function to enqueue a node to the queue


void enqueue(struct Queue* queue, struct TreeNode* treeNode) {
struct QueueNode* newQueueNode = (struct QueueNode*)malloc(sizeof(struct
QueueNode));
newQueueNode->treeNode = treeNode;
newQueueNode->next = NULL;

if (queue->rear == NULL) {
queue->front = queue->rear = newQueueNode;
return;
}

queue->rear->next = newQueueNode;
queue->rear = newQueueNode;
}

// Function to dequeue a node from the queue


struct TreeNode* dequeue(struct Queue* queue) {
if (queue->front == NULL) {
return NULL;
}

struct QueueNode* temp = queue->front;


struct TreeNode* node = temp->treeNode;
queue->front = queue->front->next;

if (queue->front == NULL) {
KIIT-DU/2024/SOT/Autumn End Semester Examination-2024
queue->rear = NULL;
}

free(temp);
return node;
}

// Function to construct a complete binary tree from a given level order traversal
struct TreeNode* buildCompleteBinaryTree(int* levelOrder, int n) {
if (n == 0) return NULL;

// Create the root node


struct TreeNode* root = createNode(levelOrder[0]);
struct Queue* queue = createQueue();

// Enqueue the root node


enqueue(queue, root);

int i = 1; // Start from the second element in the levelOrder array


while (i < n) {
struct TreeNode* current = dequeue(queue);

// Insert the left child


if (i < n) {
current->left = createNode(levelOrder[i++]);
enqueue(queue, current->left);
}

// Insert the right child


if (i < n) {
current->right = createNode(levelOrder[i++]);
enqueue(queue, current->right);
}
}

// Return the root of the binary tree


return root;
}

// Helper function to print the tree in in-order fashion


void inorderTraversal(struct TreeNode* root) {
if (root == NULL) return;
inorderTraversal(root->left);
printf("%d ", root->data);
inorderTraversal(root->right);
}

int main() {
// Example level order traversal sequence
int levelOrder[] = {1, 2, 3, 4, 5, 6, 7};
int n = sizeof(levelOrder) / sizeof(levelOrder[0]);

// Construct the complete binary tree


struct TreeNode* root = buildCompleteBinaryTree(levelOrder, n);

// Print the tree in in-order traversal


printf("In-order Traversal of the Complete Binary Tree:\n");
inorderTraversal(root);
KIIT-DU/2024/SOT/Autumn End Semester Examination-2024
return 0;
}

5. Define an input-restricted de-queue and an output-restricted de-queue with suitable [5]


diagrams and examples. Write a C code to check whether the content of the input-
(a)
restricted de-queue is palindrome or not, by traversing each element only once.
Scheme of Evaluation: Step marks can be given based on the partial correctness of the
answer.
Solution:
Input-Restricted Deque:
An Input-restricted deque allows insertions at only one end (either the front or the back),
but elements can be removed from both the front and the back.

Example:
1. Start with the deque: [3, 2, 5, 1, 4] (Front → Back).
2. Insert 6 at the back → [3, 2, 5, 1, 4, 6].
3. Delete from the front → [2, 5, 1, 4, 6].
4. Delete from the back → [2, 5, 1, 4].

Output restricted Queue:


An Output-restricted deque allows insertions at both ends (front and back), but elements
can be removed only from one end (either the front or the back).

Example:
1. Start with the deque: [3, 2, 5, 1, 4] (Front → Back).
2. Insert 6 at the back → [3, 2, 5, 1, 4, 6].
3. Insert 7 at the front → [7, 3, 2, 5, 1, 4, 6].
4. Delete from the front → [3, 2, 5, 1, 4, 6].

// C program to check whether an input-restricted dequeue is palindrome or not

#include <stdio.h>
#include <stdlib.h>
// Define a structure for the input-restricted deque
typedef struct Deque {
int *arr;
int front;
int rear;
int size;
} Deque;

// Function to initialize the deque


Deque* createDeque(int size) {
KIIT-DU/2024/SOT/Autumn End Semester Examination-2024
Deque *deque = (Deque*)malloc(sizeof(Deque));
deque->arr = (int*)malloc(sizeof(int) * size);
deque->front = -1;
deque->rear = -1;
deque->size = size;
return deque;
}

// Function to insert at the back of the deque


void insertBack(Deque *deque, int value) {
if (deque->rear == deque->size - 1) {
printf("Deque is full.\n");
return;
}
if (deque->front == -1) {
deque->front = 0; // If the deque is empty
}
deque->arr[++(deque->rear)] = value;
}

// Function to remove from the front of the deque


int removeFront(Deque *deque) {
if (deque->front == -1) {
printf("Deque is empty.\n");
return -1;
}
int value = deque->arr[deque->front];
if (deque->front == deque->rear) {
deque->front = deque->rear = -1; // Deque becomes empty
} else {
deque->front++;
}
return value;
}

// Function to remove from the back of the deque


int removeBack(Deque *deque) {
if (deque->rear == -1) {
printf("Deque is empty.\n");
return -1;
}
int value = deque->arr[deque->rear];
if (deque->front == deque->rear) {
deque->front = deque->rear = -1; // Deque becomes empty
} else {
deque->rear--;
}
return value;
}

// Function to check if the deque is a palindrome


int isPalindrome(Deque *deque) {
int frontPointer = deque->front;
int rearPointer = deque->rear;

// Traverse the deque from both ends


KIIT-DU/2024/SOT/Autumn End Semester Examination-2024
while (frontPointer < rearPointer) {
if (deque->arr[frontPointer] != deque->arr[rearPointer]) {
return 0; // Not a palindrome
}
frontPointer++;
rearPointer--;
}
return 1; // Is a palindrome
}

// Function to display the deque elements (for debugging)


void displayDeque(Deque *deque) {
for (int i = deque->front; i <= deque->rear; i++) {
printf("%d ", deque->arr[i]);
}
printf("\n");
}

// Driver code to test the palindrome check


int main() {
Deque *deque = createDeque(10);

// Insert elements into the deque


insertBack(deque, 1);
insertBack(deque, 2);
insertBack(deque, 3);
insertBack(deque, 2);
insertBack(deque, 1);

// Display the deque elements


printf("Deque contents: ");
displayDeque(deque);

// Check if the deque is a palindrome


if (isPalindrome(deque)) {
printf("The deque is a palindrome.\n");
} else {
printf("The deque is not a palindrome.\n");
}

// Clean up memory
free(deque->arr);
free(deque);

return 0;
}

OUTPUT:
Deque contents: 1 2 3 2 1
The deque is a palindrome.
(b) Write a C code to implement a priority queue using a binary heap. Explain it with an [5]
appropriate example.
Scheme of Evaluation: Step marks can be given based on the partial correctness of the
answer. Correct implementation of Priority Queue With / without using Binary Heap
should be given fullmark.
Solution:
KIIT-DU/2024/SOT/Autumn End Semester Examination-2024
#include <stdio.h>
#include <stdlib.h>

// Define the structure of a priority queue


struct PriorityQueue {
int *arr;
int size;
int capacity;
};

// Function to create a priority queue


struct PriorityQueue* createPriorityQueue(int capacity) {
struct PriorityQueue* pq = (struct PriorityQueue*)malloc(sizeof(struct
PriorityQueue));
pq->capacity = capacity;
pq->size = 0;
pq->arr = (int*)malloc(capacity * sizeof(int));
return pq;
}

// Function to swap two elements in the array


void swap(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}

// Function to maintain the max-heap property while inserting an element


void heapifyUp(struct PriorityQueue* pq, int index) {
// Bubble up until the heap property is restored
while (index > 0 && pq->arr[(index - 1) / 2] < pq->arr[index]) {
swap(&pq->arr[(index - 1) / 2], &pq->arr[index]);
index = (index - 1) / 2;
}
}

// Function to insert a new element into the priority queue


void insert(struct PriorityQueue* pq, int value) {
if (pq->size == pq->capacity) {
printf("Priority Queue is full\n");
return;
}

// Insert the new element at the end


pq->arr[pq->size] = value;
pq->size++;

// Fix the heap property by "bubbling up"


heapifyUp(pq, pq->size - 1);
}

// Function to maintain the max-heap property while removing the root element
void heapifyDown(struct PriorityQueue* pq, int index) {
int largest = index;
int leftChild = 2 * index + 1;
int rightChild = 2 * index + 2;
KIIT-DU/2024/SOT/Autumn End Semester Examination-2024
// Compare with the left child
if (leftChild < pq->size && pq->arr[leftChild] > pq->arr[largest]) {
largest = leftChild;
}

// Compare with the right child


if (rightChild < pq->size && pq->arr[rightChild] > pq->arr[largest]) {
largest = rightChild;
}

// If the largest is not the current node, swap and continue heapifying down
if (largest != index) {
swap(&pq->arr[index], &pq->arr[largest]);
heapifyDown(pq, largest);
}
}

// Function to extract the root element (highest priority) from the priority queue
int extractMax(struct PriorityQueue* pq) {
if (pq->size == 0) {
printf("Priority Queue is empty\n");
return -1; // Indicates empty queue
}

int max = pq->arr[0];

// Replace the root with the last element


pq->arr[0] = pq->arr[pq->size - 1];
pq->size--;

// Restore the heap property by "bubbling down"


heapifyDown(pq, 0);

return max;
}

// Function to print the priority queue (heap array)


void printPriorityQueue(struct PriorityQueue* pq) {
for (int i = 0; i < pq->size; i++) {
printf("%d ", pq->arr[i]);
}
printf("\n");
}

// Main function to test the priority queue implementation


int main() {
struct PriorityQueue* pq = createPriorityQueue(10);
insert(pq, 10);
insert(pq, 20);
insert(pq, 5);
insert(pq, 30);
insert(pq, 40);
printf("Priority Queue after insertions: ");
printPriorityQueue(pq);
printf("Extracted max: %d\n", extractMax(pq));
KIIT-DU/2024/SOT/Autumn End Semester Examination-2024
printf("Priority Queue after extraction: ");
printPriorityQueue(pq);
insert(pq, 25);
printf("Priority Queue after inserting 25: ");
printPriorityQueue(pq);
return 0;
}

6. What is hashing? Explain collisions in hashing. Draw and explain the different hash [5]
tables with open addressing (quadratic probing, double hashing), and chaining by using
(a)
hash functions h1(k) = k % 10, h2(k) = 7- (k % 7), as per requirements, with table size
10 (indexed from 0 to 9) by inserting the keys: 62, 53, 74, 32, 86, 23, 55 into the table in
the given order. (Note: The hash function h2(k) is only used for double hashing
technique)
Scheme of Evaluation: Step marks can be given based on the partial correctness of the
answer. What is Hashing + collision of Hashing: 1 mark, quadratic probing,: 1 mark
double hashing:2 mark, and chaining: 1 mark.
Solution:
What is Hashing?
Hashing is a process used to map data of arbitrary size (like a string or a file) to a fixed
size using a hash function. It is often used in data structures like hash tables to quickly
locate a data record given its search key. The hash function takes a key as input and
returns an index in a hash table where the corresponding value is stored.

What is a Collision in Hashing?


A collision occurs when two different keys map to the same index in a hash table. Since
the hash function maps multiple keys into a fixed number of slots (buckets), it's possible
that different keys will end up at the same location. To handle collisions, different
techniques are used like open addressing and chaining.

Hashing Techniques to Handle Collisions:

Open Addressing: In open addressing, all elements are stored within the hash table
itself. When a collision occurs, the algorithm looks for the next available slot within the
table.
Quadratic Probing: In quadratic probing, if a collision occurs at index i, the algorithm
checks (i + 1^2), (i + 2^2), and so on until an empty slot is found.
Double Hashing: In double hashing, two hash functions are used. The second hash
function determines the step size for probing. If a collision occurs at index i, the next
index is determined by i + h2(k) where h2(k) is another hash function.
Chaining: In chaining, each slot in the hash table contains a linked list (or another
structure like a tree). When a collision occurs, the new key-value pair is added to the list
at the same index.

Problem Setup:
Hash Table Size = 10
Hash Functions:
h1(k)=k%10h1(k)=k%10
h2(k)=7−(k%10)h2(k)=7−(k%10) (used only for double hashing)
Keys to Insert: 62, 53, 74, 32, 86, 23, 55

Let's insert the keys using the different collision handling techniques.

KIIT-DU/2024/SOT/Autumn End Semester Examination-2024


KIIT-DU/2024/SOT/Autumn End Semester Examination-2024
(b) Consider that a visitor X visited the seven sister states of India: Assam (AS), Arunachal [5]
Pradesh (AP), Meghalaya (ML), Nagaland (NL), Manipur (MN), Mizoram (MZ), and
Tripura (TR) based on the following adjacency matrix A:
AS AP ML NL MN MZ TR
AS 1 0 1 1 0 0 0
AP 0 0 0 1 1 0 0
ML 1 0 0 0 1 0 1
NL 1 1 0 0 0 1 0
MN 0 1 1 0 0 0 0
MZ 0 0 0 1 0 0 0
TR 0 0 1 0 0 0 0

Draw the undirected graph from matrix A, where states are vertices and edges indicate
connected states (route of visitor X). Explain the Breadth-first Search (BFS) algorithm
while applying it to traverse from start at AS to MZ. AS is the starting vertex and the
goal is to reach MZ.
Scheme of Evaluation: Step marks can be given based on the partial correctness of the
answer. Draw Graph: 2 marks, BFS: 3 marks.
Solution:
The graph can be represented as:

BFS Traversal from AS to MZ:


KIIT-DU/2024/SOT/Autumn End Semester Examination-2024
7. What is an AVL tree? Write the difference between an AVL tree and a Binary Search [5]
Tree (BST) tree. Illustrate the steps in creating an AVL tree by inserting the sequence of
(a)
elements: 11, 63, 21, 73, 85, 31, 42, 52, 75, 92, 67, 32, 19, 100, 17, 54 into the tree,
starting with an empty tree. Show the AVL tree after deleting the node value 85 from the
tree.
Scheme of Evaluation: Step marks can be given based on the partial correctness of the
answer. What is AVL:1 mark, Difference:1 mark, Steps: 3 marks.
Solution:

AVL Tree:
An AVL tree is a self-balancing binary search tree. Named after its inventors (Adelson-
Velsky and Landis), it ensures that the difference between the heights of the left and
right subtrees of any node (called the balance factor) is at most 1. This balance ensures
the tree remains approximately balanced, which helps maintain optimal time complexity
for search, insert, and delete operations.

KIIT-DU/2024/SOT/Autumn End Semester Examination-2024


KIIT-DU/2024/SOT/Autumn End Semester Examination-2024
KIIT-DU/2024/SOT/Autumn End Semester Examination-2024
KIIT-DU/2024/SOT/Autumn End Semester Examination-2024
KIIT-DU/2024/SOT/Autumn End Semester Examination-2024
(b) Write a C function to construct a modified binary search tree where each node in the [5]
modified binary search tree has at most two children, a left child and a right child, with
the left child containing values higher than the parent node and the right child
containing values lesser than the parent node. Write a C code to traverse the tree to print
the node key values in the descending order.
Scheme of Evaluation: Step marks can be given based on the partial correctness of the
answer. Construct modified BST: 2 marks, Traverse in descending order: 3 marks.
Solution:
// Function to insert a node into the modified binary search tree
struct Node* insert(struct Node* root, int data) {
if (root == NULL) {
return createNode(data); // If the tree is empty, return a new node
}

// Modify the BST insertion rule:


// If data is less than root's data, insert into the right subtree
// If data is greater than root's data, insert into the left subtree
if (data < root->data) {
root->right = insert(root->right, data);
} else {
root->left = insert(root->left, data);
}
return root;
}

// Function to perform reverse in-order traversal (right, root, left) and print the
nodes
void printDescending(struct Node* root) {
if (root == NULL) {
return;
}

// First traverse the right subtree


printDescending(root->right);

// Then print the root node


printf("%d ", root->data);

// Finally, traverse the left subtree


printDescending(root->left);
}

*****

KIIT-DU/2024/SOT/Autumn End Semester Examination-2024

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy