DAA Lab Work Book
DAA Lab Work Book
LAB WORKBOOK
1
20CS2220RA DESIGN & ANALYSIS OF ALGORITHMS
LABORATORY WORKBOOK
STUDENTNAME
REG.NO
YEAR
SEMESTER
SECTION
FACULTY
3
20CS2220RA DESIGN & ANALYSIS OF ALGORITHMS
Table of Contents
4
20CS2220RA DESIGN & ANALYSIS OF ALGORITHMS
The laboratory framework includes a creative element but shifts the time-intensive aspects
outside of the Two-Hour closed 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.
5
20CS2220RA DESIGN & ANALYSIS OF ALGORITHMS
In-Lab
S. Pre-Lab Post- Viva Voce Total Faculty
No. Date Experiment Name (5M) Lab (5M) (50M) Signature
Logic Execution Result Analysis
(5M)
(10M) (10M) (10M) (5M)
1.
2.
3.
4.
5.
6.
7.
8.
6
20CS2220RA DESIGN & ANALYSIS OF ALGORITHMS
In-Lab
S. Pre-Lab Post- Viva Voce Total Faculty
No. Date Experiment Name (5M) Lab (5M) (50M) Signature
Logic Execution Result Analysis
(5M)
(10M) (10M) (10M) (5M)
9.
10.
11.
12.
13.
14.
15.
7
20CS2220RA DESIGN & ANALYSIS OF ALGORITHMS
Pre-Lab:
Algoritm KLU(int n)
{
int count=0;
for(int i=0;i<n;i=i*2)
{
for(int j=n;j>0;j=j/3)
{
for(int k=0;k<n;k++)
{
Count++;
}
}
}
}
Solution:
8
20CS2220RA DESIGN & ANALYSIS OF ALGORITHMS
int recursive(int n)
{
if(n==1)
return (1);
else
return(recursive (n-1) + recursive (n-1));}
Solution:
9
20CS2220RA DESIGN & 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
Complete the findMedian function in the editor below.
findMedian has the following parameter(s):
int arr[n]: an unsorted array of integers
Returns
int: the median of the array
Sample Input 0
7
0124653
Sample Output 0
3
Solution:
10
20CS2220RA DESIGN & ANALYSIS OF ALGORITHMS
In-Lab:
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.
Solution:
11
20CS2220RA DESIGN & 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.
Solution:
12
20CS2220RA DESIGN & 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.
Solution:
13
20CS2220RA DESIGN & ANALYSIS OF ALGORITHMS
Solution:
14
20CS2220RA DESIGN & ANALYSIS OF ALGORITHMS
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
Solution:
15
20CS2220RA DESIGN & ANALYSIS OF ALGORITHMS
2. Discuss the Rabin Karp algorithm for string matching and explain time complexity of the
algorithm?
Solution:
16
20CS2220RA DESIGN & 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
Solution:
13
20CS2220RA DESIGN & 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;
}
Solution :
14
20CS2220RA DESIGN & 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
Solution :
15
20CS2220RA DESIGN & 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
Solution :
16
20CS2220RA DESIGN & 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'
Solution :
17
20CS2220RA DESIGN & ANALYSIS OF ALGORITHMS
LAB SESSION 03
Date of the Session: / / Time of the Session: to
Pre-Lab:
Solution:
18
20CS2220RA DESIGN & 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
Solution:
19
20CS2220RA DESIGN & 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.
In-Lab Task:
20
20CS2220RA DESIGN & ANALYSIS OF ALGORITHMS
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
2) Watson gives Sherlock an array of integers. His challenge is to find an element of the array such that the
21
20CS2220RA DESIGN & ANALYSIS OF ALGORITHMS
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
Post-Lab Task:
22
20CS2220RA DESIGN & ANALYSIS OF ALGORITHMS
*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
Solution:
23
20CS2220RA DESIGN & ANALYSIS OF ALGORITHMS
2) HackerLand National Bank has a simple policy for warning clients about possible fraudulent account activity. If
24
20CS2220RA DESIGN & ANALYSIS OF ALGORITHMS
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 prior days' transaction data.
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 be sent. Over the period, there
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 defined to be
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
25
20CS2220RA DESIGN & ANALYSIS OF ALGORITHMS
26
20CS2220RA DESIGN & ANALYSIS OF ALGORITHMS
Pre-Lab Task:
1) Trace the output of the following matrix multiplication using Strassen’s Multiplication Method
27
20CS2220RA DESIGN & 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.
28
20CS2220RA DESIGN & ANALYSIS OF ALGORITHMS
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
20CS2220RA DESIGN & 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
30
20CS2220RA DESIGN & 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.
31
20CS2220RA DESIGN & 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)?
32
20CS2220RA DESIGN & 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.
33
20CS2220RA DESIGN & ANALYSIS OF ALGORITHMS
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
34
20CS2220RA DESIGN & 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.
35
20CS2220RA DESIGN & ANALYSIS OF ALGORITHMS
36
20CS2220RA DESIGN & ANALYSIS OF ALGORITHMS
In-Lab Task:
1. 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:
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.
37
20CS2220RA DESIGN & ANALYSIS OF ALGORITHMS
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.
Solution:
38
20CS2220RA DESIGN & ANALYSIS OF ALGORITHMS
2. 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
Solution:
39
20CS2220RA DESIGN & ANALYSIS OF ALGORITHMS
Post-Lab Task:
1. 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]]
Solution:
40
20CS2220RA DESIGN & ANALYSIS OF ALGORITHMS
2. 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
8
2
4
41
20CS2220RA DESIGN & ANALYSIS OF ALGORITHMS
3
5
2
6
4
5
Sample Output 2
12
Explanation 2
Optimal distribution will be 1, 2, 1, 2, 1, 2, 1, 2.
Solution:
42
20CS2220RA DESIGN & ANALYSIS OF ALGORITHMS
43
20CS2220RA DESIGN & ANALYSIS OF ALGORITHMS
Pre-Lab:
1) Explain why 0-1 Knapsack problems cannot be solved using greedy method unlike fractional
knapsack.
Solution:
44
20CS2220RA DESIGN & 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 –
Solution:
45
20CS2220RA DESIGN & ANALYSIS OF ALGORITHMS
Solution:
46
19CS3113S ANALYSIS & DESIGN OF ALGORITHMS
In-Lab:
1) Given an array of size n that has the following specifications:
a. Each element in the array contains either a police officer or a thief.
b. Each police officer can catch only one thief.
c. A police officer cannot catch a thief who is more than K units away from the police officer.
Solution:
47
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
Solution:
48
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
Solution:
49
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.
Solution:
50
19CS3113S ANALYSIS & DESIGN OF ALGORITHMS
51
19CS3113S ANALYSIS & DESIGN OF ALGORITHMS
Pre-Lab Task:
1. In KL University, every student has to participate in NCC activity regularly. Each day NCC
activity has its own duration. You will be given number of days schedule and the number of
hours you need to spend on each day. The rule you need to follow is that you cannot skip NCC
activity 3 days in a row.
Your task is to find the minimum number of hours that you spend on activities by following given
rule.
Input:
Line 1: An integer “n” representing number of days
Line 2: n non negative integers representing the hours to spend on each day
Output:
A single non negative integer representing number of hours that you want to spend by following
the given rule.
Sample Input:
1) 10
3411232321
2) 8
32323513
3) 7
3255424
Sample Output:
1) 5 (1+1+2+1)
2) 5(2+2+1)
3) 6(2+4+2)
Solution:
52
19CS3113S ANALYSIS & DESIGN OF ALGORITHMS
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: A string S
Output: A string of length |S| satisfying above conditions.
Sample Input:475854637834259
Sample output:766655433322100
Solution:
53
19CS3113S ANALYSIS & DESIGN OF ALGORITHMS
In-Lab Task:
1. In KL University, there is scheduled hours for playing cricket every day. You will be given
number of days and hours you need to spend in each day. The rule here is that you have to skip
one day in consecutive three days.
Your task is to maximize your time in cricket by following the given rule
Input:
Line 1: An integer “n” representing number of days
Line 2: n non negative integers representing the hours to spend on each day
Output:
A single non negative integer representing number of hours that you want to spend by following
the given rule.
Sample Input:
1) 5
10 3 5 7 3
2) 8
32323513
Sample Output:
3) 23(10+3+7+3)
4) 17( 3+3+3+5+3)
54
19CS3113S ANALYSIS & DESIGN OF ALGORITHMS
2. A sequence of numbers are called symmetric if it reads the same in both directions. For example
32,25,32 is symmetric. Every sequence of one number is symmetric. Any sequence can be broken
up into parts such that each of them is symmetric. For an instance consider the sequence
25,35,25,53,45. It can be broken up into 3 symmetric sequences (25,35,25;53;45) or 5 symmetric
sequences(25;35;25;53;45). Your task is to find the smallest number x such that the given
sequence can be broken up into x symmetric sequences using dynamic programming.
Input:
First line contains, n, number of values in the sequence
Second line contains n +ve integers
Output:
A single integer giving the smallest number x so that the given sequence can broken up into x
symmetric sequences.
Sample Input:
5
25 35 25 53 45
Sample Output:
3
55
19CS3113S ANALYSIS & DESIGN OF ALGORITHMS
Post-Lab Task:
1. Raju has got 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 have to 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
have to print the root of that Optimal Binary search Tree.
Tasks:
(i)You should Find the Cost of the optimal BST 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
keys. 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
Sample-Input:
4
12 10 20 21
8 34 50 1
2
03
01
Sample-Output:
Cost of Optimal BST is 144
20
10
56
19CS3113S ANALYSIS & DESIGN OF ALGORITHMS
57
19CS3113S ANALYSIS & DESIGN OF ALGORITHMS
58
19CS3113S ANALYSIS & DESIGN OF ALGORITHMS
Pre-Lab Task:
59
19CS3113S ANALYSIS & DESIGN OF ALGORITHMS
2. There are n items with some weights and corresponding values and a bag of capacity W. The items
should be placed in the bag in such a way that the total value is maximum and total weight should
be less than knapsack capacity. In this problem 0-1 means that we can’t put the items in fraction.
Either put the complete item or ignore it. find the solution for this problem using dynamic
programming.
Sample-Input:
Enter number of items:3
Enter value and weight of items:
1 45
2 56
3 40
Enter size of knapsack:40
Sample-Output:
3
Solution:
60
19CS3113S ANALYSIS & DESIGN OF ALGORITHMS
In-Lab Task:
1. Given N cities numbered from 1 to N. Your task is to visit the cities. Here K cities are already
visited. You can visit ith city if (i-1)th or (i+1)th city is already visited. Your task is to determine
the number of ways you can visit all the remaining cities.
Input format:
First line: Two space-separated integers N and K
Second line: K space-separated integers each denoting the city that is already visited
Output format:
Print an integer denoting the number of ways to visit the remaining cities.
Sample Input:
63
126
Sample Output:
4 ({3,4,5},{3,5,4},{5,3,4},{5,4,3})
Solution:
61
19CS3113S ANALYSIS & DESIGN OF ALGORITHMS
2.Given a string X formed out of single digit numbers from 0 to 9 , you are given a set of digits S
and you need to count total substring of string X that contains all the digits in the set S.
Input:
First line contains a string as input.
Next line contains a number n as input denoting size of set S.
Next line contains n space separated integers that denote the distinct integers in the set S.
Output
Total count of substrings of the string X such that they contain all the digits in the set S
Sample Input:
333
1
3
Sample Output:
6
Solution:
62
19CS3113S ANALYSIS & DESIGN OF ALGORITHMS
Post-Lab Task:
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 is 2 5 1 4 3, oppgroup is 3 1 5 4 2 .
Given a number N, find the number of distinct groups of length N which can not be distinguished from
their oppgroups.
Input:
First line consists of a single integer T, the number of test cases.
Next T lines consist of a single integer each, representing value of N for that test case.
Output:
For each testcase, output the desired answer.
Sample input:
1
3
Sample Output:
4
Solution:
63
19CS3113S ANALYSIS & DESIGN OF ALGORITHMS
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 format:
First line: Two space-separated integers N and K
Second line: A string S of size N.
Output format:
Print the required answer.
Sample Input:
a)5 6
34212
b)2 21
11
c)5 22
34212
Sample Output:
a)1
b)2
c)3
Solution:
64
19CS3113S ANALYSIS & DESIGN OF ALGORITHMS
65
19CS3113S ANALYSIS & DESIGN OF ALGORITHMS
(For Evaluator’s use only)
Comment of the Evaluator (if Any) Evaluator’s Observation
Marks Secured: _______ out of ________
Pre-Lab Task:
1. Christy is interning at HackerRank. 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
Given a starting distribution, calculate the minimum number of operations needed so that every colleague
Example
A=[1,1,5]
A 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
Sample Input 1
STDIN Function
----- --------
1 t=1
4 arr[] size n = 4
2237 arr =[2, 2, 3, 7]
66
19CS3113S ANALYSIS & DESIGN OF ALGORITHMS
Sample Output 1
2
Explanation
Sample Input 2
1
3
10 7 12
Sample Output 2
3
Explanation 1
Solution:
67
19CS3113S ANALYSIS & DESIGN OF ALGORITHMS
68
19CS3113S ANALYSIS & DESIGN OF ALGORITHMS
2. Consider the following table with given weights and respective profit in context to 0/1 knapsack problem
using branch and bound. Draw the state space tree and solve the problem.
Pi Wi
10 2
10 4
12 6
18 9
69
19CS3113S ANALYSIS & DESIGN OF ALGORITHMS
In-Lab Task:
1. Given an integer array nums, find the contiguous subarray (containing at least one number) which
has the largest sum and return its sum.
Example 1:
Output: 6
Example 2:
Output: 1
Example 3:
Output: 23
Solution:
70
19CS3113S ANALYSIS & DESIGN OF ALGORITHMS
71
19CS3113S ANALYSIS & DESIGN OF ALGORITHMS
2. Pantelija was given a sequence of positive integers a1,a2,aNa1,a2,aN. Let's define the gcd
value of this sequence as the number of its non-empty contiguous subsequences with
greatest common divisor strictly greater than 11. The greatest common divisor of any
contiguous subsequence al,al+1,aral,al+1,ar (1≤l≤r≤N1≤l≤r≤N) is the greatest positive
integer which divides each element of this subsequence.Pantelija wants to maximize the
gcd value of this sequence. In order to do that, he may choose a valid index ii, an integer
bb (1≤b≤5⋅1051≤b≤5⋅105, since he does not like large numbers) and change the element
aiai to bb. What is the maximum possible gcd value he can obtain?
Sample input: 5
4 5 10 3 7
Sample output:
9
Solution:
72
19CS3113S ANALYSIS & DESIGN OF ALGORITHMS
Post-Lab Task:
1. You are given an array prices where prices[i] is the price of a given stock on the ith day.
You want to maximize your profit by choosing a single day to buy one stock and choosing
a different day in the future to sell that stock.
Return the maximum profit you can achieve from this transaction. If you cannot achieve any
profit, return 0.
Example 1:
Output: 5
Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.
Note that buying on day 2 and selling on day 1 is not allowed because you must buy before you
sell.
Example 2:
Output: 0
Explanation: In this case, no transactions are done and the max profit = 0.
Solution:
73
19CS3113S ANALYSIS & DESIGN OF ALGORITHMS
74
19CS3113S ANALYSIS & DESIGN OF ALGORITHMS
Pre-Lab Task:
1. A binary watch has 4 LEDs on the top which represent the hours (0-11), and the 6 LEDs on the
bottom represent the minutes (0-59). Each LED represents a zero or one, with the least significant
bit on the right.
Given an integer turnedOn which represents the number of LEDs that are currently on, return all
possible times the watch could represent. You may return the answer in any order.
The minute must be consist of two digits and may contain a leading zero.
Example 1:
Input: turnedOn = 1
Output: ["0:01","0:02","0:04","0:08","0:16","0:32","1:00","2:00","4:00","8:00"]
Example 2:
Input: turnedOn = 9
Output: []
Solution:
75
19CS3113S ANALYSIS & DESIGN OF ALGORITHMS
76
19CS3113S ANALYSIS & DESIGN OF ALGORITHMS
2. Draw the state space tree for the following travelling salesman problem using branch and bound
approach. Given a set of cities and distance between every pair of cities, the problem is to find the
shortest possible tour that visits every city exactly once and returns to the starting point
In-Lab Task:
1. Given an integer array nums and an integer k, return true if it is possible to divide this array
into k non-empty subsets whose sums are all equal.
Example 1:
Output: true
Explanation: It's possible to divide it into 4 subsets (5), (1, 4), (2,3), (2,3) with equal
sums.
Example 2:
Output: false
Solution:
77
19CS3113S ANALYSIS & DESIGN OF ALGORITHMS
78
19CS3113S ANALYSIS & DESIGN OF ALGORITHMS
2. A family is planning for a tour .That family wanted to visit some cities the cities are Paris, London,
New York, Los Angeles and we are giving the distance between each pair of cities, the problem is
to find the shortest possible route that visits every city exactly once and returns to the starting
point. Solve the below problem using Travelling Salesman problem using Branch and Bound using
programming
Sample Input:
Enter No. of cities: 4
Enter the cost matrix
Enter elements of row:1
0 10 35 30
Enter elements of row:2
10 0 30 15
Enter elements of row: 3
35 30 0 30
Enter elements of row: 4
30 15 30 0
Sample Output:
The cost list is
0 10 35 30
10 0 30 15
35 30 0 30
30 15 30 0
Optimal Solution: The path is: 1-->2-->4-->3-->1
Minimum cost:90
Solution:
79
19CS3113S ANALYSIS & DESIGN OF ALGORITHMS
80
19CS3113S ANALYSIS & DESIGN OF ALGORITHMS
Post-Lab Task:
1. You are given a string of digits num, such as "123456579". We can split it into a Fibonacci-like
sequence [123, 456, 579].
• 0 <= f[i] < 231, (that is, each integer fits in a 32-bit signed integer type),
• f.length >= 3, and
• f[i] + f[i + 1] == f[i + 2] for all 0 <= i < f.length - 2.
Note that when splitting the string into pieces, each piece must not have extra leading zeroes,
except if the piece is the number 0 itself.
Return any Fibonacci-like sequence split from num, or return [] if it cannot be done.
Example 1:
Output: [123,456,579]
Example 2:
Output: [1,1,2,3,5,8,13]
Example 3:
Output: []
Example 4:
Output: []
81
19CS3113S ANALYSIS & DESIGN OF ALGORITHMS
Explanation: Leading zeroes are not allowed, so "01", "2", "3" is not valid.
Solution:
82
19CS3113S ANALYSIS & DESIGN OF ALGORITHMS
Pre-Lab Task:
1. Given a string 'S' , u need to tell whether it is 'sumit's string or not'.A string is called
'Sumit's String' , if distance between adjacent character is 1.Consider that the alphabets
are arranged in cyclic manner from 'a' to 'z'. distance between any character 'x' and 'y' will
be defined as minimum number of steps it takes 'x' to reach 'y'. Here, character 'x' can
start moving clockwise or anti-clockwise in order to reach at position where character 'y'
is placed.
Print 'YES' if it is Sumit's string else print 'NO', for each test case.
Sample Input:
3
aba
zza
bcd
Sample Output:
YES
NO
YES
Solution:
83
19CS3113S ANALYSIS & DESIGN OF ALGORITHMS
2. Manish has got the task to frame a speech for his professor at the university at the Annual sports meet.
But the problem is that the professor has speech dyslexia and he can't speak the words clearly which have
vowels in them. So Manish has to avoid such words and has to minimize their usage in the speech letter.
Your task is to help Manish mark the vowels in the words so that he can minimize their use. You are given
a string S consisting of lower-case letters only. You need to count the number of vowels in the string S.
Input Format:
The first line will contain an integer T denoting the number of test cases. The following T lines will contain
a string S in lower case letters only.
Output Format:
Print the number the vowels in the string S.
Sample Input:
1
hashes
Sample Output:
2
Solution:
84
19CS3113S ANALYSIS & DESIGN OF ALGORITHMS
In-lab task:
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 the time taken by fun()
clock_t t;
t = clock();
fun();
t = clock() - t;
double time_taken = ((double)t)/CLOCKS_PER_SEC; // in seconds
printf("fun() took %f seconds to execute \n", time_taken);
return 0;
}
Solution:
85
19CS3113S ANALYSIS & DESIGN OF ALGORITHMS
2. You were given a pattern and a string. If the pattern is present in the string then it is known as magical
string (if present at least once). If the string is not present in the string find the minimum number of
changes that are to be made to make it magical string. If it a magical string print the number of times the
pattern is present in the string.
Solution:
86
19CS3113S ANALYSIS & DESIGN OF ALGORITHMS
Post-lab Task:
1. Given an encrypted message, Erwin encodes it the following way: Removes the median letter of
the word from the original word and appends it to the end of the encrypted word and repeats the
process until there are no letters left. A median letter in a word is the letter present in the middle
of the word and if the word length is even, the median letter is the left one out of the two middle
letters. Given an encoded string, write a program to decode it.
Input Format:
The first line of input contains T, the number of test cases. Each test case contains a String S,
denoting the encoded word.
Output Format:
Print the decoded word for each test case in a separate line.
Sample Input:
2
wrien
reen
Sample Output:
erwin
eren
Explanation In the first test case, Erwin encoded the String "erwin". At first, he wrote down the
letter 'w' after which the string became "erin", he then wrote down 'r' and the remaining string
was "ein", he then wrote 'i' and the string became "en" and so on he wrote down 'e' and 'n' to get
the encoded string as "wrien".
Solution:
87
19CS3113S ANALYSIS & DESIGN OF ALGORITHMS
88
19CS3113S ANALYSIS & DESIGN OF ALGORITHMS
Pre-Lab Task:
1. How hash values are used in Rabin Karp algorithm and explain with an example?
Solution:
89
19CS3113S ANALYSIS & DESIGN OF ALGORITHMS
2. You are given a String S of size N, consisting of lowercase English characters. Now, you need to select a
single English
lowercase alphabet, and delete all occurences of it from the given string S
Considering you do the mentioned exactly once over the given string, what is the minimum possible
length of the resultant string ?
Input Format :
The first line contains a single integer N. The next line contains a String S of length N consisting of
lowercase Englsh characters.
Output Format : Print the required answer on a single line
Constraints : 1≤N≤100,000
Note that the Expected Output feature of Custom Invocation is not supported for this contest. Sample
Input:
5
aaaaa
Sample Output:
0
Solution:
90
19CS3113S ANALYSIS & DESIGN OF ALGORITHMS
In-Lab Task:
1. Given an array of string words. Return all strings in words which is substring of another word in any
order.
String words[i] is substring of words[j], if can be obtained removing some characters to left and/or
right side of words[j]
Example 1 :
Input: words = ["mass","as","hero","superhero"]
Output: ["as","hero"] Explanation: "as" is substring of "mass" and "hero" is substring of "superhero".
["hero","as"] is also a valid answer.
Example 2:
Input: words = ["leetcode","et","code"]
Output: ["et","code"]
Explanation: "et", "code" are substring of "leetcode".
Example 3:
Input: words = ["blue","green","bu"]
Output: []
Constraints:
• 1 <= words.length <= 100
• 1 <= words[i].length <= 30
• words[i] contains only lowercase English letters.
• It's guaranteed that words[i] will be unique.
Solution:
91
19CS3113S ANALYSIS & DESIGN OF ALGORITHMS
2. Lisa is a school student. Teacher gave her an assignment to check whether the pattern is there or not
in a given text and also she mentioned that it is have solve by using kmp algorithm so when a
mismatch come other some matches in your search if she print the number of letters that we can
neglect before then she will get good marks so help her by writing a code.
Sample Input:
ABABDABACDABABCABAB
ABABCABAB
Sample 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
Solution:
92
19CS3113S ANALYSIS & DESIGN OF ALGORITHMS
Post-Lab Task:
1. There are N students standing in a row and numbered 1 through N from left to right. You are given a
string S with length N, where for each valid ii, the ii-th character of S is 'x' if the i-th student is a girl or
'y' if this student is a boy. Students standing next to each other in the row are friends.
The students are asked to form pairs for a dance competition. Each pair must consist of a boy and a
girl. Two students can only form a pair if they are friends. Each student can only be part of at most
one pair. What is the maximum number of pairs that can be formed?
Input
• The first line of the input contains a single integer T denoting the number of test cases. The
description of T test cases follows.
• The first and only line of each test case contains a single string S.
Output: For each test case, print a single line containing one integer ― the maximum number of
pairs.
Sample Input:
3
xy
xyxxy
yy
Sample Output: 1
2
0
Explanation:
Example case 1: There is only one possible pair: (first student, second student).
Example case 2: One of the ways to form two pairs is: (first student, second student) and (fourth
student, fifth student).
Another way to form two pairs is: (second student, third student) and (fourth student, fifth student).
93
19CS3113S ANALYSIS & DESIGN OF ALGORITHMS
Solution:
94
19CS3113S ANALYSIS & DESIGN OF ALGORITHMS
95