Model QP 2022 Scheme
Model QP 2022 Scheme
Note: 01. Answer any FIVE full questions, choosing at least ONE question from each MODULE.
*Bloom’
Module -1 s Mar
Taxonom ks
y Level
Q.0 a Define data structures. With a neat diagram, explain the classification
1 L2 5
of data structures with examples.
b What do you mean by pattern matching? Outline the Knuth Morris
Pratt (KMP) algorithm and illustrate it to find the occurrences of the
following pattern. L3 8
P: ABCDABD
S: ABC ABCDAB ABCDABCDABDE
c Write a program in C to implement push, pop and display operations
L3 7
for stacks using arrays.
OR
Q.0 a Explain in brief the different functions of dynamic memory allocation. L2 5
2 b Write functions in C for the following operations without using built-
in functions
i) Compare two strings. L3 8
ii) Concatenate two strings.
iii) Reverse a string
c Write a function to evaluate the postfix expression. Illustrate the same
for the given postfix expression: L3 7
ABC-D*+E$F+ and assume A=6, B=3, C=2, D=5, E=1 and F=7.
Module-2
Q. a Develop a C program to implement insertion, deletion and display
03 L3 10
operations on Linear queue.
b Write a program in C to implement a stack of integers using a
L3 10
singly linked list.
OR
Q.0 a Write a C program to implement insertion, deletion and display
4 L3 10
operations on a circular queue.
b Write the C function to add two polynomials. Show the linked
representation of the below two polynomials and their addition using a
circular singly linked list
P1: 5x3 + 4x2 +7x + 3 P2: 6x2 + 5 L3 10
Output: add the above two polynomials and represent them using the
linked list.
BCS304
Module-3
Q. a Write recursive C functions for inorder, preorder and postorder
05 traversals of a binary tree. Also, find all the traversals for the given
tree.
L3 8
L3 6
OR
Q. a Write C Functions for the following
06 i) Inserting a node at the beginning of a Doubly linked list Deleting L3 8
a node at the end of the Doubly linked list
b Define Binary tree. Explain the representation of a binary tree with
L2 6
a suitable example.
c Define the Threaded binary tree. Construct Threaded binary for the
L3 6
following elements: A, B, C, D, E, F, G, H, I
Module-4
Q. a Design an algorithm to traverse a graph using Depth First Search
07 (DFS). Apply DFS for the graph given below.
L3 8
c Define selection tree. Construct min winner tree for the runs of a game
given below. Each run consists of values of players. Find the first 5
winners.
1 9 2 6 8 9 9 1 L2 6
0 0 0 7
1 2 2 1 1 1 9 1
5 0 0 5 5 1 5 8
1 3 3 2 5 1 9 2
6 8 0 5 0 6 9 0
2
8
BCS304
OR
Q. a Define Binary Search tree. Construct a binary search tree (BST) for the
08 following elements: 100, 85, 45, 55, 120, 20, 70, 90, 115, 65, 130,
L3 8
145.
Traverse using in-order, pre-order, and post-order traversal techniques.
Write recursive C functions for the same.
b Define Forest. Transform the given forest into a Binary tree and
traverse using inorder, preorder and postorder traversal.
L2 6
c Define the Disjoint set. Consider the tree created by the weighted
union function on the sequence of unions: union(0,1), union(2,3),
L2 6
union(4,5), union(6,7), union(0,2), union(4,6), and union(0,4).
Process the simple
find and collapsing find on eight finds and compare which find is
efficient.
Module-5
Q. a What is chained hashing? Discuss its pros and cons. Construct the hash
09 table to insert the keys: 7, 24, 18, 52, 36, 54, 11, 23 in a chained hash L3 10
table of 9 memory locations. Use h(k) = k mod m.
b Define the leftist tree. Give its declaration in C. Check whether the
given binary tree is a leftist tree or not. Explain your answer.
L2 5
L2 5
Linear data structures organize data sequentially, where elements are arranged one after the other.
1. Array : A collection of elements of the same data type stored in contiguous memory locations.
2. Linked List: A collection of nodes, where each node contains data and a reference (or link) to the
next node in the sequence.
3. Stack: A collection of elements following the Last In First Out (LIFO) principle.
4. Queue: A collection of elements following the First In First Out (FIFO) principle.
1. Tree: A hierarchical structure where each node is connected to children nodes. A tree starts with a
root node.
Example: Representing file systems or organizational hierarchies.
3. Hash Table: A data structure that maps keys to values for efficient lookup using a hash function.
Example: Implementing dictionaries or caches.
Primitive Operations on Data Structures
1 b) what do you mean by pattern matching? Outline the Knuth Morris Pratt (KMP) algorithm and
illustrate it to find the occurrences of the following pattern.
Pattern: ABCDABD
String: ABC ABCDAB ABCDABCDABDE
Pattern Matching refers to the process of finding occurrences of a smaller string (the pattern) within a
larger string (the text). The goal is to locate all positions in the text where the pattern appears. Efficient
algorithms, like Knuth-Morris-Pratt (KMP), improve this process by avoiding redundant comparisons.
1c)Write a program in C to implement push, pop and display operations for stacks using arrays.
#include <stdio.h>
#include <stdlib.h>
#define STACK_SIZE 5
int top = -1;
int stack [10];
void main()
{
int choice, item;
// Perform stack operations any number of times
for (;;)
{
printf("1:Push 2:Pop 3:Display 4:Exit: ");
scanf("%d", &choice);
switch (choice)
{
case 1: printf("Enter the item: ");
scanf("%d", &item);
push (item);
break;
case 2: pop ();
break;
case 3: display ();
break;
default: exit(0);
}
}
}
Dynamic memory allocation is the process of allocating memory during run time(execution time).
Additional storage can be allocated whenever needed.
1. malloc( ):
Allocates requested number of bytes and returns a pointer to the first byte of the allocated space.
Syntax:
ptr=(datatype *)malloc(sizeof(datatype); where,
ptr is a pointer variable of type datatype
datatpe can be any of the basic datatype or user define datatype
Size is number of bytes required.
Example:
int *p;
ptr=(int*)malloc(100*sizeof(int));
2. calloc ()
It stands for contiguous allocation. It is used to allocate multiple blocks of memory.
It requires two parameters as number of elements and size of each element.
where, ptr is a pointer variable of type datatype datatype can be any of the basic datatype
n is number of blocks to be allocated size is number of bytes required
int *p;
ptr=(int*)calloc(100,sizeof(int));
3. realloc()
It changes the size of block by deleting or extending the memory at end of the block.
If memory is not available it gives complete new block.
Syntax:
ptr=(datatype *)realloc (ptr , sizeof(datatype); where,
ptr is a pointer to a block previously allocated memory either using malloc() or calloc()
Size is new size of the block.
int *p;
ptr=(int*)calloc(100,sizeof(int)); ptr=(int*)realloc(ptr,sizeof(int));
4. free()
This function is used to de-allocate(or free) the allocated block of memory which is allocated
by using functions malloc(), calloc(), realloc().
Syntax:
free(ptr);
2b)Write functions in C for the following operations without using built-in functions
i)Compare two strings. ii) Concatenate two strings. iii) Reverse a string
int scomp(char s1[ ], char s2[] ) int scat(char s1[ ], char s2[ ])
{ {
int i, j; int i, j;
if(slen(s1) != slen(s2)) for(i = slen(s1), j=0; s2[j] != '\0'; i++, j++)
{ {
return 0; s1[i] = s2[j];
} }
for(i=0; s1[i] != '\0'; i++)
{ s1[i] = '\0';
if(s1[i] != s2[i]) return 0;
{ }
return 0;
}
}
return 1;
}
void reverse()
{
char str[100], temp;
int i, j = 0;
printf("Enter The String: ");
gets(str);
i = 0;
j = strlen(str) - 1; while (i < j)
{
temp = str[i];
str[i] = str[j];
str[j] = temp; i++;
j--;
}
printf("\nReverse a String Is: %s\n\n", str);
}
2c) Write a function to evaluate the postfix expression. Illustrate the same for the given postfix
expression: ABC-D*+E$F+ and assume A=6, B=3, C=2, D=5, E=1 and F=7.
#include<stdio.h>
float compute(char symbol, float op1, float op2)
{
switch (symbol)
{
case '+': return op1 + op2;
case '-': return op1 - op2;
case '*': return op1 * op2;
case '/': return op1 / op2; case '$':
case '^': return pow(op1,op2);
}
}
void main()
{
float s[20], res, op1, op2; int top, i;
char postfix[20], symbol;
printf("\nEnter the postfix expression:\n"); scanf ("%s", postfix);
top=-1;
for (i=0; i<strlen(postfix) ;i++)
{
symbol = postfix[i];
if(isdigit(symbol))
s[++top]=symbol - '0';
else
{
op2 = s[top--];
op1 = s[top--];
res = compute(symbol, op1, op2);
s[++top] = res;
}
}
res = s[top--];
printf("\nThe result is : %f\n", res);
}
To evaluate the given postfix expression ABC-D*+E$F+ with the provided variable values A=6, B=3, C=2, D=5,
E=1, and F=7, follow these steps:
Final Result:
Stack Op2 Op1 Result = Op1 Op2
6
63
632 2 3 Result = 3 – 2 = 1
6 1 (Result) 5
615 5 1 Result = 1* 5 = 5
6 5 (Result)
65 5 6 Result = 6 + 5 = 11
11 (Result)
11 1 1 11 Result = 1 ^ 11 = 11
11
11 7 7 11 Result = 11 + 7 = 18
#include <stdio.h>
#include <stdlib.h>
#include <alloc.h>
struct node
{
int info;
struct node *link;
};
if ( first == NULL )
{
printf("List is empty cannot delete\n");
return NULL;
}
temp = first;
temp = temp->link;
printf("Item deleted = %d\n",first->info);
free(first);
return temp;
}
//Function to display the contents of the list
void display(NODE first)
{
NODE cur;
if ( first == NULL )
{
printf("List is empty\n");
return;
}
printf("The contents of singly linked list\n");
cur = first;
while ( cur != NULL )
{
printf("%d ",cur->info);
cur = cur->link;
}
printf("\n");
}
void main()
{
NODE first;
int choice, item;
first = NULL;
for (;;)
{
printf("1:Insert_Front 2:Delete_Front\n");
printf("3:Display 4:Exit\n");
printf("Enter the choice\n");
scanf("%d", &choice);
switch(choice)
{
case 1:
printf("Enter the item to be inserted\n");
scanf("%d", &item);
first = insert_front (item, first);
break;
case 2:
first = delete_front(first);
break;
case 3:
display(first);
break;
default:
exit(0);
}
}
}
4 a Write a C program to implement insertion, deletion and display operations on a circular queue
#include <stdio.h>
#include <stdlib.h>
#define Q_SIZE 5
int front = 0, rear -1, count = 0;
int queue[10];
int i, temp;
if (count=0)
{
printf("Queue is empty");
return;
}
printf("Queue: ");
temp = front;
for (i = 1; i <= count; i++)
{
printf("%d", queue [temp]);
temp = (temp +1)% Q_SIZE;
}
printf("\n");
}
void main()
{
int choice, item;
for (;;)
{
printf("1:Insert rear 2:Delete front 3:Display 4:Exit: ");
scanf("%d", &choice);
switch (choice)
{
case 1: printf("Enter the item :");
scanf("%d", &item);
insert_rear (item);
break;
case 2: delete_front();
break;
case 3: display();
break;
default: exit(0);
}
}
}
4 b. Write the C function to add two polynomials. Show the linked representation of the below two
polynomials and their addition using a circular singly linked list P1: 5x3 + 4x2 +7x + 3 P2: 6x2 + 5
Output: add the above two polynomials and represent them using the linked list.
do
{
if (t1->exp > t2->exp)
{
result = insertTerm(result, t1->coeff, t1->exp);
t1 = t1->next;
}
else if (t1->exp < t2->exp)
{
result = insertTerm(result, t2->coeff, t2->exp);
t2 = t2->next;
}
else
{
int sumCoeff = t1->coeff + t2->coeff;
result = insertTerm(result, sumCoeff, t1->exp);
t1 = t1->next;
t2 = t2->next;
}
}
while (t1 != p1 && t2 != p2);
return result;
}
To represent and add the two polynomials using a circular singly linked list, follow these steps:
Circular singly linked list P1: 5x3 + 4x2 +7x + 3 P2: 6x2 + 5
Function to traverse the Function to traverse the binary Function to traverse the
binary tree in inorder tree in preorder binary tree in postorder
In order : D B H E I A F C G
Pre order : A B D E H I C F G
Post order : D H I E B F G C A
5 b. Write C functions for the following i) Search an element in the singly linked list. ii) Concatenation of
// Function to search for an element in a singly // Function to concatenate two singly linked
linked list lists
void search(struct node *head,int key) void Concat(struct Node *first, struct Node
{ *second)
struct node *temp = head; {
while(temp != NULL) struct Node *p =
{ first;
if(temp->data == key) while (p->next !=
printf(“key found”); NULL)
temp = temp->next; {
} p = p->next;
printf(“key not found”); }
} p->next = second;
second = NULL;
}
5 c. Define Sparse matrix. For the given sparse matrix, give the linked list representation:
A sparse matrix is a matrix in which most of the elements are zero. In contrast, a dense matrix has most
elements as non-zero. Sparse matrices are often used to save memory and computational resources when dealing with
large matrices where many elements are zero.
3 at position (1,3)
4 at position (1,5)
5 at position (2,3)
7 at position (2,4)
2 at position (4,2)
6 at position (4,3)
Final Answer:
The linked list representation of the sparse matrix A is:
(3, 1, 3) -> (4, 1, 5) -> (5, 2, 3) -> (7, 2, 4) -> (2, 4, 2) -> (6, 4, 3) -> Null
6 a. Write C Functions for the following
i) Inserting a node at the beginning of a Doubly linked list
ii) Deleting a node at the end of the Doubly linked list
6 b. Define Binary tree. Explain the representation of a binary tree with a suitable example.
A binary tree is a tree which has finite set of nodes that is either empty or consist of a root and two
subtrees called left subtree and right subtree. A binary tree can be partitioned into three subgroups namely root,
left subtree and right subtree.
Root – If tree is not empty, the first node in the tree is called root node.
left subtree – It is a tree which is connected to the left of root. Since this tree comes towards left of root,
it is called left subtree.
right subtree – It is a tree which is connected to the right of root. Since this tree comes towards right of
root, it is called right subtree.
6 c. Define the Threaded binary tree. Construct Threaded binary for the following elements: A, B, C, D,
E, F, G, H, I.
A Threaded Binary Tree is a type of binary tree where the null pointers (or empty child pointers) are replaced
with threads to make the tree traversal more efficient. The threading allows faster in-order, pre-order, and post-
order traversals without needing a stack or recursion.
Right Threaded Binary Tree: In this version of the tree, each node's right child is threaded to the
node's in-order successor (the next node in an in-order traversal), if there is no right child.
Left Threaded Binary Tree: In this version of the tree, each node's left child is threaded to the node's
in-order predecessor (the previous node in an in-order traversal), if there is no left child.
Elements: A, B, C, D, E, F, G, H, I
Let’s build a Right Threaded Binary Tree and a Left Threaded Binary Tree.
Assume the elements form a complete binary tree:
A
/ \
B C
/ \ / \
D EF G
/\
H I
Inorder Traversal:
Inorder traversal is: H,D,I,B,E,A,F,C,G
Threaded Trees Visualization Right Threaded Threaded Trees Visualization Left Threaded
A - H -> D A - D <- H
/ \ - D -> I \ / - I <- D
B C B C
- I -> B - B <- I
/ \ / \ / \ / \
D EF G - B -> E D EF G - E <- B
/ \ - E -> A / \ - A <- E
H I H I
- A -> F - F <- A
- F -> C - C <- F
- C -> G - G <- C
7 a. Design an algorithm to traverse a graph using Depth First Search (DFS). Apply DFS for the graph
given below.
Depth First Search: Depth First Search (DFS) algorithm traverses a graph in a depth ward motion and uses a
stack to remember to get the next vertex to start a search
DFS Algorithm :
Step 1 − Visit the adjacent unvisited vertex. Mark it as visited. Display it. Push it in a stack.
Step 2 − If no adjacent vertex is found, pop up a vertex from the stack. (which do not have adjacent vertices.)
Step 3 − Repeat Rule 1 and Rule 2 until the stack is empty
7 b. Construct a binary tree from the Post-order and In-order sequence given below
.
In-order: GDHBAEICF Post-order: GHDBIEFCA
In-order: GDHBAEICF:
Post-order: GHDBIEFCA :
7 c. Define selection tree. Construct min winner tree for the runs of a game given below. Each run consistsof
values of players. Find the first 5 winners.
10 9 20 6 8 9 90 17
15 20 20 15 15 11 95 18
16 38 30 25 50 16 99 20
28
SELECTION TREE
This is also called as a tournament tree. This is such a tree data structure using which the winner (or
loser) of a knock out tournament can be selected.
There are two types of selection trees namely: winner tree and loser tree. WINNER TREE
This is a complete binary tree in which each node represents the smaller of its two children. Thus, the
root node represents the smallest node in the tree.
Step 1: Step 2:
Step 3: Step 4:
8 a. Define Binary Search tree. Construct a binary search tree (BST) for the following elements: 100, 85,45,
55, 120, 20, 70, 90, 115, 65, 130, 145.
Traverse using in-order, pre-order, and post-order traversal techniques. Write recursive C functions for the
same.
A Binary Search Tree (BST) is a binary tree in which every node follows these properties:
1. The value of the left child node is less than the value of its parent node.
2. The value of the right child node is greater than the value of its parent node.
3. Both the left and right subtrees must themselves be binary search trees.
The given elements are: 100, 85, 45, 55, 120, 20, 70, 90, 115, 65, 130, 145.
To construct the BST:
1. Start with the first element (100) as the root.
2. Insert the remaining elements one by one, following the BST rules.
BST Structure:
100
/ \
85 120
/ \ / \
45 90 115 130
/ \ \
20 55 145
\
70
/
65
Let’s construct the Binary Search Tree (BST) with the given elements and traverse it using in-order, pre-order, and post-order
traversal methods.
Function to traverse the Function to traverse the binary Function to traverse the
binary tree in inorder tree in preorder binary tree in postorder
8 b. Define Forest. Transform the given forest into a Binary tree and traverse using inorder, preorder and
postorder traversal.
A forest is a collection of disjoint trees. Each tree in the forest is an independent hierarchical structure
composed of nodes.
Transforming the Forest into a Binary Tree:
To transform a forest into a binary tree:
1. Maintain the hierarchical structure:
o The first child of a node becomes its left child in the binary tree.
o The subsequent siblings of a node are linked as right children in the binary tree.
Given Forest:
Tree 1 (Root = B):
B
/ | \
D E F
/ \
I J
Tree 2 (Root = C):
C
/ | \
G H K
Transformed Binary Tree:
After transformation, the forest will look like this as a binary tree:
B
/ \
D E
/ \ \
I J F
\
C
/ \
G H
\
K
A disjoint set (also known as a union-find or merge-find set) is a data structure that keeps track of a partition
of a set into disjoint subsets. It supports two primary operations:
1. Union(x, y): Merge the subsets containing xxx and yyy into a single subset.
2. Find(x): Determine which subset a particular element xxx belongs to. This can be used to check if two
elements are in the same subset.
2. Collapsing Find (Path Compression): This optimization flattens the tree whenever a find operation is
performed. It makes each node on the path from xxx to the root point directly to the root, reducing the depth
of the tree.
1. union(0,1)
2. union(2,3)
3. union(4,5)
4. union(6,7)
5. union(0,2)
6. union(4,6)
7. union(0,4)
Steps:
Step 1: union(0,1) Tree: 0→1
Step 2: union(2,3) Tree: 2→3
Step 3: union(4,5) Tree: 4→5
Step 4: union(6,7) Tree: 6→7
Step 5: union(0,2) Tree: 0→1, 0→2, 2→3
Step 6: union(4,6) Tree: 4→5, 4→6, 6→7
Step 7: union(0,4) Final tree: 0→1,0→2,2→3,0→4,4→5,4→6,6→7
Efficiency Comparison: Simple Find vs. Collapsing Find
1. Simple Find: For each find operation, you traverse the path from the node to the root. This can become
inefficient as the tree depth increases.
2. Collapsing Find: During the traversal, each node along the path points directly to the root, flattening
the tree. This makes future operations faster.
Eight Find Operations:
Suppose we perform find operations on all elements (0 to 7) after the union sequence.
Simple Find: Each find operation traverses the tree, which may take O(tree depth). For this union
sequence, some find operations could take O(logn) in the worst case.
Collapsing Find: The first find operation for each element may take O(logn), but subsequent finds are
nearly constant time, O(1), because the tree is flattened.
Comparison
Simple Find:
Time complexity: O(logn) per find in the worst case.
Total time for 8 finds: O(8logn).
Collapsing Find:
Time complexity: Nearly O(1) after the first find due to tree flattening.
Total time for 8 finds: Approximately O(8).
9 a. What is chained hashing? Discuss its pros and cons. Construct the hash table to insert the keys: 7,
24,18, 52, 36, 54, 11, 23 in a chained hash table of 9 memory locations. Use h(k) = k mod m
Chained hashing, also known as separate chaining, is a technique used to resolve collisions in hash
tables. When two or more keys hash to the same index (known as a collision), chained hashing handles these
collisions by maintaining a linked list of all elements that hash to the same index.
1. Memory Overhead: Chained hashing can have a higher memory overhead compared to other
collisionresolution techniques.
2. Cache Inefficiency: cache inefficiency, particularly for large hash tables with long linked lists.
3. Performance Degradation:
4. Poor Worst-Case Performance: Chained hashing does not guarantee constant-time performance for
lookup operations in the worst case
Solution: 7, 24,18, 52, 36, 54, 11, 23
Table size 9. An element can be mapped to location using Key % 9
Hash Table location Mapped Element
7 mod 9 = 7
0 18, 36, 54
24 mod 9 = 6
1
18 mod 9 = 0
2 11
52 mod 9 = 7 (Collision Occurred)
3
36 mod 9 = 0 (Collision Occurred)
4
54 mod 9 = 0 (Collision Occurred)
5 23
11 mod 9 = 2
6 24
23 mod 9 = 5
7 7, 52
8
Hash Table
0
18 36 54
1
2 11
3
5 23
6 24
7 7 52
8
9 b. Define the leftist tree. Give its declaration in C. Check whether the given binary tree is a leftist treeor
not. Explain your answer.
A leftist tree is a special kind of binary tree that satisfies the following properties:
1. Heap Property: The value of each node is less than or equal to the values of its children.
2. Leftist Property: For every node, the null path length (NPL) of the left child is greater than or equal
to the NPL of the right child.
The null path length (NPL) of a node is the shortest distance from that node to a null child (a non-existent
node). For a leaf node, the NPL is 0. For a null node, the NPL is −1.
C Declaration.
struct Node
{
int key;
struct Node* left;
struct Node* right;
int npl;
};
2. Bucket Splitting:
o When a bucket overflows, only that bucket is split, and its contents are redistributed.
o The decision to split is based on a split pointer, which moves sequentially from the first bucket
to the last bucket.
3. Progressive Splitting:
o Start with NN buckets and h0(k).
o When a bucket overflows, it is split into two buckets, and the new bucket uses h1(k)
o The split pointer moves to the next bucket, ensuring gradual reorganization.
Example:
Initial buckets: 0, 1 using h0(k)=k mod 2.
Keys: 2,3,5,7,11,13
Key h0(k)=k mod 2 Bucket
2 0 [2]
3 1 [3]
5 1 [3, 5]
7 1 Overflow
10 a. What is a Priority queue? Demonstrate functions in C to implement the Max Priority queue
with an example. i) Insert into the Max priority queue ii) Delete into the Max priority queue iii) Display
Max priority queue.
A Priority Queue (PQ) is a special type of queue where each element is associated with a priority. Elements
with higher priority are dequeued before elements with lower priority. In a Max Priority Queue, the element
with the highest priority (or largest value) is dequeued first. Priority queues are often implemented using heaps,
which provide an efficient way to insert and delete elements based on priority.
// Function to insert an element into the Max Priority Queue
void insert(MaxPQ *pq, int value)
{
if (pq->size == MAX_SIZE)
{
printf("Priority Queue is full!\n");
return;
}
pq->arr[pq->size] = value;
int index = pq->size;
pq->size++;
while (index > 0 && pq->arr[(index - 1) / 2] < pq->arr[index])
{
swap(&pq->arr[index], &pq->arr[(index - 1) / 2]);
index = (index - 1) / 2;
}
}
// Function to delete the maximum element (root) from the Max Priority Queue
int deleteMax(MaxPQ *pq)
{
if (pq->size == 0)
{
printf("Priority Queue is empty!\n");
return -1;
}
int maxValue = pq->arr[0];
pq->arr[0] = pq->arr[pq->size - 1];
pq->size--;
heapify(pq, 0);
return maxValue;
}
10 b. Define min Leftist tree. Meld the given min leftist trees.
2. Leftist Property: For every node, the null path length (NPL) of the left child is greater than or equal to
the NPL of the right child.
Meld Operation in Min Leftist Trees
The meld operation combines two min leftist trees into a single min leftist tree. The steps for melding two min
leftist trees are:
1. Merge Root Nodes:
o The root with the smaller key becomes the root of the new tree.
2. Recursively Meld:
o Recursively meld the right subtree of the root with the other tree.
3. Update Structure:
o After merging, swap the left and right subtrees of the root if necessary to maintain the leftist
property.
o Compare 50 and 8.
o After each meld step, update null path lengths (NPL) and swap left and right subtrees if
necessary.
This tree satisfies both the heap property and the leftist property.
10 c. Define hashing. Explain different hashing functions with examples. Discuss the properties of a good
hash function.
Hashing is a technique used to map data (keys) to fixed-size values, typically integers, called hash values or
hash codes. This mapping is performed by a hash function.
o The hash value is computed by taking the modulus of the key with a prime number mm (size of
the table).
Hash function:
h(k)=k mod m
where k is the key, and mm is the size of the table (preferably a prime number).
Example:
o Given a table size of 10, hash function h(k)=k mod 10
2. Folding Method:
o In this method, the key is divided into several parts, which are then added together to produce the
hash value.
Hash function:
o Split the key into equal-sized parts, then sum the parts and take modulo mm.
Example:
o Given key 123456, split it into parts: 12, 34, 56.
o In this method, the key is squared, and the middle digits of the result are extracted as the hash
value.
Hash function:
h(k)=middle digits of k2
Example:
o For key 23, square it: 232=529.
1. Deterministic:
o The same input should always produce the same hash value. This ensures consistency.
2. Uniform Distribution:
o The hash function should distribute the keys uniformly across the available hash values
(buckets). This helps minimize collisions and ensures efficient lookups.
3. Efficient:
o The hash function should be computationally efficient, i.e., it should take constant time,
O(1)O(1), to compute the hash value.
4. Minimize Collisions:
o A collision occurs when two different keys produce the same hash value. A good hash function
minimizes collisions as much as possible. This is particularly important for performance.
5. Easy to Compute:
o The hash function should be simple and fast to compute, especially for large datasets.
6. Avalanche Effect:
o A small change in the input should produce a large, unpredictable change in the hash value. This
property is important for cryptographic hash functions.
7. Sensitive to Input:
o A small change in the input key should produce a significantly different hash value. This ensures
that similar keys don't result in the same hash value.