0% found this document useful (0 votes)
930 views37 pages

DSU Super 25 BY RAJAN SIR - V2V

Uploaded by

prasannagavali84
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)
930 views37 pages

DSU Super 25 BY RAJAN SIR - V2V

Uploaded by

prasannagavali84
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/ 37

`

1. Differentiate between stack and queue


Ans.

2. Convert infix expression into prefix expression or postfix.


Ans.

Free Study Material Buy Ty Diploma Buy Sy Diploma Whatsapp Group for Study Material
`

3. Describe working of linear search with an example.


Ans.
In linear search, search element is compared with each element from the list in a sequence.
Comparison starts with first element from the list and continues till number is found or comparison
reaches to the last element of the list.
As each element is checked with search element, the process of searching requires more time. Time
complexity of linear search is O (n) where n indicates number of elements in list.
Linear search on sorted array:-On sorted array search takes place till element is found or comparison
reaches to an element greater than search element.

Example:- Using array representation Input list 10, 20, 30, 40, 50 and Search element 30, Index =0
Iteration 1

Free Study Material Buy Ty Diploma Buy Sy Diploma Whatsapp Group for Study Material
`

4. Find the position of element 29 using binary search method in an array ‘A’ given below. Show each step.
A={11,5,21,3,29,17,2,43}
Ans.
An array which is given A[]= {11,5,21,3,29,17,2,43} is not in sorted manner, first we need to sort them in
order; So an array will be A[ ]={2,3,5,11,17,21,29,43} and the value to be searched is VAL = 29. The binary
search algorithm will proceed in the following manner.

Free Study Material Buy Ty Diploma Buy Sy Diploma Whatsapp Group for Study Material
`

So, Element 29 is found at 6th location in given array A[]={2,3,5,11,17,21,29,43}.

5.Explain Double Ended Queue with example


Ans.
A Double-Ended Queue (Deque) is a linear data structure that allows elements to be added or removed
from both ends: the front and the rear. It is more flexible than a regular queue, as it can function both as a
queue (FIFO) and a stack (LIFO).
Key Operations:
1. Insert at Front (addFirst): Adds an element to the front of the deque.
2. Insert at Rear (addLast): Adds an element to the rear of the deque.
3. Remove from Front (removeFirst): Removes an element from the front of the deque.
4. Remove from Rear (removeLast): Removes an element from the rear of the deque.
5. Peek Front (getFirst): Retrieves the front element without removing it.
6. Peek Rear (getLast): Retrieves the rear element without removing it.
Example:
Consider a deque with operations:
1. Initial Deque: []
2. Insert 10 at Rear: [10]
3. Insert 20 at Front: [20, 10]
4. Insert 30 at Rear: [20, 10, 30]
5. Remove from Front: [10, 30]
6. Remove from Rear: [10]
Use Cases:

Free Study Material Buy Ty Diploma Buy Sy Diploma Whatsapp Group for Study Material
`

• Task Scheduling: Where


tasks can be added or removed from both ends based on priority.
• Palindrome Checking: Useful for checking if a string reads the same forwards and backwards.
Summary:
A Deque is a versatile data structure that supports insertion and removal of elements from both ends,
making it suitable for applications that require operations at both ends of the collection.

6. Describe working of bubble sort , insertion , selection with example.


Ans.

1. Bubble Sort

Working:

• Bubble sort compares adjacent elements in an array and swaps them if they are in the wrong order.
• This process is repeated for each element, and after each complete pass, the largest unsorted
element "bubbles" up to its correct position.
• The algorithm continues until no more swaps are needed, indicating that the array is sorted.

Steps:

1. Compare the first two elements. If the first is greater than the second, swap them.
2. Move to the next pair and repeat until you reach the end of the array.
3. After each full pass through the array, the largest element gets placed in its correct position.
4. Repeat the process for the remaining unsorted part of the array until the entire array is sorted.

Example (Sorting the array [5, 3, 8, 4, 2]):

1. First pass:
o Compare 5 and 3 → Swap them → [3, 5, 8, 4, 2]
o Compare 5 and 8 → No swap → [3, 5, 8, 4, 2]
o Compare 8 and 4 → Swap them → [3, 5, 4, 8, 2]
o Compare 8 and 2 → Swap them → [3, 5, 4, 2, 8]
o After the first pass, 8 is in its correct position.
2. Second pass:
o Compare 3 and 5 → No swap → [3, 5, 4, 2, 8]
o Compare 5 and 4 → Swap them → [3, 4, 5, 2, 8]
o Compare 5 and 2 → Swap them → [3, 4, 2, 5, 8]
o After the second pass, 5 is in its correct position.
3. Third pass:
o Compare 3 and 4 → No swap → [3, 4, 2, 5, 8]
o Compare 4 and 2 → Swap them → [3, 2, 4, 5, 8]
o After the third pass, 4 is in its correct position.
4. Fourth pass:
o Compare 3 and 2 → Swap them → [2, 3, 4, 5, 8]
o Now the array is sorted.

Time Complexity:

• Best case: O(n)O(n)O(n) (if the array is already sorted)


• Average and worst case: O(n2)O(n^2)O(n2)

2. Insertion Sort
Free Study Material Buy Ty Diploma Buy Sy Diploma Whatsapp Group for Study Material
`

Working:

• Insertion sort builds the final sorted array one element at a time.
• It works by picking elements from the unsorted part of the array and inserting them into the correct
position in the sorted part of the array.
• It shifts elements in the sorted part to the right to make space for the new element.

Steps:

1. Start with the second element (since the first is considered sorted).
2. Compare the current element with the elements in the sorted part.
3. Move elements that are greater than the current element to one position ahead.
4. Insert the current element in the correct position.
5. Repeat until the entire array is sorted.

Example (Sorting the array [5, 3, 8, 4, 2]):

1. Insert 3: Compare with 5 → Move 5 to the right → [3, 5, 8, 4, 2]


2. Insert 8: No change as 8 is greater than 5 → [3, 5, 8, 4, 2]
3. Insert 4: Compare with 8 → Move 8 → Compare with 5 → Move 5 → Insert 4 → [3, 4, 5, 8, 2]
4. Insert 2: Compare with 8, 5, 4, and 3 → Move all elements → Insert 2 → [2, 3, 4, 5, 8]

Time Complexity:

• Best case: O(n)O(n)O(n) (if the array is already sorted)


• Average and worst case: O(n2)O(n^2)O(n2)

3. Selection Sort

Working:

• Selection sort works by selecting the smallest (or largest) element from the unsorted part of the
array and swapping it with the first unsorted element.
• It repeats this process until the entire array is sorted.

Steps:

1. Find the smallest (or largest) element in the unsorted part of the array.
2. Swap it with the first unsorted element.
3. Move the boundary of the sorted part of the array to the right and repeat until the array is sorted.

Example (Sorting the array [5, 3, 8, 4, 2]):

1. First pass: Find the smallest element (2) and swap it with the first element → [2, 3, 8, 4, 5]
2. Second pass: Find the smallest element in the remaining unsorted part ([3, 8, 4, 5]), which is 3 →
No swap → [2, 3, 8, 4, 5]
3. Third pass: Find the smallest element in the remaining unsorted part ([8, 4, 5]), which is 4 → Swap
it with 8 → [2, 3, 4, 8, 5]
4. Fourth pass: Find the smallest element in the remaining unsorted part ([8, 5]), which is 5 → Swap it
with 8 → [2, 3, 4, 5, 8]
5. Now the array is sorted.

Free Study Material Buy Ty Diploma Buy Sy Diploma Whatsapp Group for Study Material
`

7. Construct a binary search tree for following elements: 30,100,90,15,2,25,36,72,78,10 show each step of
construction of BST
Ans.
Stepwise construction of Binary search tree for following elements: 30,100,90,15,2,25,36,72,78,10 is as
follows:

Free Study Material Buy Ty Diploma Buy Sy Diploma Whatsapp Group for Study Material
`

Free Study Material Buy Ty Diploma Buy Sy Diploma Whatsapp Group for Study Material
`

8. Describe circular linked list with suitable diagram. Also state advantage of circular linked list over linear
linked list.
Ans.
Circular Linked List A circular linked list is a variation of linked list in which the last element is linked to the first
element. This forms a circular loop.

A circular linked list can be either singly linked or doubly linked. for singly linked list, next pointer of last item
points to the first item In doubly linked list, prev pointer of first item points to last item as well. We declare
the structure for the circular linked list in the same way as follows:
Struct node
{
int data;
Struct node *next; };
Typedef struct node *Node;
Node *start = null;
Node *last = null;
For example:

Advantages of Circular Linked Lists:


1) Any node can be a starting point. We can traverse the whole list by starting from any point. We just need to stop
when the first visited node is visited again.
2) Useful for implementation of queue. Unlike this implementation, we don’t need to maintain two pointers for front
and rear if we use circular linked list. We can maintain a pointer to the last inserted node and front can always be
obtained as next of last.
3) Circular lists are useful in applications to repeatedly go around the list. For example, when multiple applications
are running on a PC, it is common for the operating system to put the running applications on a list and then to cycle
through them, giving each of them a slice of time to execute, and then making them wait while the CPU is given to
another application. It is convenient for the operating system to use a circular list so that when it reaches the end of
the list it can cycle around to the front of the list.
4) Circular Doubly Linked Lists are used for implementation of advanced data structures like Fibonacci Heap.

9. Write a program to traverse a linked list.


Ans.

Free Study Material Buy Ty Diploma Buy Sy Diploma Whatsapp Group for Study Material
`

Free Study Material Buy Ty Diploma Buy Sy Diploma Whatsapp Group for Study Material
`

10. Write C program for performing following operations on array: insertion, display.
Ans.
#include<stdio.h>
#include<conio.h>
void main()
{
inta[10],x,i,n,pos;
clrscr();
printf(“Enter the number of array element\n”);
scanf(“%d”,&n);
printf(“Enter the array with %d element\n”, n);
for(i=0;i<n;i++)
scanf(“%d”,&a[i]);
printf(“Enter the key value and its position\n”);
scanf(“%d%d” ,&x,&pos);
for(i=n; i >= pos; i--)
{
a[i]=a[i-1];
}
a[pos-1]=x;
printf(“Array element\n “);
for(i=0;i<n+1;i++)
printf(“%d\t”,a[i]);
getch();
}

11. Differentiate between binary search and sequential search.


Ans.

Free Study Material Buy Ty Diploma Buy Sy Diploma Whatsapp Group for Study Material
`

12. Evaluate the following prefix expression: - * + 4 3 2 5 and 5, 6, 2, +, *, 12, 4, /, - show diagrammatically
Ans.

Free Study Material Buy Ty Diploma Buy Sy Diploma Whatsapp Group for Study Material
`

Result of above prefix expression evaluation – 37

13. Sort the given number in ascending order using Radix sort: 348, 14, 641, 3851, 74.
Ans.

Free Study Material Buy Ty Diploma Buy Sy Diploma Whatsapp Group for Study Material
`

Free Study Material Buy Ty Diploma Buy Sy Diploma Whatsapp Group for Study Material
`

14. Write an algorithm to delete and insert a node from the beginning and end of a circular linked list.
Ans.
Delete at Beginning (Circular Queue):

Step 1:
IF FRONT = -1
◦ Write "UNDERFLOW"
◦ Goto Step 5
◦ [END of IF]

Step 2:
SET VAL = QUEUE[FRONT]

Step 3:
IF FRONT == REAR
◦ SET FRONT = REAR = -1
◦ ELSE
◦ IF FRONT = MAX - 1
◦ SET FRONT = 0
◦ ELSE
◦ SET FRONT = FRONT + 1
◦ [END of IF]
◦ [END of IF]

Step 4:
Write "Deleted Element = VAL"

Step 5:
EXIT

---

Delete at End (Circular Queue):

Step 1:
IF FRONT = -1
◦ Write "UNDERFLOW"
◦ Goto Step 5
◦ [END of IF]

Step 2:
SET VAL = QUEUE[REAR]

Step 3:
IF FRONT == REAR
◦ SET FRONT = REAR = -1
◦ ELSE
◦ IF REAR = 0
◦ SET REAR = MAX - 1
◦ ELSE
◦ SET REAR = REAR - 1
◦ [END of IF]
◦ [END of IF]

Free Study Material Buy Ty Diploma Buy Sy Diploma Whatsapp Group for Study Material
`

Step 4:
Write "Deleted Element = VAL"

Step 5:
EXIT
Insert at Beginning (Circular Queue):
Step 1:
IF (FRONT == 0 AND REAR == MAX - 1) OR (FRONT = REAR + 1)
◦ Write "OVERFLOW"
◦ Goto Step 6
◦ [END of IF]

Step 2:
IF FRONT = -1
◦ SET FRONT = REAR = 0
◦ Goto Step 5
◦ [END of IF]

Step 3:
IF FRONT = 0
◦ SET FRONT = MAX - 1
◦ ELSE
◦ SET FRONT = FRONT - 1
◦ [END of IF]

Step 4:
SET QUEUE[FRONT] = VAL

Step 5:
Write "Inserted Element = VAL"

Step 6:
EXIT

---

Insert at End (Circular Queue):

Step 1:
IF (FRONT == 0 AND REAR == MAX - 1) OR (FRONT = REAR + 1)
◦ Write "OVERFLOW"
◦ Goto Step 6
◦ [END of IF]

Step 2:
IF FRONT = -1
◦ SET FRONT = REAR = 0
◦ Goto Step 5
◦ [END of IF]

Step 3:
IF REAR = MAX - 1
◦ SET REAR = 0
◦ ELSE
◦ SET REAR = REAR + 1
◦ [END of IF]
Free Study Material Buy Ty Diploma Buy Sy Diploma Whatsapp Group for Study Material
`

Step 4:
SET QUEUE[REAR] = VAL

Step 5:
Write "Inserted Element = VAL"

Step 6:
EXIT

15. Draw an expression tree for the following expression: (a-2b+5e) 2 * (4d=6e) 5
Ans.

16.Explain stack & Queue implementation using array & representation using linked list
Ans.

1. Stack Implementation Using Array

• Concept: A stack follows the LIFO (Last In, First Out) principle. The last element added is the first
one to be removed. We use an array to store elements, and an integer top tracks the index of the last
element.

Operations:

• Push: Adds an element to the stack.


• Pop: Removes the top element from the stack.
• Peek: Returns the top element without removing it.
• isEmpty: Checks if the stack is empty.
• isFull: Checks if the stack is full.

Code:

#include <stdio.h>
#define MAX 10
Free Study Material Buy Ty Diploma Buy Sy Diploma Whatsapp Group for Study Material
`

int stack[MAX];
int top = -1;

// Push operation
void push(int data) {
if (top < MAX - 1) {
stack[++top] = data;
} else {
printf("Stack Overflow\n");
}
}

// Pop operation
int pop() {
if (top == -1) {
printf("Stack Underflow\n");
return -1;
}
return stack[top--];
}

// Peek operation
int peek() {
if (top == -1) {
return -1; // Stack is empty
}
return stack[top];
}

2. Stack Implementation Using Linked List

• Concept: A linked list-based stack uses nodes where each node has data and a pointer to the next
node. The top of the stack is the head of the linked list.

Operations:

• Push: Creates a new node and adds it at the top.


• Pop: Removes the top node and returns its value.
• Peek: Returns the value of the top node.
• isEmpty: Checks if the stack is empty.

Code:

#include <stdio.h>
#include <stdlib.h>

struct Node {
int data;
struct Node* next;
};

struct Node* top = NULL;

// Push operation
void push(int data) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = data;
newNode->next = top;

Free Study Material Buy Ty Diploma Buy Sy Diploma Whatsapp Group for Study Material
`

top = newNode;
}

// Pop operation
int pop() {
if (top == NULL) {
printf("Stack Underflow\n");
return -1;
}
struct Node* temp = top;
int data = temp->data;
top = top->next;
free(temp);
return data;
}

// Peek operation
int peek() {
if (top == NULL) {
return -1; // Stack is empty
}
return top->data;
}

3. Queue Implementation Using Array

• Concept: A queue follows the FIFO (First In, First Out) principle. The first element added is the
first one to be removed. We use an array with two pointers: front and rear.

Operations:

• Enqueue: Adds an element at the rear.


• Dequeue: Removes the element from the front.
• Front: Returns the front element without removing it.
• isEmpty: Checks if the queue is empty.
• isFull: Checks if the queue is full.

Code:

#include <stdio.h>
#define MAX 10

int queue[MAX];
int front = -1, rear = -1;

// Enqueue operation
void enqueue(int data) {
if ((rear + 1) % MAX == front) {
printf("Queue Overflow\n");
} else {
if (front == -1) front = 0;
rear = (rear + 1) % MAX;
queue[rear] = data;
}
}

// Dequeue operation
int dequeue() {
Free Study Material Buy Ty Diploma Buy Sy Diploma Whatsapp Group for Study Material
`

if (front == -1) {
printf("Queue Underflow\n");
return -1;
}
int data = queue[front];
if (front == rear) {
front = rear = -1;
} else {
front = (front + 1) % MAX;
}
return data;
}

// Front operation
int frontElement() {
if (front == -1) {
return -1; // Queue is empty
}
return queue[front];
}

4. Queue Implementation Using Linked List

• Concept: A linked list-based queue uses nodes, where each node contains data and a pointer to the
next node. The front pointer points to the first node and the rear pointer to the last node.

Operations:

• Enqueue: Adds a new node at the rear.


• Dequeue: Removes the front node.
• Front: Returns the data of the front node.
• isEmpty: Checks if the queue is empty.

Code:

#include <stdio.h>
#include <stdlib.h>

struct Node {
int data;
struct Node* next;
};

struct Node* front = NULL;


struct Node* rear = NULL;

// Enqueue operation
void enqueue(int data) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = data;
newNode->next = NULL;

if (rear == NULL) {
front = rear = newNode;
} else {
rear->next = newNode;
rear = newNode;
}
Free Study Material Buy Ty Diploma Buy Sy Diploma Whatsapp Group for Study Material
`

// Dequeue operation
int dequeue() {
if (front == NULL) {
printf("Queue Underflow\n");
return -1;
}
struct Node* temp = front;
int data = temp->data;
front = front->next;
if (front == NULL) rear = NULL; // Queue is empty
free(temp);
return data;
}

// Front operation
int frontElement() {
if (front == NULL) {
return -1; // Queue is empty
}
return front->data;
}

Summary:

Operation Stack (Array) Stack (Linked List) Queue (Array) Queue (Linked List)
Insert Push (top++) Push (new node) Enqueue (rear++) Enqueue (new node)
Remove Pop (top--) Pop (remove node) Dequeue (front++) Dequeue (remove node)
Peek/Front Peek (top) Peek (top data) Front (front data) Front (front data)
Empty isEmpty (top == isEmpty (front ==
isEmpty (top == -1) isEmpty (front == -1)
Check NULL) NULL)
isFull (top == MAX- isFull (rear == MAX-
Full Check Not applicable Not applicable
1) 1)

17. Write an algorithm to insert an element at the beginning and end of linked list
Ans.
Ans
Algorithm to insert an element at the be
ginning of linked list:
1. Start
2. Create the node pointer *temp Struct node * temp
3. Allocate address to temp using malloc
temp = malloc(sizeof(struct node));
4. Check whether temp is null, if null then
Display “Overflow”
Else
temp
--> info=data
Free Study Material Buy Ty Diploma Buy Sy Diploma Whatsapp Group for Study Material
`

te
mp --> next=start
5. Start=temp
6. stop

Algorithm to insert an element at the end of linked list:


1. Start
2. Create two node pointers *temp, *q struct node * temp, *q;
3. q= start
4. Allocate address to temp using malloc
temp = malloc(sizeof
(struct node));
5. Check whether temp is null, if null
then
Display “Overflow”
else
temp
--> info=data
temp
--> next=null
6. While(q
-->next!=
q= q
--> next
7. q
-->next= temp
8. stop

18. Write an algorithm for performing push and pop operations on stack.
Ans.
Push algorithm: - Max is maximum size of stack.
Step 1: [Check for stack full/ overflow]
If stack_top is equal to max-1 then
Display output as “Stack Overflow” and return to calling function
Otherwise
Go to step 2
Step 2: [Increment stack_top] Increment stack top pointer by one.
stack_top=stack_top +1;
Step 3: [Insert element] stack [stack_top] = item;
Step 4: return to calling function
Step 5: Stop

Pop algorithm: - Max is maximum size of stack.


Step 1: [ChecIf stack_top is equal to -1 then
Display output as “Stack Underflow” and return to calling function
Otherwise
Go to step 2
Step 2: [delete element] stack [stack_top] = item;
Step 3: [Decrement stack_top] Decrement stack top pointer by one.
stack_top=stack_top -1;
Step 4: return to calling function. k for stack empty/underflow]
Step 5: Stop
Free Study Material Buy Ty Diploma Buy Sy Diploma Whatsapp Group for Study Material
`

19. Elaborate the steps for performing selection sort for given elements of array. A={37,12,4,90,49,23,-19}
Ans.

Free Study Material Buy Ty Diploma Buy Sy Diploma Whatsapp Group for Study Material
`

20. Write an algorithm to search a particular node in the given linked list.
Ans.
Assumption: Node contains two fields: info and next pointer start pointer : Header node
that stores address of first node
step 1: start
step 2: Declare variable no, flag and pointer temp
step 3: Input search element
step 4: Initialize pointer temp with the
address from start pointer.
( temp=start), flag with 0
step 5: Repeat step 6
till
temp != NULL
step 6: compare: temp
-->info = no then set flag=1
and go to step 7
otherwise increment pointer temp and
go to step5
step 7: compare: flag=1 then display "
Node found"
otherwise
display "node not found"
step 8: stop

Free Study Material Buy Ty Diploma Buy Sy Diploma Whatsapp Group for Study Material
`

21. Create a singly linked list using data fields 90, 25, 46, 39, 56. Search a node 40 from the SLL and show
the procedure step-by-step with the help of a diagram from start to end
Ans.
To Search a data field in singly linked list, need to start searching the data field from first node of singly
linked list. ORIGINAL LIST:

SEARCHING A NODE STEP 1:


Compare 40 with 90
40!=90

Free Study Material Buy Ty Diploma Buy Sy Diploma Whatsapp Group for Study Material
`

22. Write an algorithm to count the number of nodes in a singly linked list
Ans.
Let start is pointer variable which always stores address of first node in single linked list.
If single linked list is empty then start will point to NULL.
q is pointer variable used to store address of nodes in single linked list.
Step 1: Start
Step
2: [Assign starting address of single linked list to pointer q]
q=start

Free Study Material Buy Ty Diploma Buy Sy Diploma Whatsapp Group for Study Material
`

Step 3: [ Initially set count of nodes in Linked


list as zero ]
count=0
Step 4: [ Check if Linked list empty or not]
if start==NULL
Display “Empty Linked List”
go to step 6.
St
ep 5: [ Count number of nodes in single linked list ]
while q!=NULL count++ and
q=q
-->next;
Step 6: Display count (total number of nodes in single linked list)
Step 7: stop
4.
Sort the following numbers in ascending order using Bubble sort.
Ans: Given
numbers: 29, 35, 3, 8, 11, 15, 56, 12, 1, 4, 85, 5 & write the output after each
interaction.
Pass 1
Enter no of elements :12
Enter array elements :29 35 3 8 11 15 56 12 1 4 85 5

Unsorted Data: 29 35 3 8 11 15 56 12 1 4 85 5

Free Study Material Buy Ty Diploma Buy Sy Diploma Whatsapp Group for Study Material
`

23. Traverse a tree in inorder preorder and post order


Ans.

Inorder Traversal: Q,E,F,R,D,H,B,A,I,J,K,C,L,P

Free Study Material Buy Ty Diploma Buy Sy Diploma Whatsapp Group for Study Material
`

Preorder Traversal:
A,B,D,E,Q,F,R,H,C,I,J,K,L,P
Postorder Traversal: Q,R,F,E,H,D,B,K,J,I,P,L,C,A

24. Compare Linked List and Array (any 4 points)


Ans.

Free Study Material Buy Ty Diploma Buy Sy Diploma Whatsapp Group for Study Material
`

25. Explain time and space complexity with an example.


Ans.
Time Complexity: Time complexity of program or algorithm is amount of
computer time that it needs to run to completion. To measure time
complexity of an algorithm we concentrate on developing only frequency
count for key statements.
Example:
#include<stdio.h>
void main ()
{
int i, n, sum, x;
sum=0;
printf(“\n Enter no of data to be added”);
scanf(“% d”, &n);
for(i=0 ; i<n; i++)

Free Study Material Buy Ty Diploma Buy Sy Diploma Whatsapp Group for Study Material
`

Space Complexity: Total amount of computer memory required by an algorithm to complete its execution is
called as space complexity of that algorithm. Whena program is under execution it uses the computer
memory for THREE reasons.
They are as follows...
Instruction Space: It is the amount of memory used to store compiled version of instructions.
Environmental Stack: It is the amount of memory used to store information of partially executed functions
at the time of function call.
Data Space: It is the amount of memory used to store all the variables and constants. If the amount of
space required by an algorithm is increased with the increase of input value, then that space complexity is
said to be Linear Space Complexity.
Example:
int sum(int A[ ], int n)
{
int sum = 0, i;
for(i = 0; i < n; i++)
sum = sum + A[i];
return sum;
}
In the above piece of code it requires
'n*2' bytes of memory to store array variable
'a[ ]' 2 bytes of memory for integer parameter
'n' 4 bytes of memory for local integer variables 'sum' and 'i' (2 bytes each)
2 bytes of memory for return value.
Thatmeans, totally it requires '2n+8' bytes of memory to complete its execution. Here, the total amount of
memory required depends on the value of 'n'. As 'n' value increases the space required also increases
proportionately. This type of space complexity is said to be Linear Space Complexity.

26. Explain circular Queue with it advantage and need


Ans.
A Circular Queue is a linear data structure that follows the FIFO (First In, First Out) principle but differs
from a regular queue in its way of handling the overflow condition. In a regular queue, when the queue is
full, no more elements can be added. However, in a circular queue, the last position of the queue is
connected back to the first position, forming a circle. This allows the queue to efficiently use space by
reusing the vacant positions created when elements are dequeued.

Free Study Material Buy Ty Diploma Buy Sy Diploma Whatsapp Group for Study Material
`

Advantages of Circular Queue:


1. Efficient Space Utilization: Unlike a regular queue, a circular queue allows the reuse of space that
becomes available once elements are dequeued, leading to better space utilization.
2. No Wasted Space: It ensures that there is no unused space, even if there are empty spots in the
queue.
Need of Circular Queue:
1. Fixed-Size Buffer: It is especially useful in scenarios like CPU scheduling or memory management
where a fixed-size queue is required, and elements are processed in a continuous loop.
2. Queue Overflow Prevention: It prevents overflow from happening prematurely as long as there is
available space in the queue.

27. Explain Priority queue with example


Ans.

A Priority Queue is a special type of queue where each element is associated with a priority. Elements are
dequeued in order of their priority, rather than the order they were added. In other words, the element with
the highest priority is always dequeued first, regardless of its position in the queue. A priority queue can be
implemented using various data structures such as a heap, array, or linked list.

Key Characteristics:

• Priority-Based Dequeuing: Elements with higher priority are dequeued first.


• Not FIFO: Unlike a regular queue, a priority queue does not follow the First-In-First-Out principle.

Types of Priority Queue:

• Max Priority Queue: The element with the highest priority is dequeued first.
• Min Priority Queue: The element with the lowest priority is dequeued first.

Example:

Consider a scenario where tasks are processed based on their priority in a max priority queue. Assume we
have the following tasks with priorities:

Task Priority
Task A 2
Task B 5
Task C 3
Task D 1

Steps in a Max Priority Queue:

1. Enqueueing Tasks:
o When tasks are added to the priority queue, they are stored along with their priorities.
o The queue initially contains:

arduino
Copy code
Task A (Priority 2), Task B (Priority 5), Task C (Priority 3), Task D
(Priority 1)

Free Study Material Buy Ty Diploma Buy Sy Diploma Whatsapp Group for Study Material
`

2. Dequeuing Tasks:
o The task with the highest priority (Task B, Priority 5) is dequeued first.
o After Task B is dequeued, the queue will look like:

arduino
Copy code
Task C (Priority 3), Task A (Priority 2), Task D (Priority 1)

o Next, Task C (Priority 3) is dequeued.


o Then Task A (Priority 2), and finally Task D (Priority 1).

The order of execution would be:

arduino
Copy code
Task B → Task C → Task A → Task D

Use Cases of Priority Queue:

1. Task Scheduling: In operating systems, tasks or processes can be assigned priorities and processed
in order of their priority.
2. Dijkstra's Algorithm: Used in finding the shortest path in a graph where each node is processed
based on its priority (distance).
3. Huffman Coding: Used in data compression algorithms where characters are assigned priorities
based on frequency.

Summary:

A priority queue ensures that elements are processed according to their priority rather than the order they
were added, making it an essential data structure for handling tasks that require urgent or prioritized
processing.

28. Write a program to implement insert and delete operation of Queue


Ans.
#include <stdio.h>
#include <stdlib.h>

#define MAX 5 // Define the maximum size of the queue

// Define the Queue structure


struct Queue {
int arr[MAX]; // Array to store the queue elements
int front; // Index of the front element
int rear; // Index of the rear element
};

// Function to initialize the queue


void initialize(struct Queue* q) {
q->front = -1; // Queue is empty initially
q->rear = -1; // Queue is empty initially
}

// Function to check if the queue is full


int isFull(struct Queue* q) {
Free Study Material Buy Ty Diploma Buy Sy Diploma Whatsapp Group for Study Material
`

if (q->rear == MAX - 1) {
return 1; // Queue is full
}
return 0; // Queue is not full
}

// Function to check if the queue is empty


int isEmpty(struct Queue* q) {
if (q->front == -1) {
return 1; // Queue is empty
}
return 0; // Queue is not empty
}

// Function to insert (enqueue) an element into the queue


void enqueue(struct Queue* q, int value) {
if (isFull(q)) {
printf("Queue is full. Cannot insert %d\n", value);
return;
}
if (q->front == -1) {
q->front = 0; // Set front to 0 when first element is inserted
}
q->rear++; // Move the rear to the next position
q->arr[q->rear] = value; // Insert the element
printf("Inserted %d into the queue\n", value);
}

// Function to delete (dequeue) an element from the queue


int dequeue(struct Queue* q) {
if (isEmpty(q)) {
printf("Queue is empty. Cannot dequeue\n");
return -1; // Return -1 if the queue is empty
}
int deletedValue = q->arr[q->front]; // Get the front element
if (q->front == q->rear) {
q->front = q->rear = -1; // Reset the queue to empty state
} else {
q->front++; // Move front to the next element
}
return deletedValue; // Return the deleted value
}

// Function to display the elements of the queue


void display(struct Queue* q) {
if (isEmpty(q)) {
printf("Queue is empty\n");
return;
}
printf("Queue elements: ");
for (int i = q->front; i <= q->rear; i++) {
printf("%d ", q->arr[i]);
}
printf("\n");
}

Free Study Material Buy Ty Diploma Buy Sy Diploma Whatsapp Group for Study Material
`

int main() {
struct Queue q;
initialize(&q);

// Test the enqueue and dequeue operations


enqueue(&q, 10);
enqueue(&q, 20);
enqueue(&q, 30);
enqueue(&q, 40);
enqueue(&q, 50);
display(&q);

// Try to insert an element when the queue is full


enqueue(&q, 60);

// Dequeue some elements


printf("Dequeued: %d\n", dequeue(&q));
printf("Dequeued: %d\n", dequeue(&q));
display(&q);

// Try to dequeue when the queue is not empty


printf("Dequeued: %d\n", dequeue(&q));
display(&q);

// Dequeue all elements


dequeue(&q);
dequeue(&q);
display(&q);

return 0;
}

29. Explain Recursion with Factorial Program


Ans.
Recursion is a programming technique where a function calls itself to solve a problem by breaking it down
into smaller sub-problems. Each recursive function has:
1. Base Case: A condition to stop the recursion.
2. Recursive Case: The part where the function calls itself with a smaller or simpler version of the
problem.
Factorial Program Using Recursion:
The factorial of a number n (denoted as n!) is the product of all positive integers less than or equal to n. It
is defined as:
• n! = n * (n-1) * (n-2) * ... * 1
• Base case: 0! = 1
Recursive Formula:
• For n > 0, n! = n * (n-1)!
• Base case: 0! = 1
C Program to Compute Factorial Using Recursion:

#include <stdio.h>

// Function to calculate factorial using recursion


int factorial(int n) {
if (n == 0) return 1; // Base case: 0! = 1
return n * factorial(n - 1); // Recursive case: n! = n * (n-1)!
}
Free Study Material Buy Ty Diploma Buy Sy Diploma Whatsapp Group for Study Material
`

int main() {
int number;
printf("Enter a number: ");
scanf("%d", &number);
printf("Factorial of %d is %d\n", number, factorial(number));
return 0;
}
Explanation:
• Base Case: When n == 0, the function returns 1 (since 0! = 1).
• Recursive Case: For n > 0, the function calls itself with n-1 and multiplies it by n.
• Example: For factorial(5), the function will compute 5 * 4 * 3 * 2 * 1.

Example Output:
mathematica
Copy code
Enter a number: 5
Factorial of 5 is 120

30. Define and Explain term


• Leaf Node
• Root Node
• Path
• Ancestor
• Descendants
• Level of Node
• Application of Queue
• Algorithm
• Queue Operation
• Stack Operation
• Link List Operation
• Array Operation
• Data Structure Operation
• Overflow of Stack
• Underflow of Queue
Ans.
1. Leaf Node: A leaf node is a node in a tree that has no children.
2. Root Node: The root node is the topmost node in a tree, from which all other nodes originate.
3. Path: A path is a sequence of nodes connected by edges in a tree or graph.
4. Ancestor: An ancestor of a node is any node on the path from the root to that node.
5. Descendants: Descendants are all the nodes that can be reached by traversing down from a given
node.
6. Level of Node: The level of a node is the number of edges from the root to that node.
7. Application of Queue: A queue is used in scenarios like task scheduling, BFS in graphs, and
request handling.
8. Algorithm: An algorithm is a set of step-by-step instructions designed to solve a problem or perform
a task.
9. Queue Operation: Queue operations include enqueue (insertion), dequeue (removal), and peek
(viewing front element).
10. Stack Operation: Stack operations include push (insertion), pop (removal), and peek (viewing top
element).
11. Linked List Operation: Linked list operations include insertion, deletion, traversal, and search of
nodes.
12. Array Operation: Array operations include insertion, deletion, traversal, and search of elements.
Free Study Material Buy Ty Diploma Buy Sy Diploma Whatsapp Group for Study Material
`

13. Data Structure Operation:


Data structure operations involve manipulating the elements of structures like arrays, stacks,
queues, etc.
14. Overflow of Stack: Stack overflow occurs when an attempt is made to push an element onto a full
stack.
15. Underflow of Queue: Queue underflow occurs when an attempt is made to dequeue from an empty
queue.

Free Study Material Buy Ty Diploma Buy Sy Diploma Whatsapp Group for Study Material

You might also like