Aads Lab Workbook - 23CS03HF
Aads Lab Workbook - 23CS03HF
LAB WORKBOOK
23CS03HF
3. Session 03: To implement programs on AVL Trees and Red-Black Trees.. .................………………………….....22
5. Session 05 : To implement programs on problem solving using Divide and Conquer – Scenario1. .............43
6. Session 06: To implement programs on problem solving using Divide and Conquer – Scenario2.............52
7. Session 07: To implement programs on problem solving using Greedy Approach – Scenario1.................61
8. Session 08: To implement programs on problem solving using Greedy Approach – Scenario2.................70
10. Session 10: To implement programs on problem solving using DP Approach – Scenario2........................85
11. Session 11: To implement programs on problem solving using Graph Algorithms – Scenario1.................92
12. Session 12: To implement programs on problem solving using Graph Algorithms – Scenario2...............100
13. Session 13: To implement programs on problem solving using Network Flow Algorithms.....................108
14. Session 14: To implement programs on prob.using String Matching Algorithms – Scenario 1................118
15. Session 15: To implement programs on prob. solving using String Matching Algorithms – Scenario2....128
A.Y. 2024-25 LAB CONTINUOUS EVALUATION
S.No. Date Experiment Name Pre- Lab In-Lab (25M) Post- Viva Total Faculty
(10M) Program/ Data and Analysis & Lab Voce (50M) Signature
Procedure Results Inference (10M) (5M)
(5M) (10M) (10M)
1 To implement basic
Programs on Arrays and
Linked Lists.
2 To implement basic
Programs on Stacks and
Queues.
3
To implement programs on
AVL Trees and Red-Black
Trees.
4
To implement programs on
B-Trees and Hash Tables.
5
To implement programs on
problem solving using
Divide and Conquer -–
Scenario1.
6
To implement programs on
problem solving using
Divide and Conquer –
Scenario2.
8
To implement programs on
problem solving using
Greedy Approach –
Scenario2.
9
To implement programs on
problem solving using
Dynamic Programming
Approach – Scenario1.
10
To implement programs on
problem solving using
Dynamic Programming
Approach – Scenario2.
11
To implement programs on
problem solving using
Graph Algorithms–
Scenario1
12
To implement programs on
problem solving using
Graph Algorithms–
Scenario2.
13
To implement programs on
problem solving using
Network Flow Algorithms.
14
To implement programs on
String Matching Algorithms
– Scenario1.
15
To implement programs on
String Matching Algorithms
– Scenario2.
Experiment #1 Student ID
Date Student Name
Aim/Objective: To understand the concept and implementation of programs on arrays and linked lists.
Description: The students will be able to implement programs on Arrays and Linked Lists.
Pre-Requisites:
Knowledge: Arrays and Linked Lists.
Tools: Code Blocks/Eclipse IDE
Pre-Lab:
1. An array is a type of data structure that stores elements of the same type in a contiguous
block of memory. In an array A, of size N , each memory location has some unique index
Returns
int[n]: the reversed array
Input Format
The first line contains an integer N , the number of integers in A .
The second line contains N space-separated integers that make up A.
Constraints
1 < N < 103
1 < A[i] < 104, where A[i] is the ith integer in A.
Sample Input 1
4
1432
Course Title Advanced Algorithms & Data Structures Academic Year: 2024-25
2341
Procedure/Program:
Course Title Advanced Algorithms & Data Structures Academic Year: 2024-25
2. There is a collection of input strings and a collection of query strings. For each query string,
determine how many times it occurs in the list of input strings. Return an array of the results.
Example
stringList = [‘ab’, ‘ab’, ‘abc’]
queries = [‘ab’, ‘abc’, ‘bc’]
There are 2 instances of ‘ab’, 1 of ‘abc’ and 0 of ‘bc’. For each query, add an element to the
return array, results = [2,1,0].
Function Description
Complete the function matchingStrings in the editor below. The function must return an array of
integers representing the frequency of occurrence of each query string in strings.
matchingStrings has the following parameters:
string stringList[n] – an array of strings to search
string queries[q] – an array of query strings
Returns
int[q]: an array of results for each query
Input Format
The first line contains and integer n, the size of stringList[].
Each of the next n lines contains a string stringList[i].
The next line contains q, the size of queries[].
Each of the next q lines contains a string queries[i] .
Constraints
1 < n < 103
1 < q < 103,
1 < stringList[i], queries[i] < 20
Course Title Advanced Algorithms & Data Structures Academic Year: 2024-25
Course Code 23CS03HF Page 3 of 132
Experiment #1 Student ID
Date Student Name
Procedure/Program:
Course Title Advanced Algorithms & Data Structures ACADEMIC YEAR: 2024-25
Course Code 23CS03HF Page 4 of 132
Experiment #1 Student ID
Date Student Name
In-Lab:
1. Given pointers to the heads of two sorted linked lists, merge them into a single, sorted linked
list. Either head pointer may be null meaning that the corresponding list is empty.
Example
headA refers to 1 -> 3 -> 7 -> NULL
headB refers to 1 -> 2 -> NULL
The new list is 1 -> 2 -> 3 -> 7 -> NULL
Function Description:
Complete the mergeLists function in the editor below.
mergeLists has the following parameters:
SinglyLinkedListNode pointer headA: a reference to the head of a list
SinglyLinkedListNode pointer headB: a reference to the head of a list
Returns
SinglyLinkedListNode pointer: a reference to the head of the merged list
Input Format
The first line contains an integer t, the number of test cases.
The format for each test case is as follows:
The first line contains an integer n, the length of the first linked list.
The next n lines contain an integer each, the elements of the linked list.
The next line contains an integer m, the length of the second linked list.
The next n lines contain an integer each, the elements of the second linked list.
Sample Input:
1
3
1
2
3
2
3
4
Course Title Advanced Algorithms & Data Structures ACADEMIC YEAR: 2024-25
Course Code 23CS03HF Page 5 of 132
Experiment #1 Student ID
Date Student Name
Sample Output:
12334
Explanation:
The first linked list is: 1 -> 2 -> 3 -> NULL
The second linked list is: 3 -> 4 -> NULL
Hence, the merged linked list is: 1 -> 2 -> 3 -> 3 -> 4 -> NULL
Procedure/Program:
Course Title Advanced Algorithms & Data Structures ACADEMIC YEAR: 2024-25
Course Code 23CS03HF Page 6 of 132
Experiment #1 Student ID
Date Student Name
2. You are given the pointer to the head node of a sorted linked list, where the data in the nodes is in
ascending order. Delete nodes and return a sorted list with each distinct value in the original list.
The given head pointer may be null indicating that the list is empty.
Example
head refers to the first node in the list.
1->2->2->3->3->3->3->NULL
Remove 1 of the 2 data values and return head pointing to the revised list, 1->2->3->NULL
Function Description
Complete the removeDuplicates function in the editor below.
removeDuplicates has the following parameter:
SinglyLinkedListNode pointer head: a reference to the head of the list
Returns
SinglyLinkedListNode pointer: a reference to the head of the revised list
Input Format
The first line contains an integer t , the number of test cases.
The format for each test case is as follows:
The first line contains an integer n, the number of elements in the linked list.
Each of the next n lines contains an integer, the data value for each of the elements of the linked
list.
Constraints
1<=t<=10
1<=n<=1000
1<=list[i]<=1000
Sample Input
STDIN Function
----- --------
1 t=1
5 n=5
1 data values = 1, 2, 2, 3, 4
2
2
3
4
Course Title Advanced Algorithms & Data Structures ACADEMIC YEAR: 2024-25
Course Code 23CS03HF Page 7 of 132
Experiment #1 Student ID
Date Student Name
Sample Output
1234
Procedure/Program:
Course Title Advanced Algorithms & Data Structures ACADEMIC YEAR: 2024-25
Course Code 23CS03HF Page 8 of 132
Experiment #1 Student ID
Date Student Name
Post-Lab:
1. How will you modify a linked list of integers so that all even numbers appear before all odd
numbers in the modified linked list? Also, keep the even and odd numbers in the same order.
Example:
Input: 17->15->8->12->10->5->4->1->7->6->NULL
Output: 8->12->10->4->6->17->15->5->1->7->NULL.
Procedure:
Course Title Advanced Algorithms & Data Structures ACADEMIC YEAR: 2024-25
Course Code 23CS03HF Page 9 of 132
Experiment #1 Student ID
Date Student Name
Course Title Advanced Algorithms & Data Structures ACADEMIC YEAR: 2024-25
Course Code 23CS03HF Page 10 of 132
Experiment #2 Student ID
Date Student Name
Aim/Objective: To understand the concept and implementation of programs on Stacks and Queues.
Description: The students will be able to implement programs on Stacks and Queues.
Pre-Requisites:
Knowledge: Stacks and Queues.
Tools: Code Blocks/Eclipse IDE
Pre-Lab:
1. You are given a stack of N integers. In one operation, you can either pop an element from the
stack or push any popped element into the stack. You need to maximize the top element of the
stack after performing exactly K operations. If the stack becomes empty after performing K
operations and there is no other way for the stack to be non-empty, print -1.
Input format :
The first line of input consists of two space-separated integers N and K.
The second line of input consists N space-separated integers denoting the elements of the stack.
The first element represents the top of the stack and the last element represents the bottom of the
stack.
Output format :
Print the maximum possible top element of the stack after performing exactly K operations.
Constraints :
1< N <=2*106
1< A_i < 1018
1<K<109
Sample Input :
64
124335
Sample Output :
4
Course Title Advanced Algorithms & Data Structures Academic Year: 2024-25
Explanation:
In 3 operations, we remove 1,2,4 and in the fourth operation, we push 4 back into the stack.
Hence, 4 is the answer.
Procedure/Program:
Course Title Advanced Algorithms & Data Structures Academic Year: 2024-25
2. You are given Q queries. Each query consists of a single number N. You can perform any of
the 2 operations on N in each move:
1: If we take 2 integers a and b where , N=a x b ( a≠1, b≠1), then we can change N= Max(a,b)
2: Decrease the value of N by 1.
Determine the minimum number of moves required to reduce the value of N to 0.
Input Format
The first line contains the integer Q.
The next Q lines each contain an integer, N.
Constraints
1<= Q <=103
0<= N <=106
Output Format
Output Q lines. Each line containing the minimum number of moves required to reduce the value
of N to 0.
Sample Input
2
3
4
Sample Output
3
3
Explanation
For test case 1, We only have one option that gives the minimum number of moves.
Follow 3 -> 2 -> 1 -> 0 . Hence, 3 moves.
For the case 2, we can either go 4 -> 3 -> 2 -> 1 -> 0 or 4 -> 2 -> 1 -> 0 . The 2nd option is more
optimal. Hence, 3 moves.
Course Title Advanced Algorithms & Data Structures Academic Year: 2024-25
Procedure/Program:
Course Title Advanced Algorithms & Data Structures ACADEMIC YEAR: 2024-25
Course Code 23CS03HF Page 14 of 132
Experiment #2 Student ID
Date Student Name
In-Lab:
Problem
1. A shop has a stack of chocolate boxes each containing a positive number of chocolates.
Initially, the stack is empty. During the next N minutes, either of these two things may happen:
The box of chocolates on top of the stack gets sold
You receive a box of chocolates from the warehouse and put it on top of the stack.
Determine the number of chocolates in the sold box each time he sells a box.
Notes
If C[i] = 0, he sells a box. If C[i] > 0, he receives a box containing C[i] chocolates.
It is confirmed that he gets a buyer only when he has a non-empty stack.
The capacity of the stack is infinite.
Example 1
Assumptions
Input
N=4
C = [2, 1, 0, 0]
Output: 1 2
Approach
After the first two minutes, the stack is [1, 2].
During the third minute, the box on the top having 1 chocolate is sold.
During the fourth minute, the box on the top having 2 chocolates is sold.
Function description
Complete the function solve() provided in the editor. The function takes the following 2 parameters
and returns the solution.
N: Represents the number of minutes
C: Represents the description of boxes
Input format for custom testing
Note: Use this input format if you are testing against custom input or writing code in a language
where we don’t provide boilerplate code
The first line contains N denoting the number of minutes.
The second line contains C denoting the array consisting of the box descriptions.
Output format
Print an array, representing the number of chocolates in the sold box each time you sell a box.
Course Title Advanced Algorithms & Data Structures ACADEMIC YEAR: 2024-25
Course Code 23CS03HF Page 15 of 132
Experiment #2 Student ID
Date Student Name
Constraints
1≤ N ≤105
0 ≤C[i]≤109
Sample Input
3
505
Sample Output
5
Procedure/Program:
Course Title Advanced Algorithms & Data Structures ACADEMIC YEAR: 2024-25
Course Code 23CS03HF Page 16 of 132
Experiment #2 Student ID
Date Student Name
Course Title Advanced Algorithms & Data Structures ACADEMIC YEAR: 2024-25
Course Code 23CS03HF Page 17 of 132
Experiment #2 Student ID
Date Student Name
Sample Output
54
321
Explanation
On the first day, the disk of size 4 is given. But you cannot put the disk on the bottom of the
tower as a disk of size 5 is still remaining.
On the second day, the disk of size 5 will be given so now disk of sizes 5 and 4 can be placed
on the tower.
On the third and fourth day, disks cannot be placed on the tower as the disk of 3 needs to be
given yet. Therefore, these lines are empty.
On the fifth day, all the disks of sizes 3, 2, and 1 can be placed on the top of the tower.
Procedure/Program:
Course Title Advanced Algorithms & Data Structures ACADEMIC YEAR: 2024-25
Course Code 23CS03HF Page 18 of 132
Experiment #2 Student ID
Date Student Name
Post-Lab:
1. Given an integer N with D digits without any leading zeroes. Find the largest number which
can be obtained by deleting exactly K digits from the number N.
Note: Return the largest number without any leading zeroes.
Input format
First line contains integer N.
Second line contains integer K.
Output format
Return the largest number which can be obtained by deleting exactly K digits from the
number N.
Constraints
N>0
1 ≤ D ≤ 106
0 ≤ K <D
Course Title Advanced Algorithms & Data Structures ACADEMIC YEAR: 2024-25
Course Code 23CS03HF Page 19 of 132
Experiment #2 Student ID
Date Student Name
Sample Input
44312
2
Sample Output
443
Procedure:
Course Title Advanced Algorithms & Data Structures ACADEMIC YEAR: 2024-25
Course Code 23CS03HF Page 20 of 132
Experiment #2 Student ID
Date Student Name
4. What is the time complexity of the enqueue and dequeue operations in a queue?
Course Title Advanced Algorithms & Data Structures ACADEMIC YEAR: 2024-25
Course Code 23CS03HF Page 21 of 132
Experiment #3 Student ID
Date Student Name
Aim/Objective: To understand the concepts and implementation of programs on AVL trees and Red-
Black Trees.
Description: To learn about AVL Trees and Red-Black Trees, their balancing techniques, operations,
and applications. Students will gain experience in implementing these trees, analyzing
their properties, and applying them to solve real-world problems.
Pre-Requisites:
Knowledge: BST, AVL Trees and Red-Black Trees.
Tools: Code Blocks/Eclipse IDE
Pre-Lab:
1. Extend a function to find the height of an AVL tree and verify that the tree is balanced.
Input:
Output:
Constraints :
The tree contains at most 105 nodes.
Procedure/Program:
Course Title Advanced Algorithms & Data Structures ACADEMIC YEAR: 2024-25
Course Code 23CS03HF Page 22 of 132
Experiment #3 Student ID
Date Student Name
2. Write a function that verifies if a given binary tree satisfies the Red-Black Tree properties.
Input:
Output:
Print "Valid Red-Black Tree" if the tree satisfies all Red-Black properties, otherwise, print
Constraints:
Procedure/Program:
Course Title Advanced Algorithms & Data Structures ACADEMIC YEAR: 2024-25
Course Code 23CS03HF Page 23 of 132
Experiment #3 Student ID
Date Student Name
In-Lab:
Problem :
1. Write a function to construct an AVL tree, where nodes are inserted while maintaining the
balance property. After each insertion, the tree should self-balance to remain AVL. Print the inorder
traversal of the tree after each insertion.
Input:
Output:
After each insertion, print the inorder traversal of the tree as space-separated values.
Course Title Advanced Algorithms & Data Structures ACADEMIC YEAR: 2024-25
Course Code 23CS03HF Page 24 of 132
Experiment #3 Student ID
Date Student Name
Sample Input:
5
20 15 25 10 5
Sample Output:
20
15 20
15 20 25
10 15 20 25
5 10 15 20 25
Constraints:
Each insertion should maintain the AVL property, with rotations performed as needed to keep
the tree balanced.
Procedure/Program:
Course Title Advanced Algorithms & Data Structures ACADEMIC YEAR: 2024-25
Course Code 23CS03HF Page 25 of 132
Experiment #3 Student ID
Date Student Name
2. You are given an unbalanced binary search tree, transform it into a Red-Black Tree. The program
should read the values, build the binary search tree, and then balance it into a Red-Black Tree while
maintaining its properties.
Input:
A series of integers representing the values to be inserted into the binary search tree.
Output:
Sample Input:
50 30 70 20 40 60 80
Sample Output:
20 30 40 50 60 70 80
Constraints:
The input tree must be transformed in O(n log n) time, and the Red-Black Tree properties should
be verified after the transformation.
Course Title Advanced Algorithms & Data Structures ACADEMIC YEAR: 2024-25
Course Code 23CS03HF Page 26 of 132
Experiment #3 Student ID
Date Student Name
Procedure/Program:
Course Title Advanced Algorithms & Data Structures ACADEMIC YEAR: 2024-25
Course Code 23CS03HF Page 27 of 132
Experiment #3 Student ID
Date Student Name
Post-Lab:
1. Given the root of an AVL tree and a level k, count the number of nodes at that level.
Input:
Output:
Procedure/Program:
Course Title Advanced Algorithms & Data Structures ACADEMIC YEAR: 2024-25
Course Code 23CS03HF Page 28 of 132
Experiment #3 Student ID
Date Student Name
Input:
The root node of a Red-Black tree, represented as a list of values that would form the tree
structure.
Output:
Procedure/Program:
Course Title Advanced Algorithms & Data Structures ACADEMIC YEAR: 2024-25
Course Code 23CS03HF Page 29 of 132
Experiment #3 Student ID
Date Student Name
Course Title Advanced Algorithms & Data Structures ACADEMIC YEAR: 2024-25
Course Code 23CS03HF Page 30 of 132
Experiment #4 Student ID
Date Student Name
Aim/Objective: To understand the concepts and implementation of programs on B-Trees and Hash
Tables.
Description: To learn about B-Trees and Hash Tables, operations, and applications. Students will gain
experience in implementing these data structures, analyzing their properties, and
applying them to solve real-world problems.
Pre-Requisites:
Knowledge: B-Trees, Hash Tables and Collision Resolution Techniques.
Tools: Code Blocks/Eclipse IDE.
Pre-Lab:
1. You are tasked with designing an index for a database using a B-tree of degree t. Given a dataset
of keys representing records in a database, implement an algorithm to insert these keys into a
B-tree. After constructing the B-tree, perform a series of range queries to fetch records.
Input:
Output: For each query, output the keys in the range [l, r] in sorted order.
Example
Input:
3
10
50 20 30 40 10 60 80 70 90 100
2
30 70
10 50
Course Title Advanced Algorithms & Data Structures ACADEMIC YEAR: 2024-25
Course Code 23CS03HF Page 31 of 132
Experiment #4 Student ID
Date Student Name
Output:
30 40 50 60 70
10 20 30 40 50
Procedure/Program:
Course Title Advanced Algorithms & Data Structures ACADEMIC YEAR: 2024-25
Course Code 23CS03HF Page 32 of 132
Experiment #4 Student ID
Date Student Name
2. Given a string S of length N consisting of only lower-case English alphabets, you will be asked to
process Q queries over it . In each query you will be given two lower case characters X and Y.
Your task is to find out the number of such substrings of the the string S which have the characters
X and Y on either of its end points, both X...Y and Y...X are considered to be valid.
Input Format
• The first line of the input will contain N , the length of the string.
• Next line will contain as string of length N. Next line will will contain Q , the number of
queries.
• Then Q subsequent lines will contain two lowercase characters X and Y separated by a
space.
Constraints
Output Format
Course Title Advanced Algorithms & Data Structures ACADEMIC YEAR: 2024-25
Course Code 23CS03HF Page 33 of 132
Experiment #4 Student ID
Date Student Name
Sample Input 0
5
aacbb
2
ac
ab
Sample Output 0
2
4
Procedure/Program:
Course Title Advanced Algorithms & Data Structures ACADEMIC YEAR: 2024-25
Course Code 23CS03HF Page 34 of 132
Experiment #4 Student ID
Date Student Name
In-Lab:
1. You are managing a large database system where quick insertion and search operations are essential
to handle high-volume transactions. The system uses a B-Tree to index its data for efficient disk-
based storage and retrieval.
Operations in Context:
1. Insert Operation:
A new record with key kkk (e.g., Employee ID) needs to be added to the database.
Example: Adding a new Employee ID 12345.
2. Search Operation:
A user queries the system to check if a record with a specific Employee ID exists.
Example: Searching for Employee ID 67890.
Sample Input :
26
INSERT 10123
INSERT 54321
INSERT 67890
SEARCH 10123
SEARCH 99999
SEARCH 67890
Course Title Advanced Algorithms & Data Structures ACADEMIC YEAR: 2024-25
Course Code 23CS03HF Page 35 of 132
Experiment #4 Student ID
Date Student Name
Sample Output:
YES
NO
YES
Procedure/Program:
Course Title Advanced Algorithms & Data Structures ACADEMIC YEAR: 2024-25
Course Code 23CS03HF Page 36 of 132
Experiment #4 Student ID
Date Student Name
2. Harold is a kidnapper who wrote a ransom note, but now he is worried it will be traced back to
him through his handwriting. He found a magazine and wants to know if he can cut out whole
words from it and use them to create an untraceable replica of his ransom note. The words in his
note are case-sensitive and he must use only whole words available in the magazine.
He cannot use substrings or concatenation to create the words he needs. Given the words in the
magazine and the words in the ransom note, print Yes if he can replicate his ransom
note exactly using whole words from the magazine; otherwise, print No.
Example
magazine = "attack at dawn" note = "Attack at dawn"
The magazine has all the right words, but there is a case mismatch. The answer is No .
Function Description
Complete the checkMagazine function in the editor below. It must print Yes if the note can be
formed using the magazine, or No.
Prints
string: either Yes or No. no return value is expected.
Course Title Advanced Algorithms & Data Structures ACADEMIC YEAR: 2024-25
Course Code 23CS03HF Page 37 of 132
Experiment #4 Student ID
Date Student Name
Input Format
The first line contains two space-separated integers m and n, the numbers of words in
the magazine and the note, respectively.
The second line contains m space-separated strings, each magazine[i].
The third line contains n space-separated strings, each note[i].
Constraints
1 < m < 30000
1 < lengthsofmagazine[i]andnote[i] < 5.
Each word consists of English alphabetic letters (i.e., a to z , A to Z).
Sample Input 0
64
Sample Output 0
Yes
Sample Input 1
65
Sample Output 1
No
Procedure/Program:
Course Title Advanced Algorithms & Data Structures ACADEMIC YEAR: 2024-25
Course Code 23CS03HF Page 38 of 132
Experiment #4 Student ID
Date Student Name
Post-Lab:
1. A library uses a B-Tree to manage its catalogue of books. Each book is identified by a unique
ISBN number.
Operations:
Insert: Add a new book to the catalog.
Search: Check if a book is available using its ISBN.
Course Title Advanced Algorithms & Data Structures ACADEMIC YEAR: 2024-25
Course Code 23CS03HF Page 39 of 132
Experiment #4 Student ID
Date Student Name
Procedure/Program:
Data and Results:
Course Title Advanced Algorithms & Data Structures ACADEMIC YEAR: 2024-25
Course Code 23CS03HF Page 40 of 132
Experiment #4 Student ID
Date Student Name
2. A university system uses a hash table to manage student IDs and their data.
Operations:
Insert: Add a new student to the database.
Search: Retrieve a student's information using their student ID.
Procedure/Program:
Data and Results:
Course Title Advanced Algorithms & Data Structures ACADEMIC YEAR: 2024-25
Course Code 23CS03HF Page 41 of 132
Experiment #4 Student ID
Date Student Name
Course Title Advanced Algorithms & Data Structures ACADEMIC YEAR: 2024-25
Course Code 23CS03HF Page 42 of 132
Experiment #5 Student ID
Date Student Name
Experiment Title: To implement programs on problem solving using Divide & Conquer –
Scenario1.
Aim/Objective: To understand the concept and implementation of Basic programs on Divide and
Conquer Problems..
Description: The students will understand and able to implement programs on Divide and Conquer
Problems.
Pre-Requisites:
Knowledge: Arrays, Sorting, Divide and Conquer in C/C++/Python
Tools: Code Blocks/Eclipse IDE.
Pre-Lab:
1. Given an array of integers A of size n, find the sum of the maximum subarray using the Divide
and Conquer approach.
Input Format:
The first line contains a single integer n (1≤n≤105), the size of the array.
The second line contains n integers A[i] (−104≤A[i]≤104).
Output Format:
Example 1:
Input: nums = [-2,1,-3,4,-1,2,1,-5,4]
Output: 6
Explanation: The subarray [4,-1,2,1] has the largest sum 6.
Procedure/Program:
Course Title Advanced Algorithms & Data Structures ACADEMIC YEAR: 2024-25
Course Code 23CS03HF Page 43 of 132
Experiment #5 Student ID
Date Student Name
2. Given a set of n points in a 2D plane, find the distance between the closest pair of points using the Divide
and Conquer approach.
Input Format:
The first line contains a single integer n (2 ≤ n ≤ 105).
Each of the next n lines contains two integers x and y (−106 ≤ x,y ≤ 106), representing
the coordinates of a point.
Output Format:
Print the distance between the closest pair of points, rounded to 6 decimal places.
Course Title Advanced Algorithms & Data Structures ACADEMIC YEAR: 2024-25
Course Code 23CS03HF Page 44 of 132
Experiment #5 Student ID
Date Student Name
Procedure/Program:
Course Title Advanced Algorithms & Data Structures ACADEMIC YEAR: 2024-25
Course Code 23CS03HF Page 45 of 132
Experiment #5 Student ID
Date Student Name
In-Lab:
1. Trade Unions are common these days in the industries. But the new manager of ByteComp don't
like those unions. He wants the division between them. Before he goes on process of division, he
wants to find out the number of ways in which he can divide the existing trade union in two parts
by kicking out one of the workers. Given N , the number of workers in the company and 'R' , the
number connections in the union and R pairs of connections. Find the ways in which the original
configuration of union can be divided.
Input Format:
The first line of input contains two space separated integers N and R.
The next R lines contain the relation among workers. The workers are numbered from 0 to N-1.
Output Format:
Print the number of ways in which the trade union can be divided into two parts.
Constraints:
0 < N < 10000
0 < R < 10000
Sample Input
44
20
21
23
10
Sample Output
1
Procedure/Program:
Course Title Advanced Algorithms & Data Structures ACADEMIC YEAR: 2024-25
Course Code 23CS03HF Page 46 of 132
Experiment #5 Student ID
Date Student Name
Course Title Advanced Algorithms & Data Structures ACADEMIC YEAR: 2024-25
Course Code 23CS03HF Page 47 of 132
Experiment #5 Student ID
Date Student Name
2. A bank wants to detect fraudulent transactions from a massive stream of data. Apply Divide and
Conquer approach to identify those potential frauds, that helps in preventing financial losses and
improving security.
Sample Input:
Number of transactions: 10
Transaction Data (in dollars): [500, 1500, 600, 5000, 700, 800, 1200, 2500, 100, 10000]
Explanation: Each number represents the transaction amount. The data stream represents
transactions happening in real-time.
Sample Output:
Fraudulent Transactions Detected:
- Transaction 4: $5000 (anomaly detected based on pattern analysis)
- Transaction 10: $10000 (significant deviation from typical transaction patterns)
Procedure/Program:
Course Title Advanced Algorithms & Data Structures ACADEMIC YEAR: 2024-25
Course Code 23CS03HF Page 48 of 132
Experiment #5 Student ID
Date Student Name
Post-Lab:
A GPS navigation system needs to find the shortest route in a massive map database by querying
specific road segments. Apply Divide and Conquer strategy to locate the desired road segment
quickly, that ensures the faster route calculations improving the user experience.
Sample Input:
Database of Road Segments (sorted by start location):
[
{"start": "A", "end": "B", "distance": 10},
{"start": "B", "end": "C", "distance": 15},
{"start": "C", "end": "D", "distance": 20},
{"start": "D", "end": "E", "distance": 5},
{"start": "E", "end": "F", "distance": 8},
{"start": "F", "end": "G", "distance": 12}
]
Query: Find road segment from "B" to "D"
Sample Output:
Found road segment: {"start": "C", "end": "D", "distance": 20}
Course Title Advanced Algorithms & Data Structures ACADEMIC YEAR: 2024-25
Course Code 23CS03HF Page 49 of 132
Experiment #5 Student ID
Date Student Name
Procedure/Program:
Course Title Advanced Algorithms & Data Structures ACADEMIC YEAR: 2024-25
Course Code 23CS03HF Page 50 of 132
Experiment #5 Student ID
Date Student Name
Course Title Advanced Algorithms & Data Structures ACADEMIC YEAR: 2024-25
Course Code 23CS03HF Page 51 of 132
Experiment #6 Student ID
Date Student Name
Experiment Title: To implement programs on problem solving using Divide & Conquer –
Scenario2.
Aim/Objective: To understand the concept and implementation of Basic programs on Divide and
Conquer Problems.
Description: The students will understand and able to implement programs on Divide and Conquer
Problems.
Pre-Requisites:
Knowledge: Arrays, Sorting, Divide and Conquer in C/C++/Python
Tools: Code Blocks/Eclipse IDE.
Pre-Lab:
1. Given an array arr, count the number of inversions in the array. Two elements form an inversion if arr[i]
> arr[j] and i < j. Use the Divide and Conquer method to solve the problem efficiently.
Input Format:
First line contains an integer n, the size of the array.
Second line contains n space-separated integers representing the array.
Output Format:
Example :
Input:
5
24135
Output: 3
Procedure/Program:
Course Title Advanced Algorithms & Data Structures ACADEMIC YEAR: 2024-25
Course Code 23CS03HF Page 52 of 132
Experiment #6 Student ID
Date Student Name
2. Find the kth smallest element in an array using the Median of Medians algorithm (a Divide and Conquer-
based selection algorithm).
Input Format:
First line contains two integers n and k.
Second line contains n space-separated integers representing the array.
Output Format:
Print the kth smallest element.
Course Title Advanced Algorithms & Data Structures ACADEMIC YEAR: 2024-25
Course Code 23CS03HF Page 53 of 132
Experiment #6 Student ID
Date Student Name
Example :
Input:
6 3
7 10 4 3 20 15
Output:
7
Procedure/Program:
Course Title Advanced Algorithms & Data Structures ACADEMIC YEAR: 2024-25
Course Code 23CS03HF Page 54 of 132
Experiment #6 Student ID
Date Student Name
In-Lab:
1. Choose some pivot element, p, and partition your unsorted array, arr, into three smaller
arrays: left, right, and equal, where each element in left < p, each element in right > p, and each
element in equal = p.
Example
arr = [5, 7, 4, 3, 8]
In this challenge, the pivot will always be at arr[0], so the pivot is 5.
arr is divided into left = {4,3}, equal = {5}, and right = {7,8}. Putting them all together, you
get {4,3,5,7,8}. There is a flexible checker that allows the elements of left and right to be in any
order. For example, {3,4,5,8,7} is valid as well.
Given arr and p = arr[0], partition arr into left, right, and equal using the Divide instructions
above. Return a 1-dimensional array containing each element in left first, followed by each element
in equal, followed by each element in right.
Function Description
Complete the quickSort function in the editor below.
quickSort has the following parameter(s):
int arr[n]: arr[0] is the pivot element
Returns
int[n]: an array of integers as described above
Input Format
The first line contains n, the size of arr. The second line contains n space-separated
integers arr[i] (the unsorted array). The first integer, arr[0], is the pivot element, p.
Constraints
1 <= n <= 1000
Sample Input
STDIN Function
----- --------
5 arr[] size n =5
45372 arr =[4, 5, 3, 7, 2]
Sample Output
32457
Course Title Advanced Algorithms & Data Structures ACADEMIC YEAR: 2024-25
Course Code 23CS03HF Page 55 of 132
Experiment #6 Student ID
Date Student Name
Procedure/Program:
Course Title Advanced Algorithms & Data Structures ACADEMIC YEAR: 2024-25
Course Code 23CS03HF Page 56 of 132
Experiment #6 Student ID
Date Student Name
2. You are given k painters to paint n boards. Each painter takes 1 unit of time to paint 1 unit of the
board. Find the minimum time required to paint all boards using Divide and Conquer and Binary
Search.
Input Format:
First line contains two integers n (number of boards) and k (number of painters).
Second line contains n space-separated integers representing the lengths of the boards.
Output:
Procedure/Program:
Course Title Advanced Algorithms & Data Structures ACADEMIC YEAR: 2024-25
Course Code 23CS03HF Page 57 of 132
Experiment #6 Student ID
Date Student Name
Post-Lab:
Find the longest common prefix among an array of strings using Divide and Conquer.
Input Format:
First line contains an integer n, the number of strings.
Next n lines each contain a string.
Output:
Print the longest common prefix. If there is no common prefix, print an empty string.
Sample Input:
3
flower
flow
flight
Output:
fl
Course Title Advanced Algorithms & Data Structures ACADEMIC YEAR: 2024-25
Course Code 23CS03HF Page 58 of 132
Experiment #6 Student ID
Date Student Name
Procedure/Program:
Course Title Advanced Algorithms & Data Structures ACADEMIC YEAR: 2024-25
Course Code 23CS03HF Page 59 of 132
Experiment #6 Student ID
Date Student Name
Course Title Advanced Algorithms & Data Structures ACADEMIC YEAR: 2024-25
Course Code 23CS03HF Page 60 of 132
Experiment #7 Student ID
Date Student Name
Pre-Lab:
1. You are given a list of N rescue boats and M stranded people. Each boat can rescue one person, but only if
they are within a certain distance D. Find the maximum number of people that can be rescued.
Input Format:
First line: Two integers N (boats) and M (people).
Second line: N integers representing the positions of the boats.
Third line: M integers representing the positions of the people.
Fourth line: Integer D (maximum distance a boat can travel to rescue).
Output :
Maximum number of people that can be rescued.
Example :
Input:
34
1 5 10
2 6 8 11
2
Output:
3
Procedure/Program:
Course Title Advanced Algorithms & Data Structures ACADEMIC YEAR: 2024-25
Course Code 23CS03HF Page 61 of 132
Experiment #7 Student ID
Date Student Name
2. Given a weighted directed graph, a source node, a destination node, and an integer 𝑘 k, determine the
shortest path from the source to the destination using at most 𝑘 k edges. If no path exists within the limit,
return -1
Input Format:
Graph:
Nodes: 0, 1, 2, 3
Course Title Advanced Algorithms & Data Structures ACADEMIC YEAR: 2024-25
Course Code 23CS03HF Page 62 of 132
Experiment #7 Student ID
Date Student Name
Edges:
(0 -> 1, weight: 4)
(0 -> 2, weight: 3)
(1 -> 3, weight: 2)
(2 -> 3, weight: 5)
Source: 0
Destination: 3 k: 2
Output :
Shortest Path Length: 6
Explanation:
Possible paths from 0 to 3 within 2 edges:
Path 0 -> 1 -> 3 has a total weight of 4 + 2 = 6 4+2=6.
Path 0 -> 2 -> 3 has a total weight of 3 + 5 = 8 3+5=8.
The shortest path within 2 edges is 0 -> 1 -> 3 with a total weight of 6
Procedure/Program:
Course Title Advanced Algorithms & Data Structures ACADEMIC YEAR: 2024-25
Course Code 23CS03HF Page 63 of 132
Experiment #7 Student ID
Date Student Name
In-Lab:
1. A group of friends want to buy a bouquet of flowers. The florist wants to maximize his number of
new customers and the money he makes. To do this, he decides he'll multiply the price of each
flower by the number of that customer's previously purchased flowers plus 1. The first flower will
be original price (0+1)*original price, the next will be (1 +1) * original price and so on. Given the
size of the group of friends, the number of flowers they want to purchase and the original prices of
the flowers, determine the minimum cost to purchase all of the flowers. The number of flowers
they want equals the length of the array.
Input Format
The first line contains two space-separated integers’ n and k, the number of flowers and the number
of friends. The second line contains n space-separated positive integers c[i], the original price of
each flower.
Sample Input
33
256
Sample Output
13
Course Title Advanced Algorithms & Data Structures ACADEMIC YEAR: 2024-25
Course Code 23CS03HF Page 64 of 132
Experiment #7 Student ID
Date Student Name
Procedure/Program:
Course Title Advanced Algorithms & Data Structures ACADEMIC YEAR: 2024-25
Course Code 23CS03HF Page 65 of 132
Experiment #7 Student ID
Date Student Name
2. Goodland is a country with a number of evenly spaced cities along a line. The distance between
adjacent cities is 1 unit. There is an energy infrastructure project planning meeting, and the
government needs to know the fewest number of power plants needed to provide electricity to the
entire list of cities. Determine that number. If it cannot be done, return -1. You are given a list of
city data. Cities that may contain a power plant have been labeled 1. Others not suitable for building
a plant are labeled 0. Given a distribution range of k, find the lowest number of plants that must be
built such that all cities are served. The distribution range limits supply to cities where distance is
less than k.
Example:
K=3
Arr= [0, 1, 1, 1, 0, 0, 0]
Each city is 1 unit distance from its neighbors, and we'll use based indexing. We see there are 3
cities suitable for power plants, cities 1,2, and 3. If we build a power plant at arr[2] , it can serve
arr[0] through arr[4] because those endpoints are at a distance of 2 and 2<k . To serve arr[6], we
would need to be able to build a plant in city 4,5 or 6 . Since none of those is suitable, we must
return -1. It cannot be done using the current distribution constraint.
Sample Input:
STDIN Function
----- --------
62 arr[] size n = 6, k = 2
011110 arr = [0, 1, 1, 1, 1, 0]
Sample Output:
2
Explanation
Cities c[1] ,c[2] ,c[3] , and c[4] are suitable for power plants. Each plant will have a range
of k=2. If we build in cities 2 cities c[1] and c[4], then all cities will have electricity.
Procedure/Program:
Course Title Advanced Algorithms & Data Structures ACADEMIC YEAR: 2024-25
Course Code 23CS03HF Page 66 of 132
Experiment #7 Student ID
Date Student Name
Post-Lab:
Given an array of jobs where every job has a deadline and associated profit if the job is finished before
the deadline. It is also given that every job takes a single unit of time, so the minimum possible
deadline for any job is 1. Maximize the total profit if only one job can be scheduled at a time.
Input Format:
Five Jobs with following deadlines and profits :
Course Title Advanced Algorithms & Data Structures ACADEMIC YEAR: 2024-25
Course Code 23CS03HF Page 67 of 132
Experiment #7 Student ID
Date Student Name
Procedure/Program:
Course Title Advanced Algorithms & Data Structures ACADEMIC YEAR: 2024-25
Course Code 23CS03HF Page 68 of 132
Experiment #7 Student ID
Date Student Name
Knapsack Problem?
Course Title Advanced Algorithms & Data Structures ACADEMIC YEAR: 2024-25
Course Code 23CS03HF Page 69 of 132
Experiment #8 Student ID
Date Student Name
Pre-Lab:
1. A group of children are seated in a row, each with a different performance score. Tom wants to distribute
candies in such a way that: Every child must receive at least 1 candy. Children with higher performance
scores than their neighbors should receive more candies. The total number of candies should be minimized.
Your task is to determine the total number of candies Tom should distribute.
Input Format:
The first line contains an integer n (the number of children).
The next n lines contain an integer representing the performance score of each child.
Output :
The total minimum number of candies that need to be distributed.
Sample Input:
4
1234
Sample Output:
10
Procedure/Program:
Course Title Advanced Algorithms & Data Structures ACADEMIC YEAR: 2024-25
Course Code 23CS03HF Page 70 of 132
Experiment #8 Student ID
Date Student Name
2. Given A shop sells items, and a group of friends wants to buy all of them. Each item's price increases based
on how many items that person has already purchased. Find the minimum cost to buy all items by
distributing purchases among friends.
Input:
64
713456
Course Title Advanced Algorithms & Data Structures ACADEMIC YEAR: 2024-25
Course Code 23CS03HF Page 71 of 132
Experiment #8 Student ID
Date Student Name
Output :
38
Explanation:
Assign the most expensive items first to distribute the increasing cost among friends.
Procedure/Program:
Course Title Advanced Algorithms & Data Structures ACADEMIC YEAR: 2024-25
Course Code 23CS03HF Page 72 of 132
Experiment #7 Student ID
Date Student Name
In-Lab:
1. The absolute difference is the positive difference between two values a and b, is written |a-b| or |b-a|
and they are equal. If a=3 and b=2, |3-2|=|2-3|=1. Given an array of integers, find the minimum
absolute difference between any two elements in the array.
Input Format
Arr= [-2, 2, 4]
There are 3 pairs of numbers: [-2, 2], [-2, 4] and [2, 4]. The absolute differences for these pairs are|
(-2)-2|=4, | (-2)-4 |=6and |2-4|=2. The minimum absolute difference is 2.
Function Description:
Complete the minimum Absolute Difference function in the editor below. It should return an integer
that represents the minimum absolute difference between any pair of elements.
Minimum Absolute Difference has the following parameter(s):
Int arr[n]: an array of integers
Returns int: the minimum absolute difference found
Input Format:
The first line contains a single integer n, the size of arr.
The second line contains n space-separated integers, arr[i].
Sample Input
3
3 -7 0
Sample Output
3
Course Title Advanced Algorithms & Data Structures ACADEMIC YEAR: 2024-25
Course Code 23CS03HF Page 73 of 132
Experiment #8 Student ID
Date Student Name
Procedure/Program:
Course Title Advanced Algorithms & Data Structures ACADEMIC YEAR: 2024-25
Course Code 23CS03HF Page 74 of 132
Experiment #8 Student ID
Date Student Name
2. You have a list of movies, each with a certain "energy cost" associated with watching it. After
watching a movie, the effort required for the next movie increases exponentially. Specifically, if you
have already watched i movies, the next movie will require 2i ×energy cost energy. Your task is to
determine the minimum total energy required to watch all the movies, given that you can watch them
in any order.
Input Format :
An integer n, representing the number of movies.
An array energy [] of size n, where energy[i] represents the energy cost of watching the ith movie.
Output Format:
A single integer representing the minimum total energy required to watch all movies.
Sample Input:
3
[3, 2, 5]
Sample Output:
17
Procedure/Program:
Course Title Advanced Algorithms & Data Structures ACADEMIC YEAR: 2024-25
Course Code 23CS03HF Page 75 of 132
Experiment #8 Student ID
Date Student Name
Post-Lab:
Given an array of ages of size n, where each element represents the age of a person, the task is to
group people into different age groups. Each group should contain people whose ages have a
difference of at most 2 years. Return the groups formed.
Input Format:
An integer array ages [] of size N.
Output:
A list of groups, where each group is a list containing people within an age difference of at most
2 years.
Sample Input:
ages = [25, 30, 35, 32, 28, 23, 40, 45, 22].
Input Format:
[[25, 23], [30, 32, 28], [35, 40], [45], [22]].
Procedure/Program:
Course Title Advanced Algorithms & Data Structures ACADEMIC YEAR: 2024-25
Course Code 23CS03HF Page 76 of 132
Experiment #8 Student ID
Date Student Name
Course Title Advanced Algorithms & Data Structures ACADEMIC YEAR: 2024-25
Course Code 23CS03HF Page 77 of 132
Experiment #8 Student ID
Date Student Name
3. How does the greedy strategy work in job scheduling with deadlines?
Course Title Advanced Algorithms & Data Structures ACADEMIC YEAR: 2024-25
Course Code 23CS03HF Page 78 of 132
Experiment #9 Student ID
Date Student Name
Pre-Lab:
Suppose you are given different types of Lego blocks with heights 1 cm, 2 cm, and 5 cm, and you need to build
a tower of height N = 7 cm. Determine the total number of unique combinations of blocks that can sum up to
7cm, where the order of blocks does not matter.
Input : N=7
Output : 6
Explanation :
1. 1 + 1 + 1 + 1 + 1 + 1 + 1 = 7 cm
2. 1 + 1 + 1 + 1 + 1 + 2 = 7 cm
3. 1 + 1 + 1 + 2 + 2 = 7 cm
4. 1 + 1 + 5 = 7 cm
5. 1 + 2 + 2 + 2 = 7 cm
6. 2 + 5 = 7 cm
Procedure/Program:
Course Title Advanced Algorithms & Data Structures ACADEMIC YEAR: 2024-25
Course Code 23CS03HF Page 79 of 132
Experiment #9 Student ID
Date Student Name
In-Lab:
1. Emma, working at a wildlife reserve, needs to distribute bird feed equally among several feed
stations. She can add feed to several stations in each operation. Calculate the minimum number
of operations needed to ensure all stations have the same amount of feed
Course Title Advanced Algorithms & Data Structures ACADEMIC YEAR: 2024-25
Course Code 23CS03HF Page 80 of 132
Experiment #9 Student ID
Date Student Name
Example
For Example, stations = [1, 2, 7] stations represent the starting feed amounts. She can add 2 feed
units to the first two stations. Now the distribution is [3, 4, 7]. In the next round, she adds 3 units
each to the first two stations, evening them out to [6, 7, 7], and finally, one more round of 1 unit
to the first station will result in [7, 7, 7]. The total number of rounds required is 3.
Function Description:
equalize_feed has the following parameter(s):
• int stations[n]: the feed amounts to equalize
Returns int: the minimum number of operations required
Sample Input
t = 1: Indicates the number of test cases.
n = 3: Number of stations.
stations = [1, 2, 7]: The positions of the stations.
Sample Output
3
Procedure/Program:
Course Title Advanced Algorithms & Data Structures ACADEMIC YEAR: 2024-25
Course Code 23CS03HF Page 81 of 132
Experiment #9 Student ID
Date Student Name
Post-Lab:
Suppose you are given different types of Lego blocks with heights 1 cm, 2 cm, and 5 cm, and you need to
build a tower of height N = 8 cm. Determine the total number of unique combinations of blocks that can sum
up to 8cm, where the order of blocks does not matter.
Input : N=8
Output : 9
Explanation :
1. 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 = 8 cm
2. 1 + 1 + 1 + 1 + 1 + 1 + 2 = 8 cm
3. 1 + 1 + 1 + 2 + 2 = 8 cm
4. 1 + 1 + 2 + 2 + 2 = 8 cm
5. 1 + 2 + 2 + 2 + 1 = 8 cm
6. 2 + 2 + 2 + 2 = 8 cm
7. 1 + 1 + 1 + 5 = 8 cm
8. 1 + 2 + 5 = 8 cm
9. 2 + 6 = 8 cm
Procedure/Program:
Course Title Advanced Algorithms & Data Structures ACADEMIC YEAR: 2024-25
Course Code 23CS03HF Page 82 of 132
Experiment #9 Student ID
Date Student Name
Course Title Advanced Algorithms & Data Structures ACADEMIC YEAR: 2024-25
Course Code 23CS03HF Page 83 of 132
Experiment #9 Student ID
Date Student Name
Sample VIVA-VOCE Questions (In-Lab):
Course Title Advanced Algorithms & Data Structures ACADEMIC YEAR: 2024-25
Course Code 23CS03HF Page 84 of 132
Experiment #10 Student ID
Date Student Name
Pre-Lab:
1. Given two strings s1 and s2, find the length of their longest common subsequence (LCS). A subsequence
is a sequence derived from another sequence by deleting some elements without changing the order of the
remaining elements.
Input Format:
A string s1 of length m.
A string s2 of length n.
Output Format :
A single integer, the length of the LCS.
Constraints:
1≤m,n≤103
Example Input:
abcde
ace
Example Output:
3
Procedure/Program:
Course Title Advanced Algorithms & Data Structures ACADEMIC YEAR: 2024-25
Course Code 23CS03HF Page 85 of 132
Experiment #10 Student ID
Date Student Name
In-Lab:
Christy is interning at Dairymilk. One day she has to distribute some chocolates to her colleagues. She
is biased towards her friends and plans to give them more than the others. One of the program managers
hears of this and tells her to make sure everyone gets the same number.
To make things difficult, she must equalize the number of chocolates in a series of operations. For each
operation, she can give 1,2 or 5 pieces to all but one colleague. Everyone who gets a piece in a round
receives the same number of pieces.
Given a starting distribution, calculate the minimum number of operations needed so that every colleague
has the same number of pieces.
Course Title Advanced Algorithms & Data Structures ACADEMIC YEAR: 2024-25
Course Code 23CS03HF Page 86 of 132
Experiment #10 Student ID
Date Student Name
Example
arr = [1,1,5]
arr represents the starting numbers of pieces for each colleague. She can give 2 pieces to the first
two and the distribution is then [3,3,5] . On the next round, she gives the same two 2 pieces each,
and everyone has the same number: [5,5,5] . Return the number of rounds, 2.
Function Description:
Complete the equal function in the editor below.
equal has the following parameter(s):
int arr[n]: the integers to equalize
Sample Output
2
Procedure/Program:
Course Title Advanced Algorithms & Data Structures ACADEMIC YEAR: 2024-25
Course Code 23CS03HF Page 87 of 132
Experiment #10 Student ID
Date Student Name
For each query, print YES on a new line if it's possible to make string a equal to string b . Otherwise,
print NO
Course Title Advanced Algorithms & Data Structures ACADEMIC YEAR: 2024-25
Course Code 23CS03HF Page 88 of 132
Experiment #10 Student ID
Date Student Name
Sample Input
1
daBcd
ABC
Sample Output
YES
Procedure/Program:
Course Title Advanced Algorithms & Data Structures ACADEMIC YEAR: 2024-25
Course Code 23CS03HF Page 89 of 132
Experiment #10 Student ID
Date Student Name
Post-Lab:
You are given n items, each with a weight w[i] and value v[i], and a knapsack of capacity W. Determine the
maximum value you can achieve by selecting items without exceeding the capacity of the knapsack.
Input Format:
An integer n, the number of items.
An integer W, the capacity of the knapsack.
Two arrays of integers, w and v, each of size n, where w[i] is the weight and v[i] is the value
of the ith item.
Output Format:
A single integer, the maximum value that can be achieved.
Example Input:
45
2345
3456
Example Output:
7
Procedure/Program:
Course Title Advanced Algorithms & Data Structures ACADEMIC YEAR: 2024-25
Course Code 23CS03HF Page 90 of 132
Experiment #10 Student ID
Date Student Name
1. Why does solving some problems using recursion lead to stack overflow, but not when solved
using dynamic programming?.
2. Can you reduce the space complexity of the Longest Increasing Subsequence problem? How?
3. Describe a scenario where a greedy algorithm fails, but dynamic programming succeeds.
4. In a DP problem, how do you decide the order of computation in a bottom-up approach?
5. How would you debug a DP solution that gives incorrect results?
Evaluator MUST ask Viva-voce prior to signing and posting marks for each experiment.
Course Title Advanced Algorithms & Data Structures ACADEMIC YEAR: 2024-25
Course Code 23CS03HF Page 91 of 132
Experiment #11 Student ID
Date Student Name
Knowledge: Before beginning this lab, students should have a foundational understanding of:
The concepts of DFS , BFS,Single Source Shortest Path, and All-Pairs Shortest path
algorithms.
Mathematical Background: Logarithmic complexity analysis for tree operations.
Understanding of height-balanced properties.
Tools: Code Blocks/Eclipse IDE.
Pre-Lab:
Write a program to find the shortest path from a starting point (e.g., a person’s location) to the nearest exit in
a building represented as a grid using BFS.
Procedure/Program:
Course Title Advanced Algorithms & Data Structures ACADEMIC YEAR: 2024-25
Course Code 23CS03HF Page 92 of 132
Experiment #11 Student ID
Date Student Name
In-Lab:
1. You are given a connected, undirected graph representing a network of cities. Each edge represents a
road between two cities with a given cost. Write a program to find the Minimum Spanning Tree
(MST), which connects all cities with the minimum total cost.
Procedure/Program:
Course Title Advanced Algorithms & Data Structures ACADEMIC YEAR: 2024-25
Course Code 23CS03HF Page 93 of 132
Experiment #11 Student ID
Date Student Name
Course Title Advanced Algorithms & Data Structures ACADEMIC YEAR: 2024-25
Course Code 23CS03HF Page 94 of 132
Experiment #10 Student ID
Date Student Name
Analysis and Inferences:
2. You are given a city map represented as a graph. Write a program to determine if there is a path
between two given intersections (nodes). Use Depth-First Search (DFS) or Breadth-First Search
(BFS) to solve the problem.
Procedure/Program:
Course Title Advanced Algorithms & Data Structures ACADEMIC YEAR: 2024-25
Course Code 23CS03HF Page 95 of 132
Experiment #11 Student ID
Date Student Name
Course Title Advanced Algorithms & Data Structures ACADEMIC YEAR: 2024-25
Course Code 23CS03HF Page 96 of 132
Experiment #11 Student ID
Date Student Name
Post-Lab:
Consider the following directed weighted graph and Using Floyd-Warshall Algorithm, find the shortest path
distance between every pair of vertices.
Procedure/Program:
Course Title Advanced Algorithms & Data Structures ACADEMIC YEAR: 2024-25
Course Code 23CS03HF Page 97 of 132
Experiment #11 Student ID
Date Student Name
Course Title Advanced Algorithms & Data Structures ACADEMIC YEAR: 2024-25
Course Code 23CS03HF Page 98 of 132
Experiment #11 Student ID
Date Student Name
Evaluator MUST ask Viva-voce prior to signing and posting marks for each experiment.
Course Title Advanced Algorithms & Data Structures ACADEMIC YEAR: 2024-25
Course Code 23CS03HF Page 99 of 132
Experiment #12 Student ID
Date Student Name
Knowledge: Before beginning this lab, students should have a foundational understanding of:
The concepts of Prim’s and Kruskal’s Algorithm and All-Pairs Shortest path
algorithms.
Mathematical Background: Logarithmic complexity analysis for tree operations.
Understanding of height-balanced properties.
Tools: Code Blocks/Eclipse IDE.
Pre-Lab:
You are tasked with designing an optimal railway network to connect different cities in a newly developed
region. Each pair of cities is connected by a possible railway line with a specified construction cost. Your
objective is to construct a railway network that connects all the cities with the minimum total cost,
ensuring that no cycles are formed. (Kruskal’s Algorithm)
Input Format:
A list of cities (nodes) and possible railway lines (edges) with their respective costs (weights).
The graph is represented as an edge list.
Output Format:
The edges included in the Minimum Spanning Tree (MST).
The total cost of the MST.
Steps involved in the selection of edges.
Sample Input:
There are 5 cities: A, B, C, D, and E. The possible railway connections and their costs are:
Course Title Advanced Algorithms & Data Structures ACADEMIC YEAR: 2024-25
Course Code 23CS03HF Page 100 of 132
Experiment #12 Student ID
Date Student Name
Sample Output:
The MST should connect all cities with the minimum cost.
Example output:
Edges in MST:
B -- C (2)
A -- C (3)
C -- D (5)
C -- E (7)
Total Cost: 17
Procedure/Program:
Course Title Advanced Algorithms & Data Structures ACADEMIC YEAR: 2024-25
Course Code 23CS03HF Page 101 of 132
Experiment #12 Student ID
Date Student Name
In-Lab:
You are a network engineer tasked with designing a communication network for a new office
campus. The campus consists of several buildings (nodes), and you need to lay out network cables
(edges) between these buildings to ensure all buildings are connected. The cost of laying cables
between two buildings depends on the distance between them. Your objective is to design the
network with the minimum total cost while ensuring all buildings are connected. (Prim's
Algorithm).
Input Format:
The number of buildings (nodes) and the distances (weights) between them.
The graph is represented by an adjacency matrix.
Output Format:
Example:
The campus has 5 buildings: A, B, C, D, and E. The distances between buildings are
represented in the table below:
Course Title Advanced Algorithms & Data Structures ACADEMIC YEAR: 2024-25
Course Code 23CS03HF Page 102 of 132
Experiment #12 Student ID
Date Student Name
Expected Output:
Course Title Advanced Algorithms & Data Structures ACADEMIC YEAR: 2024-25
Course Code 23CS03HF Page 103 of 132
Experiment #12 Student ID
Date Student Name
Course Title Advanced Algorithms & Data Structures ACADEMIC YEAR: 2024-25
Course Code 23CS03HF Page 104 of 132
Experiment #12 Student ID
Date Student Name
Post-Lab:
Using Dijkstra's algorithm, find out the shortest distance from the source vertex 's' to the rest of the vertices
in the given graph. Also write the order in which all the vertices of the graph are visited.
Procedure/Program:
Course Title Advanced Algorithms & Data Structures ACADEMIC YEAR: 2024-25
Course Code 23CS03HF Page 105 of 132
Experiment #12 Student ID
Date Student Name
Course Title Advanced Algorithms & Data Structures ACADEMIC YEAR: 2024-25
Course Code 23CS03HF Page 106 of 132
Experiment #12 Student ID
Date Student Name
1. What is the difference between the Single-Source Shortest Path (SSSP) and the All-Pairs Shortest
Path (APSP) problem?
2. What are some real-world applications of All-Pairs Shortest Path algorithms?
3. How does Prim’s algorithm ensure that no cycles are formed in the MST?
4. What data structure is commonly used to implement Kruskal’s algorithm?
5. How does the choice of data structure affect the efficiency of Prim’s and Kruskal’s algorithms?
Evaluator MUST ask Viva-voce prior to signing and posting marks for each experiment.
Course Title Advanced Algorithms & Data Structures ACADEMIC YEAR: 2024-25
Course Code 23CS03HF Page 107 of 132
Experiment #13 Student ID
Date Student Name
Experiment Title: To implement programs on problem solving using Network Flow Algorithms.
Pre-Lab:
You are given a directed graph representing a flow network, where each edge has a capacity. Your
task is to compute the maximum flow from a source node s to a sink node t using the Ford-Fulkerson
method.
Input Format:
An integer n, the number of nodes in the graph.
An integer m, the number of edges in the graph.
The next m lines each contain three integers u, v, and c, representing a directed edge from node
u to node v with capacity c.
Two integers s and t, the source and sink nodes.
Output Format:
A single integer representing the maximum flow from s to t.
Sample Input:
There are 5 cities: A, B, C, D, and E. The possible railway connections and their costs are:
Constraints:
2 ≤ n ≤ 100
1 ≤ m ≤ 104
1 ≤ u,v ≤ n
0 ≤ c ≤ 109
There is at least one path from s to t.
Course Title Advanced Algorithms & Data Structures ACADEMIC YEAR: 2024-25
Course Code 23CS03HF Page 108 of 132
Experiment #13 Student ID
Date Student Name
Sample Input:
45
1 2 100
1 3 100
231
2 4 100
3 4 100
14
Sample Output:
200
Procedure/Program:
Course Title Advanced Algorithms & Data Structures ACADEMIC YEAR: 2024-25
Course Code 23CS03HF Page 109 of 132
Experiment #13 Student ID
Date Student Name
In-Lab:
1. Consider a network consisting of n computers and m connections. Each connection specifies how fast
a computer can send data to another computer. Kotivalo wants to download some data from a server.
What is the maximum speed he can do this, using the connections in the network?
Input Format:
The first input line has two integers n and m: the number of computers and connections. The
computers are numbered 1,2,…,n. Computer 1 is the server and computer n is Kotivalo's
computer.
After this, there are m lines describing the connections. Each line has three integers a, b and c:
computer a can send data to computer b at speed c.
Output Format:
Print one integer: the maximum speed Kotivalo can download data.
Constraints :
1 ≤ n ≤ 500
1 ≤ m ≤ 1000
1 ≤ a,b ≤ n
1 ≤ c ≤ 109
Course Title Advanced Algorithms & Data Structures ACADEMIC YEAR: 2024-25
Course Code 23CS03HF Page 110 of 132
Experiment #13 Student ID
Date Student Name
Example:
Input:
45
123
242
134
345
413
Output:
6
Procedure/Program:
Course Title Advanced Algorithms & Data Structures ACADEMIC YEAR: 2024-25
Course Code 23CS03HF Page 111 of 132
Experiment #13 Student ID
Date Student Name
2. A game consists of n rooms and m teleporters. At the beginning of each day, you start in room 1 and
you have to reach room n. You can use each teleporter at most once during the game. How many
days can you play if you choose your routes optimally?
Input Format:
The first input line has two integers n and m: the number of rooms and teleporters. The rooms
are numbered 1,2,…,n.
After this, there are m lines describing the teleporters. Each line has two integers a and b: there
is a teleporter from room a to room b.
There are no two teleporters whose starting and ending room are the same.
Output Format:
First print an integer k: the maximum number of days you can play the game. Then, print k route
descriptions according to the example. You can print any valid solution.
Constraints :
2 ≤ n ≤ 500
1 ≤ m ≤ 1000
1 ≤ a,b ≤ n
Course Title Advanced Algorithms & Data Structures ACADEMIC YEAR: 2024-25
Course Code 23CS03HF Page 112 of 132
Experiment #13 Student ID
Date Student Name
Example:
Input:
67
12
13
26
34
35
46
56
Output:
2
3
126
4
1346
Procedure/Program:
Course Title Advanced Algorithms & Data Structures ACADEMIC YEAR: 2024-25
Course Code 23CS03HF Page 113 of 132
Experiment #13 Student ID
Date Student Name
Post-Lab:
There are n boys and m girls in a school. Next week a school dance will be organized. A dance pair
consists of a boy and a girl, and there are k potential pairs. Your task is to find out the maximum
number of dance pairs and show how this number can be achieved.
Course Title Advanced Algorithms & Data Structures ACADEMIC YEAR: 2024-25
Course Code 23CS03HF Page 114 of 132
Experiment #13 Student ID
Date Student Name
Input Format:
The first input line has three integers n, m and k: the number of boys, girls, and potential pairs.
The boys are numbered 1,2,….,n, and the girls are numbered 1,2,…,m.
After this, there are k lines describing the potential pairs. Each line has two integers a and b: boy
a and girl b are willing to dance together.
Output Format:
First print one integer r: the maximum number of dance pairs. After this, print r lines describing
the pairs. You can print any valid solution.
Constraints:
1 ≤ n,m ≤ 500
1 ≤ k ≤ 1000
1≤a≤n
1≤b≤m
Sample Input:
324
11
12
21
31
Sample Output:
2
12
31
Procedure/Program:
Course Title Advanced Algorithms & Data Structures ACADEMIC YEAR: 2024-25
Course Code 23CS03HF Page 115 of 132
Experiment #13 Student ID
Date Student Name
Course Title Advanced Algorithms & Data Structures ACADEMIC YEAR: 2024-25
Course Code 23CS03HF Page 116 of 132
Experiment #13 Student ID
Date Student Name
1. How do you construct the minimum cut from the final residual graph after finding the
maximum flow??
2. What is the time complexity of the Ford-Fulkerson method, and on what factors does it
depend?
3. Describe the significance of the bottleneck capacity in an augmenting path.
4. How does the Ford-Fulkerson method ensure that flow conservation and capacity constraints
are maintained?
5. Compare and contrast the space complexity of the Edmonds-Karp algorithm with the standard
Ford-Fulkerson implementation.
Evaluator MUST ask Viva-voce prior to signing and posting marks for each experiment.
Course Title Advanced Algorithms & Data Structures ACADEMIC YEAR: 2024-25
Course Code 23CS03HF Page 117 of 132
Experiment #14 Student ID
Date Student Name
Pre-Lab:
1. Your test string S will have the following requirements:
S must be of length 6
First character: 1, 2 or 3
Second character: 1, 2 or 0
Third character: x, s or 0
Fourth character: 3, 0, A or a
Fifth character: x, s or u
Sixth character: . or ,
Sample Input:
Test_strings = ["12x3x.", "31sA,", "20u0s.", "10xAa."]
Sample Output:
"12x3x.": Valid → True
Course Title Advanced Algorithms & Data Structures ACADEMIC YEAR: 2024-25
Course Code 23CS03HF Page 118 of 132
Experiment #14 Student ID
Date Student Name
Procedure/Program:
Course Title Advanced Algorithms & Data Structures ACADEMIC YEAR: 2024-25
Course Code 23CS03HF Page 119 of 132
Experiment #14 Student ID
Date Student Name
2. A pangram is a string that contains every letter of the alphabet. Given a sentence determine whether
it is a pangram in the English alphabet. Ignore case. Return either pangram or not pangram as
appropriate.
Example-1:
Input :
S1= “the quick brown fox jumps over the lazy dog”
Output :
Pangram
Example-2:
Input :
S2 = “We promptly judged antique ivory buckles for the prize”
Output :
Not Pangram
Procedure/Program:
Course Title Advanced Algorithms & Data Structures ACADEMIC YEAR: 2024-25
Course Code 23CS03HF Page 120 of 132
Experiment #14 Student ID
Date Student Name
In-Lab:
1. You are given a text TTT and a pattern PPP. Your task is to implement the Rabin-Karp algorithm
to find the first occurrence of PPP in TTT. If PPP exists in TTT, return the starting index of the
match (0-based indexing). Otherwise, return -1.
Example 1:
Input :
T = "ababcabcabababd"
P = "ababd"
Output:
10
Course Title Advanced Algorithms & Data Structures ACADEMIC YEAR: 2024-25
Course Code 23CS03HF Page 121 of 132
Experiment #14 Student ID
Date Student Name
Example 2:
Input :
T = "hello"
P = "world"
Output:
-1
Procedure/Program:
Course Title Advanced Algorithms & Data Structures ACADEMIC YEAR: 2024-25
Course Code 23CS03HF Page 122 of 132
Experiment #14 Student ID
Date Student Name
2. Design a program to find the length of the longest common substring between two input strings by
using KMP Algorithm (Knuth-Morris-Pratt).
Example 1:
Input:
str1 = "zohoinnovations"
str2 = "innov"
Output:
Longest Common Substring Length: 5
Procedure/Program:
Course Title Advanced Algorithms & Data Structures ACADEMIC YEAR: 2024-25
Course Code 23CS03HF Page 123 of 132
Experiment #14 Student ID
Date Student Name
Post-Lab:
1. Using the Boyer-Moore algorithm, write a program to count how many times a pattern appears in a
text string.
Example:
Input:
Text = "INFO Starting process\nERROR Invalid configuration\nINFO Retrying process\nERROR
Connection failed\nINFO Process complete\nERROR Disk full"
pattern = "ERROR"
Output :
The pattern 'ERROR' appears 3 times in the text.
Course Title Advanced Algorithms & Data Structures ACADEMIC YEAR: 2024-25
Course Code 23CS03HF Page 124 of 132
Experiment #14 Student ID
Date Student Name
Procedure/Program:
Course Title Advanced Algorithms & Data Structures ACADEMIC YEAR: 2024-25
Course Code 23CS03HF Page 125 of 132
Experiment #14 Student ID
Date Student Name
2. Find DNA Pattern Occurrences :You are given a DNA sequence (text) and a DNA pattern (substring)
consisting of the characters A, C, G, and T. Write a program to find all starting indices of the
occurrences of the DNA pattern in the DNA sequence.
Example 1:
Input:
DNA Sequence: "ACGTACGTGACG"
DNA Pattern: "ACG"
Output:
Pattern found at indices: [0, 4, 9]
Procedure/Program:
Course Title Advanced Algorithms & Data Structures ACADEMIC YEAR: 2024-25
Course Code 23CS03HF Page 126 of 132
Experiment #14 Student ID
Date Student Name
3. What is the difference between a string and a pattern in the context of string matching?
4. Explain the Naive String Matching Algorithm. Why is it considered inefficient for large inputs?
5. What are the common applications of string matching algorithms in real-world scenarios?
Evaluator MUST ask Viva-voce prior to signing and posting marks for each experiment.
Course Title Advanced Algorithms & Data Structures ACADEMIC YEAR: 2024-25
Course Code 23CS03HF Page 127 of 132
Experiment #15 Student ID
Date Student Name
Pre-Lab:
Given two strings text and pattern, implement the Knuth-Morris-Pratt algorithm to determine the
starting indices of all occurrences of pattern in text. If the pattern is not found, return an empty list.
Input Format:
A string text of length n (1≤n≤106).
A string pattern of length m (1≤m≤105).
Output Format:
A list of integers representing the starting indices (0-based) of all occurrences of pattern in text.
Constraints:
Both text and pattern consist of lowercase English letters.
Sample Input:
text: " ababcabcabababd"
pattern: "ababd"
Sample Output:
[10]
Procedure/Program:
Course Title Advanced Algorithms & Data Structures ACADEMIC YEAR: 2024-25
Course Code 23CS03HF Page 128 of 132
Experiment #15 Student ID
Date Student Name
Course Title Advanced Algorithms & Data Structures ACADEMIC YEAR: 2024-25
Course Code 23CS03HF Page 129 of 132
Experiment #15 Student ID
Date Student Name
In-Lab:
Write a function to find the occurrences of a pattern in a given string text using the Rabin-Karp
algorithm. The function should return all starting indices of pattern in text.
Input Format:
A string text of length n (1≤n≤106).
A string pattern of length m (1≤m≤105).
Output Format:
A list of integers representing the starting indices (0-based) of all occurrences of pattern in text.
Constraints:
Both text and pattern consist of lowercase English letters.
Use modular arithmetic to avoid integer overflow.
Sample Input:
text: "abracadabra"
pattern: "abra"
Sample Output:
[0,7]
Procedure/Program:
Course Title Advanced Algorithms & Data Structures ACADEMIC YEAR: 2024-25
Course Code 23CS03HF Page 130 of 132
Experiment #15 Student ID
Date Student Name
Course Title Advanced Algorithms & Data Structures ACADEMIC YEAR: 2024-25
Course Code 23CS03HF Page 131 of 132
Experiment #15 Student ID
Date Student Name
4. How would you test the performance of Boyer-Moore on different input patterns?
5. What potential errors can occur while implementing Rabin-Karp with modular arithmetic?
Evaluator MUST ask Viva-voce prior to signing and posting marks for each experiment.
Course Title Advanced Algorithms & Data Structures ACADEMIC YEAR: 2024-25
Course Code 23CS03HF Page 132 of 132