Lab Workbook: 21Cs2214Aa - Desgin and Analysis of Algorithm (Daa)
Lab Workbook: 21Cs2214Aa - Desgin and Analysis of Algorithm (Daa)
LABORATORY WORKBOOK
STUDENT NAME
REG. NO
YEAR
SEMESTER
SECTION
FACULTY
1
21CS2214AA - DESIGN AND ANALYSIS OF ALGORITHMS
Table of contents
Organization of the STUDENT LAB WORKBOOK ..................................................................................... 4
Lab 1: ....................................................................................................................................................... 7
Prerequisite:......................................................................................... Error! Bookmark not defined.
Pre-Lab Task: ....................................................................................................................................... 7
In-Lab Task: ......................................................................................................................................... 9
Post-Lab Task: ................................................................................................................................... 11
Lab 2: ..................................................................................................................................................... 13
Prerequisite:......................................................................................... Error! Bookmark not defined.
Pre-Lab Task: ........................................................................................ Error! Bookmark not defined.
In-Lab Task: ....................................................................................................................................... 23
Post-Lab Task: ................................................................................................................................... 25
Lab 3: ........................................................................................................ Error! Bookmark not defined.
Prerequisite:......................................................................................... Error! Bookmark not defined.
Pre-Lab Task: ........................................................................................ Error! Bookmark not defined.
In-Lab Task: .......................................................................................... Error! Bookmark not defined.
Post-Lab Task: ...................................................................................... Error! Bookmark not defined.
Lab 4: ........................................................................................................ Error! Bookmark not defined.
Prerequisite:......................................................................................... Error! Bookmark not defined.
Pre-Lab Task: ........................................................................................ Error! Bookmark not defined.
In-Lab-Task: .......................................................................................... Error! Bookmark not defined.
Post-Lab Task: ...................................................................................... Error! Bookmark not defined.
Lab 5: ........................................................................................................ Error! Bookmark not defined.
Prerequisite:......................................................................................... Error! Bookmark not defined.
Pre-Lab Task: ........................................................................................ Error! Bookmark not defined.
In-Lab Task: .......................................................................................... Error! Bookmark not defined.
Post-Lab Task: ...................................................................................... Error! Bookmark not defined.
Lab 6: ........................................................................................................ Error! Bookmark not defined.
Prerequisite:......................................................................................... Error! Bookmark not defined.
Pre-Lab Task: ........................................................................................ Error! Bookmark not defined.
In-Lab Task: .......................................................................................... Error! Bookmark not defined.
Post-Lab-Task: ...................................................................................... Error! Bookmark not defined.
Lab 7: ........................................................................................................ Error! Bookmark not defined.
Prerequisite:......................................................................................... Error! Bookmark not defined.
Pre-Lab Task: ........................................................................................ Error! Bookmark not defined.
2
21CS2214AA - DESIGN AND ANALYSIS OF ALGORITHMS
3
21CS2214AA - DESIGN AND ANALYSIS OF ALGORITHMS
The laboratory framework includes a creative element but shifts the time-intensive
aspects outside of the Two-Hourclosed laboratory period. Within this structure, each
laboratory includes three parts: Prelab, In-lab, and Post-lab.
a. Pre-Lab
The Prelab exercise is a homework assignment that links the lecture with the
laboratory period - typically takes 2 hours to complete. The goal is to synthesize the
information they learn in lecture with material from their textbook to produce a
working piece of software. Prelab Students attending a two-hour closed laboratory
are expected to make a good-faith effort to complete the Prelab exercise before
coming to the lab. Their work need not be perfect, but their effort must be real
(roughly 80 percent correct).
b. In-Lab
The In-lab section takes place during the actual laboratory period. The First hour of
the laboratory period can be used to resolve any problems the students might have
experienced in completing the Prelab exercises. The intent is to give constructive
feedback so that students leave the lab with working Prelab software - a significant
accomplishment on their part. During the second hour, students complete the In-lab
exercise to reinforce the concepts learned in the Prelab. Students leave the lab
having received feedback on their Prelab and In-lab work.
c. Post-Lab
The last phase of each laboratory is a homework assignment that is done following
the laboratory period. In the Post-lab, students analyze the efficiency or utility of a
given system call. Each Post-lab exercise should take roughly 120 minutes to
complete.
4
21CS2214AA - DESIGN AND ANALYSIS OF ALGORITHMS
5
21CS2214AA - DESIGN AND ANALYSIS OF ALGORITHMS
10
11
12
6
21CS2214AA - DESIGN AND ANALYSIS OF ALGORITHMS
Lab 1:
Pre-Lab Task:
1. Calculate the time complexity of the following:
2. function fn(n)
{
if(n<0) return 0;
if(n<2) return n;
return fn(n-1)+fn(n-2);
}
7
21CS2214AA - DESIGN AND ANALYSIS OF ALGORITHMS
3) The median of a list of numbers is essentially its middle element after sorting. The same number of
elements occur after it as before. Given a list of numbers with an odd number of elements, find
the median?
Example
arr=[5,3,1,2,4]
The sorted array a’=[1,2,3,4,5]. The middle element and the median is 3.
Function Description
Returns
Sample Input 0
7
0124653
Sample Output 0
8
21CS2214AA - DESIGN AND ANALYSIS OF ALGORITHMS
In-Lab Task:
1) Given an array of strings arr[], the task is to sort the array of strings according to frequency of
each string, in ascending order. If two elements have same frequency, then they are to be sorted
in alphabetical order.
Output: (“Mahesh”,”Ramesh”}
Explanation:
As both the strings have same frequency, the array is sorted in the alphabetical order.
9
21CS2214AA - DESIGN AND ANALYSIS OF ALGORITHMS
2) Given an array of strings words[] and the sequential order of alphabets, our task is to sort the
array according to the order given. Assume that the dictionary and the words only contain
lowercase alphabets.
Output: “world”,“word”,“row”
Explanation:
According to the given order ‘l’ occurs before ‘d’ hence the words “world” will be kept first.
10
21CS2214AA - DESIGN AND ANALYSIS OF ALGORITHMS
Post-Lab Task:
1) Given an array arr[] of N strings, the task is to sort these strings according to the number of upper-case
letters in them try to use zip function to get the format.
11
21CS2214AA - DESIGN AND ANALYSIS OF ALGORITHMS
Professor Hari Vege given the H = height of one pole to Mothi then asked him to print the position of
that pole, here we consider index as a position. Mothi is particularly good at algorithms, so he written
an algorithm to find that position. But he is extremely poor at finding time complexity. Your task is to
help your friend Mothi to analyze the time complexity of the given problem.
else
return BinarySearch (a, mid+1, high, tar)
}
12
21CS2214AA - DESIGN AND ANALYSIS OF ALGORITHMS
Lab 2:
Pre-Lab:
1) Given a text txt[0..n-1] and a pattern pat[0..m-1], write a function search (char pat [], char
txt[]) that prints all occurrences of pat[] in txt[] using naïve string algorithm?(assume that n > m)
Input
txt[] = "THIS IS A TEST TEXT"
pat[] = "TEST"
Output
Pattern found at index 10
Input
txt[] = "AABAACAADAABAABA"
pat[] = "AABA"
Output
Pattern found at index 0
Pattern found at index 9
13
21CS2214AA - DESIGN AND ANALYSIS OF ALGORITHMS
2) Discuss the Rabin Karp algorithm for string matching and explain time complexity of the
algorithm?
14
21CS2214AA - DESIGN AND ANALYSIS OF ALGORITHMS
3) Stefan is a guy who is suffering with OCD. He always like to align things in an order. He got a lot
of strings for his birthday party as gifts. He like to sort the strings in a unique way. He wants his
strings to be sorted based on the count of characters that are present in the string.
Input
aaabbc
cbbaaa
Output
aabbcc
aabbcc
If in case when there are two characters is same, then the lexicographically smaller one will be printed
first
Input:
aabbccdd
aabcc
Output:
aabbccdd
baacc
15
21CS2214AA - DESIGN AND ANALYSIS OF ALGORITHMS
In-Lab:
1) Naive method and KMP are two string comparison methods. Write a program for Naïve method and
KMP to check whether a pattern is present in a string or not. Using clock function find execution time
for both and compare the time complexities of both the programs (for larger inputs) and discuss which
one is more efficient and why?
#include<stdio.h>
#include<time.h>
void fun()
{
//some statements here
}
int main()
{
//calculate time taken by fun()
clock_t t;
t=clock();
fun();
t=clock()-t;
double time_taken=((double)t)/CLOCK_PER_SEC; //in seconds
printf(“fun() took %f seconds to execute \n”,time_taken);
return 0;
}
16
21CS2214AA - DESIGN AND ANALYSIS OF ALGORITHMS
2) Andrea is working in a photo studio where his boss has given him a task to arrange the photos of
family members. He is French and he do not know English somehow, he managed to send the list of
names to you (his friend). Help Andrea to sort the photos.
(Note: implement the odd even merge algorithm)
Input
5
Neil Katherine Harry Stefan Dennis
Output
Dennis Harry Katherine Neil Stefan
17
21CS2214AA - DESIGN AND ANALYSIS OF ALGORITHMS
Post-Lab:
1) Given a pattern of length- 5 window, find the valid match in the given text by step-by-step process
using Robin-Karp algorithm
Pattern: 2 1 9 3 6
Modulus: 21
Index: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
Text: 9 2 7 2 1 8 3 0 5 7 1 2 1 2 1 9 3 6 2 3 9 7
18
21CS2214AA - DESIGN AND ANALYSIS OF ALGORITHMS
2) James is sharing his information with his friend secretly in a chat. But he thinks that message should
not understandable to anyone only for him and his friend. So he sent the message in the following
format.
Input
a1b2c3d4e
Output
abbdcfdhe
Explanation:
The digits are replaced as follows:
- s[1] -> shift('a',1) = 'b'
- s[3] -> shift('b',2) = 'd'
- s[5] -> shift('c',3) = 'f'
- s[7] -> shift('d',4) = 'h'
19
21CS2214AA - DESIGN AND ANALYSIS OF ALGORITHMS
Lab 3:
Pre-Lab-Task:
20
21CS2214AA - DESIGN AND ANALYSIS OF ALGORITHMS
2) Given two arrays of integers, find which elements in the second array are missing from the
first array.
Example:
A={7,2,5,3,5,3}
B={7, 2, 5, 4, 6, 3, 5, 3}
The ‘B’ array is the original list. The numbers missing are {4, 6}.
Sample Input
10
203 204 205 206 207 208 203 204 205 206
13
203 204 204 205 206 207 205 208 203 206 205 206 204
Sample Output
21
21CS2214AA - DESIGN AND ANALYSIS OF ALGORITHMS
3) Trace out the output of the following using Merge sort. 19, 48, 32, 66, 45, 4, 7, 2, 1, 51, 78, 34,
89, 87, 36, 29, 3, 9, 11.
22
21CS2214AA - DESIGN AND ANALYSIS OF ALGORITHMS
In-Lab Task:
1) You are given an array A. You can decrement any element of the array by 1. This operation can be
repeated any number of times. A number is said to be missing if it is the smallest positive number
which is a multiple of 2 that is not present in the array A. You must find the maximum missing
number after all possible decrements of the elements.
Input Format:
The first line of input contains T denoting number if test cases.
The first line of each test case contains N, the size of the array.
The second line of each test case contains N space seperated intergers.
Output Format:
Print the answer for each test case in a new line.
Sample Input:
2
6
133367
3
302
Sample Output:
8
4
23
21CS2214AA - DESIGN AND ANALYSIS OF ALGORITHMS
2) Watson gives Sherlock an array of integers. His challenge is to find an element of the array such
that the sum of all elements to the left is equal to the sum of all elements to the right.
Example
A= [5, 6, 8, 11]
A=[1]
You will be given arrays of integers and must determine whether there is an element that meets the
Sample Input 0
2
3
123
4
1233
Sample Output 0
NO
YES
24
21CS2214AA - DESIGN AND ANALYSIS OF ALGORITHMS
Post-Lab Task:
*Note: Merge Sort is a Divide and Conquer algorithm. It divides input array in two halves, calls itself for
the two halves and then merges the two sorted halves.
Input Format
Constraints
Output Format
Sample Input 0
10
10 1 9 2 8 3 4 7 5 6
Sample Output 0
1 10
1 9 10
28
1 2 8 9 10
34
347
56
34567
1 2 3 4 5 6 7 8 9 10
25
21CS2214AA - DESIGN AND ANALYSIS OF ALGORITHMS
2)
HackerLand National Bank has a simple policy for warning clients about possible fraudulent account
activity. If the amount spent by a client on a particular day is greater than or equal to2X the
client's median spending for a trailing number of days, they send the client a notification about potential
fraud. The bank doesn't send the client any notifications until they have at least that trailing number of
Given the number of trailing days d and a client's total daily expenditures for a period of n days,
determine the number of times the client will receive a notification over all n days.
Example
expenditure=[10,20,30,40,50]
d=3
On the first three days, they just collect spending data. At day 4, trailing expenditures are [10,20,30]. The
median is 20 and the day's expenditure is 40. Because 40>=2X20, there will be a notice. The next day,
trailing expenditures are [20, 30, 40] and the expenditures are 50. This is less than 2X30 so no notice will
Note: The median of a list of numbers can be found by first sorting the numbers ascending. If there is an
odd number of values, the middle one is picked. If there is an even number of values, the median is then
Sample Input 0
STDIN Function
----- --------
95 expenditure[] size n =9, d = 5
2 3 4 2 3 6 8 4 5 expenditure = [2, 3, 4, 2, 3, 6, 8, 4, 5]
Sample Output 0
26
21CS2214AA - DESIGN AND ANALYSIS OF ALGORITHMS
27
21CS2214AA - DESIGN AND ANALYSIS OF ALGORITHMS
Lab 4:
Pre-Lab Task:
1) Trace the output of the following matrix multiplication using Strassen’s Multiplication Method
28
21CS2214AA - DESIGN AND ANALYSIS OF ALGORITHMS
2) Write a divide and conquer algorithm for finding the maximum and minimum in the sequence of
numbers. Find the time complexity.
3) Given an input is an array of points specified by their x and y co-ordinates. The output is the convex
hull of this set of points by using Divide and Conquer algorithm.
Input : points[] = {(0, 0), (0, 4), (-4, 0), (5, 0),
(0, -6), (1, 0)};
Output : (-4, 0), (5, 0), (0, -6), (0, 4)
29
21CS2214AA - DESIGN AND ANALYSIS OF ALGORITHMS
30
21CS2214AA - DESIGN AND ANALYSIS OF ALGORITHMS
In-Lab:
1) Harry’s Aunt and family treat him badly and make him work all the time. Dudley, his cousin got
homework from school and he as usual handed it over to Harry but Harry has a lot of work and his
own homework to do.
The homework is to solve the problems which are numbered in numerical he tries to solve random
question after solving random questions he did not put those questions in order Dudley will return
in a time of n*logn Harry has to arrange them as soon as possible. Help Harry to solve this
problem so that he can go on and do his own homework.
Example
Input
9
15,5,24,8,1,3,16,10,20
Output
1, 3, 5, 8, 10, 15, 16, 20, 24
31
21CS2214AA - DESIGN AND ANALYSIS OF ALGORITHMS
2) A group of 9 friends are playing a game, rules of the game are as follows: Each member will be
assigned with a number and the sequence goes like e.g.: 7,6,10,5,9,2,1,15,7.
Now they will be sorted in ascending order in such a way that tallest one will be sorted first. Now
your task is to find the order of indices based on initial position of the given sequence and print the
order of indices at the end of the iteration.
32
21CS2214AA - DESIGN AND ANALYSIS OF ALGORITHMS
Post-Lab:
1) Suppose a merge sort algorithm, for input size 64, takes 30 secs in the worst case. What is the
maximum input size that can be calculated in 6 minutes (approximately)?
33
21CS2214AA - DESIGN AND ANALYSIS OF ALGORITHMS
2) Chris and Scarlett were playing a block sorting game where Scarlett challenged Chris that he has to
sort the blocks which arranged in random order. And Scarlett puts a restriction that he should not use
reference of first, median and last blocks to sort, and after sorting one block with reference to other
block, for next iteration he must choose another block as the reference not the same block (random
pivot).
Now, Chris wants help from you to sort the blocks. He wanted to sort them in a least time. Help him
with the least time complexity sorting algorithm.
Input format
First line of input contains the number of test cases.
Next t lines of input contain
The number of blocks provided by Scarlett.
The array of blocks.
34
21CS2214AA - DESIGN AND ANALYSIS OF ALGORITHMS
Lab 5:
Pre-Lab Task:
1. Given N integers a1,a2,...aN, generate all N- dimentional points (x1,x2,...xN) such thatxi is an
integer and 0<=xi<=ai (i=1,2...N). Your task is to find the number of ways to select two points A
and B from this set, such that the midpoint of A and B also lies in this set. A and B can be same
also.
Input Format:
First line of input contains a single integer N. The second line contains N integers, the ith of them
representing ai, as defined in the problem.
Output Format:
The output contains a single integer, the answer to the problem
Sample input:
2
12
Sample Output:
10
35
21CS2214AA - DESIGN AND ANALYSIS OF ALGORITHMS
36
21CS2214AA - DESIGN AND ANALYSIS OF ALGORITHMS
2. Given an array of integers A and a positive integer k, find whether it's possible to divide this array
into sets of k consecutive numbers
Return True if its possible otherwise return False.
Example 1:
Input: A = [1,2,3,3,4,4,5,6], k = 4
Output: true
Explanation: Array can be divided into [1,2,3,4] and [3,4,5,6].
Example 2:
Input: A = [3,2,1,2,3,4,3,4,5,9,10,11], k = 3
Output: true
Explanation: Array can be divided into
[1,2,3] , [2,3,4] , [3,4,5] and [9,10,11].
Example 3:
Input: A = [3,3,2,2,1,1], k = 3
Output: true
Example 4:
Input: A = [1,2,3,4], k = 3
Output: false
Explanation: Each array should be divided in subarrays of size 3.
37
21CS2214AA - DESIGN AND ANALYSIS OF ALGORITHMS
38
21CS2214AA - DESIGN AND ANALYSIS OF ALGORITHMS
In-Lab Task:
3. A team of people would like to buy a bouquet of roses. The vendor wants to maximize his wide
variety of recent clients count and the cash he makes. To do so, he decides to multiply the price of
each rose with the aid of the wide variety of that clients previously purchased roses plus 1. The
first rose will be original price,(0+1) x original price , the next will be (1+1) x original price and so
on.
Given the size of the group of people, the number of roses they want to purchase and the original
prices of the rose, determine the minimum cost to purchase all of the roses.
For example, if there are k=3 group of people such that want to buy n=4 roses that cost c=[1,2,3,4]
each will buy one of the roses priced [2,3,4] at the original price. Having each purchased x=1 rose,
the first rose in the list,c[0] , will now cost (cuurent purchase + previous purchases) x c[0] = (1 +
1) x 1 = 2. The total cost will be 2 + 3 + 4 + 2 = 11.
Input Format
The first line contains two space-separated integers n and k, the number of roses and group of
people.
The second line contains n space-separated positive integers c[i], the original price of each rose.
Ouput Format
Sample Input 0
33
256
Sample Output 0
13
Explanation 0
There are n=3 rosess with costs c = [2,5,6] and k=3 people in the team. If each person buys one
rose, the total cost of prices paid is 2 + 5 + 6 = 13 dollars. Thus, we print 13 as our answer.
Sample Input 1
32
256
Sample Output 1
15
Explanation 1
There are n=3 flowers with costs c=[2,5,6] and k=2 people in the team. We can minimize the total
purchase cost like so:
39
21CS2214AA - DESIGN AND ANALYSIS OF ALGORITHMS
The first person purchases 2 roses in order of decreasing price; this means they buy the more
expensive rose (c1=5) first at price p1= (0 + 1) x 5 = 5 dollars and the less expensive flower
(c0=2) second at price p0= (1 + 1) x 2 = 4 dollars.
The second person buys the most expensive rose at price p2 = (0 + 1) x 6 = 6 dollars.
We then print the sum of these purchases, which is 5 + 4 + 6 = 15 , as our answer.
Sample Input 2
53
13579
Sample Output 2
29
Explanation 2
The friends buy flowers for 9, 7 and 3,5 and 1 for a cost of 9 + 7 + 5 + (1 + 1) * 3 + (1 + 1) * 1 =
29.
40
21CS2214AA - DESIGN AND ANALYSIS OF ALGORITHMS
41
21CS2214AA - DESIGN AND ANALYSIS OF ALGORITHMS
4. Given a non-negative integer N, find the largest number that is less than or equal to N with
monotonically increasing digits.
(Recall that an integer has monotonically increasing digits if and only if each pair of adjacent
digits x and y satisfy x <= y.)
Example 1:
Input: N = 10
Output: 9
Example 2:
Input: N = 1234
Output: 1234
Example 3:
Input: N = 332
Output: 299
42
21CS2214AA - DESIGN AND ANALYSIS OF ALGORITHMS
43
21CS2214AA - DESIGN AND ANALYSIS OF ALGORITHMS
Post-Lab Task:
5. There are n people whose IDs go from 0 to n - 1 and each person belongs exactly to one group.
Given the array groupSizes of length n telling the group size each person belongs to, return the
groups there are and the people's IDs each group includes.
You can return any solution in any order and the same applies for IDs. Also, it is guaranteed that
there exists at least one solution.
Example 1:
Input: groupSizes = [3,3,3,3,3,1,3]
Output: [[5],[0,1,2],[3,4,6]]
Explanation: Other possible solutions are [[2,1,6],[5],[0,4,3]] and [[5],[0,6,2],[4,3,1]].
Example 2:
Input: groupSizes = [2,1,3,3,3,2]
Output: [[1],[0,5],[2,3,4]]
44
21CS2214AA - DESIGN AND ANALYSIS OF ALGORITHMS
45
21CS2214AA - DESIGN AND ANALYSIS OF ALGORITHMS
6. Tom is a teacher in nursery school. She wants the kids in her class to get some sweets. All the kids
sit in a line and each of them has a ranking score in the class according to their results. Tom wants
to give every kid a minimum of 1 sweet. When two kids are sitting next to each other, then the one
with the better rating gets more sweets. Tom wants the total number of sweets to be minimised.and
every of them has a score score in step with his or her performance inside the class.
Input Format
The first line contains an integer, n, the size of array .
Each of the next n lines contains an integer a[i] indicating the rating of the kid at position i.
Output Format
Output a single line containing the minimum number of candies Alice must buy.
Sample Input 0
3
1
2
2
Sample Output 0
4
Explanation 0
Here 1, 2, 2 is the rating. Note that when two kids have equal rating, they are allowed to have
different number of sweets. Hence optimal distribution will be 1, 2, 1.
Sample Input 1
10
2
4
2
6
1
7
8
9
2
1
Sample Output 1
19
Explanation 1
Optimal distribution will be 1, 2, 1, 2, 1, 2, 3, 4, 2, 1.
Sample Input 2
46
21CS2214AA - DESIGN AND ANALYSIS OF ALGORITHMS
8
2
4
3
5
2
6
4
5
Sample Output 2
12
Explanation 2
Optimal distribution will be 1, 2, 1, 2, 1, 2, 1, 2.
47
21CS2214AA - DESIGN AND ANALYSIS OF ALGORITHMS
48
21CS2214AA - DESIGN AND ANALYSIS OF ALGORITHMS
Lab 6:
Pre-Lab:
1) Explain why 0-1 Knapsack problems cannot be solved using greedy method unlike fractional
knapsack.
49
21CS2214AA - DESIGN AND ANALYSIS OF ALGORITHMS
2) Categorize the Following as single source or multiple source shortest path algorithms.
Floyd-Warshall algorithm
Dijkstra’s algorithm –
Bellman-Ford algorithm –
50
19CS3113S ANALYSIS & DESIGN OF ALGORITHMS
In-Lab:
51
19CS3113S ANALYSIS & DESIGN OF ALGORITHMS
2) Given n non-negative integers a1, a2, ..., an, where each represents a point at coordinate (i, ai). n
vertical lines are drawn such that the two endpoints of the line i is at (i, ai) and (i, 0). Find two lines,
which, together with the x-axis forms a container, such that the container contains the most water.
Notice that you may not slant the container.
Input
height = [1,8,6,2,5,4,8,3,7]
Output
49
Explanation: The above vertical lines are represented by array [1,8,6,2,5,4,8,3,7]. In this case, the
max area of water (blue section) the container
52
19CS3113S ANALYSIS & DESIGN OF ALGORITHMS
Post-Lab:
1) 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. How to maximize total profit if only one job can be scheduled at
a time.
Input
4
Job ID Deadline Profit
a 4 20
b 1 10
c 1 40
d 1 30
Output
60
profit sequence of jobs is c, a
53
19CS3113S ANALYSIS & DESIGN OF ALGORITHMS
54
19CS3113S ANALYSIS & DESIGN OF ALGORITHMS
2) There are N Mice and N holes are placed in a straight line. Each hole can
accommodate only 1 mouse. A mouse can stay at his position, move one step right
from x to x + 1, or move one step left from x to x − 1. Any of these moves consumes
1 minute.Assign mice to holes so that the time when the last mouse gets inside a hole
is minimized.
55
LAB SESSION 07:
Date of the Session: / / Time of the Session: to
Pre-Lab:
1) A student named Satish is eagerly waiting to attend tomorrow’s class. As he searched the concepts of
tomorrow’s lecture in the course handout and started solving the problems, in the middle he was
stroked in the concept of strings because he was poor in this concept so help him so solve the problem,
given two strings str1 and str2 and below operations that can performed on str1. Find minimum
number of edits (operations) required to convert ‘str1’ into ‘str2’.
1. Insert
2.Remove
3.Replace
Input
str1 = "cat", str2 = "cut"
Output
1
We can convert str1 into str2 by replacing 'a' with 'u'.
Input
str1 = "sunday", str2 = "saturday"
Output
3
2) Given N numbers n1,n2,…nN and Q queries q1,q2,…qQ. Your task is to print Q (Q< j <numbers)
f1,f2,…fQ, corresponding to query qj1 max(n1=fj ,n2 ,...nq) using dynamic programming.
Input
53
54869
235
Output
589
In-Lab:
1) Bhanu is a student at KL University who likes playing with strings, after reading a question from their
lab workbook for the ADA Course she found what is meant by a subsequence.
(A subsequence is a sequence that can be derived from another sequence by deleting some or no
elements without changing the order of the remaining elements)
So, she created 2 strings out of which one she considered as a master string and the other one as a slave
string. She challenged her friend Teju to find out whether the slave string is a subsequence of the master
string or not, As Teju is undergoing her CRT classes she decided to code the logic for this question.
Help her in building the logic and write a code using Dynamic programming concept.
2) Geeta is working in a company, and she has n different projects to work on, where every project is
scheduled to be done from startTime[i] to endTime[i], obtaining a profit of profit[i]. You are given the
startTime, endTime and profit arrays, return the maximum profit you can take such that there are no
two projects that she is working on in that given subset with overlapping time range. If she chooses a
project that ends at time a then she will be able to start another project that starts at time b.
Input
startTime = [1,2,3,4,6], endTime = [3,5,10,6,9], profit = [20,20,100,70,60]
Output
150
Explanation: The subset chosen is the first, fourth and fifth project.
Profit obtained 150 = 20 + 70 + 60.
3) Teacher: good morning students!!!
Students: good morning mam
Teacher: Today topic is binary tree. Does anyone know what is binary tree?
Students: no mam
Teacher: In computer science, a binary tree is a tree data structure in which each node has
at most two children, which are referred to as the left child and the right child. Satish you
completed this topic yesterday can you explain this topic?
Satish: Sure, mam but I got doubt this concept, do anyone help me in solving this the question was
Given a binary tree, find whether if a given Binary Tree is Balanced?
Post-Lab:
1) SIRI studies at KL University and a person who is interested in Dynamic Programming, she created a
question for you to solve. she decided to give a question related to palindrome, you need to use
dynamic programming to solve this problem brute force is not allowed since she hates waiting too
long to find the answer. The question follows like this find the longest palindromic subsequence.
(Unlike substrings, subsequences are not required to occupy consecutive positions within the original
string.)
Input
ABBDCACB
Output
The length of the longest palindromic subsequence is 5
The longest palindromic subsequence is BCACB
2) Bhanu and Teju are playing dice game where there are N dice with M faces and the dice are numbered
from 1 to M. A person wins the game if the sum of the faces of dice adds up to a value X. you are
playing on Bhanu’s team, and It is Teju’s turn now.
You are supposed to find number of ways your opponent can win the game where N, M and X are
provided as input. Use Dynamic programming to solve the problem.
Using DP (Dynamic programming) to find the number of ways to get sum X.
Input
M=2
N=2
X=3
Output
2
MarksSecured: outof
Full Name of the Evaluator:
1) Your father brought you a ticket to world tour. You have a choice to go to three places, your father
knows the places you wanted to travel so he made a graph with the measuring distances from home.
Now you start from your place (1: Source) to other places as shown in the graph below apply TSP to
find shortest path to visit all places and return to home. (Ex: 2: London, 3: Paris, 4: Singapore)
2) You are given a map(graph) with the distances between the places. Here you will consider the 1st
node as the starting point and ending point, Since the route is cyclic you can take any node as starting
point and ending point. Find the minimum cost route and remember the Hamiltonian cycle.
3) Your friend works in a comparable way to a Travelling salesperson ― he always travels to new cities
to sell his delicious dishes.
Today, your friend is planning to visit N cities (numbered 1 through N). There is a direct way to travel
between each pair of cities. Each city has a specific temperature; let us denote the temperature in the i-
th city by Ci. Your friend has a fixed temperature tolerance D with the following meaning: for each
pair of cities an and b, he may travel from city a directly to city b only if |Ca−Cb|≤D, otherwise he
would catch a heavy flu because of the sudden change in temperature.
Your friend starts from city 1. Is he able to visit all N cities in such a way that each city is visited
exactly once?
Notes:
1. Your friend is not able to travel through a city without visiting it.
2. City 1 is visited at the beginning.
It is not necessary to be able to travel directly to city 1 from the last city Your friend’s visits.
Input
2
53
32145
54
10 1 3 2 9
Output
Yes
No
In-Lab:
1) Emma has a graph which represents a flow network where every edge has a capacity. Also given
two vertices source s and sink t in the graph, fin the maximum possible flow from s to t with
following constraints:
a. Flow on an edge does not exceed the given capacity of the edge.
b. Incoming flow is equal to outgoing flow for every vertex except s and t.
Find the Maximum flow using the graph and by implementing the code.
2) For the above given graph Emma wants an s-t to cut that requires the source s and the sink t to be
in different subsets, and it consists of edges going from the source’s side to the sink’s side. So, she
wants you to find the minimum capacity s-t cut of the given network. Expected output is all the
edges of minimum cut.
Post-Lab:
1) Hogwarts has yet again declared The Triwizard tournament. Harry must pass this round to get to
the next one. Each participant will be given a graph with vertices as shown below. Each vertex is a
dungeon, and a golden egg is placed in the root dungeon i.e., the root vertex. Help harry find the
dungeon with the golden egg using traversing or searching tree or graph data structure. (P.S: To
pass this round Harry must write a code).
2) KL University is starting next week. There are S subjects in total, and you need to choose K of
them to attend each day, you required number of credits to pass the semester. There are N+1
buildings. Your hostel is in building number 0. Subject j is taught in building Bj. After each
subject, you have a break, during which you go back to your hostel. There are M bidirectional
paths of length 1 which connects building b1 to building b2. Find the minimum total distance you
need to travel each day if you choose your subjects correctly.
Input
2322
01
12
20
12
Output
4
Pre-Lab:
1) What is Back Tracking methodology and when can we use Back tracking, explain with an example?
2) Mr. Anumula went to the Ice-Cream Parlor. He will be with certain amount of money to buy ice-
creams. When he goes to the counter for ordering the Ice-cream, there will be displayed with the
items and its cost, respectively. He will be checking which items he can buy according to the
money. Print "YES" if he can buy the Ice-Creams without leaving one rupee also otherwise print
"NO".
Input
costs= [100, 70, 50, 180, 120, 200, 150]
Total Money=300
Output
YES
In-Lab:
1) Mani is poor at playing chess, he was asked to arrange “N” Queens on the chess board in such a
way that no two queens are allowed to kill each other. Since he is poor at chess you were asked to
arrange them on behalf of him. (You must use Backtracking Approach)
2) Given an undirected graph and N colors, the problem is to find if it is possible to color the graph
with at most N colors, which means assigning colors to the vertices of the graph such that no two
adjacent vertices of the graph are colored with the same color.
Print "Possible" if it is possible to color the graph as mentioned above, else print "Not Possible".
Input
1
32
02
12
2
Output
Possible
Post-Lab:
1) Kiran is a very obedient boy and helping others is a habit of him. He will do any work with dedication
his teacher assigns him a work to generate all permutations of given word. Since he is busy helping
others, you are asked to help him to complete his work on behalf of him. (Use Backtracking Concept)
2) Mr. Sai joined for as an assistant at a school where he was given a job to arrange schedules for the
subject n1, n2, n3, n4, n5, n6, n7, n8. Help him schedule the timetable from the given information.
Let this be the schedule:
Here for everyone
one hour there are many subjects competing. Use backtracking and create a schedule
where each subject is assigned to a specific hour in a day. In the schedule ‘1’ represents that the
subject is competing for that hour.
Pre-Lab:
1)Given
Given a set of cities and dis
distance
tance between every pair of cities, the problem is to find the shortest
possible route that visits every city exactly once and returns to the starting point. Note the difference
between Hamiltonian Cycle and TSP. The Hamiltonian cycle problem is to find if there exist a tour
that visits every city exactly once. Here we know that Hamiltonian Tour exists (because the graph is
complete) and in fact many such tours exist, the problem is to find a minimum weight Hamiltonian
Cycle.
1) From Our Galaxy nearly 10^9+7 trillion kilometers far away, there exists a parallel Universe of
Light called the Smolen of cosmos where each planet is called a Temp. There are total N temps.
Unlike humans, the extraterrestrial can travel from one temp to another through Cosmic Bridges
and the distance observed by them between any two temps is 0 units
But the year 2012, proved to be a curse for extraterrestrial. This year, a Mega Star Urus struck their
Universe and damaged many Cosmic Bridges. However, the God of Light ensured that for any two
distinct temps t1 and t2 there exists exactly one unique path through Cosmic Bridges, but the
distance between two directly connected temps through a Bridge has now increased to 1 unit.
To prevail the existence of this Universe, the God of Light carved himself into exactly N
extraterrestrial which now rule the N temps and are independent of each other. One by one, the ith
extraterrestrial (0≤i≤N−1) transmits Light pulses through the network of Cosmic Bridges and
determines the sum of distances to the remaining N−1 extraterrestrial.
Can you help them find these quantities so they can reunite into God of Light again?
Input
5
02
03
13
34
Output
68958
2) 2 years ahead, you planned a road trip as a reunion with all your classmates. You planned to visit N
places in total, the list of their coordinates (arr []) are given in sorted order. You start the tour from the
left most location and strictly move towards the right and then upon reaching the right most location,
the tour goes strictly from right to left-back to the starting location. Find the minimum distance of the
tour so that you can save time and fuel.
Input
N=7
arr[][] = {{0, 6}, {1 0}, {2 3}, {5 4}, {6 1}, {7 5}, {8 2}}
Output
25.582
Post-Lab:
1) Jane has very less Marks in Dynamic programming test conducted by his teacher. So, the teacher had
given a problem about optimal Binary Search Tree which should be solved using Dynamic
Programming by the next class. Since, he is very weak in Dynamic programming you must help him
to solve the problem. The problem can be described as follows: An unsorted data of keys and their
frequencies are given to you and some queries where each query contains two integers which describe
the Range of the indices (index range) for which you must print the root of that Optimal Binary Search
Tree. Tasks: (i)You should Find the Cost of the optimal BST (Binary Search Tree)by considering all
the keys and print the value in a new Line. (ii)Find and print the root of the Optimal BST formed by
the range of indices (keys index range) given by each sub-query. The first line contains integer 'n'
which describes the size of the keys. The second line contains values of keys. The third Line contains
values about frequencies of each key. The fourth Line is an integer 'm' which describes no of queries.
The following lines contains two integers describing the range for each query. Print the cost of the
Optimal BST by considering all the keys. For each Query print the root of the Optimal BST based on
the given range
Input
4
12 10 20 21
2
03
01
Output
Cost of Optimal BST is 144
20
10
2) You are offered N pay packages by various companies, Congratulations! You can only select 2 unique
groups of packages each with a total of at least K. Select the 2 groups such that you choose minimum
number of companies adding up to the total of K.
Input
arr[] = {2, 4, 5, 6, 7, 8}, K = 16
Output
6
Explanation:
The subsets {2, 6, 8} and {4, 5, 7} are the two smallest subsets with sum K (= 16).
Therefore, the sum of the lengths of both these subsets = 3 + 3 = 6.4
a)
b)
In-Lab:
1) Raju prepares for the examination, but he got stuck into a concept called "NP-HARD AND "NP-
COMPLETE PROBLEMS" on Nondeterministic Algorithms. So, help Raju to score good marks.
Help him to define the Nondeterministic algorithms by sorting an array.
2) Karthik and Bavya are trying to implement a program that helps a transportation company use its
container to maximum efficiency, as part of their CS project.
Few objects are more valuable than others. Each object has a certain weight. The transportation
company wants to fill the container so that the value of the container (sum of value of objects in the
container) is maximum, while total weight of the objects does not exceed the container's capacity.
As the outcome is not fixed, this is a non-deterministic problem. This is a knapsack problem as we
must maximize value within the given weight limit.
So, to understand the problem well and implement it, help them in finding non-deterministic knapsack
algorithm.
Post-Lab:
1) Hema: Hamiltonian Path is NP-Complete.
Jaya: Well, prove that!
Hema: I will prove and let you know.
Help Hema to try and prove that Hamilton Path is NP-Complete
2) Hemanth was unable to answer the following question in exam. Here is the question, help
Hemanth to find P1 solution. Find the total cost to find the P1 solution
Pre-Lab:
1)Given an array of integers A and a positive integer k, find whether it is possible to divide this array
into sets of k consecutive numbers. Return True if it is possible otherwise return False.
Input:
A = [1,2,3,3,4,4,5,6], k = 4
Output
True
Explanation: Array can be divided into [1,2,3,4] and [3,4,5,6].
Input
A = [3,2,1,2,3,4,3,4,5,9,10,11], k = 3
Output
True
Explanation: Array can be divided into [1,2,3], [2,3,4], [3,4,5] and [9,10,11].
Input
A = [3,3,2,2,1,1], k = 3
Output
True
Input
A = [1,2,3,4], k = 3
Output
False
Explanation: Each array should be divided in subarrays of size 3.
2) Given a string Str of characters from 1 to 9. Your task is print a string Str1 of numbers using
dynamic programming such that
a. |Str1|=|Str|
b. The ith character of Str1 is the number of even characters from ith position to last position of
Str.
Input
475854637834259
Output
766655433322100
In-Lab:
1) Raju has very less Marks in Dynamic programming test conducted by his teacher. So, the teacher had
given a problem about optimal Binary Search Tree which should be solved using Dynamic
Programming by the next class. Since, he is very weak in Dynamic programming you must help him
to solve the problem. The problem can be described as follows:
An unsorted data of keys and their frequencies are given to you and some queries where each query
contains two integers which describe the range of the indices (index range) for which you must print
the root of that Optimal Binary Search Tree.
Input
4
12 10 20 21
8 34 50 1
2
03
01
Output
Cost of Optimal BST is 144
20
1
2) Karthik was given a problem in an online interview, but he cannot solve the solution help him solve
the question. There are n students whose ids vary between 0 to 9 digits; two students can have same
id's. You will be given x numbers which also vary from 0 to 9. You need to find the total number of
student id's subsets which contains all the x numbers.
Input
333
1
3
Output
6
Post-Lab:
1) Define a group of length N as a sequence of N numbers, consisting of all the numbers from 1 to N
in any order. An oppgroup of a group (let say P) is a sequence of numbers in which the ith number is
the position of number i in the original group, 1<= i<= N.i.e., if group 2 5 1 4 3, oppgroupis 3 1 5 4 2.
Given a number N, find the number of distinct groups of length N which cannot be distinguished from
their oppgroups.
Input
1
3
Output
4
2)Given a string S of length N consisting of digits 1 to 9and an integer K. Determine the number of
ways to partition the string S such that each segment value is less than K. If there is no way to perform
partition on the string, then print 0.
Input
a)5 6
34212
b)2 21
11
c)5 22
34212
Output
a)1
b)2
c)3
1) Find out Graph traversals by using BFS and DFS to the following graph.
In-Lab:
1) Dark Peace is volunteer in VISION 2K17.ChiefCO gave him a task to complete it before the
CODEGEEKS which is on 11th march. ChiefCo asks DarkPeace to do the work as soon as possible.
So, to complete the task as soon as possible Dark Peace asks you to help him. You will be given two
set of length N and M. Your task is to find whether the subset is present in the first set whose sum of
elements is equal to the member of the set. You must check for every member of the second set. Print
Yes if subset is present and if not present print No and if the member exceeds the maximum sum of
Input
33
174
10 14 4
Output
No -1 Yes
Explanation
For first member no subset gives sum to 10 so we print No. For second since maximum sum is 12 and
14 is greater than 12 so we print -1. For last subset {4} exits whose sum is equal to 4 and hence we
print Yes
Post-Lab:
1) The subset sum problem is an important problem in computer science. Below we will provide a simple
algorithm for solving this problem. The challenge is to determine if there is some subset of numbers in
an array that can sum up to some number S. These algorithms can both be implemented to solve Array
Addition I and Array Addition.
Pre-Lab:
1) Write a recursive approach to get maximum profit value with Ex-tended knapsack problem.
Input
N = 5, P[] = {2, 7, 1, 5, 3}, C[] = {2, 5, 2, 3, 4}, W = 8, K = 2.
Output
12
Explanation:
Here, the maximum possible profit is when we take 2 items: item2 (P[1] = 7 and C[1] = 5) and item4
(P[3] = 5 and C[3] = 3). Hence, maximum profit = 7 + 5 = 12
Input
N = 5, P[] = {2, 7, 1, 5, 3}, C[] = {2, 5, 2, 3, 4}, W = 1, K = 2
Output
0
Explanation: All weights are greater than 1. Hence, no item can be picked.
In-Lab:
1) Danny has a possible list of passwords of Manny's Facebook account. All passwords length is odd.
But Danny knows that Manny is a huge fan of palindromes. So, his password and reverse of his
password both should be in the list. You must print the length of Manny's password and its middle
character.
Note: The solution will be unique.
Input
4
abc
def
feg
cba
Output:
3
2) As a health expert, Vinay is keeping a close watch on the ongoing pandemic of coronavirus disease
(COVID-19). He thought of a different situation where there are 26 types of viruses, named "aorona",
"borona", "corona", …, "zorona”. You are given a string S with length N. There are N people
(numbered 1 through N) and for each valid i, the i-th person is infected by exactly one type of virus
named Siorona (i.e., "corona" with the first letter replaced by the i-th character of S).
You should answer Q queries. In each query:
You are given an integer C denoting the number of available isolation centers.
Each isolation center has an infinite capacity, but with the restriction that two people infected
with the same type of virus cannot stay in the same isolation center.
There is also a pending queue with an infinite capacity and there are no restrictions on which
people can be in the pending queue
Initially, the isolation centers and pending queue are empty.
Each of the N people should be placed in either the pending queue or one of the isolation
centers.
Since Vinay is busy finding a vaccine, he asks Swapnil to find a way to place the people in the
pending queue and isolation centers such that the number of people in the pending queue is the
smallest possible.
Help Swapnil find the size of the pending queue in that case.
Input
1
20 2
stayinghomesaveslife
1
3
Output
6
0
Explanation
Example case 1: In the pending queue for the first query, there should be 2 people with "eorona", 2
with "sorona", 1 with "aorona" and 1 with "iorona".
Post-Lab:
1) Lisa is a school student teacher gave her an assignment to check whether the pattern is
there or not in each text and, she mentioned that it is have solve by using Kmp algorithm
so when a mismatch come other some matches in your search if she prints the number of
letters that we can neglect before then she will get good marks so help her by writing a
code.
Input
ABABDABACDABABCABAB
ABABCABAB
Output
we don‟t match before 2 letters because they will match anyway
we don‟t match before 0 letters because they will match anyway
we don‟t match before 1 letter because they will match anyway
we don‟t match before 0 letters because they will match anyway
Found pattern at index 10