0% found this document useful (0 votes)
5 views52 pages

Algo

Uploaded by

01 Aditya SG
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
5 views52 pages

Algo

Uploaded by

01 Aditya SG
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 52

QI.

Given an array of integers, write an algorithm and a program to left rotate the array by specific
number of elements.*/

Algorithm for reverse Function

Step1: START
Step2: Input: An array arr, starting index start, and ending index end.
Step3: While start is less than end:
Step4: Swap the elements at start and end.
Step5: Swap the elements at start and end.
Step6: Increment start by 1
Step7: Decrement end by 1.
Step8: Output: The array arr with the elements between start and end reversed.
Step9: STOP

Algorithm for left_Rotate Function

Step10: START
Step11: Input: An array arr of size n, and the number of positions k to rotate.
Step12: Calculate k as k % n to handle cases where k is greater than n.
Step13: Reverse the first k elements of the array.
Step14: Reverse the remaining n-k elements of the array.
Step15: Reverse the entire array.
Step16: Output: The array arr rotated to the left by k positions.
Step17: STOP

Algorithm for main Function


Step11: START
Step10: Input: Number of test cases T.
Step11: For each test case:Read the size of the array n.
Step10: Read the elements of the array arr.
Step11: Read the number of positions k to rotate.
Step10: Call left_Rotate to rotate the array arr by k positions.
Step11: Print the rotated array.
Step10: Output: The left-rotated array for each test case.
Step11: STOP

ADITYA SUMAN GAGORIYA 20 K1


Q2. */Given an unsorted array of integers and two numbers a and b. Design an algorithm and write a
program to find minimum distance between a and b in this array. Minimum distance between any two
numbers a and b present in array is the minimum difference between their indices.*/

Algorithm for Minimum_Distance Function

Step1: START
Step2: Input: An array arr, size n, elements a and b.
Step3: Initialize last_pos_a and last_pos_b to -1, and dis to n.
Step4: For each element in the array: If the element is equal to a: Update last_pos_a to the current index.
Step5: If last_pos_b is not -1: Calculate the distance between last_pos_a and last_pos_b.
Step6: If the calculated distance is less than dis: Update dis to the calculated distance.
Step7: If the element is equal to b: Update last_pos_b to the current index.
Step8: If last_pos_a is not -1: Calculate the distance between last_pos_b and last_pos_a.
Step9: If the calculated distance is less than dis: Update dis to the calculated distance.
Step10: Output: Return dis if it is not equal to n, otherwise return -1.
Step11: STOP

Algorithm for main Function

Step1: START
Step2: Input: Number of test cases T.
Step3: For each test case:
Step4: Read the size of the array n.
Step5: Read the elements of the array arr.
Step6: Read the elements a and b for finding the distance.
Step7: Call Minimum_Distance to find the minimum distance between a and b.
Step8: If the distance is not -1: Print the minimum distance between a and b.
Step9: Else: Print that either a or b is not present in the array.
Step10: Output: The minimum distance between a and b for each test case.
Step11: STOP

ADITYA SUMAN GAGORIYA 20 K1


Q3. Given an array of nonnegative integers, where all numbers occur even number of times except
one number which occurs odd number of times. Write an algorithm and a program to find this
number. (Time complexity = O(n)) */

Algorithm for odd Function

Step1: START
Step2: Input: An array arr and its size n.
Step3: Initialize res to 0.
Step4: For each element in the array: Perform XOR operation between res and the current element.
Update res with the result of the XOR operation.
Step5: Output: Return res, which is the element that occurs an odd number of times.
Step6: STOP

Algorithm for main Function

Step1: START
Step2: Input: Number of test cases T.
Step3: For each test case:
Read the number of elements in the array n.
Read the elements of the array arr.
Call odd to find the element that occurs an odd number of times.
Step4: If the returned number is 0: Print "No element occurs an odd number of times."
Step5: Else:Print the number that occurred an odd number of times.
Step6: STOP

ADITYA SUMAN GAGORIYA 20 K1


Q4. Given a matrix of size n X n, where every row and every column is sorted in increasing order.Write
an algorithm and a program to find whether the given key element is present in the matrix or not. (Linear
time complexity) */

Algorithm for search_element Function


1. START
2. Input: A matrix arr of size n x n, an integer key, and the size n.
3. Initialize i to 0 and j to n-1.
4. While i < n and j >= 0:

 If arr[i][j] is equal to key:

Set found to 1.
Break the loop.
 Else if arr[i][j] is greater than key:
 Decrement j by 1.
 Else:
 Increment i by 1.
5. If found is 1:
 Print "Element is present".
6. Else:
 Print "Element is not present".
7. STOP

Algorithm for main Function


1. START
2. Input: Size of the matrix n.
3. Read the elements of the matrix arr.
4. Read the key integer key to be searched.
5. Call search_element to find the key in the matrix.
6. STOP

ADITYA SUMAN GAGORIYA 20 K1


Q5. Given a boolean matrix (contains only 0 and 1) of size m X n where each row is sorted, write an
algorithm and a program to find which row has maximum number of 1's. (Linear time complexity) */

Algorithm for count Function


1. START
2. Input: A boolean matrix arr of size m x n.
3. Initialize i to 0, j to n-1, count to 0, k to 0, a to k, and ans to -1.
4. While i < m and j >= 0:

 If arr[i][j] is 1:

 Increment count.
 Decrement j by 1.
 If a is less than count:

 Set a to count.
 Set ans to i + 1.
 Increment i by 1.
5. If ans is not -1:
 Print "Row with maximum number of 1's is: ans".
6. Else:
 Print "No 1's are present in the matrix".
7. STOP

Algorithm for main Function


1. START
2. Input: Size of the matrix m x n.
3. Read the elements of the matrix arr.
4. Call count to find the row with the maximum number of 1's.
5. STOP

ADITYA SUMAN GAGORIYA 20 K1


Q6.Given a matrix of size n X n containing positive integers, write an algorithm and a program to rotate
the elements of matrix in clockwise direction.*/

Algorithm for rotateMatrixLayerClockwise Function


1. START
2. Input: Size of the matrix n and the matrix matrix[n][n].
3. Initialize start to 0 and end to n-1.
4. While start is less than end:

 Initialize prev to matrix[start + 1][start].


 For each element from start to end in the top row:

Swap the current element with prev.



For each element from start + 1 to end in the right column:
 Swap the current element with prev.
 For each element from end - 1 to start in the bottom row:
 Swap the current element with prev.
 For each element from end - 1 to start + 1 in the left column:
 Swap the current element with prev.
 Increment start by 1 and decrement end by 1.
5. STOP

Algorithm for main Function (Q6)


1. START
2. Input: Size of the matrix n.
3. Read the elements of the matrix matrix[n][n].
4. Call rotateMatrixLayerClockwise to rotate the matrix.
5. Print the rotated matrix.
6. STOP

ADITYA SUMAN GAGORIYA 20 K1


Q7. Design an algorithm and a program to implement stack using array. The program should
implement following stack operations:*/
a) Create() - create an empty stack
b) Push(k) - push an element k into the stack
c) Pop() - pop an element from the stack snd return it
d) IsEmpty() - check if stack is empty or not
e) Size() - finds the size of the stack
f) Print() - prints the contents of stack

1. START
2. Create: Initialize an empty stack with a given size.
3. Push(k):

 If the stack is full:

 Print "Stack overflow".


 Else:
 Increment the top index and add the element k to the stack.
4. Pop():
 If the stack is empty:
 Print "Stack underflow".
 Else:
 Remove and return the top element from the stack.
5. IsEmpty():
 If the top index is -1, return 1 (true).
 Else, return 0 (false).
6. Size(): Return the number of elements in the stack.
7. Print(): Print all elements in the stack.
8. STOP

ADITYA SUMAN GAGORIYA 20 K1


Q8. Given an expression string consisting of opening and closing brackets “{“,”}”,”(“,”)”,”[“,”]”, design
an algorithm and a program to check whether this expression has balanced paranthesis or not.*/

Algorithm for parenthesis_check Function


1. START
2. Input: An expression string exp.
3. Initialize an empty stack s.
4. For each character in the expression:

 If the character is an opening bracket ({, [, ():

 Push it onto the stack.


 If the character is a closing bracket (}, ], )):
 If the stack is empty:

 Return 0 (unbalanced).
 Pop the top element from the stack.
 If the popped element does not match the closing bracket:
 Return 0 (unbalanced).
5. If the stack is empty:
 Return 1 (balanced).
6. Else:
 Return 0 (unbalanced).
7. STOP

Algorithm for main Function


START

1. Input: Number of test cases T.


2. For each test case:

 Read the expression string exp.


 Call parenthesis_check to check if the expression is balanced.
 If the expression is balanced:

Print "Parenthesis Balanced".



Else:
 Print "Parenthesis unbalanced".
3. STOP

ADITYA SUMAN GAGORIYA 20 K1


Q9. Given a string of opening and closing paranthesis, design an algorithm and a program to find the
length of the longest valid paranthesis substring. Valid paranthesis substring is a string which contains
balanced paranthesis.*/

Algorithm for longestValidParentheses Function


1. START
2. Input: A string s containing parentheses.
3. Initialize max_len to 0, left to 0, and right to 0.
4. Left to right scan:

 For each character in the string s:

 If the character is (:

 Increment left by 1.
 Else:
 Increment right by 1.
 If left is equal to right:
 Calculate len as 2 * right.
 If len is greater than max_len:

 Update max_len to len.


Else if right is greater than left:
 Reset left and right to 0.
5. Right to left scan:
 Initialize left and right to 0.
 For each character in the string s from the end to the beginning:
 If the character is (:
 Increment left by 1.
 Else:
 Increment right by 1.
 If left is equal to right:
 Calculate len as 2 * left.
 If len is greater than max_len:
 Update max_len to len.
 Else if left is greater than right:
 Reset left and right to 0.
6. Output: Return max_len.
7. STOP

Algorithm for main Function


1. START
2. Input: Number of test cases T.
3. For each test case:

 Read the string ch containing parentheses.


 Call longestValidParentheses to find the length of the longest valid parentheses substring.
 Print the length of the longest valid parentheses substring.

ADITYA SUMAN GAGORIYA 20 K1


4. STOP

ADITYA SUMAN GAGORIYA 20 K1


/*Question 10: Given an empty stack, design an algorithm and a program to reverse a string
using this stack (with and without recursion).

Algorithm for reverse Function with Recursion


1. START
2. Input: A stack st, a string str, a pointer top, the length of the string len, and a counter c.
3. If c is equal to len:

 Return.
4. Push the character str[c] onto the stack.
5. Call reverse recursively with c + 1.
6. If c is less than len:
 Pop the top character from the stack and assign it to str[len - c - 1].
7. STOP

Algorithm for main Function


1. START
2. Input: Number of test cases t.
3. For each test case:

 Read the string str.


 Initialize a stack st and top to -1.
 Call reverse to reverse the string using the stack.
 Print the reversed string.
4. STOP

Algorithm for reverse Function without Recursion


1. START
2. Input: A stack st, a string str, a pointer top, and the length of the string len.
3. For each character in the string str:

 Push the character onto the stack.


4. For each character in the string str:
 Pop the top character from the stack and assign it to str[i].
5. STOP

Algorithm for main Function


1. START
2. Input: A string str.
3. Initialize a stack st and top to -1.

ADITYA SUMAN GAGORIYA 20 K1


4. Call reverse to reverse the string using the stack.
5. Print the reversed string.
6. STOP

/*Question 11: Design an algorithm and a program to implement two stacks by using only one array i.e.
both the stacks should use the same array for push and pop operation. Array should be divided in such a
manner that space should be efficiently used if one stack contains very large number of elements and
other one contains only few elements.

1. START
2. Input: Size of the array size.
3. Initialize top1 to -1 and top2 to size.
4. Push1(value):

 If top1 + 1 is less than top2:

Increment top1 and assign value to arr[top1].


 Else:
 Print "Stack 1 overflow".
5. Push2(value):
 If top1 + 1 is less than top2:
 Decrement top2 and assign value to arr[top2].
 Else:
 Print "Stack 2 overflow".
6. Pop1():
 If top1 is greater than or equal to 0:
 Return arr[top1] and decrement top1.
 Else:
 Print "Stack 1 underflow" and return -1.
7. Pop2():
 If top2 is less than size:
 Return arr[top2] and increment top2.
 Else:
 Print "Stack 2 underflow" and return -1.
8. PrintStacks():
 Print elements from 0 to top1 for Stack 1.
 Print elements from size - 1 to top2 for Stack 2.
9. DisplayMenu():
 Print menu options for stack operations.
10. Main Function:
 Read the size of the array.
 Initialize the array and stack pointers.
 Display the menu and perform operations based on user input.
11. STOP

ADITYA SUMAN GAGORIYA 20 K1


ADITYA SUMAN GAGORIYA 20 K1
/*Question 12: Given an expression in the form of postfix representation, design an algorithm and a
program to find result of this expression.

1. START
2. Input: Number of test cases T.
3. For each test case:

 Read the postfix expression s.


 Initialize an empty stack st and top to -1.
 For each token in the expression:

 If the token is a digit:

 Push the integer value onto the stack.


 Else if the token is an operator:
 Pop two elements from the stack.
 Evaluate the operation and push the result back onto the stack.
 If the stack is not empty:
 Print the result of the operation.
 Else:
 Print an error message.
4. STOP

ADITYA SUMAN GAGORIYA 20 K1


/*Question 13: Design an algorithm and a program to implement queue using array. The
program should implement following queue operations:
a) Create() - create a queue
b) EnQueue(k) - insert an element k into the queue
c) DeQueue() - delete an element from the queue
d) IsEmpty() - check if queue is empty or not
e) Size() - finds the size of the queue

1. START
2. Create():

 Initialize front to -1 and rear to -1.


3. EnQueue(k):
 If rear is equal to n - 1:

 Print "Queue is full".


 Else:
 If front and rear are -1:

 Set front to 0.
 Increment rear by 1 and assign k to queue[rear].
4. DeQueue():
 If the queue is empty:
 Print "Queue is empty".
 Else:
 Print the dequeued element queue[front] and increment front by 1.
5. IsEmpty():
 If front is -1 or front is greater than rear:
 Return true.
 Else:
 Return false.
6. Size():
 Return rear - front + 1.
7. STOP

ADITYA SUMAN GAGORIYA 20 K1


/*Question 14: Design an algorithm and write a program to reverse a queue.

1. START
2. Input: Size of the queue n.
3. Create: Initialize front to -1, rear to -1, and top to -1.
4. EnQueue(k):

 If rear is equal to n - 1:

 Print "Queue overflow".


 Else:
 If front and rear are -1:

 Set front to 0.
 Increment rear by 1 and assign k to queue[rear].
5. DeQueue():
 If the queue is empty:
 Print "Queue underflow".
 Else:
 Print the dequeued element queue[front] and increment front by 1.
 If front is greater than rear:
 Set front and rear to -1.
6. Push(k):
 If top is equal to n - 1:
 Print "Stack overflow".
 Else:
 Increment top by 1 and assign k to stack[top].
7. Pop():
 If the stack is empty:
 Print "Stack underflow".
 Else:
 Return stack[top] and decrement top by 1.
8. Reverse():
 While the queue is not empty:
 Dequeue an element and push it onto the stack.
 While the stack is not empty:
 Pop an element and enqueue it back to the queue.
9. STOP

ADITYA SUMAN GAGORIYA 20 K1


/*Question 15: Design an algorithm and write a program to implement Deque i.e. double
ended queue. Double ended queue is a queue in which insertion and deletion can be done
from both ends of the queue. The program should implement following operations:
a) insertFront() - insert an element at the front of Deque
b) insertEnd() - insert an element at the end of Deque
c) deleteFront() - delete an element from the front of Deque
d) deleteEnd() - delete an element from the end of Deque
e) isEmpty() - checks whether Deque is empty or not
f) isFull() - checks whether Deque is full or not
g) printFront() - print Deque from front
h) printEnd() - print Deque from end

1. START
2. Create: Initialize front to -1 and rear to -1.
3. InsertFront(k):

 If the deque is full:

 Print "Deque is full".


 Else:
 If the deque is empty:

 Set front and rear to 0.


 Else if front is 0:
 Set front to MAX - 1.
 Else:
 Decrement front by 1.
 Assign k to deque[front].
4. InsertEnd(k):
 If the deque is full:
 Print "Deque is full".
 Else:
 If the deque is empty:
 Set front and rear to 0.
 Else:
 Increment rear by 1 (modulo MAX).
 Assign k to deque[rear].
5. DeleteFront():
 If the deque is empty:
 Print "Deque is empty".
 Else:
 If front is equal to rear:

ADITYA SUMAN GAGORIYA 20 K1


 Set front and rear to -1.
 Else:
 Increment front by 1 (modulo MAX).
6. DeleteEnd():
 If the deque is empty:
 Print "Deque is empty".
 Else:
 If rear is equal to front:
 Set front and rear to -1.
 Else if rear is 0:
 Set rear to MAX - 1.
 Else:
 Decrement rear by 1.
7. IsEmpty():
 If front is -1:
 Return true.
 Else:
 Return false.
8. IsFull():
 If (rear + 1) % MAX is equal to front:
 Return true.
 Else:
 Return false.
9. PrintFront():
 If the deque is empty:
 Print "Deque is empty".
 Else:
 Print elements from front to rear.
10. PrintEnd():
 If the deque is empty:
 Print "Deque is empty".
 Else:
 Print elements from rear to front.
11. STOP

ADITYA SUMAN GAGORIYA 20 K1


/*Question 16: Design an algorithm and write a program to implement stack operations using minimum
number of queues.

1. START
2. Create: Initialize front to -1 and rear to -1.
3. EnQueue(k):

 If the queue is full:

 Print "Queue is full".


 Else:
 If the queue is empty:

 Set front and rear to 0.


 Else:
 Increment rear by 1 (modulo MAX).
 Assign k to queue[rear].
4. DeQueue():
 If the queue is empty:
 Print "Queue is empty".
 Else:
 Store the dequeued element queue[front].
 If front is equal to rear:
 Set front and rear to -1.
 Else:
 Increment front by 1 (modulo MAX).
 Return the dequeued element.
5. Push(k):
 Enqueue k to the queue.
 For each element in the queue (except the last one):
 Dequeue an element and enqueue it back to the queue.
6. Pop():
 Dequeue an element and return it.
7. PrintStack():
 If the queue is empty:
 Print "Stack is empty".
 Else:
 Print elements from front to rear.
8. STOP

ADITYA SUMAN GAGORIYA 20 K1


/*Question 17: Design an algorithm and write a program to implement queue operations using minimum
number of stacks.

1. START
2. Create: Initialize top1 to -1 and top2 to -1.
3. Push(stack, k):

 If the stack is full:

 Print "Stack is full".


 Else:
 Increment top and assign k to the stack.
4. Pop(stack):
 If the stack is empty:
 Print "Stack is empty".
 Else:
 Return the top element and decrement top.
5. EnQueue(k):
 Push k onto stack1.
6. DeQueue():
 If stack2 is empty:
 While stack1 is not empty:

 Pop an element from stack1 and push it onto stack2.


 Pop an element from stack2 and return it.
7. PrintQueue():
 Print elements from stack1 and stack2.
8. STOP

ADITYA SUMAN GAGORIYA 20 K1


/*Question 18: Design an algorithm and write a program to implement circular queue.
1. Circular queue is a queue in which last position of queue is connected with first position of
2. queue to make a circle. The program should implement following operations:
3. a) Create() - create a queue of specific size
4. b) EnQueue(k) - insert an element k into the queue
5. c) DeQueue() - delete an element from the queue
6. d) IsEmpty() - check if queue is empty or not
7. e) Front() - return front item from queue
8. f) Rear() - return rear item from queue
9. START
10. Create(s):

 Set size to s.
 Initialize front and rear to -1.
11. EnQueue(k):
 If the queue is full:

 Print "Queue is full".


 Else:
 If the queue is empty:

 Set front and rear to 0.


 Else:
 Increment rear by 1 (modulo size).
 Assign k to queue[rear].
12. DeQueue():
 If the queue is empty:
 Print "Queue is empty".
 Else:
 Store the dequeued element queue[front].
 If front is equal to rear:
 Set front and rear to -1.
 Else:
 Increment front by 1 (modulo size).
 Return the dequeued element.
13. IsEmpty():
 If front is -1:
 Return true.
 Else:
 Return false.
14. Front():
 If the queue is empty:
 Print "Queue is empty".
 Return -1.
 Else:Return queue[front].

ADITYA SUMAN GAGORIYA 20 K1


15. Rear():
 If the queue is empty:
 Print "Queue is empty".
 Return -1.
 Else:
 Return queue[rear].
16. PrintQueue():
 If the queue is empty:Print "Circular Queue is empty".
 Else: Print elements from front to rear.
17. STOP

ADITYA SUMAN GAGORIYA 20 K1


/*Q 19: Write an algorithm and a program to implement singly linked list. The program should implement
following operations: a) Create(k) - create a linked list with single node of value k b)InsertFront(k) -
insert node of value k at the front of the linked list c) InsertEnd(k) - insert a node of value k at the end of
the linked list d)InsertAnywhere(p) - insert a node at specific position p e) DeleteFront() - delete a node
from the front of the linked list f) DeleteEnd() - delete a node from the end of the linked list
g)DeleteAnywhere(p) - delete a node from a specific position p h)Size() - find the size of the linked list i)
IsEmpty() - checks if the linked list is empty or not j) FindMiddle() - finds the middle element of the
linked list*/

1. START
2. Create(k):

 Allocate memory for a new node.


 Set the node's data to k.
 Set the node's next pointer to NULL.
 Set the head pointer to the new node.
3. InsertFront(k):
 Allocate memory for a new node.
 Set the node's data to k.
 Set the node's next pointer to the current head.
 Update the head pointer to the new node.
4. InsertEnd(k):
 Allocate memory for a new node.
 Set the node's data to k.
 Set the node's next pointer to NULL.
 If the list is empty:

 Set the head pointer to the new node.


 Else:
 Traverse to the end of the list.
 Set the last node's next pointer to the new node.
5. InsertAnywhere(k, p):
 Allocate memory for a new node.
 Set the node's data to k.
 If p is 0:
 Set the node's next pointer to the current head.
 Update the head pointer to the new node.
 Else:
 Traverse to the position p-1.
 If the position is out of range:

 Print "Position out of range".


 Free the new node.
 Else:
 Set the new node's next pointer to the current node's next pointer.
 Update the current node's next pointer to the new node.
6. DeleteFront():
 If the list is empty:
 Print "List is empty".
 Else:
 Store the head node in a temporary pointer.
 Update the head pointer to the next node.

ADITYA SUMAN GAGORIYA 20 K1


 Free the temporary pointer.
7. DeleteEnd():
 If the list is empty:
 Print "List is empty".
 Else:
 If the list has only one node:
 Free the head node.
 Set the head pointer to NULL.
 Else:
 Traverse to the second last node.
 Free the last node.
 Set the second last node's next pointer to NULL.
8. DeleteAnywhere(p):
 If the list is empty:
 Print "List is empty".
 Else:
 If p is 0:
 Store the head node in a temporary pointer.
 Update the head pointer to the next node.
 Free the temporary pointer.
 Else:
 Traverse to the position p-1.
 If the position is out of range:

 Print "Position out of range".


 Else:
 Store the node to be deleted in a temporary pointer.
 Update the current node's next pointer to the next node's next pointer.
 Free the temporary pointer.
9. Size():
 Initialize a counter to 0.
 Traverse the list and increment the counter for each node.
 Return the counter.
10. IsEmpty():
 If the head pointer is NULL:
 Return true.
 Else:
 Return false.
11. FindMiddle():
 If the list is empty:
 Print "List is empty".
 Else:
 Initialize two pointers, slow and fast, to the head.
 Traverse the list with slow moving one step and fast moving two steps.
 When fast reaches the end, slow will be at the middle.
 Print the data of the middle node.
12. PrintList():
 If the list is empty:
 Print "List is empty".
 Else:
 Traverse the list and print each node's data.
13. STOP

ADITYA SUMAN GAGORIYA 20 K1


ADITYA SUMAN GAGORIYA 20 K1
/*Q 20:Write an algorithm and a program to implement queue using linked list. The program should
implement following stack operations: a) Create() b) EnQueue() c) DeQueue() d) IsEmpty() e) Size()*/

1. START
2. Create():

 Initialize front and rear of the queue to NULL.


3. EnQueue(value):
 Allocate memory for a new node.
 Set the node's data to value.
 Set the node's next pointer to NULL.
 If the queue is empty:

Set both front and rear to the new node.



Else:
 Set the next pointer of rear to the new node.
 Update rear to the new node.
4. DeQueue():
 If the queue is empty:
 Print "Queue is empty".
 Else:
 Store the front node in a temporary pointer.
 Update front to the next node.
 If front is NULL:

 Set rear to NULL.


 Free the temporary pointer.
5. IsEmpty():
 If front is NULL:
 Return true.
 Else:
 Return false.
6. Size():
 Initialize a counter to 0.
 Traverse the queue from front to rear, incrementing the counter for each node.
 Return the counter.
7. PrintQueue():
 If the queue is empty:
 Print "Queue is empty".
 Else:
 Traverse the queue from front to rear, printing each node's data.
8. STOP

ADITYA SUMAN GAGORIYA 20 K1


/*Q 21:. Write an algorithm and a program to implement stack using linked list. he program should
implement following queue operations: a) Create() b) Push() c) Pop() d) IsEmpty() e) IsFull() f) Size()*/

1. START
2. Create():

 Initialize top of the stack to NULL.


3. Push(value):
 Allocate memory for a new node.
 Set the node's data to value.
 Set the node's next pointer to the current top.
 Update top to the new node.
4. Pop():
 If the stack is empty:

 Print "Stack is empty".


 Else:
 Store the top node in a temporary pointer.
 Update top to the next node.
 Free the temporary pointer.
5. IsEmpty():
 If top is NULL:
 Return true.
 Else:
 Return false.
6. IsFull():
 Allocate memory for a temporary node.
 If allocation fails:
 Return true.
 Else:
 Free the temporary node.
 Return false.
7. Size():
 Initialize a counter to 0.
 Traverse the stack from top to NULL, incrementing the counter for each node.
 Return the counter.
8. PrintStack():
 If the stack is empty:
 Print "Stack is empty".
 Else:
 Traverse the stack from top to NULL, printing each node's data.
9. STOP

ADITYA SUMAN GAGORIYA 20 K1


/*Q 22:Write an algorithm and a program to implement doubly linked list. The program should
implement following operations: a) Create(k) - create a doubly linked list node with value k.
b)InsertFront(k) - insert node at the front of the linked list. c) InsertEnd(k) - insert a node at the end of the
linked list. d)InsertIntermediate(k,p) - insert a node at specific position p. e) DeleteFront() - delete a node
from the front of the linked list. f) DeleteEnd() - delete a node from the end of the linked list.
g)DeleteIntermediate(p) – delete a node from a specific position p. h)Size() - returns the size of doubly
linked list. i) IsEmpty() - checks whether the list is empty or not. j) FindMiddle() - returns the contents of
middle node of the list.*/

1. START
2. Create(k):

 Allocate memory for a new node.


 Set the node's data to k.
 Set the node's next and prev pointers to NULL.
 Set the head pointer to the new node.
3. InsertFront(k):
 Allocate memory for a new node.
 Set the node's data to k.
 Set the node's next pointer to the current head.
 Set the node's prev pointer to NULL.
 If the list is not empty:

 Set the current head's prev pointer to the new node.


 Update the head pointer to the new node.
4. InsertEnd(k):
 Allocate memory for a new node.
 Set the node's data to k.
 Set the node's next pointer to NULL.
 If the list is empty:
 Set the node's prev pointer to NULL.
 Set the head pointer to the new node.
 Else:
 Traverse to the end of the list.
 Set the last node's next pointer to the new node.
 Set the new node's prev pointer to the last node.
5. InsertIntermediate(k, p):
 If p is less than or equal to 0:
 Call InsertFront(k).
 Else:
 Allocate memory for a new node.
 Set the node's data to k.
 Traverse to the position p-1.
 If the position is out of range:

 Call InsertEnd(k).
 Else:
 Set the new node's next pointer to the current node's next pointer.
 Set the new node's prev pointer to the current node.
 If the current node's next is not NULL:

ADITYA SUMAN GAGORIYA 20 K1


 Set the next node's prev pointer to the new node.
 Set the current node's next pointer to the new node.
6. DeleteFront():
 If the list is empty:
 Print "List is empty".
 Else:
 Store the head node in a temporary pointer.
 Update the head pointer to the next node.
 If the head is not NULL:
 Set the head's prev pointer to NULL.
 Free the temporary pointer.
7. DeleteEnd():
 If the list is empty:
 Print "List is empty".
 Else:
 Traverse to the end of the list.
 If the last node's prev is not NULL:
 Set the prev node's next pointer to NULL.
 Else:
 Set the head pointer to NULL.
 Free the last node.
8. DeleteIntermediate(p):
 If the list is empty:
 Print "List is empty".
 Else:
 Traverse to the position p.
 If the position is out of range:
 Print "Position out of range".
 Else:
 If the node's prev is not NULL:
 Set the prev node's next pointer to the node's next pointer.
 If the node's next is not NULL:
 Set the next node's prev pointer to the node's prev pointer.
 Free the node.
9. Size():
 Initialize a counter to 0.
 Traverse the list and increment the counter for each node.
 Return the counter.
10. IsEmpty():
 If the head pointer is NULL:Return true.
 Else:Return false.
11. FindMiddle():
 If the list is empty:
 Print "List is empty".
 Else:
 Initialize two pointers, slow and fast, to the head.
 Traverse the list with slow moving one step and fast moving two steps.
 When fast reaches the end, slow will be at the middle.
 Print the data of the middle node.
12. PrintList():
 If the list is empty:
 Print "List is empty".
 Else:

ADITYA SUMAN GAGORIYA 20 K1


 Traverse the list and print each node's data.
13. STOP

/*Q 23: Given a doubly linked list, design an algorithm and write a program to reverse this list without
using any extra space. */START

1. Input: A doubly linked list list.


2. Initialize temp to NULL and current to list->head.
3. While current is not NULL:

 Set temp to current->prev.


 Set current->prev to current->next.
 Set current->next to temp.
 Move current to current->prev.
4. If temp is not NULL:
 Set list->head to temp->prev.
5. STOP

ADITYA SUMAN GAGORIYA 20 K1


/*Q 24: Given a sorted doubly linked list, design an algorithm and write a program to eliminate duplicates
from this list.*/

1. START
2. Input: A sorted doubly linked list list.
3. If list->head is NULL:

 Return.
4. Initialize current to list->head.
5. While current is not NULL and current->next is not NULL:
 If current->data is equal to current->next->data:

 Set nextNode to current->next.


 Set current->next to nextNode->next.
 If nextNode->next is not NULL:

Set nextNode->next->prev to current.



Free nextNode.
 Else:
 Move current to current->next.
6. STOP

ADITYA SUMAN GAGORIYA 20 K1


/*Q 25: . Design an algorithm and write a program to implement circular linked list. The program should
implement following operations: a) Create(k) - creates a circular linked list node with value k.
b)InsertFront() - insert node at the front of list. c) InsertEnd() - insert node at the end of list.
d)InsertIntermediate() - insert node at any specified position of list. e) DeleteFront() - delete node from
the front of list. f) DeleteEnd() - delete node from the end of list. g)DeleteIntermediate() - delete node
from any specified position of list. h)Size() - return size of circular linked list. i) IsEmpty() - checks
whether list is empty or not. */

1. START
2. Create(k):

 Allocate memory for a new node.


 Set the node's data to k.
 Set the node's next pointer to point to itself.
 Set the head pointer to the new node.
3. InsertFront(k):
 Allocate memory for a new node.
 Set the node's data to k.
 If the list is empty:

 Set the node's next pointer to point to itself.


 Set the head pointer to the new node.
 Else:
 Traverse to the last node.
 Set the new node's next pointer to the current head.
 Set the last node's next pointer to the new node.
 Update the head pointer to the new node.
4. InsertEnd(k):
 Allocate memory for a new node.
 Set the node's data to k.
 If the list is empty:
 Set the node's next pointer to point to itself.
 Set the head pointer to the new node.
 Else:
 Traverse to the last node.
 Set the last node's next pointer to the new node.
 Set the new node's next pointer to the head.
5. InsertIntermediate(k, pos):
 If pos is 0:
 Call InsertFront(k).
 Else:
 Allocate memory for a new node.
 Set the node's data to k.
 Traverse to the position pos-1.
 If the position is out of range:

 Print "Position out of range".


 Else:
 Set the new node's next pointer to the current node's next pointer.
 Set the current node's next pointer to the new node.
6. DeleteFront():
 If the list is empty:

ADITYA SUMAN GAGORIYA 20 K1


 Print "List is empty".
 Else:
 If the list has only one node:
 Free the node.
 Set the head pointer to NULL.
 Else:
 Traverse to the last node.
 Store the head node in a temporary pointer.
 Update the head pointer to the next node.
 Set the last node's next pointer to the new head.
 Free the temporary pointer.
7. DeleteEnd():
 If the list is empty:
 Print "List is empty".
 Else:
 If the list has only one node:
 Free the node.
 Set the head pointer to NULL.
 Else:
 Traverse to the second last node.
 Free the last node.
 Set the second last node's next pointer to the head.
8. DeleteIntermediate(pos):
 If the list is empty:
 Print "List is empty".
 Else:
 If pos is 0:
 Call DeleteFront().
 Else:
 Traverse to the position pos-1.
 If the position is out of range:

 Print "Position out of range".


 Else:
 Store the node to be deleted in a temporary pointer.
 Update the current node's next pointer to the next node's next pointer.
 Free the temporary pointer.
9. Size():
 If the list is empty:
 Return 0.
 Initialize a counter to 1.
 Traverse the list and increment the counter for each node.
 Return the counter.
10. IsEmpty():
 If the head pointer is NULL:
 Return true.
 Else:
 Return false.
11. PrintList():
 If the list is empty:
 Print "List is empty".
 Else:
 Traverse the list and print each node's data.

ADITYA SUMAN GAGORIYA 20 K1


12. STOP

/*Q 26: Design an algorithm and write a program to concatenate two circularly linked lists */)

1. START
2. Input: Two circularly linked lists list1 and list2.
3. If both list1 and list2 are empty:

 Print "Both lists are empty".


 Return.
4. If list1 is empty:
 Set list1->head to list2->head.
 Return.
5. If list2 is empty:
 Return.
6. Traverse to the last node of list1.
7. Traverse to the last node of list2.
8. Set the next pointer of the last node of list1 to the head of list2.
9. Set the next pointer of the last node of list2 to the head of list1.
10. STOP

ADITYA SUMAN GAGORIYA 20 K1


/* Q 27: Write an algorithm and a program that will split a circularly linked list into two circularly linked
list provided position from where circular linked list has to be splitted. */

1. START
2. Input: A circularly linked list list, a position position, and two empty circularly linked lists list1 and list2.
3. If list is empty:

 Print "List is empty".


 Return.
4. Traverse the list to count the number of nodes (size).
5. If position is greater than size:
 Print "Invalid position".
 Return.
6. Traverse to the node at position position.
7. Set list1->head to list->head.
8. Set list2->head to the node after the node at position position.
9. Set the next pointer of the node at position position to list->head.
10. Traverse to the last node of list2.
11. Set the next pointer of the last node of list2 to list2->head.
12. STOP

ADITYA SUMAN GAGORIYA 20 K1


/* Q 28: Write an algorithm that will split a linked list into two linked lists, so that successive nodes go to
different lists. Odd numbered nodes to the first list while even numbered nodes to the second list. */

1. START
2. Input: A linked list head.
3. Initialize oddList and evenList to NULL.
4. Initialize oddTail and evenTail to NULL.
5. Initialize a counter count to 1.
6. While head is not NULL:

 If count is odd:

 If oddList is NULL:

 Set oddList to head.


 Set oddTail to oddList.
 Else:
 Set oddTail->next to head.
 Update oddTail to oddTail->next.
 Else:
 If evenList is NULL:
 Set evenList to head.
 Set evenTail to evenList.
 Else:
 Set evenTail->next to head.
 Update evenTail to evenTail->next.
 Move head to head->next.
 Increment count by 1.
7. If oddTail is not NULL:
 Set oddTail->next to NULL.
8. If evenTail is not NULL:
 Set evenTail->next to NULL.
9. Output: Two linked lists oddList and evenList.
10. STOP

ADITYA SUMAN GAGORIYA 20 K1


/*Q 29: Given a linked list and a number n, design an algorithm and write a program to find the value at
the n'th node from end of this linked list*/

1. START
2. Input: A linked list head and an integer n.
3. Initialize two pointers, first and second, to head.
4. Initialize a counter count to 0.
5. If head is NULL:

Print "List is empty".



Return.

6. Move the first pointer n steps ahead:
 While count is less than n:

 If first is NULL:

Print "The list has fewer than n elements".



Return.

 Move first to first->next.
 Increment count by 1.
7. Move both first and second pointers one step at a time until first reaches the end of the list:
 While first is not NULL:
 Move first to first->next.
 Move second to second->next.
8. Output: The data of the second pointer, which is the n'th node from the end.
9. STOP

ADITYA SUMAN GAGORIYA 20 K1


/* Q 30: Write a program that will reverse a linked list only by traversing it once and without using extra
space */

1. START
2. Input: A linked list head.
3. Initialize prev to NULL, current to head, and next to NULL.
4. While current is not NULL:

 Set next to current->next.


 Set current->next to prev.
 Update prev to current.
 Update current to next.
5. Set head to prev.
6. STOP

ADITYA SUMAN GAGORIYA 20 K1


/*Q 31: Design an algorithm to implement binary trees. Write a program which implements following
basic operations on binary tree: a) CreateTree() - creates a root node b) InsertNode() - insert a node in tree
c) DeleteNode() - delete a node from tree d) FindHeight() - find the height of tree e) FindSize() - find
number of nodes in tree f) Search() - search whether given specific element present in tree or not. */

1. START
2. CreateTree(data):

 Allocate memory for a new node.


 Set the node's data to data.
 Set the node's left and right pointers to NULL.
 Return the new node.
3. InsertNode(root, data):
 If root is NULL:

 Return CreateTree(data).
 If data is less than root->data:
 Set root->left to InsertNode(root->left, data).
 Else:
 Set root->right to InsertNode(root->right, data).
 Return root.
4. FindMinNode(root):
 While root is not NULL and root->left is not NULL:
 Move root to root->left.
 Return root.
5. DeleteNode(root, data):
 If root is NULL:
 Return root.
 If data is less than root->data:
 Set root->left to DeleteNode(root->left, data).
 Else if data is greater than root->data:
 Set root->right to DeleteNode(root->right, data).
 Else:
 If root->left is NULL:

 Store root->right in a temporary pointer.


 Free root.
 Return the temporary pointer.
 Else if root->right is NULL:
 Store root->left in a temporary pointer.
 Free root.
 Return the temporary pointer.
 Store the minimum node in the right subtree in a temporary pointer.
 Set root->data to the temporary pointer's data.
 Set root->right to DeleteNode(root->right, temporary pointer's data).
 Return root.
6. FindHeight(root):
 If root is NULL:
 Return -1.
 Set leftHeight to FindHeight(root->left).
 Set rightHeight to FindHeight(root->right).

ADITYA SUMAN GAGORIYA 20 K1


 Return the maximum of leftHeight and rightHeight plus 1.
7. FindSize(root):
 If root is NULL:
 Return 0.
 Return 1 plus FindSize(root->left) plus FindSize(root->right).
8. Search(root, data):
 If root is NULL:
 Return 0.
 If root->data is equal to data:
 Return 1.
 If data is less than root->data:
 Return Search(root->left, data).
 Else:
 Return Search(root->right, data).
9. InOrderTraversal(root):
 If root is not NULL:
 Call InOrderTraversal(root->left).
 Print root->data.
 Call InOrderTraversal(root->right).
10. STOP

ADITYA SUMAN GAGORIYA 20 K1


/*Q 32: Write an algorithm and a program to implement following types of traversing in the tree: a)
inorder() - (1) traverse left subtree, (2) traverse root, (3) traverse right subtree b) postorder() - (1) traverse
root, (2) traverse left subtree, (3) traverse right subtree c) preorder() - (1) traverse left subtree, (2) traverse
right subtree, (3) traverse root */
Inorder Traversal

1. START
2. Input: A binary tree root.
3. If root is not NULL:

 Call Inorder(root->left).
 Print root->data.
 Call Inorder(root->right).
4. STOP

Postorder Traversal

1. START
2. Input: A binary tree root.
3. If root is not NULL:

 Call Postorder(root->left).
 Call Postorder(root->right).
 Print root->data.
4. STOP

Preorder Traversal

1. START
2. Input: A binary tree root.
3. If root is not NULL:

 Print root->data.
 Call Preorder(root->left).
 Call Preorder(root->right).
4. STOP

ADITYA SUMAN GAGORIYA 20 K1


/* Q 33: For an expression in the form of binary tree, infix representation of the expression is given in the
form of character array.. Design an algorithm and a program to convert infix expression of this tree to
postfix expression. Postfix representation of expression should follow BODMAS rule */

1. START
2. Input: An infix expression infix.
3. Initialize an empty stack stack and an empty string postfix.
4. For each character current in infix:

 If current is an operand:

 Append current to postfix.


 If current is (:
 Push current onto stack.
 If current is ):
 While the top of stack is not (:

Pop from stack and append to postfix.



Pop ( from stack.
 If current is an operator:
 While stack is not empty and the precedence of the top of stack is greater than or equal to the
precedence of current:
 Pop from stack and append to postfix.
 Push current onto stack.
5. While stack is not empty:
 Pop from stack and append to postfix.
6. Output: The postfix expression postfix.
7. STOP

ADITYA SUMAN GAGORIYA 20 K1


/* Q 34: Design an algorithm and a program to implement binary search tree. The program should
implement following BST operations: a) Create() - creates a root node. b) Insert() - insert a node in tree.
c) Delete() - delete a node from tree. d) FindHeight() - return height of tree. e) FindDepth() - return depth
of tree. f) Search() - search whether given key is present in tree or not. */

1. START
2. Create(data):

 Allocate memory for a new node.


 Set the node's data to data.
 Set the node's left and right pointers to NULL.
 Return the new node.
3. Insert(root, data):
 If root is NULL:

 Return Create(data).
 If data is less than root->data:
 Set root->left to Insert(root->left, data).
 Else:
 Set root->right to Insert(root->right, data).
 Return root.
4. FindMin(root):
 While root is not NULL and root->left is not NULL:
 Move root to root->left.
 Return root.
5. Delete(root, data):
 If root is NULL:
 Return root.
 If data is less than root->data:
 Set root->left to Delete(root->left, data).
 Else if data is greater than root->data:
 Set root->right to Delete(root->right, data).
 Else:
 If root->left is NULL:

 Store root->right in a temporary pointer.


 Free root.
 Return the temporary pointer.
 Else if root->right is NULL:
 Store root->left in a temporary pointer.
 Free root.
 Return the temporary pointer.
 Store the minimum node in the right subtree in a temporary pointer.
 Set root->data to the temporary pointer's data.
 Set root->right to Delete(root->right, temporary pointer's data).
 Return root.
6. FindHeight(root):
 If root is NULL:
 Return -1.
 Set leftHeight to FindHeight(root->left).
 Set rightHeight to FindHeight(root->right).
 Return the maximum of leftHeight and rightHeight plus 1.

ADITYA SUMAN GAGORIYA 20 K1


7. FindDepth(root, data, depth):
 If root is NULL:
 Return -1.
 If root->data is equal to data:
 Return depth.
 Set leftDepth to FindDepth(root->left, data, depth + 1).
 If leftDepth is not -1:
 Return leftDepth.
 Return FindDepth(root->right, data, depth + 1).
8. Search(root, data):
 If root is NULL:
 Return 0.
 If root->data is equal to data:
 Return 1.
 If data is less than root->data:
 Return Search(root->left, data).
 Else:
 Return Search(root->right, data).
9. InOrder(root):
 If root is not NULL:
 Call InOrder(root->left).
 Print root->data.
 Call InOrder(root->right).
10. STOP

ADITYA SUMAN GAGORIYA 20 K1


/*Q 35: Design an algorithm and a program to convert binary search tree created in previous question into
balanced BST. Also find maximum and minimum element from this balanced BST. */

1. START
2. Input: A binary search tree root.
3. InOrderTraversal(root, arr, index):

 If root is NULL:

 Return.
 Call InOrderTraversal(root->left, arr, index).
 Set arr[index++] to root->data.
 Call InOrderTraversal(root->right, arr, index).
4. SortedArrayToBST(arr, start, end):
 If start is greater than end:
 Return NULL.
 Set mid to (start + end) / 2.
 Create a new node root with arr[mid].
 Set root->left to SortedArrayToBST(arr, start, mid - 1).
 Set root->right to SortedArrayToBST(arr, mid + 1, end).
 Return root.
5. ConvertToBalancedBST(root):
 Initialize an array arr and an index index to 0.
 Call InOrderTraversal(root, arr, &index).
 Return SortedArrayToBST(arr, 0, index - 1).
6. FindMin(root):
 While root is not NULL and root->left is not NULL:
 Move root to root->left.
 Return root.
7. FindMax(root):
 While root is not NULL and root->right is not NULL:
 Move root to root->right.
 Return root.
8. STOP

ADITYA SUMAN GAGORIYA 20 K1


/* Q 36: .Given a binary search tree, design an algorithm and write a program to find which level number
of tree has maximum number of nodes. Also print maximum number of nodes present at this level */

1. START
2. Input: A binary search tree root.
3. If root is NULL:

 Return -1.
4. Initialize a queue queue and set front and rear to -1.
5. Enqueue root to queue.
6. Initialize maxLevel to 0, maxNodes to 0, and currentLevel to 0.
7. While front is less than rear:
 Set nodeCount to rear - front.
 Increment currentLevel by 1.
 Initialize nodesAtCurrentLevel to 0.
 While nodeCount is greater than 0:

 Dequeue a node currentNode from queue.


 If currentNode->left is not NULL:

Enqueue currentNode->left to queue.



If currentNode->right is not NULL:

 Enqueue currentNode->right to queue.
 Increment nodesAtCurrentLevel by 1.
 Decrement nodeCount by 1.
 If nodesAtCurrentLevel is greater than maxNodes:
 Set maxNodes to nodesAtCurrentLevel.
 Set maxLevel to currentLevel.
8. Output: maxLevel.
9. STOP

ADITYA SUMAN GAGORIYA 20 K1


/* Q 37:Write an algorithm and a program to implement priority queue (also known as heap). Priority
queue has following properties: a) Each item has a priority associated with it. b)Element which has
heighest priority is dequeued before an element with low priority. c) If two elements have the same
priority, they are served according to their order in the queue. d)It is always in the form of complete tree.
e) Element which has highest priority should be at root, element which has priority less than root but
more than other elements comes at level 2. Hence as the level increases, priority of element decreases.
The program should implement following operations: a) create() - create root node of priority heap
b)insert() - insert an element into the priority queue. Everytime when a node is inserted, tree should be
balanced according to its priority. c) getHighestPriority() - finds the element which has highest priority d)
deleteHeighestPriority() - delete the element which has highest priority */

1. START
2. Create(capacity):

 Allocate memory for a new priority queue.


 Set the queue's capacity to capacity.
 Set the queue's size to 0.
 Allocate memory for the heap array.
 Return the priority queue.
3. Swap(a, b):
 Swap the values of a and b.
4. HeapifyUp(pq, index):
 While index is greater than 0 and pq->heap[index] is greater than pq->heap[(index - 1) / 2]:

 Swap pq->heap[index] with pq->heap[(index - 1) / 2].


 Update index to (index - 1) / 2.
5. Insert(pq, value):
 If the queue is full:
 Print "Heap is full".
 Return.
 Set pq->heap[pq->size] to value.
 Call HeapifyUp(pq, pq->size).
 Increment pq->size by 1.
6. HeapifyDown(pq, index):
 Set left to 2 * index + 1.
 Set right to 2 * index + 2.
 Set largest to index.
 If left is less than pq->size and pq->heap[left] is greater than pq->heap[largest]:
 Set largest to left.
 If right is less than pq->size and pq->heap[right] is greater than pq->heap[largest]:
 Set largest to right.
 If largest is not index:
 Swap pq->heap[index] with pq->heap[largest].
 Call HeapifyDown(pq, largest).
7. GetHighestPriority(pq):
 If the queue is empty:
 Print "Heap is empty".
 Return -1.

ADITYA SUMAN GAGORIYA 20 K1


 Return pq->heap[0].
8. DeleteHighestPriority(pq):
 If the queue is empty:
 Print "Heap is empty".
 Return.
 Set pq->heap[0] to pq->heap[pq->size - 1].
 Decrement pq->size by 1.
 Call HeapifyDown(pq, 0).
9. PrintHeap(pq):
 For each element in the heap:
 Print the element.
10. STOP

ADITYA SUMAN GAGORIYA 20 K1


/*Q 38: Given a binary tree, design an algorithm and write a program to check whether this tree is heap
or not. Tree should satisfy following heap properties: a) Tree should be complete binary tree b)Every
nodes value should be greater than or equal to its child node (incase of max heap) */

1. START
2. CreateNode(data):

Allocate memory for a new node.


Set the node's data to data.
Set the node's left and right pointers to NULL.
Return the new node.
3. isCompleteBinaryTree(root, index, nodeCount):
 If root is NULL:

 Return 1.
 If index is greater than or equal to nodeCount:
 Return 0.
 Return isCompleteBinaryTree(root->left, 2 * index + 1, nodeCount) and isCompleteBinaryTree(root->right,
2 * index + 2, nodeCount).
4. isMaxHeap(root):
 If root is NULL:
 Return 1.
 If root->left is not NULL and root->data is less than root->left->data:
 Return 0.
 If root->right is not NULL and root->data is less than root->right->data:
 Return 0.
 Return isMaxHeap(root->left) and isMaxHeap(root->right).
5. countNodes(root):
 If root is NULL:
 Return 0.
 Return 1 + countNodes(root->left) + countNodes(root->right).
6. isHeap(root):
 If root is NULL:
 Return 1.
 Set nodeCount to countNodes(root).
 Set index to 0.
 Return isCompleteBinaryTree(root, index, nodeCount) and isMaxHeap(root).
7. STOP

ADITYA SUMAN GAGORIYA 20 K1


/* Q 39: Given a complete binary tree, design an algorithm and write a program to find Kth largest
element in it. (Hint: Max heap) */

1. START
2. CreateNode(data):

Allocate memory for a new node.


Set the node's data to data.
Set the node's left and right pointers to NULL.
Return the new node.
3. Swap(a, b):
 Swap the values of a and b.
4. Heapify(root):
 If root is NULL:

 Return.
 Set largest to root.
 If root->left is not NULL and root->left->data is greater than largest->data:
 Set largest to root->left.
 If root->right is not NULL and root->right->data is greater than largest->data:
 Set largest to root->right.
 If largest is not root:
 Swap root->data with largest->data.
 Call Heapify(largest).
5. BuildMaxHeap(root):
 If root is NULL:
 Return.
 Call BuildMaxHeap(root->left).
 Call BuildMaxHeap(root->right).
 Call Heapify(root).
6. ExtractMax(root):
 If root is NULL:
 Return NULL.
 Swap root->data with root->left->data.
 Move root to root->left.
 Call Heapify(root).
 Return root.
7. FindKthLargest(root, k):
 Call BuildMaxHeap(root).
 Initialize count to 0.
 While count is less than k:
 Set root to ExtractMax(root).
 Increment count by 1.
 Return root->data.
8. STOP

ADITYA SUMAN GAGORIYA 20 K1


/* Q 40: Get two roll no as inputs from user and find out whether they are friends or not. If yes find
their all mutual friends. Also find out those students who are not friends with both of them. */

Algorithm for createNode Function


Step1: START
Step2: Input: An integer roll_no.
Step3: Allocate memory for a new Node.
Step4: Set newNode's roll_no to roll_no.
Step5: Set newNode's next to NULL.
Step6: Output: Return newNode.
Step7: STOP

Algorithm for addFriend Function


Step8: START
Step9: Input: An adjacency list adjList, an integer student, and an integer friend.
Step10: Call createNode(friend) and assign it to newNode.
Step11: Set newNode's next to adjList[student].
Step12: Set adjList[student] to newNode.
Step13: STOP

Algorithm for printGraph Function


Step14: START
Step15: Input: An adjacency list adjList, and an integer numStudents.
Step16: For each i from 1 to numStudents:
Print "Student i is friend of".
While adjList[i] is not NULL:
Print adjList[i].roll_no.
Move to next node.
Step17: STOP

Algorithm for areFriends Function


Step18: START
Step19: Input: An adjacency list adjList, an integer student1, and an integer student2.
Step20: While adjList[student1] is not NULL:
If adjList[student1].roll_no is equal to student2:
Return 1.
Move to next node.
Step21: Output: Return 0.
Step22: STOP

Algorithm for findMutualFriends Function


Step23: START
Step24: Input: An adjacency list adjList, an integer student1, and an integer student2.
Step25: For each friend in adjList[student1]:
If areFriends(adjList, student2, friend) is true:
Print friend.
Step26: If no mutual friends found, print 0.
Step27: STOP

ADITYA SUMAN GAGORIYA 20 K1


Algorithm for notFriendsWithBoth Function
Step28: START
Step29: Input: An adjacency list adjList, an integer numStudents, an integer student1, and an integer
student2.
Step30: For each i from 1 to numStudents:
If i is not student1 and i is not student2 and areFriends(adjList, student1, i) is false and
areFriends(adjList, student2, i) is false:
Print i.
Step31: STOP

Algorithm for main Function


Step32: START
Step33: Print reasons for using adjacency list.
Step34: Input: An integer numStudents.
Step35: Initialize adjList.
Step36: Input: An integer numFriendships.
Step37: For each friendship, input student and friend:
Call addFriend(adjList, student, friend).
Call addFriend(adjList, friend, student).
Step38: Call printGraph(adjList, numStudents).
Step39: Input: Two integers student1 and student2.
Step40: If areFriends(adjList, student1, student2) is true:
Print "Students student1 and student2 are friends".
Call findMutualFriends(adjList, student1, student2).
Step41: Else:
Print "Students student1 and student2 are not friends".
Step42: Call notFriendsWithBoth(adjList, numStudents, student1, student2).
Step43: Free allocated memory.
Step44: STOP

ADITYA SUMAN GAGORIYA 20 K1

You might also like