New Revised Esc101 Prutor All Labs and Quiz Problems by Sujal PDF
New Revised Esc101 Prutor All Labs and Quiz Problems by Sujal PDF
4 1 1 1 2 2 NO NONE 2 NO NONE
5 5 6 5 5 6 NO NONE 6 NO NONE
10 8968 8968 8968 889688 889688 YES SIX 889688 YES SIX
11 66 25 25 25 66 NO NONE 66 NO NONE
#include <stdio.h>
int main() {
int a, b, c, d;
if (a == b && b == c) {
int sum = a + b + c;
printf("YES BOTH");
} else if (sum % 6 == 0) {
printf("YES SIX");
} else if (sum % 9 == 0) {
printf("YES NINE");
} else {
printf("NO NONE");
} else if (a == b && b == d) {
int sum = a + b + d;
printf("YES BOTH");
} else if (sum % 6 == 0) {
printf("YES SIX");
} else if (sum % 9 == 0) {
printf("YES NINE");
} else {
printf("NO NONE");
} else if (b == c && c == d) {
int sum = b + c + d;
printf("YES BOTH");
} else if (sum % 6 == 0) {
printf("YES SIX");
} else if (sum % 9 == 0) {
printf("YES NINE");
} else {
printf("NO NONE");
} else if (a == c && c == d) {
int sum = a + c + d;
printf("YES BOTH");
} else if (sum % 6 == 0) {
printf("YES SIX");
} else if (sum % 9 == 0) {
printf("YES NINE");
} else {
printf("NO NONE");
}
return 0;
int main() {
printf("Alice");
printf("Bob");
} else {
printf("Draw");
return 0;
Power of Two
[40 Points] ---------------------------------------------------------------------- Automated Grading Scheme:
Public Test Cases (1 point each. 1*4= 4 points) Hidden Test Cases (4 point each. 4*9 = 36
points)
Manual Grading Scheme Note: Solution to this question is itself a hard-coding approach, so no
need to check for hard coding for this question. Penalty: 15 marks to be deducted if any future
concept like arrays is used or any other header file apart from stdio.h is used for solving the
problem. ----------------------------------------------------------------------
You are a new intern at a famous multinational company. Your first task given by your manager
is as follows.
You are provided with a number N where N is an integer strictly smaller than 128. First, you have
to check if N is positive. If N is a positive integer, then find the count of number of positive powers
of 2 which are smaller than N. Print all the positive powers of 2 which are less than N.
Input Format: N
The number N is an integer and is strictly smaller than 128.
Output Format:
If N is not a positive integer, then print "Invalid Input" (without quotes, the quotes are for
emphasis). If N is a positive integer, the output may span upto 2 lines. In the first line, print the
count of positive powers of 2 which are less than N. In the following line, print all the powers of 2
which are less than N.
Example Input 10 Example Output: 3 2 4 8
1 -1 Invalid Input Invalid Input
2 1 0 0
3 31 4 2 4 8 16 4 2 4 8 16
5 5 2 2 4 2 2 4
int main() {
int n;
scanf("%d", &n);
if (n <= 0) {
printf("Invalid Input\n");
} else if (n <= 2) {
printf("0\n");
} else if (n <= 4) {
printf("1\n2\n");
} else if (n <= 8) {
printf("2\n2 4\n");
printf("3\n2 4 8\n");
printf("4\n2 4 8 16\n");
printf("5\n2 4 8 16 32\n");
printf("6\n2 4 8 16 32 64\n");
return 0;
Sachin vs Virat
[34 Points] ---------------------------------------------------------------------- Automated Grading Scheme:
Public Test Cases (1 point each. 1*2= 2 points) Hidden Test Cases (32 points) Test Cases 1
to 2 are of 1 marks each. Test Cases 3 to 10 are of 3 marks each. Test Cases 11 and 12 are of 4
marks each.
Manual Grading Scheme Note: Any form of hard-coding will lead to zero marks. Eg: printf("0");
Penalty: 15 marks to be deducted if any future concept like arrays is used or any other header
file apart from stdio.h is used for solving the problem. ---------------------------------------------------------
-------------
Cricket is the most popular sport in India. The Indian cricket team has been lucky to have great
world-class talents in their side. Today we have Virat Kohli, but back in the day, we had the God
of cricket, Sachin Tendulkar. Both being such high-class talents, it is impossible for the fans to
not compare them.
Suppose you are a data analyst at a sports analytics firm. You have been assigned the duty to
find out what minimum runs Virat Kohli should score in the remaining matches, so that he
overtakes Sachin as the best batsman in the history of the sport. As a newbie, you only like to
work with integers. So, you need to first check if the average of Sachin is an integer or not. If it is
not an integer, simply print "ERROR" (without quotes), other wise print "INTEGER". If it is an
integer you need to calculate the runs Virat needs to score in order to overtake Sachin. Virat will
overtake Sachin only if his total runs scored and his net average are both higher than that of
Sachin's. In case of any equality, Sachin will be considered the better batsman.
Note: The average is calculated as the number of runs scored per match played.
Input Format:
The first line contains two numbers which represent the number of innings played by Sachin (M1)
and the total runs scored by him (R1), respectively. The next line contains three numbers, the
number of innings played by Virat Kohli (M2), total runs scored by him (R2) and the remaining
matches he is yet to play(K).
All the inputs are positive integers.
Output Format:
If the average of Sachin is not an integer, simply print "ERROR" without quotes, else print
"INTEGER". In case of integer average, you need to output the minimum runs (an integer) that
Virat needs to score to overtake Sachin at the end of his career in the next line.
----------
----------
404 17300
ERROR
380 16300 40
Explanation
• In first sample test case, Virat needs to score atleast 4001 runs more in remaining 50
matches. Doing so, his total runs (16001) and average(~45.71) will be more than
Sachin's runs(16000) and average(40).
• In second test case, Sachin's runs are 17500 and his average is 50. Virat will need to
score to atleast 3501 runs in remaining 100 matches. Doing so, his total runs will be
20001 and the average will be 50.0025, helping him overtake Sachin.
• In third test case, average of Sachin is not an integer. Thus the corresponding output is
'ERROR'.
#include <stdio.h>
int main() {
// Scan integers
if (r1 % m1 != 0) {
printf("ERROR");
} else {
printf("INTEGER\n");
// no. of runs Virat Kohli must have in total to get equal average as SRT
} else {
ans = r1 + 1 - r2;
if (ans < 0) {
printf("%d", 0);
} else {
printf("%d", ans);
}
return 0;
Lab 2
• a is the maximum of the minimums of even integers for every n integers in the sequence.
• b is the minimum of the maximums of odd integers for every n integers in the sequence.
• c is defined as the maximum of numbers that are divisible by 13 and not divisible by 37
over all the numbers. If there are no such numbers, c is 0.
Input Format: The first integer is n. It is followed by the sequence of numbers delimited by -1
(i.e., the last number in the sequence is -1).
The integer n is at least 2. For every n integers, there will be at least one even integer and one
odd integer. The total numbers input after the first number are divisible by n.
Output Format: Print a single integer, a+b-c.
Input1 Output1
6
4 5 3 63 2 1
72
481 23 13 37 99 0
22 147 111 22 22 22 -1
Input2 Output2
5
244 27 46 173 33
243
144 162 70 263 350
67 42 167 249 50 -1
Note: In the above examples the inputs are in diffierent lines its only to help in undustanding.
Actual inputs will be given as described.
Explanation (Case 1):
#include <stdio.h>
int main() {
int n;
int counter = 0;
int curr;
int c = 0;
scanf("%d", &n);
scanf("%d", &curr);
if (curr % 2 == 0) {
if (min_even == -1)
min_even = curr;
min_even = curr;
} else {
max_odd = curr;
c = curr;
scanf("%d", &curr);
counter = counter + 1;
if (counter == n) {
if (a < min_even)
a = min_even;
if (b == -1)
b = max_odd;
b = max_odd;
counter = 0;
min_even = -1;
max_odd = 0;
printf("%d", a + b - c);
return 0;
Run a Series
DK and AK are preparing for IIT exam but series is a weak topic for them. They need your help to
calculate Arithmetico-Geometric Series so that they can verify their results.
Arithmetico-Geometric Series is given by: a, (a+d)r, (a+2d)r2, (a+3d)*r3, ...
You will be given the following four inputs in a single line separated by space.
First, you will be required to give the terms of the series starting from first term separated by new
line Secondly, you will be required to give average of the series in last line. You are not allowed
to use pow() functionality. All results must be printed with 3 places of decimal.
Input Format:
First line contains input values separated by space.
Output Format:
Output will contain the terms of the series separated by new line and average of series in lastline.
Marking Scheme: Visible Test Case: 4 marks Hidden Test Case: 6*6 = 36 marks Total: 40
Marks.
2 -1.2 4 5.4 -1.200 30.240 361.584 3023.309 -1.200 30.240 361.584 3023.309
6.8 853.483 853.483
#include <stdio.h>
int main()
{ float a,r,d;
int n,i=1;
float sum=a;
float term=0;
float s=a;
float factor=1;
printf("%0.3f\n",s);
i=2;
while(i<=n)
{s+=d;
factor*=r;
term=s*factor;
sum+=term;
printf("%0.3f\n",term);
i++;
printf("%0.3f",(sum/n));
return 0;
Example 1
Input:
91 27 78 42 -1
Output:
42
Explanation:
91 > 78 > 42 > 27
Example 2
Input:
34 49 34 -1
Output:
-1
Explanation:
49 > 34, so a third largest number does not exist in the stream.
#include <stdio.h>
int main() {
int i = 0, first = -1, second = -1, third = -1;
scanf("%d", &i);
while (i != -1) {
if (i > first) {
third = second;
second = first;
first = i;
third = second;
second = i;
third = i;
scanf("%d", &i);
printf("%d", third);
return 0;
#include <stdio.h>
int main() {
int n1,n2,r1,r2,s1=0,s2=0;
scanf("%d %d",&n1,&n2);
if(n1<0 || n2<0){
printf("INVALID INPUT");
while(n1){
r1=n1%10;
s1=s1*10+r1;
n1=n1/10;
while(n2){
r2=n2%10;
s2=s2*10+r2;
n2=n2/10;
printf("%d",s1+s2);
return 0;
}
Lab 3
Finding Pretty Numbers
Your friend Naruto loves numbers with some unique qualities. He calls them pretty numbers.
You, being his only friend, decide to go on a quest to find pretty numbers. While on the quest,
you will find one number each day for N days. Pretty numbers can be described as:
Naruto also hates negative numbers and considers them ugly. He wants you to count the number
of pretty numbers and ugly numbers you encounter in your quest.
A prime number is a number n (n not equal to 1) with exactly two factors which are 1 and n
itself. For example, 2, 13, and 17.
Input
A sequence of integers separated by spaces, the last integer in the sequence is 0.(i.e. sequence
ends with 0)
Output
Two integers that are separated by ONE space. The first is the number of pretty integers and the
second is the number of ugly numbers encountered during the quest.
Output:
2 1
Input:
-100 81 96 37 23 17 -999 10 512 243 0
Output:
4 2
#include <stdio.h>
int main() {
while (1) {
int x;
scanf("%d", &x);
if (x == 0)
break;
if (x < 0) {
ugly_cnt++;
continue;
if (x == 1)
continue;
int isprime = 1;
if (x % i == 0) {
isprime = 0;
break;
if (isprime) {
pretty_cnt++;
continue;
int a = 0, b = 0, rx = x;
while (rx % 2 == 0) {
rx /= 2;
a++;
while (rx % 3 == 0) {
rx /= 3;
b++;
pretty_cnt++;
return 0;
Despite being adept at conducting expeditions, Lyza is not very good at solving Math problems
and hence asks for your help to overcome this challenge.
Input Format
The 1st line contains an integer N. (Both matrices are of size N x N). The next N lines contain N
space separated integers each where the j-th integer at the i-th row corresponds to the (i,j)-
th element of the first matrix. The next N lines contain N space separated integers each where
the j-th integer at the i-th row corresponds to the (i,j)-th element of the second matrix
Output Format:
If the required condition holds, print YES (in capital letters) in the first line. In the next line, print the
trace of the first matrix, which is also equal to the product found for the second matrix. If the
required condition does not hold, print NO (in capital letters) in the first line. In the next line, print
the trace of the first matrix, followed by the product found for the second matrix separated by a
space.
Output 1:
NO
15 384
Input 2
3
5 3 1
5 3 2
6 1 4
2 -8 4
11 3 4
1 7 5
Output 2:
YES
12
#include <stdio.h>
int main() {
int N;
scanf("%d", &N);
int mat1_sum = 0;
int mat2_prod = 1;
int aval;
scanf("%d", &aval);
if (i == j) {
mat1_sum += aval;
int bval;
scanf("%d", &bval);
if (i + j == N - 1) {
mat2_prod *= bval;
}
if (mat1_sum == mat2_prod) {
printf("YES\n");
printf("%d", mat1_sum);
} else {
printf("NO\n");
return 0;
Strange Sum
[100 Points] ---------------------------------------------------------------------- Automated Grading
Scheme: Public Test Cases (5 point each. 2*5 = 10 points) Hidden Test Cases (90 points)
Test Case numbers 1 and 2 are of 15 marks each Test Case numbers 3 and 4 are of 10 marks
each Test Case number 5 is of 20 marks Test case number 6 is of 15 marks Test case number 7
is of 5 marks Manual Grading Scheme Note: Any form of hard-coding will lead to zero marks.
Eg: printf("0"); Penalty: -20% for using array and any other future concept Penalty: -20% each
for using any library function other than printf and scanf Penalty: -20% each for using any library
other than stdio.h ---------------------------------------------------------------------------------------------------------
-----
Your genius little cousin has just learned the concept of divisors and multiples. To play with him,
you give him a sequence of positive integers and ask him to find the sum of divisors of each
number x in the sequence. Finally, you ask him to add up the sum of digits in each of these sums
and tell you the answer.
For example, for the sequence 10, 12, 6, you expect the sum of divisors being 18 for 10
(1+2+5+10), 28 for 12 (1+2+3+4+6+12) and 12 for 6 (1+2+3+6). So, what you want is (1+8) +
(2+8) + (1+2) = 22 as the sum of the sum of digits.
However, the genius that he is, he is not interested in this easy task. For each number x, he finds
the sum of divisors of x (let us call this sum_x; this is in base 10), and finally, for all these sum_x,
he converts them to base k (k being his favorite number). He tells you the sum of the sum of
digits of all these base k numbers, instead of what you originally wanted.
For example, let k=3.
1. For 10, we had the sum of divisors as 18, 18 in base 3 notation is 200
2. For 12, we had the sum of divisors as 28, 28 in base 3 notation is 1001
3. For 6, we had the sum of divisors as 12, 12 in base 3 notation is 110
Input
The first line contains 2 integers, n (number of integers in the list you have) and k (n > 0, k > 1).
The second line contains n space-separated positive integers.
Output
Two integers separated by a space. The first one is the answer you desired. The second is the
answer given by your cousin.
Output:
22 6
Input:
2 2
5 7
#include <stdio.h>
int main() {
int n, k;
int element;
scanf("%d", &element);
// Sum of divisors
int sm = 0;
if (element % j == 0)
sm += j;
basek /= k;
}
// Compute base 10 sum of digits
base10 /= 10;
return 0;
DINO WALK
Dino loves to walk during lab hours and visits various places. Each location has a unique code
place@x@y where x,y are positive integers. There are some constraints that Dino has to respect
in a walk.
Each location has a movability index which is a positive integer. If the movability index for a
location is prime, then the place acts as a barrier.
A walk is represented as place@k@l → place@k@l+1 → ........... → place@k@m , where none of the
places lying in this walk acts as a barrier and movability index of places are in non-decreasing
order. The length of a walk is defined as the number of places in the walk (it is m-l+1 for the
above example).
Dino is provided with a map which is represented as a matrix (MxN), where each entry in i row
and j column of a matrix denotes the movability index of place@i@j.
Dino is interested in finding the walk with the maximum length for every row. The sum of lengths
of these maximum length walks represents a HIGH score. As a pro-gamer (programmer) of the
Dino Game, you have to calculate the HIGH score.
Input Format: The first line will contain M and N followed by M lines, where each line contains N
integers.
Output format: A single integer representing the sum of the lengths of the maximum walk for
each row.
Example Input:
35
1 2 4 8 16
1 3 7 15 31
2 3 5 17 11
Example Output:
4
Explanation:
Row ↓ /Col → 1 2 3 4 5
1 1 2 4 8 16
2 1 3 7 15 31
3 2 3 5 17 11
In Row 1:
place@1@2 will acts as a barrier. In this row, there are 7 walks possible.
In Row 2:
Two walks are possible:
Walk 1: place@2@1
Walk 2: place@2@4
Both walks have length 1. So, walk with maximum length is 1.
In Row 3:
There are no walks in Row3 since all places have prime movability index.
Answer:
So, Higher Score = 3(for row 1) + 1 (for row 2) + 0 = 4
#include <stdio.h>
int main() {
int m, n, ans = 0;
int max_path_length = 0;
int mov_idx;
scanf("%d", &mov_idx);
int is_prime = 1;
if (mov_idx % k == 0)
is_prime = 0;
if (mov_idx == 1)
is_prime = 0;
if (is_prime) {
curr_path_length = prev_idx = 0;
continue;
curr_path_length = 1;
} else {
curr_path_length++;
prev_idx = mov_idx;
max_path_length = curr_path_length;
ans += max_path_length;
printf("%d", ans);
return 0;
Lab 4
Decode Numbers
You were taught about the binary and hexadecimal representations in the lectures about the
ASCII codes. It is also possible to have numbers represented with bases other than the powers
of two.
Let us say that you want to represent a number with the base 17. Any integer can be uniquely
represented as: an17n-1 + an-117n-2 + ... + a1*170, where for each ai, 0 <= ai < 17
In the hexadecimal representation, we represented 10 by A, 11 by B, ..., and 15 by F. Similarly,
in our base 17 representation we can represent 1-15 as we did in the hexadecimal
representation, and represent 16 by G.
Using this scheme we can represent any number to any base in the range 2-20 (even larger
bases are possible, but we are going to restrict to 20). You are given a base and a number
represented with the base. Your job is to convert the number to its decimal representation or print
"INVALID" if it is not possible to do the same.
It may not always be possible to construct the decimal representation of a given number as it
may contain characters, which should not be part of the representation. For instance, let us say
that you are asked to convert "1012" base 2 to its decimal representation. It is not possible to do
so as 2 is >= 2, and the representation of a number base k should contain characters from 0 to
(k-1) only. Similarly, if you are asked to convert "ABC" base 12 to its decimal representation, it is
not possible to do so as it contains C which represents 12, which is equal to the base. For such
cases, you should print "INVALID".
You need not worry about integer overflow issues as the inputs are small enough to fit inside the
integer datatype.
Constraints
You are not allowed to use strings, arrays, or array indexing to solve this problem, you can only
scan the input character by character.
Input:
• The first line contains an integer from 2-20 which is to be interpreted as the base of the
number.
• The second line contains the number of characters in the following representation.
• The third line contains as many characters as given in the previous input. Each of these
characters can be either uppercase English letters or numbers from 0-9.
Output:
• Your program should print the decimal representation of the number given in the third line
Sample TestCases
Test Case 1
• Input:
• 2
• 4
• 1010
• Output:
10
Test Case 2
• Input:
• 12
• 4
• AB10
• Output:
18876
• 17
• 4
• ABHE
• Output:
INVALID
int main() {
int base;
scanf("%d", &base);
char newLine;
scanf("%c", &newLine);
int numDigits;
scanf("%d", &numDigits);
scanf("%c", &newLine);
int power = 1;
int ans = 0;
char maxNumAllowed;
else
maxNumAllowed = 'A' + (base - 11);
char currDig;
int isInvalid = 0;
scanf("%c", &currDig);
// currDig is a number
isInvalid = 1;
break;
} else {
// currDig is a character
isInvalid = 1;
break;
} else {
isInvalid = 1;
break;
if (isInvalid)
printf("INVALID");
else
printf("%d", ans);
return 0;
Count Operators
Given two integers A and B. Your task is to convert A to B. You are allow to double the value
(multiply by 2) or half it (integer division by 2). These operations can be performed any number of
times.
The program should print the minimum number of multiplication and integer division required to
convert A to B.
Constraint:
1. The integer B is always in power of 2, i.e 2^n where n can be 0,1,2,3,4,....
2. Refrain from using floating point variables for storing A, B and number of operations.
Input:
• Each test case contains two space separated integer. (The program should handle long
integer too)
Output:
• The program should print the minimum number of operations required for each operator
separated by space to convert initial value into final value for each test case.
• If number of operations for both multiplication and integer division are 0. Print No
operation required.
Visible TestCases:
No operation required.
Output:
2 0
Output:
4 1
• Explanation: TEST CASE1: Initial value and final value are same. No operation required.
TEST CASE2: Multiplying 4 two times by 2 gives 16, i.e., 4 * 2 = 8, 8 * 2= 16. No need to
half the value.
TEST CASE3: Division of 5 once gives 2. Multiply 2 four times by 2 gives 32.
#include <stdio.h>
int main(void) {
initial_value = initial_value / 2;
num_div++;
num_mul++;
} else {
return 0;
Problem Description
You are given a passage. There are mistakes regarding which words should begin with capital
letters in the passage. For instance, in the following passage, the first letter of the second
sentence begins with a lowercase letter: "This course is Fundamentals of Computing. we hope
you enjoy it!" You have to write to a program to take a passage as input and print the corrected
version, with the following rule:
1. The first letter of each sentence in the corrected version begins with a capital letter.
1. The first letter of each sentence will always begin with either a lowercase or uppercase
letter.
2. Each sentence can end with either of the following 3 punctuation marks: '.', '?', '!'.
3. There is a whitespace character after each sentence, except the last one.
Constraints
• You are not allowed to use strings, arrays, or array indexing to solve this problem, you
can only scan the input character by character. You are not allowed to use any string
library functions for checking if a character is lowercase or uppercase.
Input:
• The first line contains an integer specifying the number of the sentence in the input.
• The second line contains the passage. Note that there are new newline characters in the
passage.
Output:
• Your program should print the correct version of the passage according to the rules
specified above.
• 2
• Output:
• Explanation: The above input already obeys the rule we had, hence the output is the
same as the input.
Test Case 2
• Input:
• 2
• Output:
• Explanation: As mentioned in the rules the first letter of each sentence should begin with
an uppercase letter. Hence, "the" should be transformed to the "The".
#include <stdio.h>
int main() {
int numSentences;
scanf("%d", &numSentences);
char newLine;
scanf("%c", &newLine);
while (numSentences) {
char currChar;
scanf("%c", &currChar);
printf("%c", capitalChar);
} else {
printf("%c", currChar);
scanf("%c", &currChar);
printf("%c", currChar);
scanf("%c", &currChar);
printf("%c", currChar);
// ingest and print the space at the beginning of the next sentence,
if (numSentences > 1) {
scanf("%c", &currChar);
printf("%c", currChar);
numSentences--;
return 0;
}
Secret Message
Sherlock Holmes has to send a letter to Dr. Watson providing him the address of a thief in hiding.
To stop the thief's friends from intercepting the message, they decide to use a special cipher to
encode the message that requires a key to decode it. The key is a positive integer. The message
is a sentence composed only of uppercase (A-Z) and lowercase (a-z) letters, along with spaces
separating the words. The encoding is described below.
Suppose k is the key for the cipher. Then, shift the first letter in the message by k letters, the
second letter by k+1 letters, the third letter by k+2 letters, and so on. The white spaces in the
sentence are not changed and should be printed as it is, and ignored while incrementing the key.
Moreover, the case (upper or lower) of each letter remains the same.
Consider the encoding to cycle. So shifting one letter beyond Z will take it back to A, and z to a.
Consider the following example. Suppose key is 2 and the message is HappY Boy.
Input Format
The input contains a single line. The line first has an integer giving the key k. This is followed by
a single space. Then a sentence of uppercase/lowercase letters follows with words separated by
a single space. The final character is ? which marks the end of the input.
1. Ignore the first space after the key. The sentence will start with a letter.
2. The sentence will have no trailing spaces.
3. DO NOT print the final ? in the output. It is only to mark the end of the input sentence.
Output Format
Print the encoded message. Do not print any leading/trailing white spaces or new lines.
• Output:
JdtuE Iwh
Sample Case 2
• Input:
• 5 aaaaaaaa?
• Output:
fghijklm
#include <stdio.h>
int main() {
int k;
char c;
if (c == ' ') {
printf("%c", c1);
printf("%c", c1);
}
scanf("%c", &c); // Input next letter
Lab 5
Sample Output 1
EJJGH
Explanation 1
Sample Output 2
LL
Explanation 2
#include<stdio.h>
int main(){
int n;
scanf("%d", &n);
char dummy;
scanf("%c", &dummy);
char str[n+1];
scanf("%c", &str[i]);
str[n] = '\0';
int q;
scanf("%d", &q);
while(q){
q = q-1;
int l, r;
if((str[i]-'A')>run_max){
run_max = str[i]-'A';
printf("%c", ('A'+run_max));
return 0;
Sticky Note
[50 Points] ---------------------------------------------------------------------- Automated Grading Scheme:
Public Test Cases (2 point each. 2*2= 4 points) Hidden Test Cases (46 points) Test Cases
number 1 to 2 are of 2 marks each. Test Cases number 3 to 6 are of 5 marks each. Test Case
number 7 is of 6 marks. Test Cases 8 and 9 are of 10 marks each.
Manual Grading Scheme Note: Any form of hard-coding will lead to zero marks. Eg: printf("0");
----------------------------------------------------------------------
You are a professional typist. One morning as you were finishing typing out a document, you
notice a sticky note at the back of the document which states "Could you please replace all the
occurences of alternating sequence of characters c1 and c2 with length greater than 1 in the
document with a sentence s_new?"
Apart from being skilled in typing, you are also a skilled programmer. So to avoid the hassle of
editing the document you decide to create a program for it. Suppose, you break the task into the
following points for better understanding.
Input:
The input will be across 5 lines. The first line contains the original sentence S. The second line
contains the character c1 and the third line contains the character c2. The fourth line contains an
integer denoting the length of the string s_new. The last line contains the sentence s_new.
You can assume that the length of S is <= 600 and the length of s_new is <= 50.
Output Format
The final sentence S' after replacing all the occurrences of an alternating sequence of characters
c1 and c2 in S with a sentence s_new.
Example Input
I did take a ride in Trinidad alongside Picadili Idaho
i
d
3
esc
Example Output
I esc take a resce in Trinescad alongsesce Picaescli Idaho
Brief Explanation
All the substitutions are marked in bold for clarity.
I esc take a resce in Trinescad alongsesce Picaescli Idaho
#include <stdbool.h>
#include <stdio.h>
int main() {
char str[20000];
char c;
scanf("%c", &c);
if (c == '\n')
break;
str[i] = c;
char c1;
scanf("\n%c", &c1);
char c2;
scanf("\n%c", &c2);
int s_n_len;
scanf("%d", &s_n_len);
char dummy;
scanf("%c", &dummy);
char subs1[s_n_len];
char c;
scanf("%c", &c);
subs1[i] = c;
int i = -1;
int length_str = 0;
length_str++;
int val;
int seq_len = 0;
int i2 = i;
val = -1;
if (str[i2] == c1)
flagA = false;
else
flagB = false;
i2++;
seq_len++;
if (seq_len > 1)
val = i2 - 1;
else
val = -1;
if (val >= 0) {
start = i;
end = val;
int i3 = -1;
char temp[20000];
do {
i3++;
temp[i3] = str[i3];
int j = start;
str[j++] = subs1[i3];
}
for (i3 = end + 1; i3 <= len; i3++) {
str[j++] = temp[i3];
i = start + s_n_len;
length_str = 0;
length_str++;
printf("%s", str);
return 0;
#include <stdio.h>
int r;
r = a%b;
a=b;
b=r;
return a;
int main() {
int lcm_array[(22*21)/2]; // array to store all pairwise lcms : Max_size = nC2, where n = 22
char time[9],c;
int total_time = 0;
scanf("%d\n",&n);
for(int i=0;i<8;i++){
scanf("%c",&c);
time[i]=c;
time[8]='\0';
// printf("%d\n",total_time);
scanf("%d",&array[i]);
// two players will meet again at starting point after every LCM of their times
for(i=0;i<n;i++){
for(int j=i+1;j<n;j++){
lcm_array[idx]=LCM(array[i],array[j]);
idx = idx + 1;
for(i=0;i<idx;i++){
ans1 += (total_time/lcm_array[i]);
// All of the teammates will meet together after every LCM second
ans2 = -1;
lcm_all = LCM(array[0],array[1]);
for(i=2;i<n;i++){
lcm_all = LCM(lcm_all,array[i]);
ans2 = 0;
lcm_all = -1;
break;
// printf("%d",lcm_all);
if(lcm_all !=-1){
ans2 = total_time/lcm_all;
printf("%d\n",ans1);
printf("%d",ans2);
return 0;
2 4 6 10 16 18 10 16 18 11 10 16 18 10 16 18 11 10 16 18
11 3 3 2 3 0 11 18 16 10 11 18 11 11 18 16 10 11 18 11
2 1 3 0 1 0 10 16 18 11 10 16 10 10 16 18 11 10 16 10
3 16 18 11 16 18 11
3 1 1 14 0 0 14 14
#include <stdio.h>
int main() {
int n, q;
int a[n];
while (q--) {
int l, r;
if (l == r) {
//Do Nothing
} else {
int x = a[l], y;
if ((r - l) % 2 == 1) {
y = a[r];
} else {
y = a[r - 1];
int i;
for (i = l; i + 2 <= r; i = i+2) {
a[i] = x;
int st = r;
if ((r - l) % 2 == 0)
st--;
a[i] = y;
printf("%d", a[i]);
if(i != n-1)
printf(" ");
else if(q)
printf("\n");
Lab 6
Birthday Present
Alice and Bob are invited to their friend Charlie’s birthday party. Charlie is a mathematics
enthusiast and really likes numbers, but in an orderly fashion. Alice has an array of N numbers in
an increasing order. Bob has an array of M numbers in an increasing order. Alice and Bob wish to
combine their presents and give Charlie an array of N+Mnumbers in an increasing order. You
need to output the final present given to Charlie.
Input Format:
The first line contains an integer N.
The second line contains Alice’s present (N space separated integers).
The third line contains an integer M.
The fourth line contains Bob’s present (M space separated integers).
Output Format:
Output will contain N+M spaced separated numbers i.e. Charlie's birthday present. All the starting
N+M-1 integers will be followed by a space (' ') and the last integer will be followed by next line
('\n').
5
44 67 78 89 100
41 44 55 63 67 78 89 89 100
4
41 55 63 89
1 5 44 67 78 89 100 4 41 44 55 63 67 78 41 44 55 63 67 78
41 55 63 89 89 89 100 89 89 100
3 8 0 0 5 9 45 101 600 0 0 5 9 23 45 67 88 0 0 5 9 23 45 67
899 8 23 67 88 103 101 103 470 600 899 88 101 103 470 600
470 909 1000 3405 909 1000 3405 899 909 1000 3405
#include <stdio.h>
int main()
int n;
scanf("%d", &n);
int A[n];
scanf("%d", &A[i]);
}
int m;
scanf("%d", &m);
int B[m];
scanf("%d", &B[i]);
//Merging A and B
C[ind] = A[x];
ind++;
x++;
else{
C[ind] = B[y];
ind++;
y++;
}
// Merging left over elemnets
C[ind] = A[x];
ind++;
x++;
C[ind] = B[y];
ind++;
y++;
return 0;
• double get_mean(int *ptr,int n) - The function takes a pointer to the array, calculates
the mean of the array, and returns the mean.
• int *add_array(int *ptr, int n, int x) - The function creates a new array of size
n+1, copies the contents of the original array denoted by ptr to the new array, appends
the value x at the end of the new array (i.e., after copying), and returns the pointer to the
new array. (Hint: Use malloc and free.)
You should not use statically allocated arrays for this question. You should allocate and free
arrays using dynamic memory allocation and use pointers to reference the arrays.
You should not change the given function prototypes.
The main() function is as follows.
int main(){
int *ptr = (int *)malloc(4);
int d;
scanf("%d", &d);
ptr[0]=d;
int n=1;
while(scanf("%d",&d)) {
if (d==-1) {
break;
}
ptr = add_array(ptr,n,d);
n++;
}
printf("%.2lf", get_mean(ptr,n));
return 0;
}
Input Format: The input is an arbitrary number of integers separated by a single space. The
sequence ends with -1. The input code is given in the main function snippet.
Output Format: The output is the mean. The output is rounded to two decimal places. The
output code is given in the main function snippet.
Example
Input: 1 2 3 4 5 -1
Output: 3.00
1 1 2 3 4 5 -1 3.00 3.00
2 0 0 0 0 -1 0.00 0.00
3 0 -2 -4 -6 -8 -1 -4.00 -4.00
#include<stdio.h>
#include<stdlib.h>
for(int i=0;i<n;i++){
s+=ptr[i];
return s/n;
for(int i=0;i<n;i++){
ptr2[i]=ptr[i];
ptr2[n]=x;
return ptr2;
int main(){
int d;
scanf("%d", &d);
ptr[0]=d;
int n=1;
while(scanf("%d",&d)){
if (d==-1) break;
ptr=add_array(ptr,n,d);
n++;
}
printf("%.2lf", get_mean(ptr,n));
return 0;
1. void reverse(char* substr, int len) - Reverse substr of length len. Eg: "abc" ?
"cba"
2. void cyclicShift(char* substr, int len) - Shift substring cyclically towards the right
by 2 places. Eg: "abcde" ? "deabc".
3. void swapCase(char* substr, int len) - Swap the cases of all alphabets in substr. Eg:
"Ab2" ? "aB2".
You should not change the given function prototypes. You may write other helper functions if
necessary.
Execute all the q transformations on the respective segments of str by calling the concerned
functions with the correct parameters. Print the final string obtained after all the queries have
been executed.
You should not use statically allocated arrays for this question. You should allocate and free
space for the string using dynamic memory allocation and use pointers to reference it. Do not
use array subscripting in your program. Using string library functions is also prohibited.
Input Format:
The first line is the input string str (newline is not part of the string). The second line specifies
the number of queries q. The next q lines are triplets (type, start, end), representing the
transformations you have to carry out in order.
Output Format:
The final string after applying all the queries.
Example
Input:
AbcDEFghiJ
3
1 1 4
3 0 9
2 3 7
Output:
aedGHCBfIj
Explanation:
Query 1: AbcDEFghiJ ? AEDcbFghiJ
Query 2: AEDcbFghiJ ? aedCBfGHIj
Query 3: aedCBfGHIj ? aedGHCBfIj
#include<stdio.h>
#include<stdlib.h>
char t ;
t = *b;
*b = *a;
*a = t;
swap(s, e);
if(n == 1) return;
swap(s + i, s + i + 1);
}
*(s + i) = c;
int main() {
int n = 0, q = 0;
for(;;) {
char c;
scanf("%c", &c);
*(str + (n++)) = c;
scanf("%d", &q);
int t, s, e;
case 1:
reverse(str + s, e - s + 1);
break;
case 2:
cyclicShift(str + s, e - s + 1);
break;
case 3:
swapCase(str + s, e - s + 1);
break;
printf("%s", str);
return 0;
Lab 7
Balanced String
[100 Points] ---------------------------------------------------------------------- Grading Scheme: Visible
Testcase: Testcase 1st and 2nd are of 5 marks each, and Testcase 3rd of 10 marks Hidden
Testcase: 20 marks each Note: Give 0 marks for test-case component if there is any form of
hard-coding. Eg: printf("0"); Using future concepts will deduct 20% marks Using other header
files except stdio.h will lead to penalize 20% marks Write code recursively, otherwise, 0 marks
will be given.
lexicographic order
A string S is lexicographic smaller than another string T, such that for smallest i where S[i] !=
T[i] condition S[i] < T[i] must hold. where S[i] denotes the i-th character of S, and T[i]
denotes the i-th character of T. Here, lengths of S and T are equal.
Note : '(' < ')' < '{' < '}' for lexicographic order.
Problem Statement
You have to generate all balanced string of parenthesis & curly braces of length 2n + 2m in
lexicographic order.
Input Format
The first line contains two whole numbers n and m.
Output Format
Print all the balanced strings of length 2n + 2m in lexicographic order. Note: Don't forget to print
newline character after last string.
Example Input1
3 0
Example Output1
((()))
(()())
(())()
()(())
()()()
Example Input2
1 1
Example Output2
1 1
(){}
({})
{()}
{}()
#include <stdio.h>
void balancedParenthesis(int n, int m, int lp, int rp, int lc, int rc, int len, char s[]) {
if (len == 2 * n + 2 * m) {
printf("%s\n", s);
return;
int p = 0, c = 0;
/*
*/
if (s[idx] == ')')
p -= 1;
c -= 1;
p += 1;
c += 1;
if (p > 0 || c > 0) {
break;
idx--;
if (lp < n) {
s[len] = '(';
s[len] = ')';
if (lc < m) {
s[len] = '{';
s[len] = '}';
int main() {
int n, m;
balancedParenthesis(n, m, 0, 0, 0, 0, 0, s);
return 0;
Demanding List
[100 Points] ---------------------------------------------------------------------- Grading Scheme: Visible
Testcase : 5 marks each Hidden Testcases : 45 marks each Note: Give 0 marks for test-case
component if there is any form of hard-coding. Eg: printf("0"); Using future concept will deduct
20% marks Using other header files except stdio.h will lead to penalize 20% marks Write code
recursively, otherwise, 0 marks will be given.
Subsequence of an array
A subsequence of an array is an ordered subset of the array's elements having the same
sequential ordering as the original array. It can be obtained by deleting one or more elements
form the array, while preserving the order of the remaining elements.
Example : For the array {1,2,3,4,5,6,7} we have valid subsequences as {1}, {2}, {1,2},
{1,4}, {2,3,6}, {1,2,5,7}. Some invalid subsequences would be {2,1}, {4,1,6},
{2,1,3,6,7}.
Problem Statement
We define a special sum of a sequence [a[0], a[1], .... a[n-1]] as 1*a[0] + 2*a[1] + ....
+ n*a[n-1].
Given an integer n, an array a of n elements, and an integer sum, print "YES" (without quotes) if
the array has a subsequence with special sum equal to sum. Else print "NO" (without quotes).
You will be given t testcases per input. Print the answer for each testcase in a separate line.
Make sure there are no unnecessary whitespaces.
Input Format
The first line contains an integer t, denoting the number of testcases. 3t lines follow, 3 lines for
each input.
The first line of each input contains an integer n, denoting the number of elements in the array.
The second line contains n space-separated integers, denoting the elements of array a.
The third line contains a single integer sum, denoting the target sum.
Output Format
For each testcase, print either "YES" or "NO" (without quotes).
Example Input
2
5
2 3 5 8 11
19
6
1 4 5 12 4 6
7
Example Output
YES
NO
Explanation
For the first testcase, we see that {3,8} is a valid subsequence since 1*3 + 2*8 =
19
For the second testcase, there does not exist any subsequence whose special sum is
7
#include <stdio.h>
if (sm == 0)
return 1;
if (id == n)
return 0;
if (solve(a, n, sm, id + 1, c) == 1)
return 1;
sm -= (c * a[id]);
return solve(a, n, sm, id + 1, c + 1);
int main() {
int t;
scanf("%d", &t);
while (t--) {
int n;
scanf("%d", &n);
int a[n];
scanf("%d", &a[i]);
int sm;
scanf("%d", &sm);
if (ans == 1)
printf("YES");
else
printf("NO");
if (t > 0)
printf("\n");
return 0;
Division of Stones
[100 Points] ---------------------------------------------------------------------- Grading Scheme: For visible
Testcases: 5 marks each For hidden Testcases: testcase2 of 15 marks and remaining all
Testcases of 10 marks Note: Give 0 marks for test-case component if there is any form of hard-
coding. Eg: printf("0"); Using future concepts will deduct 20% marks Using other header files
except stdio.h will lead to penalize 20% marks Write code recursively, otherwise, 0 marks will
be given.
Problem
John loves playing games and solving tough mathematical problems. Knowing this, his brother
Rick decided to give him the following riddle to solve.
You are given N stones and a number K. Your task involves making a division of the N stones into
heaps of stones such that is satisfies the following properties:
• The sum of the number of stones in all heaps must equal N, i.e., no stone can be left
unused.
• Each heap must have at least K stones in it.
10 = 3 + 3 + 4
= 3 + 7
= 4 + 6
= 5 + 5
= 10
Constraints
It is guaranteed that at least 1 division will be possible for each input. Also, N >= K >=1
Input Format
The 1st line contains two space separated integers N and K.
Output Format:
On a single line, print the number of possible partitions.
1 10 3 5 5
2 7 4 1 1
3 15 2 41 41
4 1 1 1 1
5 100 100 1 1
#include <stdio.h>
if (n == 0){
(*ctr)++;
findDivisions(j, n - j, ctr);
int main(){
int n, k;
int ctr = 0;
findDivisions(k, n, &ctr);
printf("%d", ctr);
return 0;
Lab 8
Maximum Fencing Sum
A farmer has a plot in the form of an n*m matrix (n rows, m columns). He has to create a square
fenced area within the plot. Every cell of the matrix has been assigned an integer value
representing the ease with which one can put a fence-post in that cell. This integer can be either
positive or negative. You are tasked with finding the largest square within the matrix such that the
sum of the integers on the cells along its perimeter is maximized.
NOTE: A single cell is not considered a square, i.e., the side length of the mentioned squares
must be at least 2.
Constraints
• 3 <= n,m <= 50
Input Format
• The first line contains 2 integers n and m.
• The next n lines each contain m space-separated integers. Each line gives a row of the
matrix.
Output Format
Output two space-separated integers s l, where s is the maximum sum of values along the
perimeter of the square within the matrix, and l is the side length of the square. In case the same
sum occurs for different length squares, then print the l for the largest such square.
For example, consider the following matrix. The green-highlighted square of side length 3 has the
highest sum on its perimeter (8). So the output for this case will be 8 3.
Sample Testcase
Input:
4 4
1 1 1 -1
1 -1 1 -1
1 1 1 -1
-1 -1 -1 -1
Output:
8 3
2 4 3 3 -1 3 -1 3 -1 3 -1 3 -1 3 -1 8 3 8 3
3 5 5 -5 -5 -5 -5 -5 -5 2 2 2 -5 -5 2 10 2 -5 -5 2 2 16 16
2 -5 -5 -5 -5 -5 -5 3 3
#include <stdio.h>
int main(){
int n,m;
int a[n][m];
int mx;
if(n>m) mx = n;
else mx = m;
int maxlen = 0;
scanf("%d", &a[i][j]);
int sum;
for(int len=2; len<=mx; len++){
sum = 0;
sum += a[i][y];
sum += a[i][y+len-1];
sum += a[x][j];
sum += a[x+len-1][j];
sum -= a[x][y];
sum -= a[x][y+len-1];
sum -= a[x+len-1][y];
sum -= a[x+len-1][y+len-1];
maxsum = sum;
maxlen = len;
}
}
return 0;
Pacman
The objective of Pacman is to start from a starting point and reach a destination while collecting
the maximum rewards along the way. The possible paths can be seen as a 2D grid, which will be
given as a matrix. The entries of the matrix correspond to possible cells where Pacman can
reach.
These entries of the matrix contain some numbers. -1 correspond to the cells Pacman can not
reach. These are blocked cells and the walk can not go through them. Other entries which are
the possible cells, contain some non-negative numbers corresponding to the value of reward
given to each cell. Pacman gets this reward when it lands on the corresponding cell. Your task is
to output the maximum possible value of reward that can be obtained in reaching from the point
corresponding to (0, 0) to (n-1, n-1).
The input is given as an n×n matrix containing integers. Pacman can not land on cells containing
-1, while it gets reward v if it lands on a cell containing v. The rewards along the path are added,
including the start and the destination. The top left entry of the matrix is the starting position (0,
0), while the bottom left entry is the destination (n-1, n-1). At one step, Pacman can go either
down or right, i.e. from the entry (i, j) it can either go to (i+1, j) or (i, j+1). However, it can
not go beyond the boundaries of the grid. You have to output the maximum possible reward.
Constraints:
Input:
• First line contains n, the size of the matrix.
• Next n lines contain n space separated numbers each, where each entry corresponds to
a value of a reward v, or forbidden cell-1.
Output:
• Print a single number which corresponds to the maximum value over any walks.
Sample TestCase:
Input
3
0 0 5
3 -1 -1
1 0 0
Output:
Explanation:
Pacman starts from the left top cell (0, 0). It can either go right to (1, 0) or down to (0, 1),
obtaining reward 0 in each case. The path going right ends at (2, 0) which has value 5, but
Pacman can not go down (because of -1 at (2, 1)) nor right (because the grid ends). Thus it can
only go down to (1, 0) obtaining reward 3, and then again down to (2, 0) since right was not a
possible move, obtaining a total reward of 3+1=4. Then it can only go right twice to reach (2, 2).
The output is thus the total value of reward, which is 4.
#include <stdio.h>
if(a>b){
return a;
else return b;
return -1;
else{
return -1;
int main() {
int n;
int A[n+n*n];
return 0;
}
Neighboring-elements
[70 Points] ---------------------------------------------------------------------- Automated Grading Scheme:
Manually Grading Scheme: Note: Give 0 marks for test-case component if there is any form of
hard-coding. Eg: printf("0"); Penalty : -20% each for using any library other than stdio.h, stdlib.h,
limits.h -20% for using any built-in function -50% for using single pointer or 1 dimensional array -
50% for static allocation of matrix, example int mat[100][100] or similar declaration -------------------
---------------------------------------------------
Problem Description
Given a square matrix M of size N. Calculate the sum of all neighboring elements of each diagonal
element (up, down, left, right, and 4 diagonal elements -- a total of 8 elements). The neighboring
elements for diagonal elements M[0][0] and M[N-1][N-1] is 3. Print these values corresponding
to each diagonal element. Also print the index of that diagonal element whose corresponding
sum is highest.(Row and Column index are same for a diagonal element in square matrix)
Constraint:
Input:
• First line in each test case will contain the size of square matrix N.
• The remaining N lines contains the elements of each row in the matrix.
Output:
Sample TestCase
Input
3
8 2 3
2 3 4
4 5 6
Output:
8: 7
3: 34
6: 12
index: 1
Explanation:
The first N lines print sum of all neighboring element for each diagonal element. The sum of
neighboring elements is maximum for M[1][1] i.e., diagonal element 3 hence index will be 1.
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
scanf("%d", &N);
}
for (int i = 0; i < N; i++) {
scanf("%d", &mat[i][j]);
// single pointer
// sumArr[i] =
// mat[(i-1)*N+(i-1)]+mat[(i-1)*N+i]+mat[(i-1)*N+(i+1)]+mat[i*N+(i-
1)]+mat[i*N+(i+1)]+mat[(i+1)*N+(i-1)]+mat[(i+1)*N+i]+mat[(i+1)*N+(i+1)];
if (N > 1) {
index = 0;
highest_sum = sumArr[0];
index = i;
highest_sum = sumArr[i];
index = N - 1;
}
} else {
sumArr[0] = mat[0][0];
index = 0;
highest_sum = mat[0][0];
free(sumArr);
free(mat);
return 0;
Lab 9
Find-Ranks
[15 Points] ---------------------------------------------------------------------- Automated Grading Scheme:
Public Test Cases (0.5 point each. 0.5*2 = 1 points) Hidden Test Cases (2 point each. 2*7 =
14 points)
Manual Grading Scheme Note: Any form of hard-coding will lead to zero marks. Eg: printf("0");
Penalty: Award 0 points if struct is not used. Header files Allowed: stdio.h ----------------------------
------------------------------------------
You are given N points in 2-d plane. It is also given that x and y co-ordinate of each point is
positive i.e, all the points lie in the first quadrant. You need to find rank of each point. Rank of a
point is defined as the number of points that are dominated by this point. Point A dominates
another point B if point B lies on or inside the rectangle drawn such that the upper-right corner is
the point A and the bottom-left corner is the origin.
NOTE:
1. It is MANDATORY to use struct for storing the points otherwise you will be awarded
ZERO points.
2. Output the ranks in the order as given in the input, in single line separated by space.
Input Format:
The first line contains an integer N denoting the total number of points. This is followed by N lines
each containing 2 integers denoting x and y coordinates of point respectively.
Ouput Format:
Print N space separated integers denoting the rank of each point (Do not print trailing spaces).
Sample Input:
3
11
22
33
Sample Output
012
Explanation
According to the definition point (1, 1) does not dominate any point so rank = 0.
Point (2, 2) dominates point (1, 1) thus rank = 1.
Point (3, 3) dominates point (1, 1) and (2, 2) thus rank = 2.
1 4 1 1 2 2 3 3 4 4 0 1 2 3 0 1 2 3
2 4 1 1 2 2 1 2 2 1 0 3 1 1 0 3 1 1
3 5 7 63 53 55 10 4 16 46 65 58 0 2 0 1 3 0 2 0 1 3
#include<stdio.h>
struct Point{
int x;
int y;
};
int rank = 0;
if(i != index && p[i].x <= p[index].x && p[i].y <= p[index].y)
rank = rank+1;
return rank;
int main(){
int n;
scanf("%d", &n);
if(i != n-1)
printf(" ");
return 0;
Fruit Mart
[15 Points] ---------------------------------------------------------------------- Automated Grading Scheme:
Public Test Cases (0.5 point each. 0.5*2 = 1 points) Hidden Test Cases (2 point each. 2*7 =
14 points)
Manual Grading Scheme Note: Any form of hard-coding will lead to zero marks. Eg: printf("0");
Penalty: Award 0 points if struct is not used for storing the information of the shopkeepers.
Header files Allowed: stdio.h ----------------------------------------------------------------------
There are n shopkeepers (indexed from 1 to n) who sell apples, bananas, mangoes and oranges
at their shops. Each shopkeeper has a fixed quantity of all these fruits and sells them at his own
price (per kg). Alice wants to buy some fruits for herself and obviously, she will choose the
shopkeeper who can fulfil her demands at the least cost possible. Find the shopkeeper from
which she will buy and the amount she will pay for her purchase.
Input
The first line of the input contains a positive integer n
Each of the next n lines contain 8 non-negative integers.
Let us say, the numbers on ith such line are a A b B m M o O.
Here,
a = quantity of apples that the ith shopkeeper has.
A = price charged by the ith shopkeeper for 1 kg of apples.
b = quantity of bananas that the ith shopkeeper has.
B = price charged by the ith shopkeeper for 1 kg of bananas.
m = quantity of mangoes that the ith shopkeeper has.
M = price charged by the ith shopkeeper for 1 kg of mangoes.
o = quantity of oranges that the ith shopkeeper has.
O = price charged by the ith shopkeeper for 1 kg of oranges.
Output
Print on a single line (space separated) the index number of the shopkeeper from whom Alice
buys the fruits (if there are multiple such shopkeepers, print the least index) and the amount she
pays for her purchase. Print -1 if no shopkeeper is able to fulfil her demands.
Note:
Solutions that do not use structs will be awarded ZERO points.
It is MANDATORY to use struct for storing the information of the shopkeepers.
Examples:
Input 1
1
10 10 20 20 30 30 40 40
5 10 15 20
Output 1
1 1500
Explanation 1
There is only 1 shopkeeper (index 1) and he can fulfil Alice's demands. Alice will have to pay him
a total of 5*10 + 10*20 + 15*30 + 20*40 = 1500
Input 2
2
1 2 1 4 1 8 1 16
4 10 3 10 2 10 1 10
1 2 3 4
Output 2
-1
Explanation 2
It is clear that none of the two shopkeepers can fulfil Alice's demands, hence the output is -1.
Hidden Test Cases:
In hidden.txt
Grading Scheme: 2*0.5 + 7*2 = 15
2 2 1 2 1 4 1 8 1 16 4 10 3 10 2 10 1 10 1 2 3 4 -1 -1
3 6 49 73 58 30 72 44 78 23 9 40 65 92 42 87 3 27 3 3
29 40 12 3 69 9 57 60 33 99 78 16 35 97 26 12 2120 2120
67 10 33 79 49 79 21 67 72 93 36 85 45 28 91 94
29 1 53 8
#include<stdio.h>
struct shop{
int a;
int A;
int b;
int B;
int m;
int M;
int o;
int O;
};
int main(){
int n;
scanf("%d", &n);
int x, y, z, w;
if(cost==-1){
index = i+1;
continue;
index = i+1;
if(cost == -1){
printf("%d", cost);
else{
return 0;
Example Input
9
11
12
13
21
22
23
31
32
33
Example Output
4
Explaination the points (1,1) (1,3) (3,1) (3,3) form a rectangle of area 4.
3 5 3 4 3 5 2 6 8 4 8 5 5 5
4 5 3 4 3 5 2 6 8 4 5 5 -1 -1
#include <stdio.h>
int N;
struct point {
int x, y;
};
return a < b ? a : b;
return a > b ? a : b;
return 1;
return 0;
int main()
scanf("%d", &N);
struct point a, b, c, d;
/*if(area == MAX_VAL){
area = -1;
}*/
printf("%d\n", area);
Quiz 1 sec c
Divisor-Game
Automated Grading Scheme:
Manually Grading Scheme: Note: Give 0 marks for test-case component if there is any form of
hard-coding. Eg: printf("0"); Penalty : -20% for using any future concepts -20% each for using
any library function (string library) other than printf and scanf. So getline(), gets(), fgets(), etc. are
not allowed at all. -20% each for using any library other than stdio.h --------------------------------------
------------------------------------------------------------------------
Divisor-Game
You are given a character array of N characters where each character belongs to either [A-Z] or
[a-z].
You need to perform the following operation for all possible non-empty subarrays of array.
1. Find the number of subarrays in which the characters are arranged in increasing order of
ASCII values.
2. Print the largest subarray in which the characters are arranged in increasing order of
ASCII values.
Note: If two subarrays have the same length then the subarray which starts first will be selected.
For example, in array "ABCABD", though "ABC" and "ABD" are of same length, "ABC" will be
printed as it starts first.
Input Format:
The first line contains an integer N denoting the size of the array. The next line contains N
characters without space denoting the elements of the array.
Ouput Format:
Print the number of sub arrays according to property 1 in first line and largest subarray in second
line.
Sample Input:
3
abc
Sample Output
6
abc
Explanation
Our sub-arrays are: [a], [b], [c], [ab], [bc], [abc]
All subarrays are in increasing order of ASCII value. The largest subarray is abc.
2 3 CBA 3 C 3 C
#include <stdio.h>
int main(){
int n;
scanf("%d", &n);
char a[n+1];
scanf("%s", a);
int ans = 0;
int val = 0;
int len=0,x=-1,y=-1;
for(int i=0;i<n;i++){
val= 1;
for(int k=i+1;k<n;k++){
if (a[k]<=a[k-1]) break;
val++;
ans+=val;
if(val>len){
len=val;
x=i;
y=i+val-1;
char b[len+1];
b[i-x]=a[i];
b[len]='\0';
printf("%d\n%s", ans,b);
return 0;
}
Uppercase String
Automated Grading Scheme:
Manually Grading Scheme: Note: Give 0 marks for test-case component if there is any form of
hard-coding. Eg: printf("0"); Penalty : -20% for using any future concepts -20% each for using
any library function (string library) other than printf and scanf. So getline(), gets(), fgets(), etc. are
not allowed at all. -20% each for using any library other than stdio.h Important Note If '\0' (null
character) is not appended to end of string, the output might contain garbage value across
multiple run. Try executing solution multiple times to see if no garbage value is printed as output.
---------------------------------------------------------------------
Given a character array S. The maximum length of array is 100. The words in the string are
separated by a single whitespace. The end of string is marked by newline character(\n). Print
the string after converting each alphabet in alternate word of string to UPPERCASE.
Constraint:
• The digit and special characters in the character array remain unchanged.
• Make sure, the output string does not contain garbage values.
Input:
• Each test case comprise of single line of input.
• The only line in each test case will contain the character string.
• The string will consist of uppercase, lowercase alphabets, digits and special character(@
, \ ? !) .
Output:
• The output will contains the modified string followed by a newline.
Sample TestCase :
Input
Output:
Explanation:
The first and third word of the string are converted to uppercase. The special characters, second
and fourth word of the string remains unmodified.
Sample TestCase :
Input
Hi, I AM Here.
Output:
HI, I AM Here.
Explanation:
The first word of the string is converted to uppercase. The third word was already in uppercase.
The special characters, second and fourth word of the string remains unmodified. The uppercase
alphabet in second and third word remains unchanged.
#include <stdio.h>
int main() {
char str[100];
char curr;
int word_count = 0;
scanf("%c", &curr);
str[str_length] = curr;
str_length += 1;
scanf("%c", &curr);
str[str_length] = '\0';
word_count++;
continue;
printf("%s", str);
printf("\n");
return 0;
Quiz 1 sec d
Ouput Format:
Print two lines. First line should contain k and the second line should contain k space separated
integers.
Sample Input:
2
31 43
31 43
Sample Output
1
0
Explanation
The original and encrypted messages are same. The smallest possible key is of length 1. So the
secret key is [0]. Note that [0 0] is also a secret key here but we need to output the key of
smallest length.
Sample Input:
4
1156
2368
Sample Output
2
12
Explanation
Note that there also exists a key of length 4 here but we need to output only smallest length
secret key.
#include <stdio.h>
int main(){
int n;
scanf("%d", &n);
scanf("%d", &orig_msg[i]);
scanf("%d", &enc_msg[i]);
int repeated_key[100];
repeated_key[i] = enc_msg[i]-orig_msg[i];
int key_len = 0;
int possible_flag = 1;
if(repeated_key[i] != repeated_key[i%key_len]){
possible_flag = 0;
break;
if(possible_flag == 1)
break;
printf("%d\n", key_len);
if(i != key_len-1)
printf(" ");
return 0;
Manually Grading Scheme: Note: Give 0 marks for test-case component if there is any form of
hard-coding. Eg: printf("0"); Penalty : -50% for changing template -20% for using any future
concepts -20% for using built in function ---------------------------------------------------------------------------
------
You are given an integer n. Consider the binary expansion of n denoted by the number s, i.e., s
represents a number in base 2. Let N denote the decimal equivalent of the same string in the
decimal system. Find the smallest prime number which is just greater than or equal to N.
For example, if n = 7, the binary expansion of n is 1112 where s = 111. Now, the decimal number
represented by s is N = 111, which is "one hundred and eleven". The prime just larger than or
equal to 111 will be 113, which is the correct output.
Note:
1. Stick to the template provided to define the important functions.
2. You are not allowed to use library functions.
3. You can create other user-defined functions.
4. You are required to define the three functions given in the template. Do not change the
names of the functions of the template.
Input Format:
The first line contains an integer n.
Constraints:
1. 2 <= n <= 50
Output Format:
The output should contain an integer n which will give the correct answer.
Sample Input:
5
Sample Output:
101
1 2 11 11
2 11 1013 1013
3 17 10007 10007
#include <stdio.h>
int p = 1;
p *= a;
return p;
int N = 0, idx = 0;
N += (n%2)*(pow(10, idx));
idx++;
n = n/2;
return N;
}
int is_prime(int p){
if(p%j == 0){
return 0;
return 1;
while(!is_prime(N)){
N++;
return N;
int main() {
int n;
scanf("%d", &n);
printf("%d", closest_prime(decimal_to_binary(n)));
return 0;
Lab 10
struct node {
int data;
struct node* next;
};
NOTE
• Use of ARRAYS IS NOT PERMITTED. You will get marks if you use linked lists to solve
the problem.
• The template contains initial code for list manipulation. You can modify it or use it as it is.
DO NOT change the print function.
• No marks if you do not really delete the node. The print function provided must work as-
it-is to print the modified list.
INPUT
The input will consist of two lines containing the numbers. The first line will contain a stream of
numbers. Keep accepting the input until you get a -1. The second line will contain a number nn, n
will fit in an int.
OUTPUT
Display the final linked list, with nthnth last node deleted from the linked list. You must use the
provided print routine. It prints an X at the end to mark the end of the list.
Examples
INPUT
1 2 3 4 5 -1
1
OUTPUT
1234X
#include <stdio.h>
#include <stdlib.h>
struct node {
int data;
};
struct node* insert(struct node* head, int data)
n->next=NULL;
n->data=data;
if(head==NULL)
return n;
while(tmp->next!=NULL)
tmp=tmp->next;
tmp->next=n;
return head;
while(head!=NULL)
printf("%d ",head->data);
head=head->next;
printf("X\n");
return;
{
if(head==NULL)
return head;
int k=1;
while(offset!=NULL)
if(k==n)
break;
offset=offset->next;
k++;
if(offset==NULL)
return head;
while(offset->next!=NULL)
parent=tmp;
tmp=tmp->next;
offset=offset->next;
if(parent==NULL)
head=tmp->next;
return head;
else
{
parent->next=tmp->next;
return head;
int main()
int len = 0;
while(1)
int x;
scanf("%d", &x);
if(x==-1)
break;
len++;
head=insert(head,x);
int n;
scanf("%d", &n);
head = deleteNthLast(head,(n-1)%len+1);
print(head);
return 0;
INPUT:
The input consists of n + 1 lines.The first line contains two integers n and m.The following n lines
each contain a row of matrix A.
OUTPUT:
The output should contains two lines. The first line contains the size of largest submatrix and the
next line contains (rowIdx,colIdx).
CONSTRAINTS:
1 <= n*m <= 100
Example Input
34111111011010
Example Output
2 (1,1)
2 5 8 1 0 1 0 1 0 1 0 1 1 0 1 0 1 0 1 1 1 1 0 2 2
0 0 1 1 0 1 0 1 1 1 1 1 1 0 1 0 0 1 0 1 (3,1) (3,1)
3 4 7 0 1 0 1 1 1 1 0 1 1 1 1 0 1 1 0 0 0 1 1 1 1
1 0 0 0 1 1 0 1 (3,6) (3,6)
#include <stdio.h>
#include <stdlib.h>
return a < b ? a : b;
}
int i, j, isIden = 1;
if(i == j){
if(arr[ox + i][oy + j] != 1)
isIden = 0;
}else{
if(arr[ox + i][oy + j] != 0)
isIden = 0;
return isIden;
int main() {
int n, m, i, j, k, kMax;
if(isIdentity(arr, i, j, k+1)){
size = k + 1;
idx1 = i;
idx2 = j;
if(size)
else
printf("0\n(-1,-1)");
return 0;
}
Reverse Alternate Segments in a Doubly-
Linked List
Given a doubly-linked list (say of n nodes where n > 0) and a positive integer k, rearrange the
links between the nodes of the linked list in the following way. The nodes of the linked list are
divided into segments of k nodes. If k does not divide n, then the final segment is of n % k nodes.
The order of nodes in alternate segments (1st, 3rd, 5th, ...) are to be reversed. An example is
described below.
Initial linked list:
1↔2↔3↔4↔5↔6↔7↔8↔9↔0
Note:
• The nodes in the linked list are of the following structure.
• struct node {
• int data;
• };
Input Format:
The input consists of two lines. The first line is a stream of integers that ends with -1 (not to be
included), representing the linked list. It is guaranteed that the linked list contains at least one
node. The second line is a single positive integer representing k.
Output Format:
The output consists of two lines. The first line is a stream of integers separated by spaces
representing the final linked list after transformation. The second line is also a stream of integers
that represents the same final linked list but in reverse order.
You will only need to call the print() function defined in the template with the pointer to the head
of the final doubly-linked list as an argument. This function prints both lines in the required
format.
Example
Input:
1 2 3 4 5 6 7 8 9 0 -1
3
Output:
3 2 1 4 5 6 9 8 7 0
0 7 8 9 6 5 4 1 2 3
Explanation:
Segment 1: 1 2 3 → 3 2 1
Segment 2: 4 5 6 → 4 5 6
Segment 3: 7 8 9 → 9 8 7
Segment 4: 0 → 0
#include <stdio.h>
#include <stdlib.h>
struct node {
int data;
};
if(head == NULL) {
return;
while(head->next != NULL) {
head = head->next;
printf("%d\n", head->data);
while(head->prev != NULL) {
head = head->prev;
printf("%d", head->data);
return;
n->next = NULL;
n->prev = NULL;
n->data = data;
tmp->next = n;
n->prev = tmp;
int count = 0;
next = curr->next;
curr->next = prev;
prev = curr;
curr = next;
count++;
if(head != NULL) {
head->next = curr;
prev->prev = p;
count = 0;
curr = curr->next;
count++;
return prev;
int main() {
int k, x;
scanf("%d", &x);
head->next = NULL;
head->prev = NULL;
head->data = x;
while(1) {
scanf("%d", &x);
insert(head, x);
scanf("%d", &k);
print(head);
return 0;
Quiz 2 sec c
Unique Elements
[35 Points] ---------------------------------------------------------------------- Automated Grading Scheme:
Manually Grading Scheme: Note: Give 0 marks for test-case component if there is any form of
hard-coding. Eg: printf("0"); Penalty : -20% each for using any library other than stdio.h, stdlib.h,
-20% for using any built-in function other than malloc -50% for static allocation of matrix or array,
example int mat[100][100] or similar declaration -----------------------------------------------------------------
-----
Read a square matrix of size ‘N’. Do the following task: Print all unique elements in the matrix. If
there are no unique elements, print No unique elements.
Input:
Output:
• A single line with unique (non-repetitive) elements in the matrix with space (Take care of
space at the last)
Sample TestCase:
• Input
4
5 1 2 1
4 10 3 5
2 1 4 4
1 2 0 7
• Output:
10 3 0 7
Explanation:
Only elements 10,3,0 and 7 does not repeat in the matrix.
#include <stdio.h>
#include <stdlib.h>
int i = 0, j = 0, k = 0;
int element_count = 0;
unique_arr[1][i * mat_size + j] = 0;
}
}
if (mat[i][j] == unique_arr[0][k]) {
unique_arr[1][k] += 1;
break;
int flag=0;
for (k = 0; (k < mat_size * mat_size && (element_count < mat_size * mat_size)); k++) {
element_count += unique_arr[1][k];
if (unique_arr[1][k] == 1) {
flag=1;
if(flag==0)
int main() {
int N;
int **arr;
int i = 0, j = 0;
scanf("%d", &N);
scanf("%d", &arr[i][j]);
unique_elements(arr, N);
return 0;
Is there a way
[40 Points] ---------------------------------------------------------------------- Automated Grading Scheme:
Manually Grading Scheme: Note: Give 0 marks for test-case component if there is any form of
hard-coding. Eg: printf("0"); Penalty : -20% each for using any library other than stdio.h -25% for
using global variables Note: Use of recursion is must. Otherwise, 0 marks are rewarded. -----
-----------------------------------------------------------------
You are given an N x N grid. You need to find if there exists a path from the cell (x_1, y_1) to
the cell (x_2, y_2).
If you are at (x, y) and the value at this cell of the grid is a then you can either move to (x+a, y)
or to (x, y+a), provided that you stay inside the grid.
Input
First line of the input contains the number N.
On each of the next N, lines there will be N entries where the jth entry on the ith line
cooresponds to the value at the cell (i, j) of the grid. All these entries will be positive.
The next line contains 4 integers, x_1, y_1, x_2 and y_2. All these entries are greater than or
equal to 1 and less than or equal to N.
Output
If there exists a path from (x_1, y_1) to (x_2, y_2) print YES, otherwise print NO.
Note:
The numbering of the cells starts from (1,1) and goes on to (N, N).
Examples:
Input 1
2
1 2
1 100
1 1 2 2
Output 1
YES
Explanation 1
From (1, 1) go to (1 + 1, 1) (as a = 1 for (1, 1)) and from (2, 1) go to (2, 1 + 1) (as a = 1
for (2, 1)).
Input 2
4
3 2 1 4
3 2 1 3
3 2 1 2
3 2 1 1
1 4 4 4
Output 2
NO
Explanation 2
We can move from (1, 4) to (1 + 4, 4) or (1, 4 + 4) and both these points take us out of the
grid, so it is not possible to reach (4, 4) from (1, 4).
#include<stdio.h>
int helper(int n, int grid[][n], int x1, int y1, int x2, int y2){
return 1;
int ans = 0;
next_x = x1;
return 1;
return ans;
int main(){
int n;
scanf("%d", &n);
int grid[n][n];
scanf("%d", &grid[i][j]);
printf("YES");
else{
printf("NO");
return 0;
Sec d quiz 2
Fishes
[35 Points] ---------------------------------------------------------------------- Automated Grading Scheme:
• Visible: 1 marks for 1st testcase and 2 marks each for 2nd and 3rd test cases
• Hidden: 5 each for all hidden test cases
Manually Grading Scheme: Note: Give 0 marks for test-case component if there is any form of
hard-coding. Eg: printf("0"); Penalty : -20% each for using any library other than stdio.h, -25% for
using global varibles -----------------------------------------------------------------------------------------
One day Bob went for fishing in a pond of size N x N with a net of size k x k. The pond is divided
into cells of size 1 x 1. He knows the number of fishes in each cell. To collect fishes, Bob can
throw his net only once. Bob wants to collect as many fishes as possible given the constraint.
Where should Bob throw his net so that he collects maximum number of fishes? You need to
output two integers denoting the row number and column number of the cell which should be the
top left cell of the net where Bob will throw his net to collect maximum number of fishes.
NOTE:
Input Format:
The first line contains two integers N and k separated by space. This is followed by N lines each
containing N integers denoting number of fishes in the correspoding cell.
Constraints:
1. Assume k <= N.
2. N <= 10.
3. Maximum number of fishes in one cell is 1000.
Ouput Format:
Print two integers separated by space denoting the row and column number of the cell.
Sample Input:
32
111
222
333
Sample Output
21
Explanation
Bob can collect maximum 10 fishes using his 2x2 net. There can be 2 possible top-left positions
to get 10 fishes -> (2, 1) and (2, 2). But as mentioned in the Note, you have to output 2 1 as the
answer.
1 2 1 7 7 1 3 1 1 1 1
2 2 1 7 2 7 3 1 1 1 1
3 3 2 7 8 9 2 5 3 3 9 4 1 2 1 2
#include <stdio.h>
int main(){
int n, k;
int fishes[10][10];
scanf("%d", &fishes[i][j]);
int curr_sum = 0;
curr_sum = curr_sum+fishes[row_num+i][col_num+j];
max_sum = curr_sum;
x = row_num;
y = col_num;
return 0;
Welcome Modiji
As you know PM Modi visited IIT Kanpur for convocation and your recently graduated seniors
were getting ready to witness the event. They have been told though that because of the rowdy
crowd and zigzagging queues to get into the Auditorium, it will be extremely hard to walk straight
and reach the venue in time. Thus, you may have to take a few turns along the way to optimize
the time in which you reach the place.
The part of the campus from your hostel to the Auditorium is represented by a 2D square matrix,
where you are initially at (0, 0) and the venue is at (N-1, N-1). Each of the cells (i, j) in between
has some integer points P(i, j) attached to it. P(i, j) indicates how thin the crowd is at that
location, and thus the ease of travel through that cell. You have to reach (N-1, N-1) from (0, 0),
while collecting the maximum number of points. You are only allowed to move down or right, that
is, from (i, j), you can move to (i+1, j) or (i, j+1) only.
Find out the maximum number of points that you collect along the way.
Note: Please don't alter the template given in the
question. Using dynamic memory allocation is a must.
INPUT:
The first line contains an integer N, the dimensions of the 2D array. The next N lines contain N
space separated integers, denoting the array P.
OUTPUT:
One line containing a single integer, the maximum number of points that can be collected along
the way.
EXAMPLE:
Input:
3
123
078
123
Output:
21
Explanation: (0, 0) -> (0, 1) -> (1, 1) -> (1, 2) -> (2, 2) gets you 1 + 2 + 7 + 8 + 3 = 21 points.
1 3 1 2 3 0 7 8 1 2 3 21 21
2 2 5 5 5 5 15 15
3 2 5 5 6 5 16 16
4 3 1 2 3 2 2 2 3 2 1 9 9
#include <stdio.h>
#include <stdlib.h>
return P[nrow][ncol];
if (nrow == N-1) {
if (ncol == N-1) {
int main() {
int N, i, j;
scanf("%d", &N);
// create two dimensional points array
scanf("%d", &P[i][j]);
printf("%d\n", ans);
return 0;
Lab 11
Crossing Bridges
On her adventures across some mysterious lands, Phos comes across a stream blocking her
path. Fortunately, there are a number of makeshift bridges that could help her cross the stream.
Let us consider one such bridge. This bridge consists of n stones arranged in a linear order from
one riverbank to another. Each of these stones have a numeric value associated with them,
which denotes how far you can jump if you are on that stone. For example if a stone has a value
of 5 you can make a leap skipping upto the next 4 stones, landing directly on the fifth, although,
you are allowed to make a shorter jump than that as well. If instead a stone has a value of 0 you
can not move anywhere from that position. Can you help Phos find which bridges will actually
allow her to cross the stream and which won't? (Note: You can assume that you start off standing
on the first stone of the bridge and have crossed the river if you are standing on the final stone of
the bridge)
INPUT:
The input consists of 2b+1 lines. The first line contains a single integer b denoting the number of
bridges. Of the remaining 2b lines, each pair of lines describe a single bridge. The first of these
two lines contains a single integer n, denoting the length of the bridge. The next line contains n
space separated integers denoting the numeric value associated with each stone of the bridge.
OUTPUT:
The output should consist of b lines. For each bridge you have to print YES if the bridge can
actually be crossed and NO otherwise. The output for each bridge must be printed in a separate
line.
CONSTRAINTS:
1 <= b <= 10 1 <= n <= 50
Example Input
2
5
1 1 1 0 1
5
1 1 2 0 1
Example Output
NO
YES
1 2 5 1 1 1 0 1 5 1 1 2 0 1 NO YES NO YES
#include<stdio.h>
void solve(){
int n;
scanf("%d", &n);
int a[n];
for(int i=0;i<n;i++){
scanf("%d", &a[i]);
int curmax = 0;
for(int i=0;i<n;i++){
if(i>curmax){
printf("NO\n");
return;
else{
curmax = i+a[i];
printf("YES\n");
int main() {
int b;
scanf("%d", &b);
while(b--){
solve();
return 0;
Delivery System
[100 Points] ---------------------------------------------------------------------- Automated Grading
Scheme:
Problem Statement
This problem is aimed at giving you a flavor of designing a system.
You are approached by an online delivery shipping firm, which asks you to write them code for
some tasks they face. The products they ship have some attributes, which are as follows:
All strings are of maximum length 100 and contain only alphanumeric characters.
The products arrive one by one, and a common queue is maintained for all of them. Also, there is
a fixed set of manufacturers the company has a tie-up with:
• Nike
• Adidas
• Reebok
• Puma
• Diadora
You are to automate some repetitive tasks. The tasks are as follows:
1) Add a new product to the queue. 2) Deliver the next product of the queue and print the product
information delivered. 3) Query how many products of a given manufacturer is currently present
in the queue. 4) Query how many products of a given manufacturer has been shipped already.
Initially, the product queue is empty. It is also guaranteed that when new products are added, all
information is consistent, i.e., it is a valid product from a valid partner manufacturer.
**It is necessary to maintain the queue as a linked list and there is a penalty for not doing
so.
Input Format
The first line contains an integer n, denoting the number of tasks to be performed. The following n
lines can be of the following types:
Output Format
We are supposed to take the following actions for each type of input from {1,2,3,4,5}
1) Insert the product with the given attributes at the back of the queue. Then print Product_ID
ADDED (Eg. 23 ADDED) 2) If the queue is non empty, remove the product at the front of the
queue and print all 3 attributes of the delivered product in a space separated manner. If queue is
empty, print NOTHING TO DELIVER NOW 3) Print an integer corresponding to the answer (print
-1 if the manufacturer is not a partner manufacturer) 4) Print an integer corresponding to the
answer (print -1 if the manufacturer is not a partner manufacturer)
Note that all outputs are in a new line.
Example Input
6
2
1 23 Bottle Adidas
1 56 Shoes Nike
3 Adidas
2
3 Adidas
Example Output
NOTHING TO DELIVER NOW
23 ADDED
56 ADDED
1
23 Bottle Adidas
0
Explanation
Initially, queue is empty. So nothing to deliver initially.
Then 2 products added.
Query return 1 since we have 1 product of Adidas.
Adidas product delivered, so details are printed.
Query returns 0, since Adidas product has been removed from queue.
#include <stdio.h>
#include <stdlib.h>
struct node
int prod_ID;
char label[100];
char manufacturer[20];
};
int id = 0;
id++;
return 0;
}
int get_manufacturer_ID(char* manufacturer, char* partner_maufacturers[])
for(int i=0;i<5;i++)
return -1;
curr->next = NULL;
else
curr->next = head;
head = curr;
inside_queue[get_manufacturer_ID(curr->manufacturer, partner_manufacturers)]++;
return curr;
struct node* Print(struct node* head, char* partner_manufacturers[], int inside_queue[], int
delivered[])
{
struct node* curr = head;
if(!curr)
return NULL;
while(curr->next)
prev = curr;
curr = curr->next;
inside_queue[manufacturer_ID]--;
delivered[manufacturer_ID]++;
if(!prev)
free(curr);
return NULL;
prev->next = NULL;
free(curr);
return head;
char manufacturer[20];
scanf("%s", manufacturer);
if(ID == -1)
printf("-1");
return;
printf("%d", a[ID]);
int main()
int n;
scanf("%d", &n);
for(int i=0;i<n;i++)
int typ;
scanf("%d", &typ);
while(head)
tmp = head;
head = head->next;
free(tmp);
return 0;
WORDLE
[75 Points] ---------------------------------------------------------------------- Automated Grading Scheme:
As shown above, if you have the right letter in the right spot, it shows up green. A correct letter in
the wrong spot shows up yellow. A letter that isn't in the word in any spot shows up gray.
You can enter a total of six words, meaning you can enter five burner words from which you can
learn hints about the letters and their placements. Then you get one chance to put those hints to
use. Or you can try for performance and guess the word of the day in three, two or even one go.
An Example play would be Where the word of the day is CYNIC:
Actual problem statement starts from here. I just wanted to let you know about the game
WORDLE ???? .
Score of a word/guess is defined as 2*number of green spots + number of yellow spots -
0.05*number of gray spots.
You are given a list of 5 letter distinct words and the day of the word, you have to give the
number of sequences of words with strictly increasing score and sequence must be ended by the
word of the day. Also, the length of the sequence must be at most 6.
Note: A sequence with only one word is a valid sequence.
Input Format
First line contains two integers N and K denoting the number of words and the position of the
word of the day in the list respectively. Next N lines contain the words.
Here, N is a natural number and 1 <= K <= N.
Output Format
Print the number of sequences of words with strictly increasing score and sequence must be
ended by the word of the day.
Example Input
44
STICK
CIRCA
CYCLE
CYNIC
Example Output
8
Explanation
The valid sequences are:
[STICK, CIRCA, CYCLE, CYNIC]
[CIRCA, CYCLE, CYNIC]
[STICK, CIRCA, CYNIC]
[STICK, CYCLE, CYNIC]
[STICK, CYNIC]
[CIRCA, CYNIC]
[CYCLE, CYNIC]
[CYNIC]
#include <stdio.h>
for(int i=0;i<5;i++){
wd[i] = word[i];
tg[i] = target[i];
}
float score = 0;
for(int i=0;i<5;i++){
if(wd[i] == tg[i]){
score += 2;
wd[i] = '*';
tg[i] = '#';
for(int i=0;i<5;i++){
for(int j=0;j<5;j++){
if(wd[i] == tg[j]){
score += 1;
wd[i] = '*';
tg[j] = '#';
break;
for(int i=0;i<5;i++){
if(wd[i] != '*'){
score -= 0.05;
return score;
return 0;
if(curr_score == 10)return 1;
int ans = 0;
for(int i=0;i<n;i++){
char curr[6];
for(int j=0;j<6;j++){
curr[j] = words[i][j];
return ans;
int main(){
int n,k;
k--;
char words[n][6];
char inp[6];
scanf("%s", inp);
inp[5] = '\0';
return 0; }
quiz 3 sec c
Operator Associativity
Automated Grading Scheme: Total marks: 40 Visible test case carries 5 marks. Hidden cases:
Test case 1 has 5 marks. Test cases 2, 3, and 4 have 10 marks each. -----------------------------------
----------------------------------------------------------------------------------------- Manually Grading Scheme:
Note: Give 0 marks for test-case component if there is any form of hard-coding. Eg: printf("0");
Header files allowed - stdio.h, stdlib.h, string.h ------------------------------------------------------------------
----------------------------------------------------------
Stimulus Corp has decided to design a domain-specific programming language (DSL) for a
scientific study. The language has a custom precedence and associativity of the operators.
Stimulus Corp requires you to develop a program to decide the order of operator evaluation in
the DSL. Given a sequence of operators, the program should print the order of evaluation of
operators as output.
Operator definitions
1. The sequence of operators can be a combination of the following operators.
o
Multiply (*)
o
Division (/)
o
Modulo (%)
o
Addition (+)
o
Subtraction (-)
o
Greater than (>)
o
Less than (<)
o
Bitwise XOR(^)
o
Bitwise AND (&)
o
Bitwise OR (|)
o
Assignment (=)
2. The definition of all operators is the same as in your favorite C language.
3. The associativity of all operators is left-to-right.
4. The order of precedence is as follows (low to high).
Bitwise operator (&,|,^) -> Assignment (=) -> Division/Multiplication/Modulo (/,\*,%) ->
Relational operator (<,>) -> Addition/Subtraction (+,-) .
Addition/Subtraction (+,-) implies that the addition and subtraction operators have the
same precedence.
5. An expression will be evaluated left to right for operators with the same precedence.
Constraints
1. The input is a string of operators.
2. The maximum number of operators in the string is 5.
3. Library functions are allowed.
Input
• The first line will contain the number of test cases.
• Each test case is a sequence of operators followed by a newline character\n.
Output
Your program should print the order of operator evaluation for each test case in the format given
in visible test case.
• Input
• 1
• /*+
• Output
• + / *
1 1 /*+ + / *
4 4 | % - / | % - /
Manage Library
[35 Points] ---------------------------------------------------------------------- Automated Grading Scheme:
• Visible: 1 , 2 and 2 marks for first, second and third visible test cases. Total = 5 Marks
• Hidden: 6 each for all hidden test cases. Total = 30 Marks
Manually Grading Scheme: Note: Give 0 marks for test-case component if there is any form of
hard-coding. Eg: printf("0"); Header files allowed - stdio.h, stdlib.h 0 marks for not using template.
-----------------------------------------------------------------------------------------
In this problem, you are going to use structures and dynamic memory allocation to represent the
state of a library. This library is arranged as multiple stacks of books in shelves of different sizes.
Books can be removed and added to stacks.
When a stack becomes equal in size to the capacity of the shelf, it is moved from the current
shelf to a shelf with twice the current capacity. The capacity of the shelves can only be powers of
2 (i.e. 1, 2, 4, 8 .....). For example if in a stack there were 3 books and it was in a shelf with a
capacity of 4, and another book was added, then this stack is moved from the current shelf to a
shelf with a capacity of 8.
If a book is removed from a stack, and the number of books in the stack falls below half of the
maximum capacity of the current shelf, the book is moved to a shelf with capacity equal to half
the capacity of the current shelf. For example if a stack has 4 books and is placed in a shelf with
a capacity of 8, and then a book is removed, then the stack is moved to a shelf with a capacity of
4.
You can assume that there are infite shelves of each possible capacity. But the number of stacks
will not change, i.e, we can add a book to only one of the existing stacks, and no new stacks will
be created. However each stack starts out with 0 books in a shelf with capacity 1.
Note that books can only be removed and added to the end of the stack. For example if the stack
has the following 3 books : A, B, C, and then a book D is added, then the stack will look like A, B,
C, D. If removed is called then, the stack would look like A, B, C.
We will use the following structs to represent a book and a stack respectively :
struct Book
{
/* data */
char name[20];
char author[20];
};
struct Stack
{
/* data */
struct Book * books;
int num_books;
int current_shelf_capacity;
};
Note : You can be asked to remove from empty stack, in that case you should not do anything.
You can be asked to get most recent book from empty stack, in that case return a book, with
name "NA" (without quotes) and author "NA" (without quotes).
INPUT:
The input consists of n+2 lines, where n is the number of operations. The first line contains the
number of stacks. The second line contains the number of operations. The next n lines contains :
The first number in the line contains an opcode. Opcode 1, 2, and 3 correspond to addition,
removal and get_most_recent respectively.
If the opcode is 1, the line contains which stack to do the operation on(going from 0 to number of
stacks -1), then it contains the name of book and the name of the author. Both are strings with no
spaces.
If the opcode is 2 or 3, the next thing in the line is the index of the stack.
OUTPUT:
You do not need to worry about the output, as all the output is printed in the template. The output
is the result of the opcode 3 operations, and in the end the status of all the stacks is printed. You
can look at the main function in the template code, for the output.
1
3
1 0 a b
1 0 c d
1 0 e f
• Output:
• Explanation:
1 0 a b - a, b is put on stack, and then the capacity of the shelf goes from 1 to
2, as the size of stack becomes equal to the shelf capacity
1 0 c d - c, d is put on the stack, then the capacity of the shelf goes from 2 to
4
1 0 e f - e, f is put on the stack, then the capacity remains the same as the
stack size is not equal to the shelf capacity
1
3
1 0 a b
2 0
3 0
1 0 a b - a, b is put on stack, and then the capacity of the shelf is increased
from 1 to 2, as the size of stack becomes equal to the shelf capacity
2 0 - a, b is removed from the stack, and the shelf capacity is reduced from 2 to
1, as the size of stack becomes 0 which is less than half of 2.
• Output:
NA NA
printing the status of the stacks
Stack Number 0, Shelf capacity 1
• Output:
c d
printing the status of the stacks
Stack Number 0, Shelf capacity 2
c d
• Explanation:
Quiz 3 sec d
Planet AK-99
[40 Points] ---------------------------------------------------------------------- Automated Grading Scheme:
• Visible: 2.5 marks for each visible test cases. Total = 2.5*2 = 5Marks
• Hidden: 5 marks each for all hidden test cases. Total = 5*7 = 35 Marks
Manually Grading Scheme: Note: Give 0 marks for test-case component if there is any form of
hard-coding. Eg: printf("0"); 50% penalty for not using the provided template. Header files
allowed - stdio.h, stdlib.h, math.h ------------------------------------------------------------------------------------
-----
Planet AK-99
NASA scientists discovered a newly planet which also supports life, Planet AK-99. The people
living in the planet are still developing mathematics, and have yet discovered only one 2D
geometry figure - the triangle. NASA have decided to help them teach but they want to test the
knowledge of humans first. NASA have decided to send you as their representative. Their
problem statement goes as follows :
You will be provided some number of triangles. For each triangle, you need to report its area.
Also, you need to tell for every trianle how many trianles are contained inside it.
Note A is present in B if and only if there is no part of A that lies outside of B.
Input Format
• The first line contains one integer n1. n1 represents the number of trianles.
• Each of next n1 lines contain 6 numbers (separated by space), representing the three
points of each trianle. The vertices will be in order x1,y1,x2,y2,x3,y3. Here xi and yi
represented the x and y cordinates of ith vertex respectively.
Output Format
Constraints:
1
0.500 0
001110
3
12.000 1
0 0 4 -3 4 3
0.250 0
0 1 1 1 0.5 0.5
1.650 0
2 1.5 3 1.3 3 -2
Explanation
1 1 0 0 1 1 1 0 0.500 0
Key Manager
Automated Grading Scheme:
Manually Grading Scheme: Note: Give 0 marks for test-case component if there is any form of
hard-coding. Eg: printf("0"); Penalty : -20% for using any future concepts -50% marks for using
global variable -50% for static allocation of array, example : int mat[100] or similar declaration 0
marks for not using given template. It is mandatory to utilize each component of template. ---------
---------------------------------------------------
Mr. T has joined a hotel as an intern. The hotel has N lockers for the housekeeping staff.
T is tasked with managing the lockers. Let us assume that T assigns the locker i to one
housekeeping staff. The value i is generated using the locker_index() function provided in the
template. The locker_index() function takes the input ID of the housekeeping staff. If a locker is
already occupied, T should not assign the locker to the staff.
T can perform the following operations.
Constraints
• Locker id starts from zero
• Use of global variables are not allowed
• Use of stdlib.h is allowed
• staff_id starts from 1
• N is always greater than equal to 2
• The remove operation (r) is only invoked for staff having a locker
Input
• The first line in each test case will contain the number of available lockers N.
• Each line following the first line will be of the form (ignore the angular brackets)
• The last line will contain e denoting the end of input
Output
• The program should print the correct message corresponding to each operation
o Assign a locker to the staff (a):
▪ Success: Print Locker assigned to staff .
▪ Failure: Print Locker < locker_id> to already assigned to staff <
staff_id >.
o Remove a locker assigned to a staff (r):
▪ Success: Print Removed staff < staff_id > from locker < locker_id
>.
o Search for a locker assigned to a staff (s):
▪ Success: Print Found, locker < locker_id > assigned to staff <
staff_id >.
▪ Failure: Print No locker assigned to staff < staff_id >.
• The program should output the status of lockers at the end of input using
print_locker_status() function provided in the template
• The locker status contains the locker ID and staff ID to whom the locker is assigned in
the format :
• If a locker is not assigned to any staff, do not print the details
3
a 2
a 3
s 5
s 3
a 5
e
Output