DSA Answers
DSA Answers
1
02.Pattern Matching
Pattern matching is the process of finding all occurrences
of a smaller sequence (pattern) within a larger sequence (text).
03.C to implement push, pop and display operations for stacks using arrays.
#include<stdio.h>
int stk[10], ch, n, top = -1, item, i;
void push() {
if (top >= n - 1) {
printf("STACK is overflow\n");
} else {
printf("Enter a value to be pushed: ");
scanf("%d", &item);
top++;
stk[top] = item;
printf("Pushed successfully\n");
}
}
void pop() {
if (top == -1) {
printf("Stack is underflow\n");
} else {
printf("The popped element is %d\n", stk[top]);
top--;
}
}
void display() {
if (top == -1) {
printf("STACK is empty\n");
} else {
printf("The elements in STACK are:\n");
for (i = top; i >= 0; i--)
printf("%d\n", stk[i]);
}
}
void main() {
printf("Enter the size of STACK: ");
scanf("%d", &n);
for (;;) {
printf("1.PUSH 2.POP 3.DISPLAY\n");
printf("Enter your choice: ");
scanf("%d", &ch);
switch (ch) {
2
case 1:
push();
break;
case 2:
pop();
break;
case 3:
display();
break;
default:
printf("Invalid choice! Please enter again.\n");
break;
}
}
}
Key Functions
3
05.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
06.Define Binary tree. Explain the representation of a binary tree with a suitable
example.
4
Binary Tree
A binary tree is a structure of nodes where:
● It is either empty, or
● It has a root node and two disjoint subtrees: the left subtree and the right subtree.
Mapping Rules:
● Root node: Stored at a[0]a[0].
● Left child of node at index ii: Stored at 2i+12i + 1.
● Right child of node at index ii: Stored at 2i+22i + 2.
2. Linked Representation
● Each node in the tree is represented as an object with three fields:
1. LeftChild: Points to the left subtree.
2. RightChild: Points to the right subtree.
3. Data: Stores the actual value of the node.
07. Define the Threaded binary tree. Construct Threaded binary for the following elements:
A, B, C, D, E, F, G, H, I
5
8. Define selection tree. Construct min winner tree for the runs of a game given below.
Each run consists of the values of players. Find the first 5 winners
● A selection tree helps find the smallest (or largest) value in a group efficiently.
● It’s a complete binary tree used in tournaments.
● it is also called as tournament tree
Types:
1. Winner Tree: Each node stores the smaller value of its two children, and the root holds the smallest value.
2. Loser Tree: Tracks the second smallest/largest values.
6
9.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.
7
10.Construct a binary tree from the Post-order and In-order sequence given below
In-order: GDHBAEICF
Post-order: GHDBIEFCA
11.Define Forest. Transform the given forest into a Binary tree and traverse using inorder,
preorder and postorder traversal.
Definition of a Forest
A forest is a collection of one or more disjoint trees.
8
12.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.
Chained Hashing
Advantages
● Easy to implement.
● Efficient for insertion and deletion.
● Handles dynamic data sizes.
● Works with diverse data distributions.
Disadvantages
13.Design an algorithm to traverse a graph using Depth First Search (DFS). Apply DFS for
the graph given below.
1. Step 1: Go to an unvisited adjacent vertex, mark it as visited, display it, and push it onto
the stack.
2. Step 2: If no unvisited adjacent vertex exists, pop the top vertex from the stack.
3. Step3: Continue steps 1 and 2 until the stack is empty.
9
14.Dynamic Hashing
Dynamic hashing is a technique that allows the hash table to expand or shrink as needed when new records are added or existing
records are removed. This flexibility prevents performance issues that arise when a fixed-size hash table becomes too full or too
sparse.
Key Concepts:
How It Works:
1. A hash function is used to directly calculate the exact location (address) of the data in memory.
2. This eliminates the need for an extra directory to point to buckets.
Key Points:
It’s like using a precise address to reach a house directly, instead of first looking it up in a directory.
15.Write recursive C functions for inorder, preorder and postorder traversals of a binary
tree. Also, find all the traversals for the given tree.
10
16.a Develop a C program to implement insertion, deletion and display operations on
Linear queue.
#include <stdio.h>
int q[10], ch, size, front = -1, rear = -1, item, i;
void enqueue() {
if (rear == size - 1) {
printf("Queue Overflow\n");
} else {
if (front == -1) {
front = 0;
}
printf("Insert the element in queue: ");
scanf("%d", &item);
q[++rear] = item; // Fixed rear increment before assignment
}
}
void dequeue() {
if (front == -1 || front > rear) {
printf("Queue Underflow\n");
} else {
printf("Element deleted from queue is: %d\n", q[front]);
front++;
}
}
void display() {
if (front == -1 || front > rear) {
printf("Queue is empty\n");
} else {
printf("Queue is:\n");
for (i = front; i <= rear; i++) {
printf("%d\n", q[i]);
}
}
}
int main() {
printf("Enter the size of the queue: ");
scanf("%d", &size);
while (1) {
printf("1. Insert 2. Delete 3. Display\n");
printf("Enter your choice: ");
scanf("%d", &ch);
switch (ch) {
case 1:
enqueue();
break;
case 2:
dequeue();
break;
case 3:
display();
break;
default:
printf("Invalid choice! Try again.\n");
}
}
return 0;
}
11
17.Write a C program to implement insertion, deletion and display operations on a
circular queue.
#include <stdio.h>
#define SIZE 10
int cq[SIZE], front = -1, rear = -1, item, ch, i;
void enQueue()
{
if (front == (rear + 1) % SIZE)
{
printf("CIRCULAR QUEUE IS OVERFLOW\n");
}
else
{
printf("Enter element:\n");
scanf("%d", &item);
rear = (rear + 1) % SIZE;
cq[rear] = item;
printf("Inserted\n");
}
}
void deQueue()
{
if (front == -1)
{
printf("CIRCULAR QUEUE IS UNDERFLOW\n");
}
else
{
printf("\nDeleted element -> %d\n", cq[front]);
if (front == rear)
front = rear = -1; // Reset the queue
else
front = (front + 1) % SIZE;
}
}
void display()
{
if (front == -1)
{
printf("CIRCULAR QUEUE IS EMPTY\n");
}
else
{
printf("Items are:\n");
for (i = front; i != rear; i = (i + 1) % SIZE)
{
printf("%d\n", cq[i]);
}
printf("%d\n", cq[i]); // Print the last element
}
}
void main()
{
while (1)
{
printf("1. Insert 2. Delete 3. Display 4. Exit\n");
printf("Enter your choice:\n");
scanf("%d", &ch);
switch (ch)
12
{
case 1: enQueue(); break;
case 2: deQueue(); break;
case 3: display(); break;
case 4: return; // Exit the program
default: printf("Invalid choice, try again!\n");
}
}
}
18.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>
#include <string.h>
#include <math.h>
#include <ctype.h>
float compute(char symbol, float op1, float op2) { POSTFIX EXPRESSION
switch (symbol) {
case '+': return op1 + op2;
case '-': return op1 - op2;
case '*': return op1 * op2;
case '/': return op1 / op2;
case '$': // Fallthrough for '^'
case '^': return pow(op1, op2);
default:
printf("Invalid operator: %c\n", symbol);
return 0;
}
}
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'; // Convert character digit to integer
} 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);
}
13
19. 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
poly_pointer padd(poly_pointer a, poly_pointer b) {
poly_pointer c, rear, temp;
int sum;
// Initialize rear and front pointers
rear = (poly_pointer)malloc(sizeof(poly_node));
c = rear;
// Traverse through both polynomial lists
while (a && b) {
switch (COMPARE(a->expon, b->expon)) {
case -1:
/* a->expon < b->expon */
attach(b->coef, b->expon, &rear);
b = b->link;
break;
case 0:
/* a->expon == b->expon */
sum = a->coef + b->coef;
if (sum)
attach(sum, a->expon, &rear);
a = a->link;
b = b->link;
break;
case 1:
/* a->expon > b->expon */
attach(a->coef, a->expon, &rear);
a = a->link;
break;
}
}
// Attach the remaining terms from either polynomial
while (a) {
attach(a->coef, a->expon, &rear);
a = a->link;
}
while (b) {
attach(b->coef, b->expon, &rear);
b = b->link;
}
14
20 Define Sparse matrix. For the given sparse matrix, give the linked list representation:
21..Define the Disjoint set. Consider the tree created by the weighted union function on
the sequence of unions: union(0,1), union(2,3), 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.
15
Disjoint:Disjoint set is a set of which element are not repeated inside the disjoint set
should be unique and should not be repeated
16
22. 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
● It is a collection of ordered elements that provides fast access to the minimum or maximum element.
17
23.Define hashing. Explain different hashing functions with examples. Discuss the
properties of a good hash function.
Definition: Hashing is a process of mapping large data (keys) to smaller, fixed-size values (hash codes) using a
mathematical function (hash function).
● Method: Use the modulus operator to divide the key by the table size mm.
● Formula: H(x)=KEY%mH(x) = \text{KEY} \% m.
● Example:
○ Key: x=23x = 23, Table size: m=10m = 10.
○ H(x)=23%10=3H(x) = 23 \% 10 = 3.
○ The key 2323 is placed at the 3rd location.
● Method: Square the key, extract digits from the middle, and use them as the address.
● Example:
○ Key: 1616.
○ Square: 162=25616^2 = 256.
○ Extract middle digits: 5656 (if 2-digit address is required).
○ Address: 5656.
● Method: Partition the key into equal parts and process them.
(a) Fold-Shifting:
4. Digit Analysis
● Method: Analyze the key's digits statistically and use frequently occurring digits to form the address.
● Example:
○ Key: 98612349861234.
○ Select positions: 3rd3^{rd} and 5th5^{th} digits (6,26, 2).
○ Combine digits: 6262.
○ Reverse the digits: 2626 (final address).
18
19