SlideShare a Scribd company logo
TCS_Digital_Advanced_Coding_Student copy.pptx
Topic/Course
Sub-Topic (Example: name of college)
TCS Digital Advanced
Coding
Topic/Course
Sub-Topic (Example: name of college)
Set A
question 1
Ayush is working on a strange algorithm where he wants to convert a string
from A to B, both the strings of equal length N.
Below are the rules which can be performed to convert a string.
String A and B are of equal length
Both of them are in lower case
Choose a subset X from the string A, between the index 1 and N.
Let ‘s’ be the letter which alphabetically comes before all other letters in the
subset. Let ‘s’ be called the ‘smallest element’ in the subset.
Replace all the elements of subset with the letter ‘s’
question 1
Find the minimum number of moves which is required to perform the
conversion. If it is not possible to convert the string from A to b then return -1
Let us try to understand it with and examples
Suppose there are 2 strings
A = abcab
B = aabab
Operation 1:
Now we have chosen a subset S, let us say we have taken index 2,3,5 from A
question 1
Then the subset S becomes [bcb]
Next, we have to choose the smallest element , 6041 here, which is b here in b
& c
Next, we have to replace all the other elements in subset with this element. So
‘b’ with replace everything in [bcb]. which becomes [bbb].
Now we will place all the respective elements back to their respective index.
This will update the original string as [abbab]
Operation 2:
Original string [abbab]
Now we have chosen a subset S, let say we have taken a index 1,2,4 from A
question 1
Then the subset become [aba]
Next, we have to choose the smallest element, which is here in a & b.
Next, we have to replace the smallest with all the other elements in subset. So
‘a’ will replace everything in [aba]
Now we will place all the respective elements back to their respective index.
This will update the original string as [aabab]
This is exactly same as String B
Hence it is possible to convert string A to B, with 2 operations. So, the answer
is 2.
question 1
Example 1:
Input:
2-> Input integer, N
de-> input string, A
cd-> Input string, B
Output:
-1
Explanation:
In the above example we can clearly see that there is an alphabet in A which is
completely different from B. hence it is not possible to convert A to B
So the answer is -1
question 1
Example 2:
Input:
4-> input integer, N
abab-> input string, A
abaa-> input string A
Output:
1 -> Output
Explanation:
Operation 1:
Now we have chosen a subset S, let say we have taken index 3,4 from A
then the Subset S becomes [ab]
question 1
Next, we have to choose the smallest element, which is a here in a & b
Next, we have to replace the smallest with all the other elements in subset. So
‘a’ will replace everything in [abl, which becomes [aa]
Now we will place all the respective elements back to their respective index.
This will update the original string as [abaa]
This is exactly same as String B
Hence it is possible to convert string A to B. with 1 operation. So, the answer is
1.
Constraints:
1<=N<=1000
N integer
Only lower case letters of the English alphabet
Length of A,B = N
question 1
The input format for testing
First Input-Accept value of Integer, N.
Second Input-Accept value of string, A (Next Line)
Third Input-Accept value of string, B(Next Line)
Additional messages in output will cause the failure of test cases
The Output format for testing
The output is an integer as per above logic. (Check the output in Example 1,
Example 21
Additional messages in output will cause the failure of test cases
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void transformString(char* str1, char* str2) {
int N = strlen(str1);
int convChar[26][N];
int convCharSize[26] = { 0 };
int str1array[26][N];
int str1arraySize[26] = { 0 };
int convertMap[N];
// Initialize convertMap
for (int i = 0; i < N; i++) {
convertMap[i] = -1;
}
// Filling str1array and convChar
for (int i = 0; i < N; i++) {
str1array[str1[i] - 'a'][str1arraySize[str1[i] - 'a']++] = i;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
for (int i = 0; i < N; i++) {
// Not possible to convert
if (str1[i] < str2[i]) {
printf("-1n");
return;
} else if (str1[i] == str2[i]) {
continue;
} else {
int index = str2[i] - 'a';
convChar[index][convCharSize[index]++] = i;
convertMap[i] = str2[i];
}
}
// Calculate result
int ret = 0;
int retv[N][N];
int retvSize = 0;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
for (int i = 25; i >= 0; i--) {
int* v = convChar[i];
int vSize = convCharSize[i];
if (vSize == 0)
continue;
ret++;
int* v1 = str1array[i];
int v1Size = str1arraySize[i];
if (v1Size == 0) {
printf("-1n");
return;
}
int isScompleted = 0;
for (int j = 0; j < v1Size; j++) {
if (convertMap[v1[j]] != -1) {
char a = convertMap[v1[j]];
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
if (a > i + 'a')
continue;
else {
v[vSize++] = v1[j];
isScompleted = 1;
memcpy(retv[retvSize++], v, vSize * sizeof(int));
break;
}
} else {
v[vSize++] = v1[j];
isScompleted = 1;
memcpy(retv[retvSize++], v, vSize * sizeof(int));
break;
}
}
if (!isScompleted) {
printf("-1n");
return;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
printf("%dn", ret);
}
int main() {
int N;
char A[1000], B[1000];
// Read the input values
scanf("%d", &N);
scanf("%s", A);
scanf("%s", B);
transformString(A, B);
return 0;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <bits/stdc++.h>
using namespace std;
void transformString(string str1,string str2)
{
int N = str1.length();
vector<int> convChar[26];
vector<int> str1array[26];
// Initialize both arrays
for (int i = 0; i < 26; i++)
{
vector<int> v;
convChar[i] = v;
str1array[i] = v;
}
// Stores the index of character
map<int, char> convertMap;
// Filling str1array, convChar
// and hashmap convertMap.
for (int i = 0; i < N; i++)
{
str1array[str1[i] - 'a'].push_back(i);
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
for (int i = 0; i < N; i++)
{
// Not possible to convert
if (str1[i] < str2[i])
{
cout << -1 << endl;
return;
}
else if (str1[i] == str2[i])
continue;
else
{
convChar[str2[i] - 'a'].push_back(i);
convertMap[i] = str2[i];
}
}
// Calculate result
// Initializing return values
int ret = 0;
vector<vector<int> > retv;
// Iterating the character from
// the end
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
for (int i = 25; i >= 0; i--)
{
vector<int> v = convChar[i];
if (v.size() == 0)
continue;
// Increment the number of
// operations
ret++;
vector<int> v1 = str1array[i];
// Not possible to convert
if (v1.size() == 0)
{
cout << -1 << endl;
return;
}
// to check whether the final
// element has been added
// in set S or not.
bool isScompleted = false;
for (int j = 0; j < v1.size(); j++)
{
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
if (convertMap.find(v1[j])
!= convertMap.end())
{
char a = convertMap[v1[j]];
// Already converted then
// then continue
if (a > i + 'a')
continue;
else
{
v.push_back(v1[j]);
isScompleted = true;
retv.push_back(v);
break;
}
}
else
{
v.push_back(v1[j]);
isScompleted = true;
retv.push_back(v);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
}
}
// Not possible to convert
if (!isScompleted)
{
cout << -1 << endl;
return;
}
}
// Print the result
cout << ret << endl;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
int main()
{
int N;
string A, B;
// Read the input values
cin >> N;
cin >> A;
cin >> B;
transformString(A, B);
return 0;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
public class Main {
public static void transformString(String str1, String str2) {
int N = str1.length();
List<Integer>[] convChar = new ArrayList[26];
List<Integer>[] str1array = new ArrayList[26];
// Initialize both arrays
for (int i = 0; i < 26; i++) {
convChar[i] = new ArrayList<>();
str1array[i] = new ArrayList<>();
}
// Stores the index of character
Map<Integer, Character> convertMap = new HashMap<>();
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// Filling str1array, convChar and hashmap convertMap.
for (int i = 0; i < N; i++) {
str1array[str1.charAt(i) - 'a'].add(i);
}
for (int i = 0; i < N; i++) {
// Not possible to convert
if (str1.charAt(i) < str2.charAt(i)) {
System.out.println(-1);
return;
} else if (str1.charAt(i) == str2.charAt(i)) {
continue;
} else {
convChar[str2.charAt(i) - 'a'].add(i);
convertMap.put(i, str2.charAt(i));
}
}
// Calculate result
// Initializing return values
int ret = 0;
List<List<Integer>> retv = new ArrayList<>();
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// Iterating the character from the end
for (int i = 25; i >= 0; i--) {
List<Integer> v = convChar[i];
if (v.size() == 0)
continue;
// Increment the number of operations
ret++;
List<Integer> v1 = str1array[i];
// Not possible to convert
if (v1.size() == 0) {
System.out.println(-1);
return;
}
// to check whether the final element has been added in set S or not.
boolean isScompleted = false;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
for (int j = 0; j < v1.size(); j++) {
// Check if v1[j] is present in hashmap or not
if (convertMap.containsKey(v1.get(j))) {
char a = convertMap.get(v1.get(j));
// Already converted then continue
if (a > i + 'a')
continue;
else {
v.add(v1.get(j));
isScompleted = true;
retv.add(v);
break;
}
} else {
v.add(v1.get(j));
isScompleted = true;
retv.add(v);
break;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// Not possible to convert
if (!isScompleted) {
System.out.println(-1);
return;
}
}
// Print the result
System.out.println(ret);
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int N = scanner.nextInt();
String A = scanner.next();
String B = scanner.next();
transformString(A, B);
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
def transformString(str1, str2):
N = len(str1)
convChar = [[] for _ in range(26)]
str1array = [[] for _ in range(26)]
# Initialize both arrays
convertMap = {}
# Filling str1array, convChar and hashmap convertMap.
for i in range(N):
str1array[ord(str1[i]) - ord('a')].append(i)
for i in range(N):
# Not possible to convert
if str1[i] < str2[i]:
print(-1)
return
elif str1[i] == str2[i]:
continue
else:
convChar[ord(str2[i]) - ord('a')].append(i)
convertMap[i] = str2[i]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# Calculate result
# Initializing return values
ret = 0
retv = []
# Iterating the character from the end
for i in range(25, -1, -1):
v = convChar[i]
if len(v) == 0:
continue
# Increment the number of operations
ret += 1
v1 = str1array[i]
# Not possible to convert
if len(v1) == 0:
print(-1)
return
# to check whether the final element has been added in set S or not.
isScompleted = False
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
for j in range(len(v1)):
# Check if v1[j] is present in hashmap or not
if v1[j] in convertMap:
a = convertMap[v1[j]]
# Already converted then continue
if a > chr(i + ord('a')):
continue
else:
v.append(v1[j])
isScompleted = True
retv.append(v)
break
else:
v.append(v1[j])
isScompleted = True
retv.append(v)
break
# Not possible to convert
if not isScompleted:
print(-1)
return
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# Print the result
print(ret)
# Read the input values
N = int(input())
A = input()
B = input()
transformString(A, B)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
question 2
A boy enters a stationery shop. There are N number of pencils and M
number of erasers available in the shop. But the boy's mother insists that he
can buy only P number of pencils and E number of erasers. The task here is
to find the number of ways the boy can choose 'P' pencils and 'E' erasers
from the available N and M pencils & erasers respectively.
Note:
The boy can choose in any order.
N-number of pencils available in the shop
M-number of erasers available in the shop
P-number of pencils he can choose to buy from N
E-number of erasers he can choose to buy from M
Example 1:
question 2
Input:
3 Value of N M
1 Value of M W
2 Value of P X
1 Value of E Y
Output:
3 Number of ways we can choose
Explanation 1
From the input given above
1st way of selecting:
Select 1st and 2nd pencils, 1 eraser
2nd way of selecting:
question 2
Select 2nd and 3rd pencils, 1 eraser
1st way of selecting:
Select 1st and 3rd pencils, 1 eraser
The Possible number of ways selecting 2 pencils and 1 eraser is 3
Hence the output is 3.
Example 2
Input:
5->Value of N
3->Value of M
5->Value of P
3->Value of E
Output:
question 2
->.Number of ways we can choose
Explanation 2
From the input given above:
1st way of selecting:
Select 1,2,3,4,5 Pencils and 1,2,3 erasers
There is only one possible way of selecting 5 pencils and 3
Hence, the output is 1.
Constarins:
0<N<<=50
0<M<=50
0<=P<=50
0<=E<=50
question 2
The Input format for testing
The candidate has to write the code to accept 4 input(s).
First Input - Accept value for N(Positive integer number)
Second Input-Accept value for M(Positive integer number)
Third input Accept value for P(Positive integer number)
Fourth input Accept value for E(Positive integer number)
The Output format for testing
The output should be a positive integer number or print the message (if any)
given in the problem statement
(Check the output in Example 1, Example 2)
#include <stdio.h>
// Function to calculate the factorial of a number
int factorial(int n)
{
int fact = 1;
for (int i = 1; i <= n; i++)
{
fact *= i;
}
return fact;
}
// Function to calculate the number of ways to choose 'P' pencils and 'E' erasers
int countWaysToChoose(int N, int M, int P, int E)
{
// Calculate the number of ways to choose 'P' pencils
int waysToChoosePencils = factorial(N) / (factorial(P) * factorial(N - P));
// Calculate the number of ways to choose 'E' erasers
int waysToChooseErasers = factorial(M) / (factorial(E) * factorial(M - E));
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// Calculate the total number of ways
int totalWays = waysToChoosePencils * waysToChooseErasers;
return totalWays;
}
int main()
{
int N, M, P, E;
scanf("%d %d %d %d", &N, &M, &P, &E);
int ways = countWaysToChoose(N, M, P, E);
printf("%dn", ways);
return 0;
}
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#include <iostream>
using namespace std;
// Function to calculate the factorial of a number
int factorial(int n)
{
int fact = 1;
for (int i = 1; i <= n; i++)
{
fact *= i;
}
return fact;
}
// Function to calculate the number of ways to choose 'P' pencils and 'E' erasers
int countWaysToChoose(int N, int M, int P, int E)
{
// Calculate the number of ways to choose 'P' pencils
int waysToChoosePencils = factorial(N) / (factorial(P) * factorial(N - P));
// Calculate the number of ways to choose 'E' erasers
int waysToChooseErasers = factorial(M) / (factorial(E) * factorial(M - E));
// Calculate the total number of ways
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
E));
// Calculate the total number of ways
int totalWays = waysToChoosePencils * waysToChooseErasers;
return totalWays;
}
int main()
{
int N, M, P, E;
cin >> N >> M >> P >> E;
int ways = countWaysToChoose(N, M, P, E);
cout << ways;
return 0;
}
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
import java.util.Scanner;
public class Main
{
// Function to calculate the factorial of a number
public static int factorial(int n)
{
int fact = 1;
for (int i = 1; i <= n; i++)
{
fact *= i;
}
return fact;
}
// Function to calculate the number of ways to choose 'P' pencils and 'E' erasers
public static int countWaysToChoose(int N, int M, int P, int E)
{
// Calculate the number of ways to choose 'P' pencils
int waysToChoosePencils = factorial(N) / (factorial(P) * factorial(N - P));
// Calculate the number of ways to choose 'E' erasers
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
int waysToChooseErasers = factorial(M) / (factorial(E) * factorial(M - E));
// Calculate the total number of ways
int totalWays = waysToChoosePencils * waysToChooseErasers;
return totalWays;
}
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
int N = scanner.nextInt();
int M = scanner.nextInt();
int P = scanner.nextInt();
int E = scanner.nextInt();
int ways = countWaysToChoose(N, M, P, E);
System.out.println(ways);
}
}
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# Function to calculate the factorial of a number
def factorial(n):
fact = 1
for i in range(1, n+1):
fact *= i
return fact
# Function to calculate the number of ways to choose 'P' pencils and 'E' erasers
def countWaysToChoose(N, M, P, E):
# Calculate the number of ways to choose 'P' pencils
waysToChoosePencils = factorial(N) // (factorial(P) * factorial(N - P))
# Calculate the number of ways to choose 'E' erasers
waysToChooseErasers = factorial(M) // (factorial(E) * factorial(M - E))
# Calculate the total number of ways
totalWays = waysToChoosePencils * waysToChooseErasers
return totalWays
# Main function
def main():
N = int(input())
M = int(input())
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
P = int(input())
E = int(input())
ways = countWaysToChoose(N, M, P, E)
print(ways)
# Call the main function
main()
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
question 3
Question: 3
One day Bob is playing Zombie World video game.
In Zombie World game each round will contain N zombies and each
zombie's energy is Zi (where 1<=i<=N). Bob will start the round with B
energy. In order to move to the next level Bob need to kill all the N
zombie's but Bob can select any one among N Zombie's. If energy of
Bob (B) is less than Zombie energy (Zi) then Bob will die and lose the
round else Bob will won, during the fighting with zombie, Bob will lose
his energy by (Zi%2)+(Zi/2). At any point of game Bob will play optimally.
Now your task is to find out whether Bob can reach to the next level or
question 3
not.Input FormatThe first line of input contain B and N, where B is the
energy of Bob and N is the number of ZombiesThe second line of input
contain Zi, where Zi is a list containing energy of zombies separated by
spaceOutput FormatPrint "YES" or "NO" depending upon whether Bob
can reach the next level or not. Constraints
1<=N<=10^41<=B<=10^91<=Zi<=10^5
Sample Test Case :
Input: 35 3
5 9 6
Output: YES
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#include<stdio.h>
void swap(int* xp, int* yp) {
int temp = *xp;
*xp = *yp;
*yp = temp;
}
// Function to perform Selection Sort
void sort(long int arr[], long int n) {
int i, j, min_idx;
// One by one move boundary of unsorted subarray
for (i = 0; i < n - 1; i++) {
// Find the minimum element in unsorted array
min_idx = i;
for (j = i + 1; j < n; j++)
if (arr[j] < arr[min_idx])
min_idx = j;
// Swap the found minimum element
// with the first element
swap(&arr[min_idx], &arr[i]);
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
int main(){
long int b,n;
scanf("%ld%ld",&b,&n);
long int z[n];
for(long int i=0;i<n;i++)
scanf("%ld",&z[i]);
sort(z, n);
for(long int i=0;i<n;i++)
b-=(z[i]%2)+(z[i]/2);
if(b<0)
printf("NO");
else
printf("YES");
}
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#include <algorithm>
#include<iostream>
using namespace std;
int main(){
long int b,n;
cin>>b>>n;
long int z[n];
for(long int i=0;i<n;i++)
cin>>z[i];
sort(z, z+n);
for(long int i=0;i<n;i++)
b-=(z[i]%2)+(z[i]/2);
if(b<0)
cout<<"NO";
else
cout<<"YES";
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import java.util.Scanner;
import java.util.Arrays;
class Main{
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
long b;
b = sc.nextLong();
int n = sc.nextInt();
long z[]= new long[n];
for(int i=0;i<n;i++)
z[i]=sc.nextLong();
Arrays.sort(z);
for(int i=0;i<n;i++)
b-=(z[i]%2)+(z[i]/2);
if(b<0)
System.out.print("NO");
else
System.out.print("YES");
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
b ,n= [int(x) for x in input().split()]
z = [int(x) for x in input().split()]
z.sort()
for i in range(n):
b-=(z[i]%2)+(z[i]/2)
if(b<0):
print("NO")
else:
print("YES")
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
question 4
Alice and Bob are batch mates and Alice got placed in a well-reputed product-
based company and his friend Bob is demanding a pizza party from him. Alice
is ready for giving party and he ordered N pizzas from the nearest restaurant.
Now pizzas can have at most K different flavors (It is not necessary that there
should be one pizza of each flavor), numbered from 1 to K such that ⅈ^th
pizza can have Ai flavor (1 <= Ai <=k).
Bob is on dieting, and he can only eat pizza of at most k-1 flavors but he can
eat as many pizzas of ith flavor and he wanted to choose maximum possible
pizzas which are in contiguous sequence to one another such that all pizzas
in sequence has atmost k-1 flavors.
For example
6 2 -> here 6 is the number pizzas of and 2 is number of distinct
flavors
1 1 1 2 2 1 -> ith pizza has flavor ai
question 4
Example 1:
Input
6 2 -> Size of input Array and K distinct flavors
1 1 1 2 2 1 -> input array (N Different pizza flavors )
Output
3
Explanation
Maximum length subarray with at most k-1 distinct flavors is 3 and sub array
is 1 1 1
question 4
Example 2:
Input:
5 3 -> Size of inputs Arrays and K distinct flavors
1 1 2 2 1 -> input array (N Different Pizza Flavors)
Output
5
Explanation
Since N pizza in total has only 2 flavors so bob can eat all pizza so maximum
length of subarray with at most k-1 distinct flavors is 5
question 4
Constraints
1<N<100000>Size of Array
2<K<100000> Number of different flavors
1<A[i]<100000> Value of ith flavor 0 base indexing
The Input format for testing
The candidate has to write the code to accept 2 inputs.
First Input: It will contain two integer N and K
Second Input: It will contain a N integer separated by space.
Output format for testing
The output will contain a single line containing an integer denoting maximum
possible length of subarray.
question 4
Additional messages in output will cause the failure of test cases.
Instructions:
System doesn't allow any kind of hard coded input value/values. Written
program code by the candidate will be verified against the inputs which are
supplied from the system
#include <stdio.h>
int main() {
int n, k;
scanf("%d %d", &n, &k);
int arr[n];
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
int maxcount = 0;
for (int i = 0; i < n; i++) {
int count = 0;
while (i < n && arr[i] <= k - 1) {
count++;
i++;
}
maxcount = (count > maxcount) ? count : maxcount;
}
printf("%dn", maxcount);
return 0;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>
using namespace std;
int main() {
int n, k;
cin >> n >> k;
int arr[n];
for (int i = 0; i < n; i++) {
cin >> arr[i];
}
int maxcount = 0;
for (int i = 0; i < n; i++) {
int count = 0;
while (i < n && arr[i] <= k - 1) {
count++;
i++;
}
maxcount = (count > maxcount) ? count : maxcount;
}
cout << maxcount << endl;
return 0;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int k = scanner.nextInt();
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = scanner.nextInt();
}
int maxcount = 0;
for (int i = 0; i < n; i++) {
int count = 0;
while (i < n && arr[i] <= k - 1) {
count++;
i++;
}
maxcount = Math.max(count, maxcount);
}
System.out.println(maxcount);
scanner.close();
}}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
n,k=map(int,input().split())
arr=list(map(int,input().split()))
maxcount=0
for i in range(n):
count=0
while i<n and arr[i]<=k-1:
count+=1
i+=1
maxcount=max(maxcount, count)
print(maxcount)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
question 5
Alice had to go to play with his friends. But his brother is not leaving. So, he
thought to ask a question so that in the mean time he can go. So , the
problem is as follows: He will be given numbers n,m and k. Calculate T. (T =
(nm)/k) His brother has to find the three coordinates of the XY plane (2D
points) such that the area of the triangle formed by those points should be
equal to T. If there is any solution print YES. else NO.
NOTE: 1 x1,y1, x2,y2, x3, y3 109
≤ ≤
Example 1:
Input:
4 3 3
question 5
Output:
YES
Explanation:
One possible way is (1,0), (2,3) and (4,1) are the
points where there area is equal to T.
Example - 2:
Input:
4 4 7
Output.
NO
question 5
Constraints:
1 n,m 109
≤ ≤
2 k 109
≤ ≤
The input format for testing:
•The first line represents the n, m and k, each separated by a space.
The Output format for testing:
•Print YES if there is any solution else NO
Instructions:
•The system does not allow any kind of hard- coded input value/ values.
•Written program code by the candidate will be verified against the inputs
which are supplied from the system.
#include <stdio.h>
#include <math.h>
char* check_triangle_area(int n, int m, int k) {
double T = (double)(n * m) / k;
for (int x1 = 1; x1 <= n; x1++) {
for (int y1 = 0; y1 <= m; y1++) {
for (int x2 = 0; x2 <= n; x2++) {
for (int y2 = 0; y2 <= m; y2++) {
double area = 0.5 * fabs(x1 * (y2 - y1) + x2 * (y1 - 0) + n * (0 - y2));
if (area == T) {
return "YES";
}
}
}
}
}
return "NO";
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
int main() {
int n, m, k;
scanf("%d %d %d", &n, &m, &k);
char* result = check_triangle_area(n, m, k);
printf("%sn", result);
return 0;
}
#include <iostream>
#include <cmath>
using namespace std;
string check_triangle_area(int n, int m, int k) {
double T = static_cast<double>(n * m) / k;
for (int x1 = 1; x1 <= n; x1++) {
for (int y1 = 0; y1 <= m; y1++) {
for (int x2 = 0; x2 <= n; x2++) {
for (int y2 = 0; y2 <= m; y2++) {
double area = 0.5 * abs(x1 * (y2 - y1) + x2 * (y1 - 0) + n * (0 - y2));
if (area == T) {
return "YES";
}
}
}
}
}
return "NO";
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
int main() {
int n, m, k;
cin >> n >> m >> k;
string result = check_triangle_area(n, m, k);
cout << result << endl;
return 0;
}
import java.util.Scanner;
public class Main {
static String checkTriangleArea(int n, int m, int k) {
double T = (double) (n * m) / k;
for (int x1 = 1; x1 <= n; x1++) {
for (int y1 = 0; y1 <= m; y1++) {
for (int x2 = 0; x2 <= n; x2++) {
for (int y2 = 0; y2 <= m; y2++) {
double area = 0.5 * Math.abs(x1 * (y2 - y1) + x2 * (y1 - 0) + n * (0 - y2));
if (area == T) {
return "YES";
}
}
}
}
}
return "NO";
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
long n = scanner.nextLong();
long m = scanner.nextLong();
long k = scanner.nextLong();
if (!isTrianglePossible(n, m, k))
System.out.println("NO");
}
}
def check_triangle_area(n, m, k):
T = (n * m) / k
for x1 in range(1, n + 1):
for y1 in range(m + 1):
for x2 in range(n + 1):
for y2 in range(m + 1):
area = 0.5 * abs(x1 * (y2 - y1) + x2 * (y1 - 0) + n * (0 - y2))
if area == T:
return "YES“
return "NO“
if _name_ == "_main_":
n, m, k = map(int, input().split())
result = check_triangle_area(n, m, k)
print(result)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
question 6
You have given n piles in which each pile contains some numbers of
stones/coins and you have also given the information about who can made
the first move from player 1 and 2. In each turn, a player can choose only
one pile and remove any number of stones (at least one) from that pile. The
player who cannot move is considered to lose the game (i.e., one who take
the last stone is the winner). ”
Input Format :
First line will contain two integers n and t - number of piles and who will
made the first move first or 2nd player (if t is 1 then 1st player will start game
otherwise 2nd player will start the game) (1 <= n <= 10^5, 1 <= t <= 2).
Second line will contain n space separated integers (1 <= a[i] <= 100000).
question 6
Output Format :
Print 1 if player 1 will win otherwise print 2.
Sample Input 1:
3 1
3 4 5
Sample Output 1:
1
Sample Input 2:
3 2
3 4 5
Sample Output 2:
2
#include <stdio.h>
#define int long long
#define COMPUTER 1
#define HUMAN 2
int calculateNimSum(int piles[], int n)
{
int i, nimsum = piles[0];
for (i = 1; i < n; i++)
nimsum = nimsum ^ piles[i];
return nimsum;
}
void knowWinnerBeforePlaying(int piles[]
, int n, int whoseTurn) {
if (calculateNimSum(piles, n) !
= 0) {
if (whoseTurn == COMPUTER)
printf("1");
else
printf("2");
} else {
if (whoseTurn == COMPUTER)
printf("2");
else
printf("1");
}
}
int main() {
int n, turn;
scanf("%lld %lld", &n, &turn);
int piles[n];
for (int i = 0; i < n; i++)
scanf("%lld", &piles[i]);
knowWinnerBeforePlaying(piles, n, t
urn);
return 0;
}
using namespace std;
#define int long long
#define COMPUTER 1
#define HUMAN 2
int calculateNimSum(int piles[], int n)
{
int i, nimsum = piles[0];
for (i = 1; i<n; i++)
nimsum = nimsum ^ piles[i];
return(nimsum);
}
void knowWinnerBeforePlaying(int piles[]
, int n,
int whoseTur
n)
{
if (calculateNimSum(piles, n) != 0)
{
if (whoseTurn == COMPUTER)
cout << 1;
else
cout << 2;
}
else
{
if (whoseTurn == COMPUTER)
cout << 2;
else
cout << 1;
}
return;
}
signed main()
{
int n, turn;
cin >> n >> turn;
int piles[n];
for(int i = 0; i < n; i+
+) cin >> piles[i];
knowWinnerBeforePlaying(piles, n, t
urn);
return(0);
}
import java.util.Scanner;
public class Main{
public static long calculateNimSum(l
ong[] piles, int n) {
long nimsum = piles[0];
for (int i = 1; i < n; i++) {
nimsum = nimsum ^ piles[i];
}
return nimsum;
}
public static void knowWinnerBeforeP
laying(long[] piles, int n, int whoseTur
n) {
if (calculateNimSum(piles, n) !
= 0) {
if (whoseTurn == 1) {
System.out.print("1");
} else {
System.out.print("2");
}
} else {
if (whoseTurn == 1) {
System.out.print("2");
} else {
System.out.print("1");
}
}
}
public static void main(String[] ar
gs) {
Scanner scanner = new Scanner(S
ystem.in);
int n = scanner.nextInt();
int turn = scanner.nextInt();
long[] piles = new long[n];
for (int i = 0; i < n; i++) {
piles[i] = scanner.nextLong
();
}
knowWinnerBeforePlaying(piles,
n, turn);
scanner.close();
}
def calculateNimSum(piles, n):
nimsum = piles[0]
for i in range(1, n):
nimsum = nimsum ^ piles[i]
return nimsum
def knowWinnerBeforePlaying(piles, n, wh
oseTurn):
if calculateNimSum(piles, n) != 0:
if whoseTurn == 1:
print("1", end="")
else:
print("2", end="")
else:
if whoseTurn == 1:
print("2", end="")
else:
print("1", end="")
if __name__ == "__main__":
n, turn = map(int, input().split())
piles = list(map(int, input().split
()))
knowWinnerBeforePlaying(piles, n, t
urn)
question 7
A man wants to do rock climbing and reach the top of a steep peak. There is
'N' number of Convenient rocks on the mountain which the mountaineer can
step onto to reach the peak a little easily. The initial position/rock on which the
rock climber is standing currently is denoted as 'I'. From each rock, the person
can skip utmost 'X' rocks. The task here is to find the number of ways a
mountaineer can climb to reach the peak.
Example 1:
Input:
6-> Value of N
3-> Value of I
2-> Value of X
Output:
3-> Number of ways he can reach the peak
#include <stdio.h>
int countClimbingWays(int N, int I, int X)
{
int ways[N + 1];
ways[I] = 1;
ways[I - 1] = 1;
for (int i = I + 1; i <= N; i++)
{
ways[i] = 0;
for (int j = 1; j <= X && i - j >= I; j++)
{
ways[i] += ways[i - j];
}
}
return ways[N];
}
int main()
{
int N, I, X;
scanf("%d", &N);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
scanf("%d", &I);
scanf("%d", &X);
int numWays =
countClimbingWays(N, I, X);
printf("%dn", numWays);
return 0;
}
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#include <iostream>
using namespace std;
int countClimbingWays(int N, int I, int X)
{
int ways[N + 1];
ways[I] = 1;
ways[I - 1] = 1;
for (int i = I + 1; i <= N; i++)
{
ways[i] = 0;
for (int j = 1; j <= X && i - j >= I; j++)
{
ways[i] += ways[i - j];
}
}
return ways[N];
}
int main()
{
int N, I, X;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
cin >> N;
cin >> I;
cin >> X;
int numWays = countClimbingWays(N, I,
X);
cout <<numWays;
return 0;
}
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
import java.util.Scanner;
public class Main
{
public static int countClimbingWays(int
N, int I, int X)
{
int[] ways = new int[N + 1];
ways[I] = 1;
ways[I - 1] = 1;
for (int i = I + 1; i <= N; i++)
{
ways[i] = 0;
for (int j = 1; j <= X && i - j >= I; j++)
{
ways[i] += ways[i - j];
}
}
return ways[N];
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
}
public static void main(String[] args)
{
Scanner scanner = new
Scanner(System.in);
int N, I, X;
N = scanner.nextInt();
I = scanner.nextInt();
X = scanner.nextInt();
int numWays = countClimbingWays(N,
I, X);
System.out.println(numWays);
}
}
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
def countClimbingWays(N, I, X):
ways = [0] * (N + 1)
ways[I] = 1
ways[I - 1] = 1
for i in range(I + 1, N + 1):
ways[i] = 0
for j in range(1, X + 1):
if i - j >= I:
ways[i] += ways[i - j]
return ways[N]
N = int(input())
I = int(input())
X = int(input())
numWays = countClimbingWays(N, I, X)
print(numWays)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
question 8
An event management company has come up with a unique idea of printing
their event tickets. Based on the ticket number combination (str1), the visitor
is directed towards a particular class of audience. The task is to create a
program/application to fetch the ticket number based on the following
conditions:
Any occurrences of digits EF and G should be deleted. The characters EF
should be in the same format.
Input format
The candidate has to write the code to accept 1 input(s). First Input -Accept
value for str1 which is a string consisting of numbers and uppercase
alphabets without any spaces
Output format
question 8
The output should be a string without any spaces (Check the output in
Example 1 and Example 2) Additional messages in output will cause the failure
of test cases.
Constraints
Str ((A,Z),(0-9))
No spaces and special characters allowed.
Only uppercase alphabets in the input string
Example 1:
Input:
4523EF58G -> A value of STR1
question 8
Output :
452358 -> A after removal of characters EF and G
Example 2:
Input:
E12F35G58 -> A value of STR1
Output :
E12F3558 -> A after removal of characters “G”
Explanation:
In the above example, characters E and F are not together So, they won't be
deleted. The output will be with only character G removed.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char* removeCharacters(const char* str)
{
char* result = (char*)malloc(strlen(str) +
1);
int resultIndex = 0;
int isEF = 0;
for (int i = 0; str[i] != '0'; i++)
{
if (str[i] == 'E' && !isEF)
{
isEF = 1;
}
else if (isEF && str[i] == 'F')
{
isEF = 0;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
}
else if (str[i] != 'G')
{
result[resultIndex++] = str[i];
}
}
result[resultIndex] = '0';
return result;
}
int main()
{
char ticketNumber[100];
scanf("%s", ticketNumber);
char* modifiedTicketNumber =
removeCharacters(ticketNumber);
printf("%sn", modifiedTicketNumber);
free(modifiedTicketNumber);
return 0;
}
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#include <iostream>
#include <string>
using namespace std;
string removeCharacters(const string& str)
{
string result;
bool isEF = false;
for (char ch : str)
{
if (ch == 'E' && !isEF)
{
isEF = true;
}
else if (isEF && ch == 'F')
{
isEF = false;
}
else if (ch != 'G')
{
result.push_back(ch);
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
}
return result;
}
int main()
{
string ticketNumber;
cin >> ticketNumber;
string modifiedTicketNumber =
removeCharacters(ticketNumber);
cout << modifiedTicketNumber << "n";
return 0;
}
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
import java.util.Scanner;
public class Main
{
public static String
removeCharacters(String str)
{
StringBuilder result = new
StringBuilder();
boolean isEF = false;
for (char ch : str.toCharArray())
{
if (ch == 'E' && !isEF)
{
isEF = true;
}
else if (isEF && ch == 'F')
{
isEF = false;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
else if (ch != 'G')
{
result.append(ch);
}
}
return result.toString();
}
public static void main(String[] args)
{
Scanner scanner = new
Scanner(System.in);
String ticketNumber =
scanner.nextLine();
String modifiedTicketNumber =
removeCharacters(ticketNumber);
System.out.println(modifiedTicketNumber
);
}
}
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
def remove_characters(ticket_number):
result = ""
is_ef = False
for ch in ticket_number:
if ch == 'E' and not is_ef:
is_ef = True
elif is_ef and ch == 'F':
is_ef = False
elif ch != 'G':
result += ch
return result
def main():
ticket_number = input()
modified_ticket_number =
remove_characters(ticket_number)
print(modified_ticket_number)
main()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
question 9
The person is travelling from place A to place B. He will take 12 hours to
reach the destination by roads. As the person starts his journey, he has to
note the current time in hours H and minutes M ( non negative integer
input ).The task is to find the time left for him to reach the destination
(output).If current time (hours or minutes) is a value exceeding 24 hours, the
output should be a negative integer value, representing total exceeded hours
and minutes (See the Example 3).
Input format
The candidate has to write the code to accept two inputs separated by a new
line.
First Input Accept value for hours which is H.
Second Input- Accept value for minutes which is M.
Output format
question 9
The output should be time in 24 hour format (Check the output in Example 1
and 2 above). The hours and minutes should be separated by "::" without any
additional space(See the output in examples).
Additional messages in output will cause the failure of test cases.
Constraints:
0<H<=100
0<M<=60
Example 1:
Input:
14 value of H i.e Hours
20 value of M i.e Minutes
question 9
Output:
9::40 Time left to reach the destination
Example 2:
Input:
1 value of H i.e Hours
15 value of M i.e Minutes
Output:
22::45 Time left to reach the destination
Example 3:
Input:
30 value of H i.e Hours
5 value of M i.e Minutes
Output:
-6::5 Time left to reach the destination
#include <stdio.h>
int main()
{
int H, M;
scanf("%d", &H);
scanf("%d", &M);
// Convert hours to minutes
int currentTotalMinutes = H * 60 + M;
// Calculate time left in minutes
int timeLeftMinutes = 24 * 60 - currentTotalMinutes;
// Convert time left to hours and minutes
int timeLeftHours = timeLeftMinutes / 60;
int timeLeftMins = timeLeftMinutes % 60;
printf("%02d::%02dn", timeLeftHours, timeLeftMins);
return 0;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <bits/stdc++.h>
using namespace std;
int main()
{
int H, M;
cin >> H;
cin >> M;
// Convert hours to minutes
int currentTotalMinutes = H * 60 + M;
// Calculate time left in minutes
int timeLeftMinutes = 24 * 60 - currentTotalMinutes;
// Convert time left to hours and minutes
int timeLeftHours = timeLeftMinutes / 60;
int timeLeftMins = timeLeftMinutes % 60;
cout << setfill('0') << setw(2) << timeLeftHours << "::"
<< setfill('0') << setw(2) << timeLeftMins;
return 0;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
int H, M;
H = scanner.nextInt();
M = scanner.nextInt();
// Convert hours to minutes
int currentTotalMinutes = H * 60 + M;
// Calculate time left in minutes
int timeLeftMinutes = 24 * 60 - currentTotalMinutes;
// Convert time left to hours and minutes
int timeLeftHours = timeLeftMinutes / 60;
int timeLeftMins = timeLeftMinutes % 60;
System.out.printf("%02d::%02d", timeLeftHours, timeLeftMins);
scanner.close();
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
H = int(input())
M = int(input())
# Calculate total minutes
currentTotalMinutes = H * 60 + M
# Check if current time exceeds 24 hours
if currentTotalMinutes > 24 * 60:
timeExceededMinutes = currentTotalMinutes - (24 * 60)
timeExceededHours = timeExceededMinutes // 60
timeExceededMinutes %= 60
print("-{}::-{:02d}".format(timeExceededHours, timeExceededMinutes))
else:
# Calculate time left in minutes
timeLeftMinutes = 24 * 60 - currentTotalMinutes
# Calculate time left hours and minutes
timeLeftHours = timeLeftMinutes // 60
timeLeftMinutes %= 60
# Format and print the output
print("{:02d}::{:02d}".format(timeLeftHours, timeLeftMinutes))
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
question 10
A shopkeeper in a nearby town always starts a business ₹0. He never uses
the previous days money for transaction. Any item in his shop costs
₹30.There are N number of customers waiting in the queue to buy items. A
customer can buy any number of items but worth only ₹30.The customer
can transact with shopkeeper only with the denominations
₹30,₹60,₹120.The task here is to find the transaction between the
shopkeeper and customer is possible.
The customer should be able to buy the item.
The amount each customer uses for his transaction is given as array
elements .
The shopkeeper should be able to return the exact change.
Display ‘Transaction Successful’ on the successful transaction with all the
customers in the queue.
Display ‘Transaction failed’ on the unsuccessful transaction with any one
customer in the queue.
question 10
Example 1
Sample Input:
3 -> value of N
30
30
60->a[] ,Elements a[0] to a[N-1],where input of each element is seperated
by a new line.
Sample Output:
Transaction successful.
#include <stdio.h>
int isTransactionPossible(int a[], int N)
{
int change30 = 0;
int change60 = 0;
int change120 = 0;
for (int i = 0; i < N; i++)
{
if (a[i] == 30)
{
// If customer pays ₹30, no change required
change30++;
}
else if (a[i] == 60)
{
// If customer pays ₹60, return ₹30 change if available
if (change30 > 0)
{
change30--;
}
else
{
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
return 0;
}
change60++;
}
else if (a[i] == 120)
{
// If customer pays ₹120, return ₹90 change if available
if (change30 > 0 && change60 > 0)
{
change30--;
change60--;
}
else if (change30 >= 3)
{
change30 -= 3;
}
else
{
return 0;
}
change120++;
}
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
}
return 1;
}
int main()
{
int N;
scanf("%d", &N);
int a[N];
for (int i = 0; i < N; i++)
{
scanf("%d", &a[i]);
}
if (isTransactionPossible(a, N))
{
printf("Transaction successful");
}
else
{
printf("Transaction failed");
}
return 0;
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#include <iostream>
using namespace std;
bool isTransactionPossible(int a[], int N)
{
int change30 = 0;
int change60 = 0;
int change120 = 0;
for (int i = 0; i < N; i++)
{
if (a[i] == 30)
{
// If customer pays ₹30, no change required
change30++;
}
else if (a[i] == 60)
{
// If customer pays ₹60, return ₹30 change if available
if (change30 > 0)
{
change30--;
}
else
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
{
return false;
}
change60++;
}
else if (a[i] == 120)
{
// If customer pays ₹120, return ₹90 change if available
if (change30 > 0 && change60 > 0)
{
change30--;
change60--;
}
else if (change30 >= 3)
{
change30 -= 3;
}
else
{
return false;
}
change120++;
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
}
return true;
}
int main()
{
int N;
cin >> N;
int a[N];
for (int i = 0; i < N; i++)
{
cin >> a[i];
}
if (isTransactionPossible(a, N))
{
cout << "Transaction successful" << endl;
}
else
{
cout << "Transaction failed" << endl;
}
return 0;
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
import java.util.Scanner;
public class Main
{
public static int isTransactionPossible(int[] a, int N)
{
int change30 = 0;
int change60 = 0;
int change120 = 0;
for (int i = 0; i < N; i++)
{
if (a[i] == 30)
{
// If customer pays ₹30, no change required
change30++;
}
else if (a[i] == 60)
{
// If customer pays ₹60, return ₹30 change if available
if (change30 > 0)
{
change30--;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
else
{
return 0;
}
change60++;
}
else if (a[i] == 120)
{
// If customer pays ₹120, return ₹90 change if available
if (change30 > 0 && change60 > 0)
{
change30--;
change60--;
}
else if (change30 >= 3)
{
change30 -= 3;
}
else
{
return 0;
}
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
change120++;
}
}
return 1;
}
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
int N = scanner.nextInt();
int[] a = new int[N];
for (int i = 0; i < N; i++)
{
a[i] = scanner.nextInt();
}
if (isTransactionPossible(a, N) == 1)
{
System.out.println("Transaction successful");
}
else
{
System.out.println("Transaction failed");
}
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
scanner.close();
}
}
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
def is_transaction_possible(a, N):
change30 = 0
change60 = 0
change120 = 0
for i in range(N):
if a[i] == 30:
# If customer pays ₹30, no change required
change30 += 1
elif a[i] == 60:
# If customer pays ₹60, return ₹30 change if available
if change30 > 0:
change30 -= 1
else:
return 0
change60 += 1
elif a[i] == 120:
# If customer pays ₹120, return ₹90 change if available
if change30 > 0 and change60 > 0:
change30 -= 1
change60 -= 1
elif change30 >= 3:
change30 -= 3
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
else:
return 0
change120 += 1
return 1
N = int(input())
a = []
for i in range(N):
a.append(int(input()))
if is_transaction_possible(a, N) == 1:
print("Transaction successful")
else:
print("Transaction failed")
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
Set B
question 11
Given a string in which the same character occurs in many consecutive
character elements. Your task is to find the characters that have even
frequency and are consecutive. Display the sum of every frequency count( For
even frequency only)
Example 1:
Sample Input:
aaabbaccccdd
Sample Output:
8
Example 2
Sample Input:
vdkkmmmnn
Sample Output:
4
#include <stdio.h>
#include <string.h>
int findSumOfEvenFrequency(char str[])
{
int sum = 0;
int count = 1;
for (int i = 1; i < strlen(str); i++)
{
if (str[i] == str[i - 1])
{
count++;
}
else
{
if (count % 2 == 0)
{
sum += count;
}
count = 1;
}
}
// Check the count of the last character sequence
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
if (count % 2 == 0)
{
sum += count;
}
return sum;
}
int main()
{
char input[100];
scanf("%s", input);
int result = findSumOfEvenFrequency(input);
printf("%dn", result);
return 0;
}
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#include <iostream>
using namespace std;
int findSumOfEvenFrequency(string str)
{
int sum = 0;
int count = 1;
for (int i = 1; i < str.length(); i++)
{
if (str[i] == str[i - 1])
{
count++;
}
else
{
if (count % 2 == 0)
{
sum += count;
}
count = 1;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// Check the count of the last character sequence
if (count % 2 == 0)
{
sum += count;
}
return sum;
}
int main()
{
string input;
cin >> input;
int result = findSumOfEvenFrequency(input);
cout << result << endl;
return 0;
}
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
import java.util.Scanner;
public class Main
{
public static int findSumOfEvenFrequency(String str)
{
int sum = 0;
int count = 1;
for (int i = 1; i < str.length(); i++)
{
if (str.charAt(i) == str.charAt(i - 1))
{
count++;
}
else
{
if (count % 2 == 0)
{
sum += count;
}
count = 1;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
}
// Check the count of the last character sequence
if (count % 2 == 0)
{
sum += count;
}
return sum;
}
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
String input = scanner.next();
int result = findSumOfEvenFrequency(input);
System.out.println(result);
}
}
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
def find_sum_of_even_frequency(string):
sum = 0
count = 1
for i in range(1, len(string)):
if string[i] == string[i - 1]:
count += 1
else:
if count % 2 == 0:
sum += count
count = 1
# Check the count of the last character sequence
if count % 2 == 0:
sum += count
return sum
input_str = input()
result = find_sum_of_even_frequency(input_str)
print(result)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
question 12
Given N Rupees. A liter plastic bottle of milk costs R1 Rupees and a liter of the
glass bottle of milk costs R2 Rupees. But the empty glass bottle after buying
can be exchanged for R3 Rupees. Find the maximum liters of milk which can be
bought with N Rupees.
Example-1:
Input:
10 Value of N
→
11 Value of R1 i.e. price of plastic bottle
→
9 Value of R2 i.e. price of glass bottle
→
8 Value of R3 i.e. price of empty glass bottle
→
Output:
2
#include <stdio.h>
int max(int a, int b) {
return (a > b) ? a : b;
}
void maxLitres(int budget, int plastic, int glass, int refund) {
if (glass - refund < plastic) {
int ans = max((budget - refund) / (glass - refund), 0);
budget -= ans * (glass - refund);
ans += budget / plastic;
printf("%dn", ans);
} else {
printf("%dn", budget / plastic);
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
int main() {
int budget, plastic, glass, refund;
scanf("%d", &budget);
scanf("%d", &plastic);
scanf("%d", &glass);
scanf("%d", &refund);
maxLitres(budget, plastic, glass, refund);
return 0;
}
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#include<bits/stdc++.h>
using namespace std;
void maxLitres(int budget, int plastic, int glass
, int refund)
{
if (glass - refund < plastic)
{
int ans = max((budget - refund) / (glass - r
efund), 0);
budget -= ans * (glass - refund);
ans += budget / plastic;
cout << ans << endl;
}
else
cout << (budget / plastic) << endl;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
int main()
{
int budget, plastic, glass, refund;
cin >> budget;
cin >> plastic;
cin >> glass;
cin >> refund;
maxLitres(budget, plastic, glass, refund);
return 0;
}
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
import java.util.Scanner;
public class Main {
public static int max(int a, int b) {
return (a > b) ? a : b;
}
public static void maxLitres(int budget, int plastic, int glass, int refund) {
if (glass - refund < plastic) {
int ans = max((budget - refund) / (glass - refund), 0);
budget -= ans * (glass - refund);
ans += budget / plastic;
System.out.println(ans);
} else {
System.out.println(budget / plastic);
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int budget = scanner.nextInt();
int plastic = scanner.nextInt();
int glass = scanner.nextInt();
int refund = scanner.nextInt();
maxLitres(budget, plastic, glass, refund);
}
}
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
def maxLitres(budget, plastic, glass, refund):
if glass - refund < plastic:
ans = max((budget - refund) // (glass - refund), 0)
budget -= ans * (glass - refund)
ans += budget // plastic
print(ans)
else:
print(budget // plastic)
budget = int(input())
plastic = int(input())
glass = int(input())
refund = int(input())
maxLitres(budget, plastic, glass, refund)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
question 13
I guess you all remember that number game where you used to ask your
friend to choose a number, then multiply it by some number, then add by some
number, and after doing multiple operations, then the answer.
And you were successfully able to find that initial number that was chosen by
your friend the be02ginning of the game.
We are going to make something similar to this. So, you asked your friend to
choose a number N, and multiply it by a given number A.
Next, your friend has to choose a divisor of N, let's say 'Z', and add it to the
above product. Now the final result becomes a number say X.
If we frame it as an equation, it can be represented as X = AN
So, now you know the value of A and X. Your task is to find the number N,
which was chosen by your friend. The values of N can be multiple, You have to
print all the possible values separated by SPACE. If there is no valid value of N,
then reply None. This means your friend didn't give you the correct reply.
question 13
Let us try to understand it with an example.
Consider you have given a value of A = 3 and finally received the output value x
= 35 Putting the values in equation X=A*N+Z,we get:
35-3*N+Z, and Z is one of the divisors of N. With a smaller number like 1 or 2,
this is not possible. So, we will start with some bigger numbers such as N = 8
Then Z can be 2 or 4 or 8, but in that case, the result will be even, but the
answer is odd. So, we move to the next value 9.
With N = 9 ,Z can be 3putting this in the equation: 35 =3*N+Z, and Z is one of
the divisors of N.
3*9+3 = 30 which doesn't matches with 35. So, we move
to the next integer.
With N = 10 , Z can be 2 or 5, putting this in the equation:
35=3*N+Z
With Z = 2
question 13
3 + 10 + 2 = 32 still not equal to 35.
With z = 5
3*10 + 5 = 35 , still now equal to 35.
So, one of the values of N is 10.
Likewise, if we proceed, we cannot find any other value which could satisfy the
above conditions.
So, the output is only 10.
Example 1:
Input:
50 5 -> Input integer, A, X
Output:
None ->Output
question 13
Input format:
First Input Accept value of Integer A.
Second Input-Accept value of Integer, K (Next Line).
Output format :
question 13
The output are either None or integers values (separated by space) value as
per above logic. (Check the output in Example 1, Example 2). Additional
messages in output will cause the failure of test cases.
Constraints:
1 <= xx = 1000000
1 <= A <= X
Only positive integer values
#include <stdio.h>
int isDivisor(int number, int divisor)
{
return number % divisor == 0;
}
int main()
{
// Get user inputs
int X, A;
scanf("%d", &X);
scanf("%d", &A);
for (int N = 1; N <= X; N++)
{
for (int Z = 1; Z <= N; Z++)
{
if (X == A * N + Z && isDivisor(N, Z))
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
{
printf("%d", N);
// Exit the loops as the equation is satisfi
ed
return 0;
}
}
}
printf("None"); // If no values of N and Z sat
isfy the equation
return 0;
}
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#include <iostream>
using namespace std;
bool isDivisor(int number, int divisor)
{
return number % divisor == 0;
}
int main()
{
// Get user inputs
int X, A;
cin >> X;
cin >> A;
for (int N = 1; N <= X; N++)
{
for (int Z = 1; Z <= N; Z++)
{
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
if (X == A * N + Z && isDivisor(N, Z))
{
cout << N;
// Exit the loops as the equation is satisfi
ed
return 0;
}
}
}
cout << "None"; // If no values of N and Z s
atisfy the equation
return 0;
}
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
import java.util.Scanner;
public class Main {
public static boolean isDivisor(int number, i
nt divisor) {
return number % divisor == 0;
}
public static void main(String[] args) {
// Get user inputs
Scanner scanner = new Scanner(System.i
n);
int X = scanner.nextInt();
int A = scanner.nextInt();
scanner.close();
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
for (int N = 1; N <= X; N++) {
for (int Z = 1; Z <= N; Z++) {
if (X == A * N + Z && isDivisor(N, Z)) {
System.out.print(N);
// Exit the loops as the equation is
satisfied
return;
}
}
}
System.out.print("None"); // If no values
of N and Z satisfy the equation
}
}
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
def isDivisor(number, divisor):
return number % divisor == 0
X, A = map(int, input().split())
for N in range(1, X+1):
for Z in range(1, N+1):
if X == A * N + Z and isDivisor(N, Z):
print(N)
exit()
print("None")
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
QUESTION 14
In the city of Tasgi, the array of competition is going on.You have been
invited to the game is as follows:
You are given an array A of size N.
The array is called good if and only if an integer 1 k N. Such that a1 <
≤ ≤
a2<….. <ak and ak >ak+1 > ak+2 >> aN.
You can do the following operation. i.e., select any index (i) such that ai > 0
and decrease the ai by 1. (ie., a¡= a¡-1)
The prize money for winners in that competition is 1 million dollars.
So, You want to win.
Print Yes if it is possible to make an array good by using operation as many
times you want else No
Example - 1:
Input:
6 ->N(number of elements of an array)
100 11 15 9 7 8 ->N elements of an array
QUESTION 14
Output:
Yes
Explanation:
We can transform the array into [3.11.15,9.74] (decrease the first element
97 times and decrease the last element 4 times). It is good because
3<11<15 and 15>9>7>4
Example 2:
Input:
3
12 10 8
Output:
Yes
#include <stdio.h>
int isGoodArray(int* nums, int n)
{
int maxNum = nums[0];
int minNum = nums[n - 1];
for (int i = 1; i < n; i++)
{
if (nums[i] >= maxNum || nums[i] <=
minNum)
{
return 0;
}
maxNum = nums[i];
}
return 1;
}
int main()
{
int N;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
scanf("%d", &N);
int nums[N];
for (int i = 0; i < N; i++)
{
scanf("%d", &nums[i]);
}
int first = nums[0];
int last = nums[N - 1];
if (first > last)
{
printf("Yesn");
}
else
{
if (isGoodArray(nums, N))
{
printf("Yesn");
}
else
{
printf("Non");
}
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#include <iostream>
#include <vector>
using namespace std;
bool isGoodArray(vector<int>& nums)
{
int n = nums.size();
int maxNum = nums[0];
int minNum = nums[n - 1];
for (int i = 1; i < n; i++)
{
if (nums[i] >= maxNum || nums[i] <=
minNum)
{
return false;
}
maxNum = nums[i];
}
return true;
}
int main()
{
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
cin >> N;
vector<int> nums(N);
for (int i = 0; i < N; i++)
{
cin >> nums[i];
}
int first = nums[0];
int last = nums[N - 1];
if (first > last)
{
cout << "Yes" << endl;
}
else
{
cout << "No" << endl;
}
return 0;
}
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
import java.util.Scanner;
public class Main {
public static boolean isGoodArray(int[] nums, int n) {
int maxNum = nums[0];
int minNum = nums[n - 1];
for (int i = 1; i < n; i++) {
if (nums[i] >= maxNum || nums[i] <= minNum) {
return false;
}
maxNum = nums[i];
}
return true;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int N = scanner.nextInt();
int[] nums = new int[N];
for (int i = 0; i < N; i++) {
nums[i] = scanner.nextInt();
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
int first = nums[0];
int last = nums[N - 1];
if (first > last) {
System.out.println("Yes");
} else {
if (isGoodArray(nums, N)) {
System.out.println("Yes");
} else {
System.out.println("No");
}
}
}
}
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
def is_good_array(nums):
max_num = nums[0]
min_num = nums[-1]
for num in nums[1:]:
if num >= max_num or num <= min_num:
return False
max_num = num
return True
N = int(input())
nums = list(map(int, input().split()))
first = nums[0]
last = nums[-1]
if first > last:
print("Yes")
else:
if is_good_array(nums):
print("Yes")
else:
print("No")
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
QUESTION 15
The lanes of the city market are very narrow and always bustling with
crowds. There is no space for parking 2 or 4 wheelers. To solve this problem
the officials of the area have converted a nearby open space into parking
area. Vehicles can be parked in 2 separate lanes. There is space for N
number of vehicles in each lane. Every parked vehicle has a specific amount
of fuel in the tank. The amount of fuel in which each vehicle is represented
by following series :
Lane 1 : b, b+a, b+2a…..b+(n-1)a
Lane 2 : d,d+c, d+2c,…..d+(n-1)c
The above two series will have the same value at some point in series. The
task here is to find the value which will be the same in both series. Also,
display a message as “No same amount of fuel found” if there is no value
that is the same in both the series.
Note:
Values a, b, c, d in the series non zero values
QUESTION 15
Example 1 :
Input :
50 ->Value of N
20 ->Value of a
2 ->Value of b
9 -> Value of c
19->Value of d
Output :
82 ->same value in both the series
Explanation:
from the table we can deduce the output is 82
QUESTION 15
LANE 1 SERIES LANE 2 SERIES
b 2 d 28
b+a 22 d+a 37
b+2a 42 d+2a 46
b+3a 62 d+3a 55
b+4a 82 d+4a 64
b+5a 102 d+5a 73
b+6a 122 d+6a 82
b+7a 142 d+7a 91
b+(n-1)a 982 d+(n-1)d 460
QUESTION 15
Example 2 :
Input :
9 >Value of N
2 ->Value of a
2 ->Value of b
10->Value of c
15 -> Value of d
Output :
No same amount of fuel found
Explanation:
QUESTION 15
LANE 1 SERIES LANE 2 SERIES
b 2 d+c 25
b+a 4 d+2c 35
b+2a 6 d+3c 45
b+3a 8 d+4c 55
b+4a 10 d+5c 65
b+5a 12 d+6c 75
b+6a 14 d+7c 85
b+7a 16 d+8c 95
b+8a 18
#include <stdio.h>
int findCommonFuel(int N, int a, int b, int c, int d)
{
for (int i = 0; i < N; i++)
{
int fuelInLane1 = b + (a * i);
for (int j = 0; j < N; j++)
{
int fuelInLane2 = d + (c * j);
if (fuelInLane1 == fuelInLane2)
{
return fuelInLane1;
}
}
}
return -1; // No same amount of fuel found
}
int main()
{
int N, a, b, c, d;
scanf("%d", &N);
scanf("%d", &a);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
scanf("%d", &c);
scanf("%d", &d);
int commonFuel = findCommonFuel(N, a, b, c, d);
if (commonFuel == -1)
{
printf("No same amount of fuel foundn");
}
else
{
printf("%d",commonFuel);
}
return 0;
}
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#include <iostream>
using namespace std;
int findCommonFuel(int N, int a, int b, int c, int d)
{
for (int i = 0; i < N; i++)
{
int fuelInLane1 = b + (a * i);
for (int j = 0; j < N; j++)
{
int fuelInLane2 = d + (c * j);
if (fuelInLane1 == fuelInLane2)
{
return fuelInLane1;
}
}
}
return -1; // No same amount of fuel found
}
int main()
{
int N, a, b, c, d;
cin >> N;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
cin >> a;
cin >> b;
cin >> c;
cin >> d;
int commonFuel = findCommonFuel(N, a, b, c, d);
if (commonFuel == -1)
{
cout << "No same amount of fuel found" << endl;
}
else
{
cout << commonFuel;
}
return 0;
}
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
import java.util.Scanner;
public class Main
{
public static int findCommonFuel(int N, int a, int b, int c, int d)
{
for (int i = 0; i < N; i++) {
int fuelInLane1 = b + (a * i);
for (int j = 0; j < N; j++)
{
int fuelInLane2 = d + (c * j);
if (fuelInLane1 == fuelInLane2)
{
return fuelInLane1;
}
}
}
return -1; // No same amount of fuel found
}
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
int N = scanner.nextInt();
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
int b = scanner.nextInt();
int c = scanner.nextInt();
int d = scanner.nextInt();
int commonFuel = findCommonFuel(N, a, b, c, d);
if (commonFuel == -1)
{
System.out.println("No same amount of fuel found");
}
else
{
System.out.println(commonFuel);
}
}
}
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
def find_common_fuel(N, a, b, c, d):
for i in range(N):
fuel_in_lane1 = b + (a * i)
for j in range(N):
fuel_in_lane2 = d + (c * j)
if fuel_in_lane1 == fuel_in_lane2:
return fuel_in_lane1
return -1 # No same amount of fuel found
N = int(input())
a = int(input())
b = int(input())
c = int(input())
d = int(input())
common_fuel = find_common_fuel(N, a, b, c, d)
if common_fuel == -1:
print("No same amount of fuel found")
else:
print(common_fuel)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
question 16
jack is a sports teacher at St. Patrick’s School. He makes games not only to make
the student fit, but also smart .So, he lined up all the N number of students in
his class. At each position he has fixed a board with the integer number printed
on it. Each of the numbers are unique and are in exactly the range of N. Let us
say there are 10 students, then the boards will be printed with numbers from 1
to 10 in a random order given by the sequence A[].
As a rule, all students wear a jersey with their numbers printed on it. So, if there
are N students, each will have a number, just like a football team.
Now, in the beginning, all the students will stand as per the increasing order of
their jersey numbers, from left to right.
The only difference will be their respective board number which is placed at
their respective location. The board location is fixed and cannot be changed. We
can consider the arrangement as below. Suppose there are 5 students, and the
board is placed in the order of [23154]
question 16
Board-2, 3, 1, 5,4
Student's Jersey-1,2,3,4,5
Now the game begins.
•After every beat of the drum, each student will have to move to that location
(index), where his board is pointing to. In the above case student with jersey #1
is standing with board #2, so now he will have to move to location #2. Similarly,
all the other students will do.
So after first beat of the drum, the alignment will be:
Board 2, 3, 1, 5, 4
Student's Jersey --3. 1, 2, 5.4
Jersey #1 has moved to Index2.
Jersey #2 has moved to Index 3.
Jersey #3 has moved to index 1.
Jersey #4 has moved to index 5.
Jersey #5 has moved to Index 4.
question 16
Now again with the next beat of the drum, same task as shown below:
Board - 2, 3, 1, 5, 4
Student's Jersey-2,3,1,4,5
Jersey #3 has moved to index 2.
Jersey #1 has moved to index 3.
Jersey #2 has moved to index 1.
Jersey #5 has moved to index 5.
Jersey #4 has moved to index 4.
This keeps going on and on, until all the students are back the way they were at
the beginning. So ,after 6 beats of the drum, all the students will be aligned the
same way as before. Given N and the order of board of the respective positions,
find the number of beats required to bring back the students to their original
position.
So ,for the above case the answer is 6.
question 16
Example 1:
Input:
3 ->Input integer, N
1 2 3->Input integer 9[] board alignment
Output:
1->Output
Explanation:
All the students will be standing as below,with the board positions:
Board-1,2,3
Student jersey- 1,2,3
After first beat of drum:
Jersey #1 has moved to index 1.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int n;
scanf("%d", &n);
int* B = (int*)malloc(n * sizeof(int));
for (int i = 0; i < n; i++)
{
scanf("%d", &B[i]);
}
int* arr = (int*)malloc(n * sizeof(int));
for (int i = 0; i < n; i++)
{
arr[i] = i + 1;
}
int ans = 0;
int* original_arr = (int*)malloc(n * sizeof(int));
for (int i = 0; i < n; i++)
{
original_arr[i] = arr[i];
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
while (1)
{
ans++;
int* ar = (int*)malloc(n * sizeof(int));
for (int i = 0; i < n; i++)
{
ar[i] = arr[B[i] - 1];
}
int isEqual = 1;
for (int i = 0; i < n; i++)
{
if (ar[i] != original_arr[i])
{
isEqual = 0;
break;
}
}
if (isEqual)
{
free(ar);
break;
}
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
free(arr);
arr = ar;
}
printf("%dn", ans);
free(B);
free(arr);
free(original_arr);
return 0;
}
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main()
{
int n;
cin >> n;
vector<int> B(n);
for (int i = 0; i < n; i++)
{
cin >> B[i];
}
vector<int> arr(n);
for (int i = 0; i < n; i++)
{
arr[i] = i + 1;
}
int ans = 0;
vector<int> original_arr = arr; // Store the original arrangement
while (true)
{
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
ans++;
vector<int> ar(n);
for (int i = 0; i < n; i++)
{
ar[i] = arr[B[i] - 1];
}
if (ar == original_arr)
{
break;
}
arr = ar;
}
cout << ans << endl;
return 0;
}
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
List<Integer> B = new ArrayList<>();
for (int i = 0; i < n; i++)
{
B.add(scanner.nextInt());
}
List<Integer> arr = new ArrayList<>();
for (int i = 0; i < n; i++)
{
arr.add(i + 1);
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
int ans = 0;
List<Integer> originalArr = new ArrayList<>(arr); // Store the original arrangement
while (true)
{
ans++;
List<Integer> ar = new ArrayList<>();
for (int i = 0; i < n; i++)
{
ar.add(arr.get(B.get(i) - 1));
}
if (ar.equals(originalArr))
{
break;
}
arr = new ArrayList<>(ar);
}
System.out.println(ans);
}
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
n = int(input())
B = list(map(int, input().split()))
arr = list(range(1, n+1))
ans = 0
while True:
ans += 1
ar = [None] * n
for i in range(n):
ar[i] = arr[B[i] - 1]
if ar == sorted(ar):
break
arr = ar
print(ans)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
question 17
Joe is playing a game where there are N group of balloons. He is given a gun
which can shoot one round per minute.
For each round it can hit 1 balloon in K groups each.If the group has zero
balloons left, then we say that particular group is destroyed completely, and it
would not be counted. The gun is deactivated if the number of groups falls
below K.
Find the maximum number of minutes the gun will be activated based on the
above factors.
Let us try to understand it with an example.
Let say there are N groups N=5 and K = 3 means if there are less than 3 groups
the gun will be de-activated. In order to stay in the game for longer time, he will
play optimally. Also note that the K group may be formed arbitrary selecting K
members from N groups.
Each of the 5 groups has below number of balloons :
B = [4,3,5,6,7]
question 17
So, in the beginning this is the configuration of all groups with their respective
balloons: 4 3 5 6 7
Below the timeline:
Minute 1: the gun takes 1 shot and it will hit 1 balloon in k=3 groups, now the
configuration of each group will be: 4 3 3 4 5 6
Minute 2: the gun takes 1 shot and it will hit 1 balloon in K =3 group, now the
configuration of each group will be: 4 3 3 4 5
Minute 3: the gun takes 1 shot a -3 group, now the configuration of each group
will be 4 3 2 3 4
Minute 4: the gun takes 1 shot and it will hit 1 balloon in K =3 group, now the
configuration of each group will be: 3 3 2 2 3
Minute 5:the gun takes 1 shot and it will hit 1 balloon in K =3 group, the
configuration of each group will be: 3 3 1 1 2.
Minute 6: the gun takes 1 shot and it will hit 1 balloon in K =3 group, now the
configuration of each group will be: 22 1 1 1
question 17
Minute 7: the gun takes 1 shot and it will hit 1 balloon in K=3 group, now the
configuration of each group will be 1 1 0 1 1
Minute 8: the gun takes 1 shot and it will hit 1 balloon in K =3 group, now the
configuration of each group will be:0 0 0 0 1
Now there are less than K-3 groups, other have lost all their balloons. And the
maximum time Joe was busy was 8 minutes.
So, the final answer is 8
The input format for testing:
First Input-Accept value of Integer, N
Second Input -Accept value of Integer, K (Next Line)
Next 'N' Lines-Elements of sequence B
The Output format for testing:
question 17
The output is an integer value as per above logic (Check the output in Example
1, Example 2)
Additional messages in output will cause the failure of test cases.
Constraints:
1<= N<=1000
1 <= K<=N
1<=B[]<=100000
Only integer values
Example 1:
Input:
2-> Input integer N
2-> Input integer
2 -> Input integer, B[]
3 ->Input integer, B
question 17
Output:
2 ->output
Explanation:
In the above example, there are K=2 groups whicha gun can fire at a time.
Initial configuration of each groups : 2 3
Minute 1: the gun takes 1 shot and it will hit 1 balloon in k -2 groups, now the
configuration of each group will be: 1 2
Minute 2: the gun takes 1 shot and it will hit 1 balloon in K -2 group, now the
configuration of each group will be: 0 1
Now there are less than K-2 groups, other have lost all their balloons. And the
maximum time Joe was busy was 2 minutes.
Example 2:
question 17
Input:
5-> Input integer N
3-> Input integer K
4 -> Input integer, B[]
3 ->Input integer, B[]
5 ->Input integer, B[]
6 ->Input integer, B[]
7 ->Input integer, B[]
Output:
8 ->output
#include <stdio.h>
#include <stdlib.h>
int compare(const void *a, const void *b)
{
return (*(int*)b - *(int*)a);
}
int getMaxActiveTime(int N, int K, int* balloons)
{
qsort(balloons, N, sizeof(int), compare);
int minutes = 0;
int remainingGroups = N;
while (remainingGroups >= K)
{
for (int i = 0; i < K; i++)
{
balloons[i] -= 1;
if (balloons[i] == 0)
{
remainingGroups--;
}
}
minutes++;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
qsort(balloons, N, sizeof(int), compare);
}
return minutes;
}
int main()
{
int N, K;
scanf("%d %d", &N, &K);
int* balloons = (int*)malloc(N * sizeof(int));
for (int i = 0; i < N; i++)
{
scanf("%d", &balloons[i]);
}
int result = getMaxActiveTime(N, K, balloons);
printf("%dn", result);
free(balloons);
return 0;
}
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int getMaxActiveTime(int N, int K, vector<int>& balloons)
{
sort(balloons.rbegin(), balloons.rend()); // Sort balloons in descending order
int minutes = 0;
int remainingGroups = N;
while (remainingGroups >= K)
{
for (int i = 0; i < K; i++)
{
balloons[i] -= 1; // Shoot one balloon in K groups
if (balloons[i] == 0)
{
remainingGroups--; // Reduce the count of remaining groups
}
}
minutes++; // Increment the minutes
sort(balloons.rbegin(), balloons.rend()); // Sort balloons again
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
return minutes;
}
int main()
{
int N, K;
cin >> N >> K;
vector<int> balloons(N);
for (int i = 0; i < N; i++)
{
cin >> balloons[i];
}
int result = getMaxActiveTime(N, K, balloons);
cout << result << endl;
return 0;
}
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
import java.util.*;
public class Main
{
public static int getMaxActiveTime(int N, int K, List<Integer> balloons)
{
Collections.sort(balloons, Collections.reverseOrder()); // Sort balloons in descending
order
int minutes = 0;
int remainingGroups = N;
while (remainingGroups >= K)
{
for (int i = 0; i < K; i++)
{
int balloon = balloons.get(i) - 1; // Shoot one balloon in K groups
balloons.set(i, balloon);
if (balloon == 0)
{
remainingGroups--; // Reduce the count of remaining groups
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
minutes++; // Increment the minutes
Collections.sort(balloons, Collections.reverseOrder()); // Sort balloons again
}
return minutes;
}
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
int N = scanner.nextInt();
int K = scanner.nextInt();
List<Integer> balloons = new ArrayList<>();
for (int i = 0; i < N; i++)
{
balloons.add(scanner.nextInt());
}
int result = getMaxActiveTime(N, K, balloons);
System.out.println(result);
}
}
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
def get_max_active_time(N, K, balloons):
balloons.sort(reverse=True) # Sort balloons in descending order
minutes = 0
remaining_groups = N
while remaining_groups >= K:
for i in range(K):
balloon = balloons[i] - 1 # Shoot one balloon in K groups
balloons[i] = balloon
if balloon == 0:
remaining_groups -= 1 # Reduce the count of remaining groups
minutes += 1 # Increment the minutes
balloons.sort(reverse=True) # Sort balloons again
return minutes
N = int(input())
K = int(input())
balloons = []
for _ in range(N):
balloons.append(int(input()))
result = get_max_active_time(N, K, balloons)
print(result)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
question 18
Mike came up with a new way of sorting a string. What he does is he takes all
the unique alphabets from the string and sorts it in that order. Let say there is a
string "apple", now it contains a p l e as distinct alphabets.
He sorts the string apple based on his own keys let say eapl. So, first all "e" will
be picked from the string "apple", and then all "a", and so on till "T". Hence the
final sorted word becomes "eappl".
The Input format for testing
The candidate has to write the code to accept 2 input(s)
•First Input - Accept value for input string.
•First Input - Accept value for input key.
The Output format for testing
question 18
•The output should be a sorted string based on the input key given by the user
as mentioned in the above criteria. (Check the output in Example 1, Example 2)
•Additional messages in output will cause the failure of test cases.
Constraints:
0<length(input String)<=50
Input key should contain all the alphabets of inputstrings
No duplicates in input keys.
Example 1:
Input:
apple->Input string
eapl -> Input string, sorting key value
question 18
Output:
eappl->output string with sorted value based on the user keys.
Explanation:
The input by the user is "apple” and the key is "eapl". So, as per the key, all "e"
has to be sorted first. Then all the a's and the all the p's, and finally all the
1’s .Note that here we have 2 p's so they will be sorted together in the output.
Putting everything together the final string comes as “eappl”
Example 2:
Input:
welcome ->input string
lowmec -> input string,sorting key value
question 18
Output:
lowmeec ->output string with sorted value based on the user keys.
Explanation:
The input by the user is “welcome” and the key is “lowmec". So, as per the key,
all 1’s has to be sorted first,then all the 0's and then all the w's and then all the
m's ,the all the e's, and finally all the c’s .Note that here we have 2 p's so they will
be sorted together in the output. Putting everything together the final string
comes as “lowmeec”
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
char* sortString(const char* input, const char* key)
{
size_t len = strlen(input);
char* sortedString = malloc((len + 1) * sizeof(char));
strcpy(sortedString, input);
for (int i = 0; i < len; i++)
{
for (int j = i + 1; j < len; j++)
{
char a = tolower(sortedString[i]);
char b = tolower(sortedString[j]);
const char* indexA = strchr(key, a);
const char* indexB = strchr(key, b);
if (indexA != NULL && indexB != NULL && indexA > indexB)
{
char temp = sortedString[i];
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
sortedString[i] = sortedString[j];
sortedString[j] = temp;
}
}
}
return sortedString;
}
int main()
{
char input[100];
char key[100];
scanf("%s %s", input, key);
char* sortedString = sortString(input, key);
printf("%sn", sortedString);
free(sortedString);
return 0;
}
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#include <iostream>
#include <string>
using namespace std;
string sortString(const string& input, const string& key)
{
string sortedString = input;
// Sort the string using the key as the custom sorting criterion
for (int i = 0; i < sortedString.length(); i++)
{
for (int j = i + 1; j < sortedString.length(); j++)
{
char a = tolower(sortedString[i]);
char b = tolower(sortedString[j]);
size_t indexA = key.find(a);
size_t indexB = key.find(b);
if (indexA > indexB)
{
swap(sortedString[i], sortedString[j]);
}
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
return sortedString;
}
int main()
{
string input, key;
cin >> input >> key;
string sortedString = sortString(input, key);
cout << sortedString << endl;
return 0;
}
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
import java.util.Scanner;
public class Main
{
public static String sortString(String input, String key)
{
char[] sortedString = input.toCharArray();
// Sort the string using the key as the custom sorting criterion
for (int i = 0; i < sortedString.length; i++)
{
for (int j = i + 1; j < sortedString.length; j++)
{
char a = Character.toLowerCase(sortedString[i]);
char b = Character.toLowerCase(sortedString[j]);
int indexA = key.indexOf(a);
int indexB = key.indexOf(b);
if (indexA > indexB)
{
char temp = sortedString[i];
sortedString[i] = sortedString[j];
sortedString[j] = temp;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
return new String(sortedString);
}
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
String input = scanner.next();
String key = scanner.next();
String sortedString = sortString(input, key);
System.out.println(sortedString);
}
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
def sort_string(input_str, key):
sorted_str = list(input_str)
# Sort the string using the key as the custom sorting criterion
for i in range(len(sorted_str)):
for j in range(i + 1, len(sorted_str)):
a = sorted_str[i].lower()
b = sorted_str[j].lower()
index_a = key.find(a)
index_b = key.find(b)
if index_a > index_b:
sorted_str[i], sorted_str[j] = sorted_str[j], sorted_str[i]
return ''.join(sorted_str)
input_str = input()
key = input()
sorted_string = sort_string(input_str, key)
print(sorted_string)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
question 19
Mikes likes to play with numbers. His friends are also good with numbers and
often plays mathematical games. They made a small game where they will spell
the last digit of a factorial of a number other than 0. Let say the given number is
5, so 5! (5 factorial) will be
5 *4* 3* 2* 1= 120.
Here 0 is the last digit. But, we don't want 0, we want a
number other than 0.
Then the last digit is 2. This is what we have to output
Example 1:
Input
5 ->Input number
Output
2->last non-zero digit
question 19
Explanation:
Input number is 5, so 5!=120. The last nonzero digit is 2. And this is the output.
Example 2
Input:
9-> Input number.
Output:
8-> last non-zero digit
Explanation:
Input number is 9, so 9!=362880. The last nonzero digit is 8. And this is the
output.
question 19
Constraints:
•1<=input number<105
•Only integers
The candidate has to write the code to accept 2 input(s)
•First input-Accept the value of integer
The output format for testing
•The output is the last nonzero digit, of a factorial of the input number (Checks
the output in Example 1, Example 2).
Additional messages in output will cause the failure of test cases.
Instructions
•System doesn’t allow any kind of hard coded input.
•Written program cade by the candidate will be verified against inputs which are
supplied from the system.
#include <stdio.h>
//Recursive function to calculate the factorial
int fact(int n)
{
if(n <= 1) //Base Condition
return 1;
return n*fact(n-1);
}
int main()
{
int n;
scanf("%d",&n);
int factorial = fact(n);
while(factorial%10==0)
{
factorial /= 10;
}
printf("%d",factorial%10);
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>
using namespace std;
int fact(int n)
{
if (n <= 1) // Base Condition
return 1;
return n * fact(n - 1);
}
int main()
{
int n;
cin>>n;
int factorial = fact(n);
while (factorial % 10 == 0)
{
factorial /= 10;
}
cout << factorial % 10;
return 0;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import java.util.Scanner;
public class Main
{
// Recursive function to calculate the factorial
public static int fact(int n)
{
if (n <= 1) // Base Condition
return 1;
return n * fact(n - 1);
}
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int factorial = fact(n);
while (factorial % 10 == 0)
{
factorial /= 10;
}
System.out.println(factorial % 10);
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
def fact(n):
if n <= 1: # Base Condition
return 1
return n * fact(n - 1)
n = int(input())
factorial = fact(n)
while factorial % 10 == 0:
factorial //= 10
print(factorial % 10)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
sortedString[i] = sortedString[j];
sortedString[j] = temp;
}
}
}
return sortedString;
}
int main()
{
char input[100];
char key[100];
scanf("%s %s", input, key);
char* sortedString = sortString(input, key);
printf("%sn", sortedString);
free(sortedString);
return 0;
}
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
question 20
Raju is a traveller and travels to many different places around the world.
This time he went to an island that had its own currency. They only have 2 coin
system currency. They call Aana, and these are coins. So in this islands they
have either 1-Aana or 2- Aana.
Just like all the other coins these Aana also have their heads and tails.
Also, while paying anything to the shopkeeper here, you have tofollow their
ritual and ritual says,
•There is a wooden board at each shop where a customer places the coins in a
squences while paying to shopkeeper.
•You should always place the coin on a wooden board just like a squences.
•The first coin in the sequence should always be facing the side of head.
Now your task is to find out in how many ways he can pay the shopkeeper here,
given some Xamount. The answer can be huge, so you can give an output with
module 109+7.
Let us try understand it with an example.
question 20
Consider that Raj has to pay 2 cents to the shopkeeper, so X=10.
He can pay it as either 2coins of 1-Aana or 1coin of 2-Aana.
2coins of 1-Aana can be given as below:
•First coin placed as H, other coin can be as H(heads).
•First coin placed as H, other coin be as T(tails).
1coin of 2-Aana can be given as below:
•Firstcoin placed as H.
•No other combination for 2-Aana coin can exists.
Hence total of 3 different combinations can exist to pay a sum of 3-Aana value.
Hence the answer is 3.
Given X, find out different number of ways in which Raj can pay to the
shopkeeper.
Example 1:
Input:
1->Input integer, X
question 20
Output:
1->output
Explanation:
If the amount which we have to pay is just 1, then we can pay it with just one
coin, which 1-Aana and the combination for it will be just 1-H
Hence the answer is 1.
Example 2:
Input:
2->Input integer,
Output:
3->Output
question 20
Explanation:
In this scenario where, he need to pay 2-Aana to the shopkeeper, he can pay it
as either 2 coins of 1-Aana or one coin of 2-Aana
2 coin of 1-Aana can be given as below:
•First coin placed as H, other coins can be as H(heads)
•First coin placed as H, other coins can be as T(tails)
1 coin of 2-Aana can be given as below:
•First coin placed as H.
#include <stdio.h>
#include <stdlib.h>
#define MOD 1000000007
int countPaymentWays(int X)
{
if (X == 1)
return 1;
if (X == 2)
return 3;
int* dp = (int*)malloc((X + 1) * sizeof(int));
dp[0] = 1;
dp[1] = 1;
dp[2] = 3;
for (int i = 3; i <= X; i++)
{
dp[i] = (dp[i - 1] + dp[i - 2]) % MOD;
}
int ways = dp[X];
free(dp);
return ways;
}
int main()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
{
int X;
scanf("%d", &X);
int ways = countPaymentWays(X);
printf("%dn", ways);
return 0;
}
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#include <iostream>
#include <vector>
using namespace std;
const int MOD = 1e9 + 7;
int countPaymentWays(int X)
{
if (X == 1)
return 1;
if (X == 2)
return 3;
vector<int> dp(X + 1, 0);
dp[0] = 1;
dp[1] = 1;
dp[2] = 3;
for (int i = 3; i <= X; i++)
{
dp[i] = (dp[i - 1] + dp[i - 2]) % MOD;
}
return dp[X];
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
int main()
{
int X;
cin >> X;
int ways = countPaymentWays(X);
cout <<ways;
return 0;
}
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
import java.util.Scanner;
public class Main
{
private static final int MOD = 1000000007;
public static int countPaymentWays(int X)
{
if (X == 1)
return 1;
if (X == 2)
return 3;
int[] dp = new int[X + 1];
dp[0] = 1;
dp[1] = 1;
dp[2] = 3;
for (int i = 3; i <= X; i++)
{
dp[i] = (dp[i - 1] + dp[i - 2]) % MOD;
}
return dp[X];
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
int X = scanner.nextInt();
int ways = countPaymentWays(X);
System.out.println(ways);
}
}
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
MOD = 1000000007
def countPaymentWays(X):
if X == 1:
return 1
if X == 2:
return 3
dp = [0] * (X + 1)
dp[0] = 1
dp[1] = 1
dp[2] = 3
for i in range(3, X + 1):
dp[i] = (dp[i - 1] + dp[i - 2]) % MOD
return dp[X]
X = int(input())
ways = countPaymentWays(X)
print(ways)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
Set C
question 21
A game company has designed an online lottery game. Bingo, in this game, N
number cards are displayed. Each card has a value on it. The value can be
negative or positive. The player must choose two cards. To win one game, the
product of the values of the two cards must be maximum value possible for any
pair of cards in the display. The winning amoint will be the sum of the two cards
chosen by the player.
Write an algorithm to find the winning amount as the sum of the value of the
cards whose product value is maximum.
Input
The second line consists of N space-separated integers - val1, val2....., valN
representing the values on the cards.
Output
Print an integer representing the sum of the values of the two cards whose
product value is maximum.
question 21
Constraints
0 < numCards < 106
-106 < vali < 106
0 < i < numCards
Example
Input:
7
9 -3 8 -6 -7 8 10
Output:
19
Explanation:
The maximum product of the values of is 90, i.e. 9*10.
So the sum of the values of the selected cards is 19.
#include <stdio.h>
int main() {
int numCustomers;
scanf("%d", &numCustomers);
int balance[numCustomers];
for (int i = 0; i < numCustomers; i++) {
scanf("%d", &balance[i]);
}
int product = 0; // smallest product
int sum = 0; // sum of two balance values whose product is the smallest
for (int i = 0; i < numCustomers - 1; i++) {
for (int j = i + 1; j < numCustomers; j++) {
if (balance[i] * balance[j] > product) {
product = balance[i] * balance[j];
sum = balance[i] + balance[j];
}
}
}// display output
printf("%dn", sum);
return 0;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>
#include <vector>
int main() {
int numCustomers;
std::cin >> numCustomers;
std::vector<int> balance(numCustomers);
for (int i = 0; i < numCustomers; i++) {
std::cin >> balance[i];
}
int product = 0; // smallest product
int sum = 0; // sum of two balance values whose product is the smallest
for (int i = 0; i < numCustomers - 1; i++) {
for (int j = i + 1; j < numCustomers; j++) {
if (balance[i] * balance[j] > product) {
product = balance[i] * balance[j];
sum = balance[i] + balance[j];
}
}
}
// display output
std::cout << sum << std::endl;
return 0;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int numCustomers = scan.nextInt();
int[] balance = new int[numCustomers];
for(int i=0; i<numCustomers; i++) {
balance[i] = scan.nextInt();
}
int product = 0;//smallest product
int sum=0; //sum of 2 balance values whose product is the smallest
for(int i=0; i<numCustomers-1; i++) {
for(int j=i+1; j<numCustomers; j++) {
if(balance[i]*balance[j] > product) {
product = balance[i] * balance[j];
sum = balance[i] + balance[j];
}
}
}
//display output
System.out.println(sum);
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
numCustomers = int(input())
balance = []
for _ in range(numCustomers):
balance.append(int(input()))
product = 0 # smallest product
sum_values = 0 # sum of two balance values whose product is the smallest
for i in range(numCustomers - 1):
for j in range(i + 1, numCustomers):
if balance[i] * balance[j] > product:
product = balance[i] * balance[j]
sum_values = balance[i] + balance[j]
# display output
print(sum_values)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
question 22
A new medicine named "Medio-cine" is out in the market which helps in
treating auto-immune diseases in humans. These are very common in 0-10
year old kids or greater than or equal to 81 year old senior citizens. Both
these age groups are considered at a very high risk.
The government wants to distribute the medicine as soon as possible among
all age groups. There is only one(1) political center from where this medicine
is distributed. In a single day we cannot provide to both high risk and non
high risk age groups.Each person requires only one capsule and there can be
L capsules distributed in a day. The high risk humans are supposed to be
considered first.There are 'N' humans and 'L' capsules per day. Find the
minimum number of days required to medicate all the N humans.
Input format
question 22
Input format
First Line: Contains a Positive Integer denoting N and L denoting number of
medicines.
Next line Contains N elements of the array A space separated denoting age.
Constraints:
1<=N<10000
1<=L=1000
1<=A[i]=1000
Example 1:
Input:
5 2 -> N, L
11 81 27 72 79 -> array A (age of N humans respectively)
question 22
Output:
3 Days
Explanation:
At max 2 can be medicated on a single day One of the optimal solution is 81
on day 11,27 and 72 on day 2. Remaining on day 3
Example 2:
Input:
11 1
10 10 10 10 14 15 57 38 49 28 32
Output:
11
Explanation:
At max 1 can be medicated on a single day
#include <stdio.h>
#include <stdlib.h>
int compare(const void *a, const void *b)
{
return (*(int*)a - *(int*)b);
}
int minimumDays(int N, int L, int *ages)
{
qsort(ages, N, sizeof(int), compare); // Sort the ages in ascending order
int highRiskCount = 0;
int nonHighRiskCount = 0;
// Count the number of high-risk and non-high-risk individuals
for (int i = 0; i < N; i++)
{
if (ages[i] <= 10 || ages[i] >= 81)
{
highRiskCount++;
}
else
{
nonHighRiskCount++;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
}
int days = 0;
while (highRiskCount > 0 || nonHighRiskCount > 0)
{
int capsules = L; // Number of capsules available for the day
// Distribute capsules to high-risk individuals first
while (capsules > 0 && highRiskCount > 0)
{
capsules--;
highRiskCount--;
}
// Distribute capsules to non-high-risk individuals
while (capsules > 0 && nonHighRiskCount > 0)
{
capsules--;
nonHighRiskCount--;
}
days++; // Increment the number of days
}
return days;
}
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
int main()
{
int N, L;
scanf("%d %d", &N, &L);
int *ages = (int*)malloc(N * sizeof(int));
for (int i = 0; i < N; i++)
{
scanf("%d", &ages[i]);
}
int result = minimumDays(N, L, ages);
printf("%d Daysn", result);
free(ages);
return 0;
}
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#include <iostream>
#include <vector>
#include <algorithm>
int minimumDays(int N, int L, std::vector<int>& ages) {
std::sort(ages.begin(), ages.end()); // Sort the ages in ascending order
int highRiskCount = 0;
int nonHighRiskCount = 0;
// Count the number of high-risk and non-high-risk individuals
for (int i = 0; i < N; i++) {
if (ages[i] <= 10 || ages[i] >= 81) {
highRiskCount++;
} else {
nonHighRiskCount++;
}
}
int days = 0;
while (highRiskCount > 0 || nonHighRiskCount > 0) {
int capsules = L; // Number of capsules available for the day
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// Distribute capsules to high-risk individuals first
while (capsules > 0 && highRiskCount > 0) {
capsules--;
highRiskCount--;
}
// Distribute capsules to non-high-risk individuals
while (capsules > 0 && nonHighRiskCount > 0) {
capsules--;
nonHighRiskCount--;
}
days++; // Increment the number of days
}
return days;
}
int main() {
int N, L;
std::cin >> N >> L;
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
std::vector<int> ages(N);
for (int i = 0; i < N; i++) {
std::cin >> ages[i];
}
int result = minimumDays(N, L, ages);
std::cout << result << " Days" << std::endl;
return 0;
}
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;
public class Main
{
public static int minimumDays(int N, int L, List<Integer> ages)
{
Collections.sort(ages); // Sort the ages in ascending order
int highRiskCount = 0;
int nonHighRiskCount = 0;
// Count the number of high-risk and non-high-risk individuals
for (int i = 0; i < N; i++)
{
if (ages.get(i) <= 10 || ages.get(i) >= 81)
{
highRiskCount++;
}
else
{
nonHighRiskCount++;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
}
int days = 0;
while (highRiskCount > 0 || nonHighRiskCount > 0)
{
int capsules = L; // Number of capsules available for the day
// Distribute capsules to high-risk individuals first
while (capsules > 0 && highRiskCount > 0)
{
capsules--;
highRiskCount--;
}
// Distribute capsules to non-high-risk individuals
while (capsules > 0 && nonHighRiskCount > 0)
{
capsules--;
nonHighRiskCount--;
}
days++; // Increment the number of days
}
return days;
}
public static void main(String[] args)
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
{
Scanner scanner = new Scanner(System.in);
int N = scanner.nextInt();
int L = scanner.nextInt();
List<Integer> ages = new ArrayList<>();
for (int i = 0; i < N; i++)
{
ages.add(scanner.nextInt());
}
int result = minimumDays(N, L, ages);
System.out.println(result + " Days");
}
}
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
def minimum_days(N, L, ages):
ages.sort() # Sort the ages in ascending order
high_risk_count = 0
non_high_risk_count = 0
# Count the number of high-risk and non-high-risk individuals
for age in ages:
if age <= 10 or age >= 81:
high_risk_count += 1
else:
non_high_risk_count += 1
days = 0
while high_risk_count > 0 or non_high_risk_count > 0:
capsules = L # Number of capsules available for the day
# Distribute capsules to high-risk individuals first
while capsules > 0 and high_risk_count > 0:
capsules -= 1
high_risk_count -= 1
# Distribute capsules to non-high-risk individuals
while capsules > 0 and non_high_risk_count > 0:
capsules -= 1
non_high_risk_count -= 1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
days += 1 # Increment the number of days
return days
N, L = map(int, input().split())
ages = list(map(int, input().split()))
result = minimum_days(N, L, ages)
print(result, "Days")
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
question 23
Jack and Jill went to a carnival, there are many games counter in the carnival.
And if you win you may get good prizes.
One of the games there was Check-and-win. The game was simple but a bit
tricky. Below are the rules of the game:
• There will be a strip with N integers mentioned on it.
•Each player will get their respective number strips.Each time one player has to
pick a number from the strip. The index chosen by the one player cannot be
used further in the game. We will understand more in below example.
•The next player has to pick a number from another index from their respective
strip. Once that index is used, it won't be used again in the game by either of
the payers.
• At the end of the when all the indexes are checked. The sum will be calculated
for each player.
• The player with the maximum sum will be the winner.
question 23
Jack decided a rule, that he will always start first. Print Jack if he wins, or Jill
when Jill wins. If there is a tie, print Tie.
Considering that both the players are playing optimally. find the output.
Let us try to understand it with an example. Consider the strip of 3 integers.
Means N = 3. Respective strip for Jack and Jill is as follows:
JK: [134]
JL: (531)
The rule says that Jack always plays first.
Step 1: Jack plays first and chooses the largest element his number-strip JK[3] =
4.
Now index 3 is checked.
Step 2: Jill plays next, now she has to find the largest number among index 1
and 2. Within these 2 indices she has the largest number at index 1. So, she
chooses JL[1] Now index 1 is checked.
question 23
Step 3: Its Jack's turn now, and the only index left is 2. So, he chooses JK[2]
Sum of each:
Jack : 4 + 3 =7
jill :5
Clearly jack wins.
Hence the answer is jack.
Input format
First Input -Accept value of Integer, N.
Next 'N' Lines-Elements of sequence JK[]
Next 'N' Lines-Elements of sequence JI[]
Output format
question 23
Step 3: Its Jack's turn now, and the only index left is 2. So, he chooses JK[2]
Sum of each:
Jack : 4 + 3 =7
jill :5
Clearly jack wins.
Hence the answer is jack.
Input format
First Input -Accept value of Integer, N.
Next 'N' Lines-Elements of sequence JK[]
Next 'N' Lines-Elements of sequence JI[]
Output format
question 23
The output is an integer value as per above logic. (Check the output in Example
1, Example 2).
additional messages in output will cause the failure of test cases.
Constraints
1<=N<=1000
1 <= Jk[], JL[]<=10000
Only integer values
Example 1:
Input:
2 ->Input integer , N
1 1->Input integer , Jk[]
2 2->Input integer , JL[]
question 23
Output:
Jill->output
Explanation:
Step 1: Jack plays first and chooses the largest element from his number-strip
JK[1]=1 Now index 1 is checked.
step 2: Jill plays next, now she has to find the largest number only present at
index 2. So, she chooses JL[2] Now index 2 is checked. Sum of each:
Jack=1
Jill=2
Clearly jill wins.
Hence the answer is jill
question 23
Example 2:
Input:
4-> Input integer , N
1 2 3 4->Input integer , Jk[]
4 3 2 1->Input integer , JL[]
Output:
Tie->output
Explanation:
Step 1: Jack plays first and chooses the largest element from his number-strip
JK[4] =4 Now index 4 is checked.
Step 2: Jill plays next, now she has to find the largest number among index 1, 2
and 3, So he chooses JL[1] = 4. Now index 1 is checked.
question 23
Step 3: jack plays next and now he has to find the large number among index 2
and 3. JK[3] =3 Now index 3 is checked.
Step 4: Jill plays next, now she has to find the largest number only present at
index 2. So, he chooses JL[2] = 3 Now index 2 is checked. All indices are checked
now. Sum of each
#include <stdio.h>
#include <stdbool.h>
char* findWinner(int N, int JK[], int JL[])
{
bool checked[N + 1];
for (int i = 0; i <= N; i++)
{
checked[i] = false;
}
int jackSum = 0, jillSum = 0;
for (int i = 0; i < N; i++)
{
int maxJK = -1, maxJL = -1;
// Find the maximum available number for Jack
for (int j = 0; j < N; j++)
{
if (!checked[j] && JK[j] > maxJK)
{
maxJK = JK[j];
}
}
// Mark the chosen index as checked
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
for (int j = 0; j < N; j++)
{
if (JK[j] == maxJK)
{
checked[j] = true;
break;
}
}
// Find the maximum available number for Jill
for (int j = 0; j < N; j++)
{
if (!checked[j] && JL[j] > maxJL)
{
maxJL = JL[j];
}
}
// Mark the chosen index as checked
for (int j = 0; j < N; j++)
{
if (JL[j] == maxJL)
{
checked[j] = true;
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
}
}
// Calculate the sum for each player
jackSum += maxJK;
jillSum += maxJL;
}
// Determine the winner
if (jackSum > jillSum)
{
return "Jack";
}
else if (jillSum > jackSum)
{
return "Jill";
}
else
{
return "Tie";
}
}
int main()
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
{
int N;
scanf("%d", &N);
int JK[N], JL[N];
for (int i = 0; i < N; i++)
{
scanf("%d", &JK[i]);
}
for (int i = 0; i < N; i++)
{
scanf("%d", &JL[i]);
}
char* winner = findWinner(N, JK, JL);
printf("%sn", winner);
return 0;
}
67
68
69
70
71
72
73
74
75
76
78
79
80
81
82
83
84
85
86
87
88
89
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
string findWinner(int N, vector<int>& JK, vector<int>& JL)
{
vector<bool> checked(N + 1, false); // To keep track of checked indices
int jackSum = 0, jillSum = 0;
for (int i = 0; i < N; i++)
{
int maxJK = -1, maxJL = -1;
// Find the maximum available number for Jack
for (int j = 0; j < N; j++)
{
if (!checked[j] && JK[j] > maxJK)
{
maxJK = JK[j];
}
}
// Mark the chosen index as checked
for (int j = 0; j < N; j++)
{
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
if (JK[j] == maxJK)
{
checked[j] = true;
break;
}
}
// Find the maximum available number for Jill
for (int j = 0; j < N; j++)
{
if (!checked[j] && JL[j] > maxJL)
{
maxJL = JL[j];
}
}
// Mark the chosen index as checked
for (int j = 0; j < N; j++)
{
if (JL[j] == maxJL)
{
checked[j] = true;
break;
}
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
}
// Calculate the sum for each player
jackSum += maxJK;
jillSum += maxJL;
}
// Determine the winner
if (jackSum > jillSum)
{
return "Jack";
}
else if (jillSum > jackSum)
{
return "Jill";
}
else
{
return "Tie";
}
}
int main()
{
int N;
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
cin >> N;
vector<int> JK(N), JL(N);
for (int i = 0; i < N; i++)
{
cin >> JK[i];
}
for (int i = 0; i < N; i++)
{
cin >> JL[i];
}
string winner = findWinner(N, JK, JL);
cout << winner << endl;
return 0;
}
67
68
69
70
71
72
73
74
75
76
78
79
80
81
82
83
84
85
86
87
88
89
import java.util.Scanner;
public class Main
{
public static String findWinner(int N, int[] JK, int[] JL)
{
boolean[] checked = new boolean[N + 1];
int jackSum = 0, jillSum = 0;
for (int i = 0; i <= N; i++)
{
checked[i] = false;
}
for (int i = 0; i < N; i++)
{
int maxJK = -1, maxJL = -1;
// Find the maximum available number for Jack
for (int j = 0; j < N; j++)
{
if (!checked[j] && JK[j] > maxJK)
{
maxJK = JK[j];
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// Mark the chosen index as checked
for (int j = 0; j < N; j++)
{
if (JK[j] == maxJK)
{
checked[j] = true;
break;
}
}
// Find the maximum available number for Jill
for (int j = 0; j < N; j++)
{
if (!checked[j] && JL[j] > maxJL)
{
maxJL = JL[j];
}
}
// Mark the chosen index as checked
for (int j = 0; j < N; j++)
{
if (JL[j] == maxJL)
{
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
checked[j] = true;
break;
}
}
// Calculate the sum for each player
jackSum += maxJK;
jillSum += maxJL;
}
// Determine the winner
if (jackSum > jillSum)
{
return "Jack";
}
else if (jillSum > jackSum)
{
return "Jill";
}
else
{
return "Tie";
}
}
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
int N = scanner.nextInt();
int[] JK = new int[N];
int[] JL = new int[N];
for (int i = 0; i < N; i++)
{
JK[i] = scanner.nextInt();
}
for (int i = 0; i < N; i++)
{
JL[i] = scanner.nextInt();
}
String winner = findWinner(N, JK, JL);
System.out.println(winner);
}
}
67
68
69
70
71
72
73
74
75
76
78
79
80
81
82
83
84
85
86
87
88
89
def findWinner(N, JK, JL):
checked = [False] * (N + 1)
jackSum = 0
jillSum = 0
for i in range(N):
maxJK = -1
maxJL = -1
# Find the maximum available number for Jack
for j in range(N):
if not checked[j] and JK[j] > maxJK:
maxJK = JK[j]
# Mark the chosen index as checked
for j in range(N):
if JK[j] == maxJK:
checked[j] = True
break
# Find the maximum available number for Jill
for j in range(N):
if not checked[j] and JL[j] > maxJL:
maxJL = JL[j]
# Mark the chosen index as checked
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
for j in range(N):
if JL[j] == maxJL:
checked[j] = True
break
# Calculate the sum for each player
jackSum += maxJK
jillSum += maxJL
# Determine the winner
if jackSum > jillSum:
return "Jack"
elif jillSum > jackSum:
return "Jill"
else:
return "Tie"
N = int(input())
JK = list(map(int, input().split()))
JL = list(map(int, input().split()))
winner = findWinner(N, JK, JL)
print(winner)
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
for j in range(N):
if JL[j] ==
maxJL:
checked[j] =
True
break
# Calculate the
sum for each player
jackSum +=
maxJK
jillSum += maxJL
# Determine the
winner
if jackSum >
jillSum:
return "Jack"
elif jillSum >
jackSum:
return "Jill"
else:
return "Tie"
N = int(input())
JK = list(map(int,
input().split()))
JL = list(map(int,
question 24
You are given a non-negative integer num`. You will also be given an array
`Digits of size exactly 10 where each element of the array will be between 0-9
inclusive.
You can perform the following operation on the given integer ‘num’ at most
once.
You can select a continuous part of ‘num’ and name it ‘x’. For each digit ‘D’ in
the number ‘x’, you can change it to digits [D] (consider 0-based indexing).
You need to convert the given integer ‘num’ to a maximum possible number
after performing the given operation at most once.
Example 1:
question 24
Input:
132 -> ‘num’
9 8 1 2 7 6 5 4 0 3 -> Elements of Array`Digits (Size of Array 'Digits is always 10
and elements of the array are space separated)
Output:
832
Explanation:
You can change the first digit from 1 to 8, then the final number will be 832.
Digit 3 can be mapped to 2, but it will change 832 to 822 which is lesser.
So, 832 is the maximum number possible.
question 24
Example 2:
Input:
021 -> ‘num’
9435721906 -> Elements of Array ‘Digits’ (size of Array ‘digits’ is always 10 and
Elements of the array are space separated)
Output:
934
Explanation:
You can change the first digit from 0 to 9, then the number will be 921.
Then you can change the digit from 2 to 3 the number will be 931.
question 24
Then you can change the digit from 1 to 4 the number will be 934.
Show 934 is the maximum number possible.
Constraints:
•0<=num<=10100
•0<=Digits[i]<=9, for all valid i(0<=i<10)
•Digit Length ==10
•Integer ‘num’ can contain zeros at the start. (For example, ‘012’ is also a valid
input)
The Input format for testing:
•First line: Contains a non negative integer ‘num’
•Second line: contention array ‘Digits’ of size 10 (All elements of the array are
space separated)
question 24
The output format for testing:
•Output a single integer denoting the maximum possible integer after
performing some operations on the given integer ‘num’
•(Number of digits in the output should be the same as the number of digits in
the input ‘num’)
Instructions:
•The system does not allow any kind of hard coded input value/ values.
•Written programme code by the candidate will be verified against the inputs
which are supplied from the system.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char num[100];
scanf("%s", num);
int digits[10];
for (int i = 0; i < 10; i++)
{
scanf("%d", &digits[i]);
}
int length = strlen(num);
for (int i = 0; i < length; i++)
{
int digit = num[i] - '0';
if (digit < digits[digit])
{
num[i] = digits[digit] + '0';
}
else if (digit > digits[digit])
{
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
break;
}
}
printf("%sn", num);
return 0;
}
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#include <iostream>
#include <vector>
using namespace std;
int main()
{
string num;
cin >> num;
vector<int> digits(10);
for (int i = 0; i < 10; i++)
{
cin >> digits[i];
}
for (int i = 0; i < num.length(); i++)
{
int digit = num[i] - '0';
if (digit < digits[digit])
{
num[i] = digits[digit] + '0';
}
else if (digit > digits[digit])
{
break;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
}
}
cout << num << endl;
return 0;
}
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
String num = scanner.nextLine();
int[] digits = new int[10];
for (int i = 0; i < 10; i++)
{
digits[i] = scanner.nextInt();
}
int length = num.length();
for (int i = 0; i < length; i++)
{
int digit = Character.getNumericValue(num.charAt(i));
if (digit < digits[digit])
{
char[] numArray = num.toCharArray();
numArray[i] = (char) (digits[digit] + '0');
num = String.valueOf(numArray);
} else if (digit > digits[digit])
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
{
break;
}
}
System.out.println(num);
}
}
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
num = input()
digits = list(map(int, input().split()))
for i in range(len(num)):
digit = int(num[i])
if digit < digits[digit]:
num = num[:i] + str(digits[digit]) + num[i+1:]
elif digit > digits[digit]:
break
print(num)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
question 25
You are in the Marvel Universe and Doctor strange has to defend a little girl
named ‘America’ from the scarlet witch. The Scarlet witch is really strong thus
Doctor strange has assembled an army of ‘n’ magicians to fight her. She throws
magical red balls toward her enemy to get rid of him.
Each magician in Doctor Strange's army has some strength denoted by 'Pi'
element in an array. The scarlet witch has the power to fire any number of
magical red balls at the same time in her single attack. She can do 'q' number
of attacks. The opponent can stand against her till he has strength. One
magical red ball decreases strength by 1. I.e., if a person has the strength of 2
and she throws 1 magical ball in her first attack then his strength becomes 1
and he is saved. But if she threw one more then he would die. But this is the
point where the twist comes,
question 25
Doctor Strange is not weak, he has a darkhold. When all the magicians of
Doctor Strange's army die, he with the help of his magic and darkhold, revives
them all and they stand up again for fighting. i.e., if at the second all his
magicians die then at the end of that i second all his magicians will stand up
again for fighting. You are Doctor Strange’s assistant cell him how many
magicians are left alive for fighting at the end of each attack by the Scarlet
witch note that, as soon as all the magicians die, Doctor Strange will
instantaneously make them alive.
Example 1:
Input:
10 3 ->Number of magicians in
Doctor strange army and the number of attacks by the scarlet witch space-
separated.
question 25
1 1 1 1 1 1 1 1 1 1 -> strength of each soldier in the army
10 10 5 -> Number of magical red balls fired by the scarlet witch in her each
attack
Output:
10 10 5 -> The respective numbers
(space-separated) of magicians left alive after each attack of the scarlet witch
Explanation:
Here there will be 3 attacks.The scenario will be as follows :
Attack 1: All 10 magicians die and as soon as all magicians die, they are
brought back to life again, thus at end of the 1st attack 10 magicians are alive
again.
question 25
Attack 2: Same Scenario
Attack 3: 5 magicians die, thus 5 are left.
Example 2:
Input:
5 2 -> Number of magicians in doctor strange army and the number of attacks
by the scarlet witch space-separated.
1 2 1 1 1 -> Strength of each soldier in the army
2 3 -> Number of magical red balls fired by the scarlet witch in her each attack
Output:
4 1 -> The respective numbers(space-separated) of magicians left alive after
each attack of the scarlet witch
question 25
Explanation:
Here there will be 2 attacks.The scenario will be as follows :
Attack 1: Only 1 magician die and second one’s strength will be decreased to
1,thus army’s condition is – 1 1 1 1
Attack 2: Here in the second attack next three magicians die and only 1 left.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int n, q;
scanf("%d %d", &n, &q);
int* strength = (int*)malloc(n * sizeof(int));
for (int i = 0; i < n; i++)
{
scanf("%d", &strength[i]);
}
int* balls = (int*)malloc(q * sizeof(int));
for (int i = 0; i < q; i++)
{
scanf("%d", &balls[i]);
}
int* magicians = (int*)malloc(n * sizeof(int));
for (int i = 0; i < n; i++)
{
magicians[i] = 1; // Initialize all magicians as alive
}
for (int i = 0; i < q; i++)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
{
int ballsThrown = balls[i];
int alive = 0; // Number of magicians alive after each attack
for (int j = 0; j < n; j++)
{
if (magicians[j] > 0)
{
if (ballsThrown >= strength[j])
{
ballsThrown -= strength[j];
magicians[j] = 0; // Mark magician as dead
}
else
{
alive++; // Magician survives the attack
strength[j] -= ballsThrown; // Decrease magician's strength
ballsThrown = 0; // All balls are used
}
}
}
if (alive == 0)
{
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
for (int j = 0; j < n; j++)
{
magicians[j] = 1; // Revive all magicians
}
alive = n;
}
printf("%d ", alive);
}
printf("n");
free(strength);
free(balls);
free(magicians);
return 0;
}
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#include <iostream>
#include <vector>
using namespace std;
int main()
{
int n, q;
cin >> n >> q;
vector<int> strength(n);
for (int i = 0; i < n; i++)
{
cin >> strength[i];
}
vector<int> balls(q);
for (int i = 0; i < q; i++)
{
cin >> balls[i];
}
vector<int> magicians(n, 1); // Initialize all magicians as alive
for (int i = 0; i < q; i++)
{
int ballsThrown = balls[i];
int alive = 0; // Number of magicians alive after each attack
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
for (int j = 0; j < n; j++)
{
if (magicians[j] > 0)
{
if (ballsThrown >= strength[j])
{
ballsThrown -= strength[j];
magicians[j] = 0; // Mark magician as dead
}
else
{
alive++; // Magician survives the attack
strength[j] -= ballsThrown; // Decrease magician's strength
ballsThrown = 0; // All balls are used
}
}
}
if (alive == 0)
{
for (int j = 0; j < n; j++)
{
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
magicians[j] = 1; // Revive all magicians
}
alive = n;
}
cout << alive << " ";
}
cout <<endl;
return 0;
}
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int q = scanner.nextInt();
int[] strength = new int[n];
for (int i = 0; i < n; i++)
{
strength[i] = scanner.nextInt();
}
int[] balls = new int[q];
for (int i = 0; i < q; i++)
{
balls[i] = scanner.nextInt();
}
int[] magicians = new int[n];
for (int i = 0; i < n; i++)
{
magicians[i] = 1; // Initialize all magicians as alive
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
for (int i = 0; i < q; i++)
{
int ballsThrown = balls[i];
int alive = 0; // Number of magicians alive after each attack
for (int j = 0; j < n; j++)
{
if (magicians[j] > 0)
{
if (ballsThrown >= strength[j])
{
ballsThrown -= strength[j];
magicians[j] = 0; // Mark magician as dead
}
else
{
alive++; // Magician survives the attack
strength[j] -= ballsThrown; // Decrease magician's strength
ballsThrown = 0; // All balls are used
}
}
}
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
if (alive == 0)
{
for (int j = 0; j < n; j++)
{
magicians[j] = 1; // Revive all magicians
}
alive = n;
}
System.out.print(alive + " ");
}
System.out.println();
scanner.close();
}
}
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
n, q = map(int, input().split())
strength = list(map(int, input().split()))
balls = list(map(int, input().split()))
magicians = [1] * n
for i in range(q):
ballsThrown = balls[i]
alive = 0
for j in range(n):
if magicians[j] > 0:
if ballsThrown >= strength[j]:
ballsThrown -= strength[j]
magicians[j] = 0
else:
alive += 1
strength[j] -= ballsThrown
ballsThrown = 0
if alive == 0:
magicians = [1] * n
alive = n
print(alive, end=' ')
print()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
QUESTION NO : 26
Your friend had a child. You wanted to give him a nice nickname of length N
and k length repetitive by modifying his real name S of length N.
The nickname is called nice if and only if the S is a palindrome and the S has
a period of k. (Here period nothing but repetition of the substring for every k
intervals i.e.. S1 to k=S(k+1) to (2*k) =. .. . .= S(x*k+1) to N. Here you will be
given string S length N and k where N % k=0. To make a nickname nice, you
can use the following operation.
The operation follows:
You can choose any index (i) of the string S and change the ith letter with
some other letter.
Find the minimum number of operations required to convert string S to a
nice nickname.
QUESTION NO : 26
Example - 1:
Input:
8 2 ------> N (length of the string) and
Abaacbaa ------> String S.
Output:
3
Explanation:
One possible solution is aaaaaaaa. so that we can get the minimum number
of operations required to convert S to a nice nick name.
QUESTION NO : 26
Example - 2:
Input:
10 2
Aabcbaacba
Output:
5
Constraints:
1<=N<=105
1<=N and N%k=0
The input format for testing:
The first line represents the N and K.
The second line represents the string S.
QUESTION NO : 26
The output format for testing:
Print the minimum number of operations required to convert the string S to
a nice nickname.
Instructions:
The system does not allow any kind of hard coded input
import java.util.Scanner;
public class Main
{
public static int minOperationsForNiceNickname(int N, int k, String S)
{
int operations = 0;
for (int i = 0; i < k / 2; i++)
{
int[] freq = new int[26];
// Count the frequency of characters at indices i and (k - i - 1)
for (int j = i; j < N; j += k)
{
freq[S.charAt(j) - 'a']++;
freq[S.charAt(j + (k - 2 * i - 1)) - 'a']++;
}
int maxFreq = 0;
int totalFreq = 0;
// Find the most frequent character and calculate the total frequency
for (int f : freq)
{
maxFreq = Math.max(maxFreq, f);
totalFreq += f;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
}
// Subtract the most frequent character's frequency from the total frequency
operations += totalFreq - maxFreq;
}
return operations;
}
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
int N = scanner.nextInt();
int k = scanner.nextInt();
String S = scanner.next();
int minOperations = minOperationsForNiceNickname(N, k, S);
System.out.println(minOperations);
}
}
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#include <stdio.h>
#include <string.h>
int minOperationsForNiceNickname(int N, int k, const char* S)
{
int operations = 0;
for (int i = 0; i < k / 2; i++)
{
int freq[26] = {0};
// Count the frequency of characters at indices i and (k - i - 1)
for (int j = i; j < N; j += k)
{
freq[S[j] - 'a']++;
freq[S[j + (k - 2 * i - 1)] - 'a']++;
}
int maxFreq = 0;
int totalFreq = 0;
// Find the most frequent character and calculate the total frequency
for (int f = 0; f < 26; f++)
{
maxFreq = (freq[f] > maxFreq) ? freq[f] : maxFreq;
totalFreq += freq[f];
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// Subtract the most frequent character's frequency from the total frequency
operations += totalFreq - maxFreq;
}
return operations;
}
int main()
{
int N, k;
scanf("%d %d", &N, &k);
char S[N + 1];
scanf("%s", S);
int minOperations = minOperationsForNiceNickname(N, k, S);
printf("%dn", minOperations);
return 0;
}
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int minOperationsForNiceNickname(int N, int k, const string& S)
{
int operations = 0;
for (int i = 0; i < k / 2; i++)
{
vector<int> freq(26, 0);
// Count the frequency of characters at indices i and (k - i - 1)
for (int j = i; j < N; j += k)
{
freq[S[j] - 'a']++;
freq[S[j + (k - 2 * i - 1)] - 'a']++;
}
int maxFreq = 0;
int totalFreq = 0;
// Find the most frequent character and calculate the total frequency
for (int f : freq)
{
maxFreq = max(maxFreq, f);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
totalFreq += f;
}
// Subtract the most frequent character's frequency from the total frequency
operations += totalFreq - maxFreq;
}
return operations;
}
int main()
{
int N, k;
cin >> N >> k;
string S;
cin >> S;
int minOperations = minOperationsForNiceNickname(N, k, S);
cout << minOperations << endl;
return 0;
}
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
def min_operations_for_nice_nickname(N, k, S):
operations = 0
for i in range(k // 2):
freq = [0] * 26
# Count the frequency of characters at indices i and (k - i - 1)
for j in range(i, N, k):
freq[ord(S[j]) - ord('a')] += 1
freq[ord(S[j + (k - 2 * i - 1)]) - ord('a')] += 1
max_freq = 0
total_freq = 0
# Find the most frequent character and calculate the total frequency
for f in freq:
max_freq = max(max_freq, f)
total_freq += f
#Subtract the most frequent character's frequency from the total frequency
operations += total_freq - max_freq
return operations
N, k = map(int, input().split())
S = input()
min_operations = min_operations_for_nice_nickname(N, k, S)
print(min_operations)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
QUESTION NO : 27
Ria likes to play a number game always. Today she decided to find the
largest number that can be made using all of the digits of the given
input(Non negative integer) value N.
Example 1:
Input :
3675092 -> value of N
Output:
9765320
Example 2 :
Input:
2856 -> value of N
Output:
8652
QUESTION NO : 27
Note:
Since, input value, N accepts integer value only, hence digit 0 that comes
before the first non-zero digit should not take into consideration of input.
Constraints:
1<N<10000000
The input format for testing:
The candidate has to write the court to accept a positive integer number.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int compare(const void *a, const void *b)
{
return (*(char*)b - *(char*)a);
}
char* largestNumber(int N)
{
char numStr[12];
sprintf(numStr, "%d", N);
qsort(numStr, strlen(numStr), sizeof(char), compare);
return strdup(numStr);
}
int main()
{
int N;
scanf("%d", &N);
char* largestNum = largestNumber(N);
printf("%sn", largestNum);
free(largestNum);
return 0; }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <algorithm>
using namespace std;
bool compare(char a, char b)
{
return a > b;
}
string largestNumber(int N)
{
string numStr = to_string(N);
sort(numStr.begin(), numStr.end(), compare);
return numStr;
}
int main()
{
int N;
cin >> N;
string largestNum = largestNumber(N);
cout << largestNum << endl;
return 0;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import java.util.Arrays;
import java.util.Scanner;
public class Main
{
public static String largestNumber(int N)
{
String numStr = Integer.toString(N);
char[] numArr = numStr.toCharArray();
Arrays.sort(numArr);
StringBuilder sb = new StringBuilder();
for (int i = numArr.length - 1; i >= 0; i--)
{
sb.append(numArr[i]);
}
return sb.toString();
}
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
int N = scanner.nextInt();
String largestNum = largestNumber(N);
System.out.println(largestNum); }}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
def largestNumber(N):
numStr = str(N)
numArr = list(numStr)
numArr.sort(reverse=True)
largestNum = ''.join(numArr)
return largestNum
N = int(input())
largestNum = largestNumber(N)
print(largestNum)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
QUESTION NO : 28
Rahul, a mathematical genius will be given a positive number N and he
needs to reduce it to 0 (zero) by following operations
mentioned as under:
Take one of the divisors of N – which is different from N itself and subtract it
from N.
Perform the above operation till the original number is reduced to 0 (zero).
The task here is to find the minimum number of steps Rahul needs to
perform such that N is reduced to 0 (zero)
Note:
If the N is 1 during the operation, then in order to reduce 1 to 0 (zero)
subtract 1 from it.
It is shown in the following examples
QUESTION NO : 28
Example 1
Input
5
Output
4
Explanation
Divisors of 5 are 1, 5 but you cannot subtract 5 so then subtract 1 from 5
The reduced number is 5-1 = 4
Divisors of 4 are 1, 2 and 4 but you cannot subtract 4 so reduce it by 2, after
reducing it by 2, number becomes 4 – 2 = 2
Divisor of 2 are 1, 2 and after reducing it by 1, number becomes 2 – 1 = 1
You can subtract 1 by 1 and then the number becomes 0.
So for N = 5, the minimum number of steps are 4.
QUESTION NO : 28
Example 2
Input
8
Output
4
Explanation
In first step, subtract 4 from 8, number becomes 8 – 4 = 4
In second step, subtract 2 from 4, number becomes 4 – 2 = 2
In third step, subtract 1 from 2, number becomes 2 – 1 = 1
In fourth step, subtract 1 from 1, number becomes 1 – 1 = 0
Example 3
Input
6
Output
4
#include<stdio.h>
int fun(int n)
{
int count = 0;
int fact = 1;
while(n != 0)
{
for(int i = 1; i < n; i++)
{
if(n % i == 0)
{
fact = i;
}
}
n = n - fact;
count = count + 1;
}
return count;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
int main()
{
int n;
scanf("%d", &n);
printf("%d", fun(n));
return 0;
}
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#include<iostream>
using namespace std;
int fun(int n)
{
int count = 0;
int fact = 1;
while(n != 0)
{
for(int i = 1; i < n; i++)
{
if(n % i == 0)
{
fact = i;
}
}
n = n - fact;
count = count + 1;
}
return count;
}
int main()
{
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
int n;
cin >> n;
cout << fun(n);
return 0;
}
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
import java.util.Scanner;
public class Main
{
public static int fun(int n)
{
int count = 0;
int fact = 1;
while (n != 0) {
for (int i = 1; i < n; i++)
{
if (n % i == 0)
{
fact = i;
}
}
n = n - fact;
count = count + 1;
}
return count;
}
public static void main(String[] args)
{
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
System.out.println(fun(n));
scanner.close();
}
}
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
def fun(n):
count = 0
fact = 1
while n != 0:
for i in range(1, n):
if n % i == 0:
fact = i
n = n - fact
count = count + 1
return count
n = int(input())
print(fun(n))
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
QUESTION NO : 29
Given a positive integer number N. the task is to find the number of ways in
which the given number can be represented as the
product of two distinct numbers.
Example 1
Input
14
Output
2
Explanation
14 can be represented as 1 * 14 and 2 * 7
Example 2
Input
16
Output
2
QUESTION NO : 29
Explanation
16 can be represented as 1*16 and 2 * 8
Note
4*4 is not valid way because both the numbers are same.
#include <iostream>
#include <cmath>
using namespace std;
int fun(int n)
{
int count = 0;
for (int i = 1; i * i <= n; i++)
{
if (n % i == 0 && (n / i != i))
{
count++;
}
}
return count;
}
int main()
{
int n;
cin >> n;
cout << fun(n);
return 0;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include<stdio.h>
#include<math.h>
int fun(int n)
{
int count = 0;
for(int i = 1; i*i <= n; i++)
{
if(n % i == 0 && (n / i != i) )
{
count++;
}
}
return count;
}
int main()
{
int n;
scanf("%d", &n);
printf("%d", fun(n));
return 0; }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import java.util.Scanner;
public class Main
{
public static int fun(int n)
{
int count = 0;
for (int i = 1; i * i <= n; i++)
{
if (n % i == 0 && (n / i != i))
{
count++;
}
}
return count;
}
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
System.out.println(fun(n));
scanner.close();
} }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
def fun(n):
count = 0
for i in range(1, int(n**0.5) + 1):
if n % i == 0 and n // i != i:
count += 1
return count
n = int(input())
print(fun(n))
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
QUESTION NO : 30
Given a number N, the task is to split the Num into multiple parts in such a
fashion as to find the highest product.
Print the highest product value.
Consider N = 4.
Best: 4 = 2 + 2 and 2 * 2 = 4
Similarly for N = 6, (3 * 3) = 9
For N = 8, (2 * 3 * 3) = 18
For N = 15, (3 * 3 * 3 * 3 * 3) = 243
Constraints
1 <= N <= 100
Input format
The candidate has to write the code to accept a non-negative integer
number only.
Output format
The output should be a positive integer only.
QUESTION NO : 30
Example 1
Input
4
Output
4
Example 2
Input Output
9 6
#include<stdio.h>
int fun(int n)
{
if(n == 2 || n == 3)
return n-1;
int res = 1;
while(n > 4)
{
n = n - 3;
res = res * 3;
}
return (n * res);
}
int main()
{
int n;
scanf("%d", &n);
printf("%d", fun(n));
return 0; }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>
using namespace std;
int fun(int n)
{
if (n == 2 || n == 3)
return n - 1;
int res = 1;
while (n > 4)
{
n = n - 3;
res = res * 3;
}
return (n * res);
}
int main()
{
int n;
cin >> n;
cout << fun(n);
return 0;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import java.util.Scanner;
public class Main
{
public static int fun(int n)
{
if (n == 2 || n == 3)
return n - 1;
int res = 1;
while (n > 4)
{
n = n - 3;
res = res * 3;
}
return (n * res);
}
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
System.out.println(fun(n));
scanner.close(); }}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
def fun(n):
if n == 2 or n == 3:
return n - 1
res = 1
while n > 4:
n = n - 3
res = res * 3
return n * res
n = int(input())
print(fun(n))
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
Topic/Course
Sub-Topic (Example: name of college)
Set D
QUESTION NO : 31
You are at your 1(containing zeros of size N) The magic operation is nothing
but in this operation, you select any index (i) in the array B and add (k to the
power i) to the B[i].So, if you are able to build the A array from the B array
then print YES else NO.
NOTE: The array A is 0 indexed.
QUESTION NO : 31
Example 1:
Input:
3 2 ->N (length of an array A) and k
(weapon)
46 54 100 ->A array of length N
Output:
NO
Explanation:
Initially B=[0,0,0]
Here, we can get A[0] by applying magic operations 46 times on index 0 and
25 times on index-2, but cannot get A[1] by applying magic operations.
#include <stdio.h>
#include <stdbool.h>
bool isPossibleToBuildArray(int A[], int n, int k)
{
int B[n];
B[0] = 1;
for (int i = 1; i < n; i++)
{
B[i] = B[i - 1] * k;
}
for (int i = 0; i < n; i++)
{
int count = 0;
int power = B[i];
while (A[i] >= power)
{
A[i] -= power;
count++;
}
if (A[i] != 0 || count > 1)
{
return false;}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
}
}
return true;
}
int main()
{
int n, k;
scanf("%d %d", &n, &k);
int A[n];
for (int i = 0; i < n; i++)
{
scanf("%d", &A[i]);
}
bool possible = isPossibleToBuildArray(A, n, k);
printf("%s", possible ? "YES" : "NO");
return 0;
}
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#include <iostream>
#include <vector>
#include <cmath>
using namespace std;
bool isPossibleToBuildArray(vector<int>& A, int k)
{
int n = A.size();
vector<int> B(n, 0);
for (int i = 0; i < n; i++)
{
int power = pow(k, i);
B[i] = power;
}
for (int i = 0; i < n; i++)
{
int count = 0;
while (A[i] >= B[i])
{
A[i] -= B[i];
count++;
}
if (A[i] != 0 || count > 1)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
{
return false;
}
}
return true;
}
int main()
{
int n, k;
cin >> n >> k;
vector<int> A(n);
for (int i = 0; i < n; i++)
{
cin >> A[i];
}
bool possible = isPossibleToBuildArray(A, k);
cout << (possible ? "YES" : "NO");
return 0;
}
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
import java.util.Scanner;
import java.util.ArrayList;
class Main
{
public static boolean isPossibleToBuildArray(ArrayList<Integer> A, int k)
{
int n = A.size();
ArrayList<Integer> B = new ArrayList<Integer>(n);
for (int i = 0; i < n; i++)
{
int power = (int) Math.pow(k, i);
B.add(power);
}
for (int i = 0; i < n; i++)
{
int count = 0;
while (A.get(i) >= B.get(i))
{
A.set(i, A.get(i) - B.get(i));
count++;
}
if (A.get(i) != 0 || count > 1)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
{
return false;
}
}
return true;
}
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int k = scanner.nextInt();
ArrayList<Integer> A = new ArrayList<Integer>(n);
for (int i = 0; i < n; i++)
{
A.add(scanner.nextInt());
}
boolean possible = isPossibleToBuildArray(A, k);
System.out.println(possible ? "YES" : "NO");
scanner.close();
}
}
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
def isPossibleToBuildArray(A, k):
n = len(A)
B = []
for i in range(n):
power = k ** i
B.append(power)
for i in range(n):
count = 0
while A[i] >= B[i]:
A[i] -= B[i]
count += 1
if A[i] != 0 or count > 1:
return False
return True
n, k = map(int, input().split())
A = list(map(int, input().split()))
possible = isPossibleToBuildArray(A, k)
print("YES" if possible else "NO")
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
QUESTION NO : 32
Ram is a very busy business man. Everyday he has to travel to different cities.
There are N cities in the list(a[]) that he has to pass through to reach his
destination.
His destination is the last city in the list. He always starts from his home
city(a[0]).
The maximum distance Ram can travel when he is at city i is given by a[i]. It
takes 1 unit of time each he travels from any one city to another city. His goal
is to reach the destination city(a[N-1]) at the end of the day.
Given N, a , the task here is to help Ram to travel from his home city to
destination in the minimum amount of time.
Give the time as output
Note: Assume,the destination can always be reached
QUESTION NO : 32
Example 1:
Input:
5-> Value of N
2 1 2 5 3-> a[], Elements a[0] to a[N-1], where each input element is separated
by new line
Output:
2
QUESTION NO : 32
Explanation:
From the inputs given above:
Ram starts from his home city (a[0]):2
Maximum distance Ram can travel is 2 places ahead that is Ram can either go
to a[1] or a[2]
Ram will go to a city at a[2]
Amount of time spent is 1 unit
Again he starts from a[2]
Maximum distance Rankan travel is two places ahead that is Ram can either
go to a[3] or a[4]
Ram will go to a[4] which is the destination
Amount of time spent is 1 unit.
QUESTION NO : 32
Example 2:
Input :
8-> Value of N
1 2 1 1 3 5 6 4-> a[], Elements a[0] to a[N-1] where each input element is
separated by new line
Output:
4
QUESTION NO : 32
Explanation:
From the inputs given above:
Iran starts from his home city (a[0]):1
Maximum distance Ram can travel is 1 place ahead that is Ram can go only to
a[1]
Amount of time spent is 1 unit.
Again he starts from a[1]
Maximum distance from can travel is 2 places ahead that is Ram can either go
to a[2] or a[3]
Ram will go to a city at a[3].
Amount of time spent is 1 unit.
Again he starts from a[3]
QUESTION NO : 32
Maximum distance from can travel is 1 places ahead that is Ram can either go
to a[4]
Ram will go only to a city a[4].
Amount of time spent is 1 unit.
Again he starts from a[4]
Maximum distance from can travel is 3 places ahead that is Ram can either go
to a[5] or a[6] or a[7].
Ram will go a to city at a[7] which is the destination.
Amount of time spent is 1 unit.
The total amount of time spent is 4 units.
This is the least amount of time Ron has to spend to travel from source to
destination.
Hence, the output is 4.
QUESTION NO : 32
Constraints:
1<N<10000000
The input format testing:
The candidate has to write the code to accept a positive integer number
#include <stdio.h>
int minTime(int N, int *a)
{
int currMaxDist = 0; // Current maximum distance Ram can travel
int minTime = 0; // Minimum time spent to reach the destination
for (int i = 0; i < N - 1; i++)
{
if (i + a[i] > currMaxDist)
{
currMaxDist = i + a[i]; // Update the current maximum distance
}
if (currMaxDist >= N - 1)
{
break; // Destination reached
}
minTime++; // Increment the minimum time spent
}
return minTime;
}
int main()
{
int N;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
scanf("%d", &N);
int a[N];
for (int i = 0; i < N; i++)
{
scanf("%d", &a[i]);
}
int minTravelTime = minTime(N, a);
printf("%dn", minTravelTime);
return 0;
}
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#include <iostream>
using namespace std;
int minTime(int N, int *a)
{
int currMaxDist = 0; // Current maximum distance Ram can travel
int minTime = 0; // Minimum time spent to reach the destination
for (int i = 0; i < N - 1; i++)
{
if (i + a[i] > currMaxDist)
{
currMaxDist = i + a[i]; // Update the current maximum distance
}
if (currMaxDist >= N - 1)
{
break; // Destination reached
}
minTime++; // Increment the minimum time spent
}
return minTime;
}
int main()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
{
int N;
cin >> N;
int a[N];
for (int i = 0; i < N; i++)
{
cin >> a[i];
}
int minTravelTime = minTime(N, a);
cout << minTravelTime << endl;
return 0;
}
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
import java.util.Scanner;
public class Main
{
public static int minTime(int N, int[] a)
{
int currMaxDist = 0; // Current maximum distance Ram can travel
int minTime = 0; // Minimum time spent to reach the destination
for (int i = 0; i < N - 1; i++)
{
if (i + a[i] > currMaxDist)
{
currMaxDist = i + a[i]; // Update the current maximum distance
}
if (currMaxDist >= N - 1)
{
break; // Destination reached
}
minTime++; // Increment the minimum time spent
}
return minTime;
}
public static void main(String[] args)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
{
Scanner scanner = new Scanner(System.in);
int N = scanner.nextInt();
int[] a = new int[N];
for (int i = 0; i < N; i++)
{
a[i] = scanner.nextInt();
}
int minTravelTime = minTime(N, a);
System.out.println(minTravelTime);
scanner.close();
}
}
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
def minTime(N, a):
currMaxDist = 0 # Current maximum distance Ram can travel
minTime = 0 # Minimum time spent to reach the destination
for i in range(N - 1):
if i + a[i] > currMaxDist:
currMaxDist = i + a[i] # Update the current maximum distance
if currMaxDist >= N - 1:
break # Destination reached
minTime += 1 # Increment the minimum time spent
return minTime
N = int(input())
a = list(map(int, input().split()))
minTravelTime = minTime(N, a)
print(minTravelTime)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
QUESTION NO : 33
Rohan has a board of N*M dimensions where N is number of rows and M is
number of columns. He has X number of coins numbered.
They are playing a game on this with the below rule:
•You need to fill the board with coins. You can fill each cell of board with a
minimum of 0 coins or a maximum of X coins.
•Each cell can be filled with coins between 0 to X.
•For every pair of neighbor cells, the number of coins in both cells should not
exceed a given number Y. Two cells are neighbor if they share a side.
Your task is to find the maximum number of coins which can be filled inside
the board at a particular time, considering the above mentioned condition.
The Input will be:
N: Number of rows
M : Number of columns
X : Number of coins per cell
Y : Maximum sum of neighbor cells.
QUESTION NO : 33
Example 1:
Input :
2 2 5 2-> Input integer, N, M, X and Y.
Output :
4->Output
Explanation:
In the above matrix which is 2*2. The maximum sum of neighbours can be at
most 2.
We can have below arrangement
In the arrangement above, All the conditions satisfies
•Maximum coin can be only 2.
•The neighbour has at most 2 coins.
Clearly the maximum coin which we can adjust in this board the are 4.
Example 2:
Input:
3 3 6 3->Input integers N, M, X and Y
QUESTION NO : 33
Output:
15->Output
Explanation:
In the above matrix which is 3*3 the maximum sum of neighbours can be at
most 3.
We can have the below arrangement
In the arrangement above, All the conditions satisfies
•Maximum coin can be only 6.
•The neighbour has at most 3 coins.
Clearly the maximum coin which we can adjust in this board the are 15.
Constraints:
•1<=N,M<=100
•1<=X,Y<=100
•Only lowercase allowed
QUESTION NO : 33
The input format for testing:
•First input - Accept value of integer N
•Second input -accept value of integer M(Next Line)
•Third input -accept value of integer X (Next Line)
Fourth input accept value of integer y(Next Line)
The output format for testing:
•The output is an integer as per above logic (check the output in example 1,
example 2)
•Additional message in output will cause the failure of test cases.
Instructions:
•System does not allow any kind of hard coded input value or values.
•Return programme code by the candidate will be verified against the inputs
which are supplied from the system.
#include <stdio.h>
int maxCoins(int N, int M, int X, int Y)
{
int maxCoins = 0;
// Handle the special cases where N or M is 1
if (N == 1 || M == 1)
{
maxCoins = (N * M) * (X < Y ? X : Y);
return maxCoins;
}
// Calculate the maximum number of coins based on the position on the board
int diagonalSize = (X <= Y) ? X : Y;
maxCoins = diagonalSize;
for (int i = 2; i <= N; i++)
{
for (int j = 2; j <= M; j++)
{
if ((i % 2 == 0 && j % 2 == 0) || (i % 2 != 0 && j % 2 != 0))
{
maxCoins += diagonalSize;
}
else
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
{
maxCoins += (X <= Y) ? X : Y;
}
}
}
return maxCoins;
}
int main()
{
int N, M, X, Y;
scanf("%d", &N);
scanf("%d", &M);
scanf("%d", &X);
scanf("%d", &Y);
int result = maxCoins(N, M, X, Y);
printf("%dn", result);
return 0;
}
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#include <iostream>
using namespace std;
int maxCoins(int N, int M, int X, int Y)
{
int maxCoins = 0;
// Handle the special cases where N or M is 1
if (N == 1 || M == 1)
{
maxCoins = (N * M) * (X < Y ? X : Y);
return maxCoins;
}
// Calculate the maximum number of coins based on the position on the board
int diagonalSize = (X <= Y) ? X : Y;
maxCoins = diagonalSize;
for (int i = 2; i <= N; i++)
{
for (int j = 2; j <= M; j++)
{
if ((i % 2 == 0 && j % 2 == 0) || (i % 2 != 0 && j % 2 != 0))
{
maxCoins += diagonalSize;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
else
{
maxCoins += (X <= Y) ? X : Y;
}
}
}
return maxCoins;
}
int main()
{
int N, M, X, Y;
cin >> N >> M >> X >> Y;
int result = maxCoins(N, M, X, Y);
cout << result << endl;
return 0;
}
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
import java.util.Scanner;
public class Main
{
public static int maxCoins(int N, int M, int X, int Y)
{
int maxCoins = 0;
// Handle the special cases where N or M is 1
if (N == 1 || M == 1)
{
maxCoins = (N * M) * (X < Y ? X : Y);
return maxCoins;
}
int diagonalSize = (X <= Y) ? X : Y;
maxCoins = diagonalSize;
for (int i = 2; i <= N; i++)
{
for (int j = 2; j <= M; j++)
{
if ((i % 2 == 0 && j % 2 == 0) || (i % 2 != 0 && j % 2 != 0))
{
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
}
else
{
maxCoins += (X <= Y) ? X : Y;
}
}
}
return maxCoins;
}
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
int N = scanner.nextInt();
int M = scanner.nextInt();
int X = scanner.nextInt();
int Y = scanner.nextInt();
int result = maxCoins(N, M, X, Y);
System.out.println(result);
}
}
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
def maxCoins(N, M, X, Y):
maxCoins = 0
# Handle the special cases where N or M is 1
if N == 1 or M == 1:
maxCoins = (N * M) * min(X, Y)
return maxCoins
# Calculate the maximum number of coins based on the position on the board
diagonalSize = X if X <= Y else Y
maxCoins = diagonalSize
for i in range(2, N + 1):
for j in range(2, M + 1):
if (i % 2 == 0 and j % 2 == 0) or (i % 2 != 0 and j % 2 != 0):
maxCoins += diagonalSize
else:
maxCoins += X if X <= Y else Y
return maxCoins
# Get input in a single line
N, M, X, Y = map(int, input().split())
result = maxCoins(N, M, X, Y)
print(result)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
QUESTION NO : 34
You will be given a String 's' of length, 'n' and you need to find out the two
longest non-intersecting subsequences of the given string ‘S’which are
anagrams to each other.
Formally, you need to find out two subsequences from the given string such
that the last index of the first subsequence is less than the first index of
second subsequence and they are anagrams to each other.
Anagram Strings: Two strings are anagrams of each other if they are of the
same length and each character appears in both of them the same number of
times. For e.g., “time” and “mite” are anagrams.
Subsequence: Any string that can be obtained by deleting zero or more
characters from a given string keeping the order of characters the same.
For example S =“aaababcd”
Subsequences "aab" (0,1,3) and "aab" (2,4,5) are invalid. They a are anagrams
but they are intersecting (i.e., the last index of first subsequence {3} is greater
than the first Index of second Subsequence {2}).
QUESTION NO : 34
Subsequences "ab" {0.3} and "ab" {4,5} are valid. They are anagrams as well as
not intersecting.
You need to find out the longest such subsequence. Have a look at
explanations of sample examples for better understanding.
String's will contain only the English lowercase letters (a-z).
Example 1:
Input:
11 -> n (length of string)
codingisfun -> Sting ‘s’
Output:
2
Explanation:
The longest possible subsequences are “in”->{3,4} and “in”->{6,10}. They are
anagrams to each other as well as they are non intersecting.
QUESTION NO : 34
Example 2:
Input:
11 -> n (length of string)
maharashtra ->string ‘s’
Output:
4
Explanation:
The longest possible sub-sequences are ”ahar”->{1,2,3,4}and ”ahar” {5,7,9,10}.
They are anagrams and non intersecting subsequences.
:
1<=n<=10000
String S wiConstraintsll only contain English lowercase letters (a-z) without
any other symbols.
QUESTION NO : 34
The input format for testing:
First line: Contains an integer n [length of strings]
Second line: Contains string ‘s’ (of length ‘n’)
The output format for testing:
Output is a single integer denoting the maximum length of the string
#include <stdio.h>
#include <string.h>
int max(int a, int b)
{
return a > b ? a : b;
}
int longestAnagramSubsequence(int n, char s[])
{
int frequencies[26] = {0}; // Array to store the frequency of each character
int dp[26][n + 1];
memset(dp, 0, sizeof(dp)); // Initialize dp array with 0
for (int i = 1; i <= n; i++)
{
int currChar = s[i - 1] - 'a';
frequencies[currChar]++;
for (int j = 0; j < 26; j++)
{
dp[j][i] = dp[j][i - 1]; // Carry forward the length from previous index
if (j == currChar)
{
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
for (int k = 0; k < j; k++)
{
if (frequencies[j] - frequencies[k] > 0)
{
dp[j][i] = max(dp[j][i], dp[k][i - 1] + 1);
}
}
}
}
}
int maxLength = 0;
// Find the maximum length among all characters
for (int i = 0; i < 26; i++)
{
maxLength = max(maxLength, dp[i][n]);
}
return maxLength;
}
int main()
{
int n;
char s[10001];
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
scanf("%d", &n);
scanf("%s", s);
int result = longestAnagramSubsequence(n, s);
printf("%dn", result);
return 0;
}
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#include <iostream>
#include <cstring>
using namespace std;
int max(int a, int b)
{
return a > b ? a : b;
}
int longestAnagramSubsequence(int n, char s[])
{
int frequencies[26] = {0}; // Array to store the frequency of each character
int dp[26][n + 1]; // dp[i][j] stores the length of the longest subsequence ending at index j
memset(dp, 0, sizeof(dp)); // Initialize dp array with 0
for (int i = 1; i <= n; i++)
{
int currChar = s[i - 1] - 'a';
frequencies[currChar]++;
for (int j = 0; j < 26; j++)
{
dp[j][i] = dp[j][i - 1]; // Carry forward the length from previous index
if (j == currChar)
{
dp[j][i]++; // Increment the length for the current character
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// Adjust the length based on the frequency of the character
for (int k = 0; k < j; k++)
{
if (frequencies[j] - frequencies[k] > 0)
{
dp[j][i] = max(dp[j][i], dp[k][i - 1] + 1);
}
}
}
}
}
int maxLength = 0;
// Find the maximum length among all characters
for (int i = 0; i < 26; i++)
{
maxLength = max(maxLength, dp[i][n]);
}
return maxLength;
}
int main()
{
int n;
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
char s[10001];
cin >> n;
cin >> s;
int result = longestAnagramSubsequence(n, s);
cout << result << endl;
return 0;
}
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
import java.util.Arrays;
import java.util.Scanner;
public class Main
{
public static int max(int a, int b)
{
return a > b ? a : b;
}
public static int longestAnagramSubsequence(int n, char[] s)
{
int[] frequencies = new int[26]; // Array to store the frequency of each character
int[][] dp = new int[26][n + 1]; // dp[i][j] stores the length of the longest subsequence ending
Arrays.fill(frequencies, 0); // Initialize frequencies array as 0
for (int i = 1; i <= n; i++)
{
int currChar = s[i - 1] - 'a';
frequencies[currChar]++;
for (int j = 0; j < 26; j++)
{
dp[j][i] = dp[j][i - 1]; // Carry forward the length from the previous index
if (j == currChar)
{
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
dp[j][i]++; // Increment the length for the current character
// Adjust the length based on the frequency of the character
for (int k = 0; k < j; k++)
{
if (frequencies[j] - frequencies[k] > 0)
{
dp[j][i] = max(dp[j][i], dp[k][i - 1] + 1);
}
}
}
}
}
int maxLength = 0;
// Find the maximum length among all characters
for (int i = 0; i < 26; i++)
{
maxLength = max(maxLength, dp[i][n]);
}
return maxLength;
}
public static void main(String[] args)
{
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
char[] s = scanner.next().toCharArray();
int result = longestAnagramSubsequence(n, s);
System.out.println(result);
scanner.close();
}
}
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
def max(a, b):
return a if a > b else b
def longestAnagramSubsequence(n, s):
frequencies = [0] * 26 # Array to store the frequency of each character
dp = [[0] * (n + 1) for _ in range(26)] # dp[i]
[j] stores the length of the longest subsequence ending at index j with character i
for i in range(1, n + 1):
currChar = ord(s[i - 1]) - ord('a')
frequencies[currChar] += 1
for j in range(26):
dp[j][i] = dp[j][i - 1] # Carry forward the length from previous index
if j == currChar:
dp[j][i] += 1 # Increment the length for the current character
# Adjust the length based on the frequency of the character
for k in range(j):
if frequencies[j] - frequencies[k] > 0:
dp[j][i] = max(dp[j][i], dp[k][i - 1] + 1)
maxLength = 0
# Find the maximum length among all characters
for i in range(26):
maxLength = max(maxLength, dp[i][n])
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
return maxLength
n = int(input())
s = input()
result = longestAnagramSubsequence(n, s)
print(result)
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
QUESTION NO : 35
Rohan was assigned a strange homework. He is always passionate about
working on sequences, but this time, he finds things to be a bit messy. So, he
called his friend Jack to work with him and solve the sequence problem.
So, the problem states that:
Consider a sequence S with N elements, all the elements are integer values.
Find the number of pairs in the format of (x,y) such that the element ‘x’ has
occurred in sequence S, minimum ‘y’ times. And the element ‘y’ has occurred
in sequence S minimum ‘x’ times. So, x and y are the elements of S as well.
Jack has to find all such combinations and return the total number of such
combinations.
Let us try to understand it with an example.
Consider N=5, and
A=[1, 2, 3, 4, 5]
QUESTION NO : 35
The number of pairs from the above elements of the sequence can be as
follows:
(1,1): Can be considered as 1(x) occurred a minimum number of 1(y) number of
times.
(1,2): Cannot be considered as 1(x) didn’t occur a minimum of 2(y) number of
times.
(1,3)-(1,4)-(1,5): Similar to (1,2): Cannot be considered.
(2,2)- till (2,5): Cannot be considered.
We can follow other combinations as well, but none of them follows the above
conditions like (1,1). Hence there is only one pair, which follows the rule.
Hence the answer is 1.
Example 1:
Input :
5 -> Input integer, N
1 1 2 2 3 -> Input integer, S[]
QUESTION NO : 35
Explanation:
We can have the below combination:
(1,1): Can be considered as 1(x) occurred a minimum of 1(y) number of times
(1,2): Can be considered as 1(x) occurred at minimum of 2(y) number of times,
and who has acquired a minimum of 2(y) number if times.
Example 2:
Input :
5 -> Input integer, N
1 2 3 4 5 ->Input integer, S[]
Output :
1 -> output
Explanation:
In this scenario, as explained in the demo example we have only 1 pair that
matches the criteria hence the answer is 1.
QUESTION NO : 35
Constraints:
2<=N<=100000
1<=S[]<=100000
Only positive integer values
The input format for testing
First input -accept value of integer N
Next ‘N’ Lines –Elements of sequence S[]
The output format for testing:
The output is an integer value as per the above logic.
(Check the output in Example 1, Example 2).
Additional message in output will cause the failure of test cases.
Instructions:
System doesn’t allow any kind of hard coded input value or values.
Open programme for salaries will be verified against the input which are
supplied from the system.
#include <stdio.h>
#include <stdlib.h>
#define MAX_SIZE 100000
// Function to find the number of valid pairs
int findValidPairs(int N, int S[])
{
int frequency[MAX_SIZE + 1] = {0}; // Array to store the frequency of each ele
// Calculate the frequencies of elements
for (int i = 0; i < N; i++)
{
frequency[S[i]]++;
}
// Find the number of valid pairs
int validPairs = 0;
for (int i = 0; i < N; i++)
{
int x = S[i];
int y = frequency[x];
if (y >= x)
{
validPairs++;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
}
return validPairs;
}
int main()
{
int N;
scanf("%d", &N);
int S[MAX_SIZE];
for (int i = 0; i < N; i++)
{
scanf("%d", &S[i]);
}
int result = findValidPairs(N, S);
printf("%dn", result);
return 0;
}
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#include <iostream>
using namespace std;
#define MAX_SIZE 100000
// Function to find the number of valid pairs
int findValidPairs(int N, int S[])
{
int frequency[MAX_SIZE + 1] = {0};
// Calculate the frequencies of elements
for (int i = 0; i < N; i++)
{
frequency[S[i]]++;
}
// Find the number of valid pairs
int validPairs = 0;
for (int i = 0; i < N; i++)
{
int x = S[i];
int y = frequency[x];
if (y >= x)
{
validPairs++;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
}
return validPairs;
}
int main()
{
int N;
cin >> N;
int S[MAX_SIZE];
for (int i = 0; i < N; i++)
{
cin >> S[i];
}
int result = findValidPairs(N, S);
cout << result;
return 0;
}
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
import java.util.Scanner;
public class Main
{
public static final int MAX_SIZE = 100000;
// Function to find the number of valid pairs
public static int findValidPairs(int N, int[] S)
{
int[] frequency = new int[MAX_SIZE + 1];
// Calculate the frequencies of elements
for (int i = 0; i < N; i++)
{
frequency[S[i]]++;
}
// Find the number of valid pairs
int validPairs = 0;
for (int i = 0; i < N; i++)
{
int x = S[i];
int y = frequency[x];
if (y >= x)
{
validPairs++;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
}
}
return validPairs;
}
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
int N = scanner.nextInt();
int[] S = new int[MAX_SIZE];
for (int i = 0; i < N; i++)
{
S[i] = scanner.nextInt();
}
int result = findValidPairs(N, S);
System.out.println(result);
}
}
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# Function to find the number of valid pairs
def findValidPairs(N, S):
frequency = [0] * (MAX_SIZE + 1)
# Calculate the frequencies of elements
for i in range(N):
frequency[S[i]] += 1
# Find the number of valid pairs
validPairs = 0
for i in range(N):
x = S[i]
y = frequency[x]
if y >= x:
validPairs += 1
return validPairs
MAX_SIZE = 100000
N = int(input())
S = list(map(int, input().split()))
result = findValidPairs(N, S)
print(result)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
QUESTION NO : 36
Rohan went to a gold showroom. All the jewellery is tagged with an index on it.
The indices are integers from 1 to N. He wanted to two items of jewellery for his
wife. When asked for a discount on jewellery items, the store manager who is
retired mathematics professor replied with an unusual response:
The discount will be the number of all those elements falling between the
indices (inclusive of both) of 2 items which have a prime number of divisors.
Assuming that Rohan will buy 2 different pieces of jewellery, which is present at
index ‘i’ and ‘j’, respectively. Find the discount percentage he will receive from the
jewellery store.
Input is the two indices of the respective jewellery items.
Output is the integer value; which Rohan is going to receive as a discount.
Let to try to understand it with an example.
Let’s say Rohan picked 2 items that are present at index 10 and 15 respectively.
This M means I = 10 and J = 15.
QUESTION NO : 36
Now let us check the number of divisors for each number from 10 to 15:
10:Number of divisors are 1,2,5, and 10, total 4, and 4 is not prime. Excluded.
11 : Number of divisors are 1 and 11, total 2, 2 is prime. Included.
12 : Number of divisors are 1,2,3,4,6 and 12, total 6, 6 is not prime. Excluded.
13 : Number of divisors are 1 and 13, total 2, 2 is prime. Included.
14 : Number of divisors are 1,2,7 and 14, total 4, 4 is not prime. Excluded.
15 : Number of divisors are 1,3,5 and 15, total 4, 4 is not prime. Excluded.
So, the total number of elements with a prime number of divisors is only 2
between 10 and 15.
Hence the answer is 2.
Example 1:
Input :
10 -> Input integer, I
16 -> Input integer, j
Output :
3-> output
QUESTION NO : 36
Explanation:
In the abo scenario let’s check the number of divisors for each number from 10
to 16.
10: Number of divisors are 1,2,5 and 10. Total 4 and 4 is not prime. Excluded
11: Number of divisors are 1 and 11. Total 2 and 2 is prime. Included
10: Number of divisors are 1,2,3,4,6 and 12. Total 5 and 5 is not prime. Excluded
13: Number of divisors are 1 and 13. Total 2 and 2 is prime. Included
14: Number of divisors are 1,2,7 and 14. Total 4 and 4 is not prime. Excluded
15: Number of divisors are 1,3,5 and 15. Total 4 and 4 is not prime. Excluded
•Example 2:
•Input :
•32 -> Input integer, I
•40 -> Input integer, j
•Output :
•1 -> output
QUESTION NO : 36
Explanation:In the abo scenario let’s check the number of divisors for each
number from 32 to 40.
32: Number of divisors are 1,2,4,8,16 and 32. Total 6 and 6 is not prime. Excluded
33: Number of divisors are 1,3,11 and 33. Total 4 and 4 is not prime. Excluded
34: Number of divisors are 1,2,17 and 34. Total 4 and 4 is not prime. Excluded
35: Number of divisors are 1,5,7 and 35. Total 4 and 4 is not prime. Excluded
36: Number of divisors are 1,2,3,4,6,9,12,18 and 36. Total 9 and 9 is not
prime.Excluded
37: Number of divisors are 1 and 37. Total 2 and 2 is prime. Included.
38: Number of divisors are 1,2,19 and 38. Total 4 and 4 is not prime. Excluded
39: Number of divisors are 1,3,13 and 39. Total 4 and 4 is not prime. Excluded
QUESTION NO : 36
Constraints:
•1<=i<j<=100000
•Only integers
The candidate has to write the court to accept 2 inputs:
First input accept value of integer
Second input accept value of integer.
Instructions:
•System does not allow any kind of hard coded input value/values.
•Return programme code by the candidate will be verified against the inputs
which are supplied from the system
#include <stdio.h>
#include <math.h>
int isPrime(int n)
{
if (n <= 1)
{
return 0;
}
for (int i = 2; i * i <= n; i++)
{
if (n % i == 0)
{
return 0;
}
}
return 1;
}
int calculateDiscount(int i, int j)
{
int count = 0;
for (int num = i; num <= j; num++)
{
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
int divisors = 0;
for (int divisor = 1; divisor <= num; divisor++)
{
if (num % divisor == 0)
{
divisors++;
}
}
if (isPrime(divisors))
{
count++;
}
}
return count;
}
int main()
{
int i, j;
scanf("%d %d", &i, &j);
int discount = calculateDiscount(i, j);
printf("%dn", discount);
return 0; }
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#include <iostream>
#include <cmath>
using namespace std;
int isPrime(int n)
{
if (n <= 1)
{
return 0;
}
for (int i = 2; i * i <= n; i++)
{
if (n % i == 0)
{
return 0;
}
}
return 1;
}
int calculateDiscount(int i, int j)
{
int count = 0;
for (int num = i; num <= j; num++)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
{
int divisors = 0;
for (int divisor = 1; divisor <= num; divisor++)
{
if (num % divisor == 0)
{
divisors++;
}
}
if (isPrime(divisors))
{
count++;
}}
return count;
}
int main()
{
int i, j;
cin >> i >> j;
int discount = calculateDiscount(i, j);
cout << discount;
return 0; }
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
import java.util.Scanner;
public class Main
{
public static int isPrime(int n)
{
if (n <= 1)
{
return 0;
}
for (int i = 2; i * i <= n; i++)
{
if (n % i == 0)
{
return 0;
}
}
return 1;
}
public static int calculateDiscount(int i, int j)
{
int count = 0;
for (int num = i; num <= j; num++)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
{
int divisors = 0;
for (int divisor = 1; divisor <= num; divisor++)
{
if (num % divisor == 0)
{
divisors++;
}
}
if (isPrime(divisors) == 1)
{
count++;
}
}
return count;
}
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
int i = scanner.nextInt();
int j = scanner.nextInt();
int discount = calculateDiscount(i, j);
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
System.out.println(discount);
}
}
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
def isPrime(n):
if n <= 1:
return 0
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return 0
return 1
def calculateDiscount(i, j):
count = 0
for num in range(i, j + 1):
divisors = 0
for divisor in range(1, num + 1):
if num % divisor == 0:
divisors += 1
if isPrime(divisors) == 1:
count += 1
return count
i = int(input())
j=int(input())
discount = calculateDiscount(i, j)
print(discount)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
QUESTION NO : 37
You are given an Array ‘Arr’ of ‘N’ positive integers. You need to convert the given
array ‘Arr’ to Zero-Array.
An Array ‘A’ is know as Zero-Array if the bitwise AND (&) of all the elements of the
array is Zero.
In other words, Array ‘A’ with length ‘L’ is known as Zero –Array if A[0] & A[1] &
A[2]………& A[L] = 0.
For example array [1,2,3]is a Zero-Array, you can perform the following move any
number of times:
•Choose any array elements from Array ‘Arr’, say Arr[i], and flip exactly one bit in
Arr[i] (Flipping a bit means if the bit is 1 then covert it to 0 and if the bit is 0 then
convert it to 1)
•You need to find the minimum number of moves to convert the given array ‘Arr’
to Zero-Array .
QUESTION NO : 37
The input format for testing
First Line Contains a positive Integer N (Size of the array)
Next Line Contains N space-separated positive integers
The Output format for testing:
The output is an integer value as per above logic. (Check the output in Example 1,
Example 2).
Additional messages in output will cause the failure of test cases.
Constraints:
N==Length of Array ‘Arr’
1<=N<= 1000
1<=Arr[i]<= 10000,
for all valid (0 <=i<=N-1)
QUESTION NO : 37
Example 1:
Input:
5 -> N (size of the array)
10 11 13 5 3 -> Array ‘Arr’ (Elements of the array will be space separated
Output:
0
Explanation:
The given array is already a zero Array since 10 & 11 & 13 & 5 & 3 = 0.
So,minimum number of moves required are 0.
#include <stdio.h>
int main()
{
int N;
scanf("%d", &N); // Read the size of the array
int Arr[N];
for (int i = 0; i < N; i++)
{
scanf("%d", &Arr[i]); // Read the elements of the array
}
int minMoves = 0;
int bitwiseAnd = Arr[0]; // Initialize the bitwise AND with the first element
// Calculate the bitwise AND of all elements in the array
for (int i = 1; i < N; i++)
{
bitwiseAnd &= Arr[i];
}
// Count the number of set bits in the bitwise AND
while (bitwiseAnd != 0)
{
if (bitwiseAnd & 1)
{
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
minMoves++;
}
bitwiseAnd >>= 1;
}
printf("%dn", minMoves); // Print the minimum number of moves
return 0;
}
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#include <iostream>
using namespace std;
int main()
{
int N;
cin >> N; // Read the size of the array
int Arr[N];
for (int i = 0; i < N; i++)
{
cin >> Arr[i]; // Read the elements of the array
}
int minMoves = 0;
int bitwiseAnd = Arr[0]; // Initialize the bitwise AND with the first element
// Calculate the bitwise AND of all elements in the array
for (int i = 1; i < N; i++)
{
bitwiseAnd &= Arr[i];
}
// Count the number of set bits in the bitwise AND
while (bitwiseAnd != 0)
{
if (bitwiseAnd & 1)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
{
minMoves++;
}
bitwiseAnd >>= 1;
}
cout << minMoves; // Print the minimum number of moves
return 0;
}
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
int N = scanner.nextInt(); // Read the size of the array
int[] Arr = new int[N];
for (int i = 0; i < N; i++)
{
Arr[i] = scanner.nextInt(); // Read the elements of the array
}
int minMoves = 0;
int bitwiseAnd = Arr[0];
// Calculate the bitwise AND of all elements in the array
for (int i = 1; i < N; i++)
{
bitwiseAnd &= Arr[i];
}
// Count the number of set bits in the bitwise AND
while (bitwiseAnd != 0)
{
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
if ((bitwiseAnd & 1) == 1)
{
minMoves++;
}
bitwiseAnd >>= 1;
}
System.out.println(minMoves); // Print the minimum number of moves
}
}
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
N = int(input()) # Read the size of the array
Arr = list(map(int, input().split())) # Read the elements of the array
minMoves = 0
bitwiseAnd = Arr[0] # Initialize the bitwise AND with the first element
# Calculate the bitwise AND of all elements in the array
for i in range(1, N):
bitwiseAnd &= Arr[i]
# Count the number of set bits in the bitwise AND
while bitwiseAnd != 0:
if bitwiseAnd & 1 == 1:
minMoves += 1
bitwiseAnd >>= 1
print(minMoves) # Print the minimum number of moves
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
QUESTION NO : 38
You are given an Array ‘Arr’ of ‘N’ positive integers. You need to convert the given
array ‘Arr’ to Zero-Array.
An Array ‘A’ is know as Zero-Array if the bitwise AND (&) of all the elements of the
array is Zero.
In other words, Array ‘A’ with length ‘L’ is known as Zero –Array if A[0] & A[1] &
A[2]………& A[L] = 0.
For example array [1,2,3]is a Zero-Array, you can perform the following move any
number of times:
•Choose any array elements from Array ‘Arr’, say Arr[i], and flip exactly one bit in
Arr[i] (Flipping a bit means if the bit is 1 then covert it to 0 and if the bit is 0 then
convert it to 1)
•You need to find the minimum number of moves to convert the given array ‘Arr’
to Zero-Array .
QUESTION NO : 38
The input format for testing
First Line Contains a positive Integer N (Size of the array)
Next Line Contains N space-separated positive integers
The Output format for testing:
The output is an integer value as per above logic. (Check the output in Example 1,
Example 2).
Additional messages in output will cause the failure of test cases.
Constraints:
N==Length of Array ‘Arr’
1<=N<= 1000
1<=Arr[i]<= 10000,
for all valid (0 <=i<=N-1)
QUESTION NO : 38
Example 1:
Input:
5 -> N (size of the array)
10 11 13 5 3 -> Array ‘Arr’ (Elements of the array will be space separated
Output:
0
Explanation:
The given array is already a zero Array since 10 & 11 & 13 & 5 & 3 = 0.
So,minimum number of moves required are 0.
#include <stdio.h>
int main()
{
int N;
scanf("%d", &N); // Read the size of the array
int Arr[N];
for (int i = 0; i < N; i++)
{
scanf("%d", &Arr[i]); // Read the elements of the array
}
int minMoves = 0;
int bitwiseAnd = Arr[0]; // Initialize the bitwise AND with the first element
// Calculate the bitwise AND of all elements in the array
for (int i = 1; i < N; i++)
{
bitwiseAnd &= Arr[i];
}
// Count the number of set bits in the bitwise AND
while (bitwiseAnd != 0)
{
if (bitwiseAnd & 1)
{
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
minMoves++;
}
bitwiseAnd >>= 1;
}
printf("%dn", minMoves); // Print the minimum number of moves
return 0;
}
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#include <iostream>
using namespace std;
int main()
{
int N;
cin >> N; // Read the size of the array
int Arr[N];
for (int i = 0; i < N; i++)
{
cin >> Arr[i]; // Read the elements of the array
}
int minMoves = 0;
int bitwiseAnd = Arr[0]; // Initialize the bitwise AND with the first element
// Calculate the bitwise AND of all elements in the array
for (int i = 1; i < N; i++)
{
bitwiseAnd &= Arr[i];
}
// Count the number of set bits in the bitwise AND
while (bitwiseAnd != 0)
{
if (bitwiseAnd & 1)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
{
minMoves++;
}
bitwiseAnd >>= 1;
}
cout << minMoves; // Print the minimum number of moves
return 0;
}
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
int N = scanner.nextInt(); // Read the size of the array
int[] Arr = new int[N];
for (int i = 0; i < N; i++)
{
Arr[i] = scanner.nextInt(); // Read the elements of the array
}
int minMoves = 0;
int bitwiseAnd = Arr[0];
// Calculate the bitwise AND of all elements in the array
for (int i = 1; i < N; i++)
{
bitwiseAnd &= Arr[i];
}
// Count the number of set bits in the bitwise AND
while (bitwiseAnd != 0)
{
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
if ((bitwiseAnd & 1) == 1)
{
minMoves++;
}
bitwiseAnd >>= 1;
}
System.out.println(minMoves); // Print the minimum number of moves
}
}
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
N = int(input()) # Read the size of the array
Arr = list(map(int, input().split())) # Read the elements of the array
minMoves = 0
bitwiseAnd = Arr[0] # Initialize the bitwise AND with the first element
# Calculate the bitwise AND of all elements in the array
for i in range(1, N):
bitwiseAnd &= Arr[i]
# Count the number of set bits in the bitwise AND
while bitwiseAnd != 0:
if bitwiseAnd & 1 == 1:
minMoves += 1
bitwiseAnd >>= 1
print(minMoves) # Print the minimum number of moves
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
QUESTION NO : 39
An English teacher wants the overall development of the students. She plans a
surprise quiz to test the analytical skills of the students. She gives two words
(str1,str2), the task for the students here is:
Observe both the words carefully. Change the word1 to word2.
The student who can change the words with a minimum number of steps is the
winner.
Note:
Only of the operations – insert, delete or replace can be performed in one step.
All the operators should be performed only on word1. The string cannot have any
special characters, space or number.
Constraints:
Str1={a-z)
Str1 != (A-Z0-9,special characters)
No spaces between characters
Size of Str1 and Str2<50
QUESTION NO : 39
Input format for testing
The candidate has to write the code to accept 2 input(s).
First Input - Accept value str1 which is a string.
Second Input -Accept value str1 which is a string.
Output format for testing
The output should be a single integer value or a message if given in the problem
statement (Check the output in Example 1. Example 2)
Additional messages in output will cause the failure of test cases.
Example 1
Input:
Capture -> value of str 1
Capsule -> value of str 2
Output:
2-> number of steps required to convert str 1 to str 2
QUESTION NO : 39
Explanation:
To convert capture to capsule in
Step 1: 't' is replaced with ‘s’(capsure)
Step 2: 'r' is replaced with ‘l' (capsule)
Hence, the output is 2.
Example 2
Input:
Computer -> value of str 1
Compute -> value of str 2
Output:
1 -> number of steps required to convert computer to compute,
Explanation:
To convert from computer to compute, in
Step 1: ‘r’ is removed (computer)
Hence, the output is 1.
#include <stdio.h>
#include <string.h>
int min(int a, int b, int c)
{
if (a <= b && a <= c)
return a;
else if (b <= a && b <= c)
return b;
else
return c;
}
int findMinSteps(char *str1, char *str2)
{
int m = strlen(str1);
int n = strlen(str2);
// Create a 2D table to store subproblem results
int dp[m+1][n+1];
// Fill the table bottom-up
for (int i = 0; i <= m; i++)
{
for (int j = 0; j <= n; j++)
{
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// If str1 is empty, then we need to insert all characters from str2
if (i == 0)
dp[i][j] = j;
// If str2 is empty, then we need to delete all characters from str1
else if (j == 0)
dp[i][j] = i;
// If the last characters are the same, no operation needed
else if (str1[i-1] == str2[j-1])
dp[i][j] = dp[i-1][j-1];
// If the last characters are different, consider all possibilities
else
dp[i][j] = 1 + min(dp[i][j-1], dp[i-1][j], dp[i-1][j-1]); } }
return dp[m][n]; }
int main() {
char str1[50], str2[50];
scanf("%s", str1);
scanf("%s", str2);
int minSteps = findMinSteps(str1, str2);
printf("%d",minSteps);
return 0;
}
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#include <iostream>
#include <cstring>
using namespace std;
int min(int a, int b, int c)
{
if (a <= b && a <= c)
return a;
else if (b <= a && b <= c)
return b;
else
return c;
}
int findMinSteps(const char* str1, const char* str2)
{
int m = strlen(str1);
int n = strlen(str2);
// Create a 2D table to store subproblem results
int dp[m + 1][n + 1];
// Fill the table bottom-up
for (int i = 0; i <= m; i++)
{
for (int j = 0; j <= n; j++)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
{
// If str1 is empty, then we need to insert all characters from str2
if (i == 0)
dp[i][j] = j;
// If str2 is empty, then we need to delete all characters from str1
else if (j == 0)
dp[i][j] = i;
// If the last characters are the same, no operation needed
else if (str1[i - 1] == str2[j - 1])
dp[i][j] = dp[i - 1][j - 1];
// If the last characters are different, consider all possibilities
else
dp[i][j] = 1 + min(dp[i][j - 1], dp[i - 1][j], dp[i - 1][j - 1]);
}
}
return dp[m][n];
}
int main()
{
char str1[50], str2[50];
cin >> str1 >> str2;
int minSteps = findMinSteps(str1, str2);
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
cout << minSteps;
return 0;
}
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
import java.util.Scanner;
public class Main
{
public static int min(int a, int b, int c)
{
if (a <= b && a <= c)
return a;
else if (b <= a && b <= c)
return b;
else
return c;
}
public static int findMinSteps(String str1, String str2)
{
int m = str1.length();
int n = str2.length();
// Create a 2D table to store subproblem results
int[][] dp = new int[m + 1][n + 1];
// Fill the table bottom-up
for (int i = 0; i <= m; i++)
{
for (int j = 0; j <= n; j++)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
{
// If str1 is empty, then we need to insert all characters from str2
if (i == 0)
dp[i][j] = j;
// If str2 is empty, then we need to delete all characters from str1
else if (j == 0)
dp[i][j] = i;
// If the last characters are the same, no operation needed
else if (str1.charAt(i - 1) == str2.charAt(j - 1))
dp[i][j] = dp[i - 1][j - 1];
// If the last characters are different, consider all possibilities
else
dp[i][j] = 1 + min(dp[i][j - 1], dp[i - 1][j], dp[i - 1][j - 1]);
}
}
return dp[m][n];
}
public static void main(String[] args)
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
int minSteps = findMinSteps(str1, str2);
System.out.println(minSteps);
}
}
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
def min(a, b, c):
if a <= b and a <= c:
return a
elif b <= a and b <= c:
return b
else:
return c
def findMinSteps(str1, str2):
m = len(str1)
n = len(str2)
# Create a 2D table to store subproblem results
dp = [[0] * (n + 1) for _ in range(m + 1)]
# Fill the table bottom-up
for i in range(m + 1):
for j in range(n + 1):
# If str1 is empty, then we need to insert all characters from str2
if i == 0:
dp[i][j] = j
# If str2 is empty, then we need to delete all characters from str1
elif j == 0:
dp[i][j] = i
# If the last characters are the same, no operation needed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
elif str1[i - 1] == str2[j - 1]:
dp[i][j] = dp[i - 1][j - 1]
# If the last characters are different, consider all possibilities
else:
dp[i][j] = 1 + min(dp[i][j - 1], dp[i - 1][j], dp[i - 1][j - 1])
return dp[m][n]
str1 = input()
str2 = input()
minSteps = findMinSteps(str1, str2)
print(minSteps)
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
QUESTION NO : 40
A single currency note(N) and a coin(R) are given. The task is to fight in how many
ways can make the value that is equal to the currency note using the coin.The
coin can be used in the following ways:
The value of the coin represents the maximum range values(1,R) that can be used
to make the sum equal to N. Each integer value up to the range C can be used
multiple times to make the sum.
Constraints:
1< =N<=100
1<=R <=100
The Input format for testing
•The candidate has to write the code to accept 2 input(s)
•First Input - Accept value for input string.
•First Input - Accept value for input key.
QUESTION NO : 40
The Output format for testing
•The output should be a sorted string based on the input key given by the user as
mentioned in the above criteria. (Check the output in Example 1, Example 2)
•Additional messages in output will cause the failure of test cases.
Example 1:
Input:
8 -> Value of N
2 -> Value of R
Output:
5 Maximum combinations using values up to R to get the sum equal to N
→
QUESTION NO : 40
Explanation:
The various combinations the currency note N=8 can be formed using the values
upto range 2 are:
1+1+1+1+1+1+1+1=8
2+1+1+1+1+1+1=8
2+2+1+1+1+1=8
2+2+2+1+1=8
2+2+2+2=8
Hence there are 5 ways the coin with range up to 2 can be used to get the value
of currency note i.e 8
QUESTION NO : 40
Example 2:
Input:
2 -> Value of N
2-> Value of R
Output:
2 Maximum combinations using values up to R to get the sum equal to N
→
Explanation:
The various combinations the currency note N=2 can be formed using the values
upto range 2 are:
R={1,2}
1+1=2
Hence there are 2 ways the coin with range up to 2 can be used to get the value
of currency note i.e 2
#include <stdio.h>
int findCombinations(int N, int R)
{
int dp[101] = {0}; // Dynamic programming array
dp[0] = 1; // Base case
for (int i = 1; i <= R; i++)
{
for (int j = i; j <= N; j++)
{
dp[j] += dp[j - i]; a
}
}
return dp[N];
}
int main() {
int N, R;
scanf("%d", &N);
scanf("%d", &R);
int combinations = findCombinations(N, R);
printf("%d", combinations);
return 0;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>
using namespace std;
int findCombinations(int N, int R)
{
int dp[101] = {0}; // Dynamic programming array
dp[0] = 1; // Base case
for (int i = 1; i <= R; i++)
{
for (int j = i; j <= N; j++)
{
dp[j] += dp[j -i]; }
}
return dp[N];
}
int main()
{
int N, R;
cin >> N >> R;
int combinations = findCombinations(N, R);
cout << combinations;
return 0;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import java.util.Scanner;
public class Main
{
public static int findCombinations(int N, int R)
{
int[] dp = new int[101]; // Dynamic programming array
dp[0] = 1; // Base case
for (int i = 1; i <= R; i++)
{
for (int j = i; j <= N; j++)
{
dp[j] += dp[j - i];
}
}
return dp[N]; }
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
int N = scanner.nextInt();
int R = scanner.nextInt();
int combinations = findCombinations(N, R);
System.out.println(combinations); }}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
def findCombinations(N, R):
dp = [0] * (N + 1) # Dynamic programming array
dp[0] = 1 # Base case
for i in range(1, R + 1):
for j in range(i, N + 1):
dp[j] += dp[j - i] # Calculate combinations using values up to range R
return dp[N]
N = int(input())
R = int(input())
combinations = findCombinations(N, R)
print(combinations)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
Topic/Course
Sub-Topic (Example: name of college)
Set E
QUESTION NO : 41
Given N stones, each stone has some weight assigned to it. A box with C capacity
is also given. The task is to find out, the minimum number po/boxes which are e
require the box.
Note: C>Arr[0] to Arr[N], where Arr[i] represents the weight of ith stone.
Example 1:
Input:
5 -> Value of N
10 20 30 40 50 -> Element of Arr[]
60 -> Value of C
Output:
3 ->Minimum 3 boxes required.
Explanation:
Arr[]={10,20,30,40,50} and C-60
1st box={10,20,30}
2nd box=(40)
QUESTION NO : 41
Constraints:
1<N<=100
1<=Arr[i]<=100
Arr[i]<C<=200
Example 2:
Input:
4 -> Value of N
10 20 30 30 -> Element of Arr[]
80 -> Value of C
Output:
2 -> Minimum 2 boxes required.
#include <iostream>
using namespace std;
int minBoxesRequired(int n, int arr[], int c)
{
int boxes = 0;
int currentCapacity = c;
for (int i = 0; i < n; i++)
{
if (arr[i] <= currentCapacity)
{
currentCapacity -= arr[i];
}
else
{
boxes++;
currentCapacity = c - arr[i];
}
}
if (currentCapacity < c)
boxes++;
return boxes;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
int main()
{
int n;
cin >> n;
int arr[n];
for (int i = 0; i < n; i++)
{
cin >> arr[i];
}
int c;
cin >> c;
int minBoxes = minBoxesRequired(n, arr, c);
cout << minBoxes;
return 0;
}
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#include<stdio.h>
int minBoxesRequired(int n, int arr[], int c)
{
int boxes = 0;
int currentCapacity = c;
for (int i = 0; i < n; i++)
{
if (arr[i] <= currentCapacity)
{
currentCapacity -= arr[i];
}
else
{
boxes++;
currentCapacity = c - arr[i];
}
}
if (currentCapacity < c)
boxes++;
return boxes;
}
int main()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
{
int n;
scanf("%d", &n);
int arr[n];
for (int i = 0; i < n; i++)
{
scanf("%d", &arr[i]);
}
int c;
scanf("%d", &c);
int minBoxes = minBoxesRequired(n, arr, c);
printf("%d", minBoxes);
return 0;
}
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
import java.util.Scanner;
public class Main
{
public static int minBoxesRequired(int n, int[] arr, int c)
{
int boxes = 0;
int currentCapacity = c;
for (int i = 0; i < n; i++)
{
if (arr[i] <= currentCapacity)
{
currentCapacity -= arr[i];
}
else
{
boxes++;
currentCapacity = c - arr[i];
}
}
if (currentCapacity < c)
boxes++;
return boxes;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
}
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int[] arr = new int[n];
for (int i = 0; i < n; i++)
{
arr[i] = scanner.nextInt();
}
int c = scanner.nextInt();
int minBoxes = minBoxesRequired(n, arr, c);
System.out.println(minBoxes);
scanner.close();
}
}
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
def min_boxes_required(n, arr, c):
boxes = 0
current_capacity = c
for i in range(n):
if arr[i] <= current_capacity:
current_capacity -= arr[i]
else:
boxes += 1
current_capacity = c - arr[i]
if current_capacity < c:
boxes += 1
return boxes
n = int(input())
arr = list(map(int, input().split()))
c = int(input())
min_boxes = min_boxes_required(n, arr, c)
print(min_boxes)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
QUESTION NO : 42
Given a string Str, which contains numbers (0 to 9)and also letters of the English
and to 'Z'). The task is to reverse string the string in such a way that the positiors
of numbers in the string are left unaltered.
Example 1:
Input:
a1b2igh3 -> Value of Str
Output:
h1g2iba3
Explanation:
Without changing the positions of 1, 2 and 3, only the positions of characters 'h',
'g, "i', 'b' and 'a' have been reversed.
QUESTION NO : 42
Example 2:
Input:
Ab5c7de96 -> Value of Str
Output:
ed5c7bA96
#include <stdio.h>
#include <ctype.h>
void reverseString(char str[])
{
int len = 0;
while (str[len] != '0')
{
len++;
}
int start = 0;
int end = len - 1;
while (start < end)
{
// Skip numbers in the string
while (isdigit(str[start]))
{
start++;
}
while (isdigit(str[end]))
{
end--;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// Swap characters
char temp = str[start];
str[start] = str[end];
str[end] = temp;
start++;
end--;
}
}
int main()
{
char str[100];
scanf("%s", str);
reverseString(str);
printf("%s", str);
return 0;
}
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#include <iostream>
#include <cctype>
using namespace std;
void reverseString(char str[])
{
int len = 0;
while (str[len] != '0')
{
len++;
}
int start = 0;
int end = len - 1;
while (start < end)
{
// Skip numbers in the string
while (isdigit(str[start]))
{
start++;
}
while (isdigit(str[end]))
{
end--;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
}
// Swap characters
char temp = str[start];
str[start] = str[end];
str[end] = temp;
start++;
end--;
}
}
int main()
{
char str[100];
cin >> str;
reverseString(str);
cout << str;
return 0;
}
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
import java.util.Scanner;
public class Main
{
public static void reverseString(char[] str)
{
int len = str.length;
int start = 0;
int end = len - 1;
while (start < end)
{
// Skip numbers in the string
while (Character.isDigit(str[start]))
{
start++;
}
while (Character.isDigit(str[end]))
{
end--;
}
// Swap characters
char temp = str[start];
str[start] = str[end];
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
str[end] = temp;
start++;
end--;
}
}
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
String input = scanner.nextLine();
char[] str = input.toCharArray();
reverseString(str);
System.out.println(str);
scanner.close();
}
}
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
def reverseString(str):
start = 0
end = len(str) - 1
while start < end:
# Skip numbers in the string
while str[start].isdigit():
start += 1
while str[end].isdigit():
end -= 1
# Swap characters
str[start], str[end] = str[end], str[start]
start += 1
end -= 1
# Main function
input_str = input()
str_list = list(input_str)
reverseString(str_list)
print("".join(str_list))
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
QUESTION NO : 43
A thief pretending to be a customer entered a jewellery store. On the same night,
he planned a burglary. There is 'N' number of items with their (a[]) on display
boards. The thief scans through the prices of all the items. The task here is to find
the most valuable (costliest) items of jewellery to steal.
Example 1:
Input:
8 Value of N
→
102 101 5 7 99 1 2 3 a[], Elements a[0]to a[N- 1], where input each element is
→
seperated by a new line
Output:
111 Number of elements whose adjacent elements are greater
→
QUESTION NO : 43
Explanation:
Starting from the first element we create subarrays of elements which are in
ascending order.
a[0]>a[1]
Subarray 1: {102}
a[1]>a[2]
Subarray 2: {101}
a[2]<a[3]
In this case,we will continue to compare with next element until we find a greater
number.
a[3]<a[4],continue
a[4]>a[5],stop and create sub array
Subarray 3: {5,7,99}
a[5]>a[6],continue
a[6]>a[7],end of array
QUESTION NO : 43
Subarray 4:{1,2,3}
Summing up prices of each subarray:
above,we can deduce the sub array 3 has the most valuable items.
Hence the output is 111.
Example 2:
Input:
5 Value of N
→
10 20 30 40 50 a[], Elements a[0]to a[N- 1], where input each element is
→
seperated by a new line
Output:
150 Number of elements whose adjacent elements are greater
→
#include <stdio.h>
int countValuableItems(int a[], int N)
{
int count = 0;
int maxSum = 0;
int currentSum = 0;
for (int i = 0; i < N - 1; i++)
{
if (a[i] < a[i + 1])
{
currentSum += a[i];
count++;
}
else
{
currentSum += a[i];
if (currentSum > maxSum)
{
maxSum = currentSum;
}
currentSum = 0;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
}
// Check if the last element is part of a valuable item
if (a[N - 2] < a[N - 1])
{
currentSum += a[N - 1];
count++;
}
if (currentSum > maxSum)
{
maxSum = currentSum;
}
return maxSum;
}
int main()
{
int N;
scanf("%d", &N);
int a[N];
for (int i = 0; i < N; i++)
{
scanf("%d", &a[i]);
}
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
int result = countValuableItems(a, N);
printf("%dn", result);
return 0;
}
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#include <iostream>
using namespace std;
int countValuableItems(int a[], int N)
{
int count = 0;
int maxSum = 0;
int currentSum = 0;
for (int i = 0; i < N - 1; i++)
{
if (a[i] < a[i + 1])
{
currentSum += a[i];
count++;
}
else
{
currentSum += a[i];
maxSum = max(maxSum, currentSum);
currentSum = 0;
}
}
// Check if the last element is part of a valuable item
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
if (a[N - 2] < a[N - 1])
{
currentSum += a[N - 1];
count++;
}
maxSum = max(maxSum, currentSum);
return maxSum;
}
int main()
{
int N;
cin >> N;
int a[N];
for (int i = 0; i < N; i++)
{
cin >> a[i];
}
int result = countValuableItems(a, N);
cout <<result << endl;
return 0;
}
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
import java.util.Scanner;
public class Main
{
public static int countValuableItems(int[] a, int N)
{
int count = 0;
int maxSum = 0;
int currentSum = 0;
for (int i = 0; i < N - 1; i++)
{
if (a[i] < a[i + 1])
{
currentSum += a[i];
count++;
}
else
{
currentSum += a[i];
if (currentSum > maxSum)
{
maxSum = currentSum;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
currentSum = 0;
}
}
// Check if the last element is part of a valuable item
if (a[N - 2] < a[N - 1])
{
currentSum += a[N - 1];
count++;
}
if (currentSum > maxSum)
{
maxSum = currentSum;
}
return maxSum;
}
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
int N = scanner.nextInt();
int[] a = new int[N];
for (int i = 0; i < N; i++)
{
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
a[i] = scanner.nextInt();
}
int result = countValuableItems(a, N);
System.out.println(result);
}
}
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
def countValuableItems(a, N):
count = 0
maxSum = 0
currentSum = 0
for i in range(N - 1):
if a[i] < a[i + 1]:
currentSum += a[i]
count += 1
else:
currentSum += a[i]
if currentSum > maxSum:
maxSum = currentSum
currentSum = 0
# Check if the last element is part of a valuable item
if a[N - 2] < a[N - 1]:
currentSum += a[N - 1]
count += 1
if currentSum > maxSum:
maxSum = currentSum
return maxSum
N = int(input())
a = list(map(int, input().split()))
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
result = countValuableItems(a, N)
print(result)
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
QUESTION NO : 44
An automation company is about to launch its beta version of automatic doors
for the home. Before using voice assistant or Smartphone control, they build a
remote control to operate the doors. Due to technical wirework issues, the
automation process isn't operating correctly. Assume, there are an N number of
doors in a home. It so happens that if one door is opened/closed using a remote
control, all the doors in the following indexes will also change their state. i.e. if
the initial state of a door(a[0]) is open(1), on pressing the open button on the
remote control, all the doors(a[1],a[2],a[3]........) change
their state. Initially, the state of each whether doors open close (0) is given as
array elements. The task hereis to find the LEAST number of times the button
(On/Off) on the remote control has to be used such that all the doors are opened.
Note: The On/Off button for each door can be pressed multiple times.
QUESTION NO : 44
Example 1:
Input:
5 -> value of N
(1,0,1,1,1] a[], Element of a[0]to a[N-1],While
→
Input each element is separated by new line
Output:
2 Least count of button press
→
Explanation:
a0=[1,0,1,1,1]
Press button 1: [1,1,0,0,0]
Press button 2: [1,1,1,1,1]
Hence, Least 2 button press required to open the all doors
#include <stdio.h>
int findLeastButtonPress(int doors[], int n)
{
int count = 0;
int i, j;
// Iterate over the doors
for (i = 0; i < n; i++)
{
// If the current door is closed (0), press the button
if (doors[i] == 0)
{
count++;
// Change the state of all following doors
for (j = i; j < n; j++)
{
doors[j] = 1 - doors[j];
}
}
}
return count;
}
int main()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
{
int N;
scanf("%d", &N);
int doors[N];
int i;
for (i = 0; i < N; i++)
{
scanf("%d", &doors[i]);
}
int result = findLeastButtonPress(doors, N);
printf("%dn", result);
return 0;
}
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#include <iostream>
#include <vector>
using namespace std;
int findLeastButtonPress(vector<int>& doors)
{
int n = doors.size();
int count = 0;
// Iterate over the doors
for (int i = 0; i < n; i++)
{
// If the current door is closed (0), press the button
if (doors[i] == 0)
{
count++;
// Change the state of all following doors
for (int j = i; j < n; j++)
{
doors[j] = 1 - doors[j];
}
}
}
return count;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
}
int main()
{
int N;
cin >> N;
vector<int> doors(N);
for (int i = 0; i < N; i++)
{
cin >> doors[i];
}
int result = findLeastButtonPress(doors);
cout << result << endl;
return 0;
}
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
import java.util.Scanner;
public class Main
{
public static int findLeastButtonPress(int[] doors, int n)
{
int count = 0;
// Iterate over the doors
for (int i = 0; i < n; i++)
{
// If the current door is closed (0), press the button
if (doors[i] == 0)
{
count++;
// Change the state of all following doors
for (int j = i; j < n; j++)
{
doors[j] = 1 - doors[j];
}
}
}
return count;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
int N = scanner.nextInt();
int[] doors = new int[N];
for (int i = 0; i < N; i++)
{
doors[i] = scanner.nextInt();
}
int result = findLeastButtonPress(doors, N);
System.out.println(result);
}
}
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
def findLeastButtonPress(doors, n):
count = 0
# Iterate over the doors
for i in range(n):
# If the current door is closed (0), press the button
if doors[i] == 0:
count += 1
# Change the state of all following doors
for j in range(i, n):
doors[j] = 1 - doors[j]
return count
# Main function
N = int(input())
doors = list(map(int, input().split()))
result = findLeastButtonPress(doors, N)
print(result)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
QUESTION NO : 45
A safety and security services agency communicates to its employees only in
secret messages in case of emergency. The employee sends the message with a
secret code(key). Here, the code will be same combination of characters in both
the messages(strings) sent. The task is to find the combination of letters(key) that
is present both the strings.
Input format for testing:
The candidate has to write the code to accept 2 inputs.
First Input- Accept a string value consisting of only literal characters.
Second Input-Accept a string value consisting of only characters.
Output format for testing:
The output should be string of characters which is same in both the input strings
(check the output in Example 1 and 2)
The output should be generated in alphabetic order sequence.
Additional message in output cause the failure of test cases.
QUESTION NO : 45
Constraints:
Str 1= {a-z}
Str 2= {a-z}
0<size of str 1 <20
0< size of str 2 <20
Example1:
Input:
beads -> value for str1
leaps value for str2
→
Output:
aes -> the key ‘aes’ is present in both strings
QUESTION NO : 45
Example2:
Input:
abcdefgh -> value for str1
abcdxyz value for str2
→
Output:
abcd –> key ‘abcd’ is present in both the strings
#include <stdio.h>
#include <string.h>
char* findCommonKey(const char* str1, const char* str2)
{
static char commonKey[20];
int count1[26] = {0};
int count2[26] = {0};
int len1 = strlen(str1);
int len2 = strlen(str2);
for (int i = 0; i < len1; i++)
{
count1[str1[i] - 'a']++;
}
for (int i = 0; i < len2; i++)
{
count2[str2[i] - 'a']++;
}
int index = 0;
for (int i = 0; i < 26; i++)
{
int minCount = (count1[i] < count2[i]) ? count1[i] : count2[i];
for (int j = 0; j < minCount; j++)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
{
commonKey[index++] = 'a' + i;
}
}
commonKey[index] = '0';
return commonKey;
}
int main()
{
char str1[20], str2[20];
scanf("%s %s", str1, str2);
char* commonKey = findCommonKey(str1, str2);
printf("%sn", commonKey);
return 0;
}
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#include <iostream>
#include <string>
using namespace std;
string findCommonKey(const string& str1, const string& str2)
{
string commonKey;
int count1[26] = {0};
int count2[26] = {0};
for (char ch : str1)
{
count1[ch - 'a']++;
}
for (char ch : str2)
{
count2[ch - 'a']++;
}
for (int i = 0; i < 26; i++)
{
int minCount = min(count1[i], count2[i]);
for (int j = 0; j < minCount; j++)
{
commonKey += 'a' + i;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
}
}
return commonKey;
}
int main()
{
string str1, str2;
cin >> str1 >> str2;
string commonKey = findCommonKey(str1, str2);
cout << commonKey << endl;
return 0;
}
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
import java.util.Scanner;
public class Main
{
public static String findCommonKey(String str1, String str2)
{
StringBuilder commonKey = new StringBuilder();
int[] count1 = new int[26];
int[] count2 = new int[26];
for (char ch : str1.toCharArray())
{
count1[ch - 'a']++;
}
for (char ch : str2.toCharArray())
{
count2[ch - 'a']++;
}
for (int i = 0; i < 26; i++)
{
int minCount = Math.min(count1[i], count2[i]);
for (int j = 0; j < minCount; j++)
{
commonKey.append((char)('a' + i));
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
}
}
return commonKey.toString();
}
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
String str1 = scanner.nextLine();
String str2 = scanner.nextLine();
String commonKey = findCommonKey(str1, str2);
System.out.println(commonKey);
}
}
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
def find_common_key(str1, str2):
common_key = ""
count1 = [0] * 26
count2 = [0] * 26
for ch in str1:
count1[ord(ch) - ord('a')] += 1
for ch in str2:
count2[ord(ch) - ord('a')] += 1
for i in range(26):
min_count = min(count1[i], count2[i])
common_key += chr(ord('a') + i) * min_count
return common_key
str1 = input()
str2 = input()
common_key = find_common_key(str1, str2)
print(common_key)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
QUESTION NO : 46
An upmarket housing society has N number of row houtes The electrical boards
of all the houses are connected through common wiring. Due to the faulty wiring
system a major fire broke out and all the houses are in the grave danger. The fire
brigade has arrived and they have started evacuating people from their
houses.The number of people in each house depicts the elements of
array(a[]).the task here is to find the number of steps that the fire fighters Will
require to evacuate members the houses in the following manner –
1.evacuate the house with the largest number of members(L)
2.Next,clear all the houses to the right of the house 1
3.Repeat step 1 and step 2.
4.The task is complete when all the members are evacuated.
QUESTION NO : 46
Example 1:
Input:
5 -> value of N
10 5 15 6 25-> a[],Elements a[0] to a[N-1] ,where input of each element is
seperated by a new line.
Output:
3 -> value of S
#include <stdio.h>
int findEvacuationSteps(int* houses, int N)
{
int steps = 0;
int maxMembers = houses[0];
for (int i = 1; i < N; i++)
{
if (houses[i] > maxMembers)
{
maxMembers = houses[i];
}
}
while (maxMembers > 0)
{
steps++;
int maxIndex = 0;
for (int i = 0; i < N; i++)
{
if (houses[i] == maxMembers)
{
maxIndex = i;
break;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
}
}
for (int i = maxIndex; i < N; i++)
{
houses[i] = 0;
}
maxMembers = 0;
for (int i = 0; i < N; i++)
{
if (houses[i] > maxMembers)
{
maxMembers = houses[i];
}
}
}
return steps;
}
int main()
{
int N;
scanf("%d", &N);
int houses[N];
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
for (int i = 0; i < N; i++)
{
scanf("%d", &houses[i]);
}
int evacuationSteps = findEvacuationSteps(houses, N);
printf("%dn", evacuationSteps);
return 0;
}
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#include <iostream>
#include <algorithm>
using namespace std;
int findEvacuationSteps(int* houses, int N)
{
int steps = 0;
int maxMembers = *max_element(houses, houses + N);
while (maxMembers > 0)
{
steps++;
int maxIndex = distance(houses, find(houses, houses + N, maxMembers));
for (int i = maxIndex; i < N; i++)
{
houses[i] = 0;
}
maxMembers = *max_element(houses, houses + N);
}
return steps;
}
int main()
{
int N;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
cin >> N;
int houses[N];
for (int i = 0; i < N; i++)
{
cin >> houses[i];
}
int evacuationSteps = findEvacuationSteps(houses, N);
cout << evacuationSteps << endl;
return 0;
}
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
import java.util.Scanner;
public class Main
{
public static int findEvacuationSteps(int[] houses, int N)
{
int steps = 0;
int maxMembers = houses[0];
for (int i = 1; i < N; i++)
{
if (houses[i] > maxMembers)
{
maxMembers = houses[i];
}
}
while (maxMembers > 0)
{
steps++;
int maxIndex = 0;
for (int i = 0; i < N; i++)
{
if (houses[i] == maxMembers)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
{
maxIndex = i;
break;
}
}
for (int i = maxIndex; i < N; i++)
{
houses[i] = 0;
}
maxMembers = 0;
for (int i = 0; i < N; i++)
{
if (houses[i] > maxMembers)
{
maxMembers = houses[i];
}
}
}
return steps;
}
public static void main(String[] args)
{
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
Scanner scanner = new Scanner(System.in);
int N = scanner.nextInt();
int[] houses = new int[N];
for (int i = 0; i < N; i++)
{
houses[i] = scanner.nextInt();
}
int evacuationSteps = findEvacuationSteps(houses, N);
System.out.println(evacuationSteps);
}
}
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
def find_evacuation_steps(houses, N):
steps = 0
max_members = max(houses)
while max_members > 0:
steps += 1
max_index = houses.index(max_members)
for i in range(max_index, N):
houses[i] = 0
max_members = max(houses)
return steps
N = int(input())
houses = list(map(int, input().split()))
evacuation_steps = find_evacuation_steps(houses, N)
print(evacuation_steps)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
QUESTION NO : 47
Our Friend Monk has finally found the Temple of Programming secrets. However,
the door of the temple is firmly locked. Now, as per the rules of the temple, Monk
needs to enter a Secret Password in a special language to unlock the door. This
language, unlike English consists of K alphabets. The properties of this secret
password are:
1.It has a length of N characters.
2.It is composed only of the K characters belonging to the Special language.
3.Each character belonging to the special language has been used at max once in
the secret code.
Now, Monk has no idea about what the ideal password may be and needs you
help. You need to help Monk find the total number of distinct candidate Strings
for it Modulo 109+7.
QUESTION NO : 47
Input Format:
The first line contains a single integer T denoting the number of test cases. Each
of the next T lines contain two integers N and K denoting the length of the Secret
Password and the number of characters of the Special language to be used
respectively.
Output Format:
For each test case, output the number of possible distinct secret
passwords Modulo 109+7.
Constraints:
1 T 10
≤ ≤
1 N K 105
≤ ≤ ≤
QUESTION NO : 47
Note:
You need to print the value of each element and not their weight.
Sample Input:
1
3 3
Output:
6
QUESTION NO : 47
Explanation:
Let's number the characters of the special language to be 1 , 2 and 3 respectively.
So, all possible candidate Strings are:
123
132
213
231
312
321
So, here we have 6 possible passwords. So, the answer = 6%(109+7)=6
#include <stdio.h>
#define ll long long int
ll MOD = 1000000007;
int main()
{
ll T, n, res, k, i;
scanf("%lld", &T);
while (T--)
{
scanf("%lld %lld", &n, &k);
res = 1;
for (i = k - n + 1; i <= k; i++)
res = (res * i) % MOD;
printf("%lldn", res);
}
return 0;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include<bits/stdc++.h>
using namespace std;
#define ll long long int
ll MOD = 1000000007;
int main()
{
ll T,n,res,k,i;
cin>>T;
while(T--)
{
cin>>n>>k;
res = 1;
for(i=k-n+1;i<=k;i++)
res = (res*i)%MOD;
cout<<res<<"n";
}
return 0;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import java.util.Scanner;
public class Main
{
static long MOD = 1000000007;
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
long T = scanner.nextLong();
while (T-- > 0)
{
long n = scanner.nextLong();
long k = scanner.nextLong();
long res = 1;
for (long i = k - n + 1; i <= k; i++)
{
res = (res * i) % MOD;
}
System.out.println(res);
}
scanner.close(); } }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
MOD = 1000000007
T = int(input())
for _ in range(T):
n, k = map(int, input().split())
res = 1
for i in range(k - n + 1, k + 1):
res = (res * i) % MOD
print(res)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
QUESTION NO : 48
Alice did a survey of students training for competitive programming, where the
ith student gave the response - "I practiced for xi hours".
Alice recorded the observations as the number of minutes each student practiced
(60 * xi). She could also have written the number with leading zeroes. For
example if a student said "I studied for 2 hours", Alice could have stored the data
as 00120 instead of 120.
Now Bob took Alice's notebook and for each number, he did one of the following
operations :
1.Rearranged its digits
2.Wrote a Random number instead of it.
Thus Bob generated number y1, y2, ... yn.
Your task is to tell for each number yi, can it be a permutation of numbers
divisible by 60(possibly with leading zeroes)
QUESTION NO : 48
Input
The first line of input contains a single integer N - the number of people
surveyed. (1 <= N <= 500)
The next N lines contains a single number of 2 to 100 digits.
Output
For each number print YES, if yi can be a permutation of numbers divisible by 60,
else NO.
QUESTION NO : 48
Example 1
Input
5
603
006
205
228
1053
Output
YES
YES
NO
NO
NO
QUESTION NO : 48
Example 2
Input
1
0000000000000000000000000000000000000000000000
Output
YES
#include <stdio.h>
#include <stdbool.h>
#include <string.h>
bool isDivisibleBy3(const char* s)
{
int sum = 0, ct_0 = 0, even = 0;
int len = strlen(s);
for (int i = 0; i < len; i++)
{
sum += s[i] - '0';
ct_0 += s[i] == '0';
even += (s[i] - '0') % 2 == 0;
}
return (sum % 3 == 0 && ct_0 > 0 && even > 1);
}
int main()
{
int n;
scanf("%d", &n);
for (int t = 0; t < n; t++)
{
char s[100];
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
scanf("%s", s);
if (isDivisibleBy3(s))
{
printf("YESn");
}
else
{
printf("NOn");
}
}
return 0;
}
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#include <bits/stdc++.h>
using namespace std;
int main()
{
int n;
cin >> n;
for(int t = 0; t < n; t++)
{
string s;
cin >> s;
int sum = 0, ct_0 = 0, even = 0;
for(int i = 0; i < (int)s.size(); i++)
{
sum += s[i] - '0';
ct_0 += s[i] == '0';
even += (s[i] - '0') % 2 == 0;
}
sum % 3 == 0 and ct_0 > 0 and even > 1 ? cout << "YESn" : cout << "NOn";
}
return 0;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import java.util.Scanner;
public class Main
{
public static boolean isDivisibleBy3(String s)
{
int sum = 0, ct_0 = 0, even = 0;
int len = s.length();
for (int i = 0; i < len; i++)
{
sum += s.charAt(i) - '0';
ct_0 += s.charAt(i) == '0' ? 1 : 0;
even += (s.charAt(i) - '0') % 2 == 0 ? 1 : 0;
}
return (sum % 3 == 0 && ct_0 > 0 && even > 1);
}
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
scanner.nextLine();
for (int t = 0; t < n; t++)
{
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
String s = scanner.nextLine();
if (isDivisibleBy3(s))
{
System.out.println("YES");
}
else
{
System.out.println("NO");
}
}
scanner.close();
}
}
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
def is_divisible_by_3(s):
_sum = 0
ct_0 = 0
even = 0
for i in range(len(s)):
_sum += int(s[i])
ct_0 += 1 if s[i] == '0' else 0
even += 1 if int(s[i]) % 2 == 0 else 0
return _sum % 3 == 0 and ct_0 > 0 and even > 1
n = int(input())
for _ in range(n):
s = input()
if is_divisible_by_3(s):
print("YES")
else:
print("NO")
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
QUESTION NO : 49
Nick went to a carnival where he saw one of the booths having a strange game.
The game was simple.
There will be an integer number A displayed on the Screen, and you will be gwen
another number B from the booth.
Now, you can convert the same number.B into binary,right-adjust the binary
digits any number of times, and then give back the decimal conversion C of it.You
have to return a number such that, if your number C and the number displayed
on the screen A goes through an Exclusive-OR operation it should output the
maximum result.Your task is to find out the minimum right binary operation
which has to be performed to achieve the maximum results.
Below is an idea of right-adjust operation:
Suppose there is a binary number represented as
D1,D2,D3,D4, where D1, D2, D3 and D4 are the different digits.
QUESTION NO : 49
1. Right-Shift operation will make the number as D3D1D2D3
The next Right-Shift operation will make the number as D3D4D1D2
Given A and B, find the number of operations requir28231160 achieve the
maximum result of A (EX-OR) B, and also output the result of it.
**Note: while performing an Exclusive-OR operation, the number of binary digits
should be the same.
Let us try to understand it with an example.
consider the input A= 4 and B=5
The respective binary of:
A = 100
B=101
Default: A(EX-OR) B= 100 (EX-OR) 101=001 = 1
Right-Shift-#1:
B become 110
A (EX-OR) B = 100 (EX-OR)110=010=2
QUESTION NO : 49
Right-Shift-#2:
B become 011
A (EX-OR) B = 100 (EX-OR)011=111=7
For a 3 digit binary,this is the highest value that can be acheived.Hence after 2
operations,the result was 7.So the answer is 2 7(separated by space)
Input format
First Input -Accept value of Integer, A.
Second Input -Accept value of Integer, B (Next Line)
Output format
The output are 2 integer values (Separated by Space) as per above logic. (Check
the output in Example 1. Example 2)
Additional messages in output will cause the failure of test cases.
Constraints:
1<=A, B<=1000000
Only positive Integer values
QUESTION NO : 49
Example 1:
Input:
1 -> Input integer ,A
3 ->Input integer , B
Output:
0 2 ->Output
Explanation:
In this scenario, the respective binary ofA=01 B=110Default: A (EX-OR) B=01 (EX-
OR) 11=10=2 Right-Shift-1:
become 11
(EX-OR)=01 (EX-OR) 11=10=2
There will not be any change the value of B after performing any number of
Right-Shift operations Hence the output is going to be the same always.
So the output will be 0 2.
#include <stdio.h>
int countRightShifts(int num)
{
int count = 0;
while (num % 2 == 0)
{
num >>= 1;
count++;
}
return count;
}
int main()
{
int A, B;
scanf("%d %d", &A, &B);
int shifts = countRightShifts(B);
int result = A ^ (B >> shifts);
printf("%d %dn", shifts, result);
return 0;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>
using namespace std;
int countRightShifts(int num)
{
int count = 0;
while (num % 2 == 0)
{
num >>= 1;
count++;
}
return count;
}
int main()
{
int A, B;
cin >> A >> B;
int shifts = countRightShifts(B);
int result = A ^ (B >> shifts);
cout << shifts << " " << result << endl;
return 0;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import java.util.Scanner;
public class Main
{
public static int countRightShifts(int num)
{
int count = 0;
while (num % 2 == 0)
{
num >>= 1;
count++;
}
return count;
}
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
int A = scanner.nextInt();
int B = scanner.nextInt();
int shifts = countRightShifts(B);
int result = A ^ (B >> shifts);
System.out.println(shifts + " " + result);
} }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <stdio.h>
int main()
{
char s[100];
scanf("%s", s);
int sum = 0;
for (int i = 0; s[i] != '0'; i++)
{
if (s[i] >= 'a' && s[i] <= 'z')
sum += (s[i] - 'a' + 1);
else if (s[i] >= 'A' && s[i] <= 'Z')
sum += (s[i] - 'A' + 1);
}
if (sum % 9 == 0)
printf("9n");
else
printf("%dn", sum % 9);
return 0;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
def count_right_shifts(num):
count = 0
while num % 2 == 0:
num >>= 1
count += 1
return count
A = int(input())
B = int(input())
shifts = count_right_shifts(B)
result = A ^ (B >> shifts)
print(shifts, result)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
QUESTION NO : 50
You are given a string that contains a name hidden in it. Find the hidden name
and try to find the Lucky number for it.
Input Format
The input contains a single string with a maximum of 32 characters in it.
Output Format:
The output contains a single integer representing the lucky number for the name
decoded from the input.
Explanation :
Find the alpha characters and find the sum of alphabetical values. The lucky
number is the digital sum reduced up to a single digit.
Constraints:
TC: O(n)
ASC: O(1)
QUESTION NO : 50
Sample Input 1:
D@h*o1n&i%
Sample Output 1:
5
Explanation:
The hidden name is Dhoni. So the sum will be 4+8+15+14+9 = 50
Digital sum reduced up to single-digit will be 50 => 5+0 = 5.
Sample Input 2:
!K#o$h*l@i
Sample Output 2:
1
Explanation:
The hidden name isKohli. So the sum will be 11+15+8+12+9 = 55
Digital sum reduced upto single digit will be 55 => 5+5 = 10 => 1+0 = 1
#include <stdio.h>
int main()
{
char s[100];
scanf("%s", s);
int sum = 0;
for (int i = 0; s[i] != '0'; i++)
{
if (s[i] >= 'a' && s[i] <= 'z')
sum += (s[i] - 'a' + 1);
else if (s[i] >= 'A' && s[i] <= 'Z')
sum += (s[i] - 'A' + 1);
}
if (sum % 9 == 0)
printf("9n");
else
printf("%dn", sum % 9);
return 0;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <bits/stdc++.h>
using namespace std;
int main()
{
string s ;
cin >> s ;
int sum = 0 ;
for(int i = 0 ; s[i] ; i++)
{
if(s[i]>='a'&&s[i]<='z')
sum += (s[i]-'a'+1) ;
else if(s[i]>='A'&&s[i]<='Z')
sum += (s[i]-'A'+1) ;
}
if(sum%9==0) cout << 9 ;
else cout << sum%9 ;
return 0 ;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
String s = scanner.next();
int sum = 0;
for (int i = 0; i < s.length(); i++)
{
char c = s.charAt(i);
if (Character.isLowerCase(c))
sum += (c - 'a' + 1);
else if (Character.isUpperCase(c))
sum += (c - 'A' + 1);
}
if (sum % 9 == 0)
System.out.println("9");
else
System.out.println(sum % 9);
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
s = input()
sum = 0
for c in s:
if c.islower():
sum += ord(c) - ord('a') + 1
elif c.isupper():
sum += ord(c) - ord('A') + 1
if sum % 9 == 0:
print("9")
else:
print(sum % 9)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
s = input()
sum = 0
for c in s:
if c.islower():
sum += ord(c) - ord('a') + 1
elif c.isupper():
sum += ord(c) - ord('A') + 1
if sum % 9 == 0:
print("9")
else:
print(sum % 9)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
QUESTION NO : 51
Given a string S and a character C, write a program to count the number of
sub-strings of S that contains only the character C.
Input:
First line contains the string S
Second line contains the character C.
Output:
Single Integer denoting the no.of sub-string containing only the given
character C.
Examples:
Input:
0110111
1
Output:
9
QUESTION NO : 51
Explanation:
The sub-strings containing only ‘1’ are:
“1” — 5 times
“11” — 3 times
“111” — 1 time
Hence, the count is 9.
#include <stdio.h>
void countSubString(char *S, char C)
{
int count = 0;
int conCount = 0;
for (int i = 0; S[i] != '0'; i++)
{
char ch = S[i];
if (ch == C)
conCount++;
else
{
count += (conCount * (conCount + 1)) / 2;
conCount = 0;
}
}
count += (conCount * (conCount + 1)) / 2;
printf("%d", count);
}
int main()
{
char S[100];
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
char C;
fgets(S, sizeof(S), stdin);
scanf("%c", &C);
countSubString(S, C);
return 0;
}
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#include <bits/stdc++.h>
using namespace std;
void countSubString(string S, char C)
{
int count = 0;
int conCount = 0;
for (int i =0;S[i]!='0';i++)
{
char ch = S[i];
if (ch == C)
conCount++;
else
{
count += (conCount * (conCount + 1))/ 2;
conCount = 0;
}
}
count += (conCount* (conCount + 1))/ 2;
cout << count;
}
int main()
{
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
string S;
char C;
getline(cin,S);
cin>>C;
countSubString(S, C);
return 0;
}
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
import java.util.Scanner;
class Main
{
public static void countSubString(String S, char C)
{
int count = 0;
int conCount = 0;
for (int i = 0; i < S.length(); i++)
{
char ch = S.charAt(i);
if (ch == C)
conCount++;
else
{
count += (conCount * (conCount + 1)) / 2;
conCount = 0;
}
}
count += (conCount * (conCount + 1)) / 2;
System.out.print(count);
}
public static void main(String[] args)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
{
Scanner scanner = new Scanner(System.in);
String S = scanner.nextLine();
char C = scanner.next().charAt(0);
countSubString(S, C);
}
}
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
import sys
def countSubString(S, C):
count = 0
conCount = 0
for i in range(len(S)):
ch = S[i]
if ch == C:
conCount += 1
else:
count += (conCount * (conCount + 1)) // 2
conCount = 0
count += (conCount * (conCount + 1)) // 2
sys.stdout.write(str(count))
S = input()
C = input()[0]
countSubString(S, C)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
QUESTION NO : 52
Rahul is working with his friend Jitu on a sequence (1 based index).
The intention is to simplify the sequence, but they were not very sure about
the rules with which they are going to reduce it.
But then Jitu came up with a rule. He said the sequence has to be simplified in
the following manner:
•Select a particular index ‘i’ within 1 to N range.
•Chose an integer divisor D of A[i] such that D<= K
•Divide A[i] by D
•Replace A[i] with the quotient of A[i]/D
You can perform the above operation any number of times.
You must simplify the sequence such that there is no such integer value
greater than 1 which can divide every element of the sequence A. Alternatively
we can say that the GCD of all the elements of the sequence
QUESTION NO : 52
You can perform the above operation any number of times.
You must simplify the sequence such that there is no such integer value
greater than 1 which can divide every element of the sequence A. Alternatively
we can say that the GCD of all the elements of the sequence A is 1.
Return “Yes” if it is possible to bring simplify the sequence with the above
conditions such that the GCD of each element of A is 1.
Otherwise, print “No”.
Consider number of element N=3 and K=6.
And each element of A= [10,15,30]
Lets choose the
•Element A[1] = 10, we need to choose a divisor less than or equal to k=6. Let
us choose 5.
Then A[1] becomes 10/5=2
QUESTION NO : 52
•Element A[2] = 15, we need to choose a divisor less than or equal to k=6. Let
us choose 5.
Then A[2] becomes 15/5=3
•Element A[3]=30, we need to choose a divisor less than or equal to k=6. Let us
choose 5.
Then A[3] becomes 30/5=6.
•Again , if we choose element A[3] = 6, we need to choose a divisor less than
or equal k=6. Let us choose 6. Then A[3] becomes6/6 = 1.
Now, the updated sequence is as [2 3 1].
And the GCD of the elements of the sequence would be 1.
Hence the answer is 1.
QUESTION NO : 52
Example 1:
Input:
3 4_> Input integer, N, K
5 10 20 -> Input integer, A[]
Output:
No-> Output
Example 2:
Input:
3 5 -> Input integer, N, K
10 15 20 -> Input integer, A[]
Output:
Yes-> Output
#include <stdio.h>
#include <stdbool.h>
bool simplifySequence(int N, int K, int A[])
{
for (int i = 0; i < N; i++)
{
int num = A[i];
while (num > 1)
{
bool foundDivisor = false;
for (int j = 2; j <= K; j++)
{
if (num % j == 0 && A[i] % j == 0)
{
num /= j;
foundDivisor = true;
break;
}
}
if (!foundDivisor)
{
return false;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
} } }
return true; }
int main() {
int N, K;
scanf("%d", &N);
scanf("%d", &K);
int A[N];
for (int i = 0; i < N; i++)
{
scanf("%d", &A[i]);
}
if (simplifySequence(N, K, A))
{
printf("Yesn");
}
else
{
printf("Non");
}
return 0;
}
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#include <vector>
using namespace std;
bool simplifySequence(int N, int K, vector<int>& A)
{
for (int i = 0; i < N; i++)
{
int num = A[i];
while (num > 1)
{
bool foundDivisor = false;
for (int j = 2; j <= K; j++)
{
if (num % j == 0 && A[i] % j == 0)
{
num /= j;
foundDivisor = true;
break;
}
}
if (!foundDivisor)
{
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
return false; } }}
return true;
}
int main() {
int N, K;
cin >> N;
cin >> K;
vector<int> A(N);
for (int i = 0; i < N; i++)
{
cin >> A[i];
}
if (simplifySequence(N, K, A))
{
cout << "Yes" << endl;
}
else
{
cout << "No" << endl;
}
return 0;
}
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
import java.util.Scanner;
public class Main
{
public static boolean simplifySequence(int N, int K, int[] A)
{
for (int i = 0; i < N; i++)
{
int num = A[i];
while (num > 1)
{
boolean foundDivisor = false;
for (int j = 2; j <= K; j++)
{
if (num % j == 0 && A[i] % j == 0)
{
num /= j;
foundDivisor = true;
break;
}
}
if (!foundDivisor)
{
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
return false; } }}
return true; }
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int N = scanner.nextInt();
int K = scanner.nextInt();
int[] A = new int[N];
for (int i = 0; i < N; i++) {
A[i] = scanner.nextInt(); }
if (simplifySequence(N, K, A))
{
System.out.println("Yes");
}
else
{
System.out.println("No");
}
}
}
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
def simplify_sequence(N, K, A):
for i in range(N):
num = A[i]
while num > 1:
found_divisor = False
for j in range(2, K + 1):
if num % j == 0 and A[i] % j == 0:
num //= j
found_divisor = True
break
if not found_divisor:
return False
return True
N, K = map(int, input().split())
A = list(map(int, input().split()))
if simplify_sequence(N, K, A):
print("Yes")
else:
print("No")
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
QUESTION NO : 53
Jack has given a word to its student to check whether it is palindrome.
But there is catch, if the word is not palindrome, they will get 1 chance to swap
2 alphabets to make it palindrome.
After 1 swap, if the word becomes palindrome, then the student wins,
otherwise they lose.
Create a program that return True, if just 1 swap makes the word palindrome,
otherwise False.
QUESTION NO : 53
Example 1
Input :
abab
Output:
True
Explanation:
The input word is abab. If the first and second alphabet swap each other, then
it makes the word as baab, which ultimately makes it palindrome.
So the result is True.
QUESTION NO : 53
Example 2
Input :
abcabc
Output:
True
Explanation:
The input word is abcabc. If the first and third alphabet swap each other, then
it makes the word as cbaabc, which ultimately makes it palindrome.
So the result is True.
#include <stdio.h>
#include <stdbool.h>
#include <string.h>
bool isPalindromePossible(char* input)
{
int length = strlen(input);
int diffCount = 0;
int i = 0;
char diff[2][2] = {'0'};
while (i < length / 2)
{
if (input[i] != input[length - i - 1])
{
if (diffCount == 2)
{
return false;
}
diff[diffCount][0] = input[i];
diff[diffCount][1] = input[length - i - 1];
diffCount++;
}
i++;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
}
if (diffCount == 0)
{
return true;
}
else if (diffCount == 1)
{
char midChar = input[i];
if (length % 2 != 0 && (diff[0][0] == midChar || diff[0][1] == midChar))
{
return true;
}
}
else if (diffCount == 2)
{
if ((diff[0][0] == diff[1][0] && diff[0][1] == diff[1][1]) ||
(diff[0][0] == diff[1][1] && diff[0][1] == diff[1][0]))
{
return true;
}
}
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
return false;
}
int main()
{
char input[100];
scanf("%s", input);
if (isPalindromePossible(input))
{
printf("Truen");
}
else
{
printf("Falsen");
}
return 0;
}
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#include <iostream>
#include <cstring>
using namespace std;
bool isPalindromePossible(const char* input)
{
int length = strlen(input);
int diffCount = 0;
int i = 0;
char diff[2][2] = {'0'};
while (i < length / 2)
{
if (input[i] != input[length - i - 1])
{
if (diffCount == 2)
{
return false;
}
diff[diffCount][0] = input[i];
diff[diffCount][1] = input[length - i - 1];
diffCount++;
}
i++;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
}
if (diffCount == 0)
{
return true;
}
else if (diffCount == 1)
{
char midChar = input[i];
if (length % 2 != 0 && (diff[0][0] == midChar || diff[0][1] == midChar))
{
return true;
}
} else if (diffCount == 2)
{
if ((diff[0][0] == diff[1][0] && diff[0][1] == diff[1][1]) ||
(diff[0][0] == diff[1][1] && diff[0][1] == diff[1][0]))
{
return true;
}
}
return false;
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
}
int main()
{
char input[100];
cin >> input;
if (isPalindromePossible(input))
{
cout << "True" ;
}
else
{
cout << "False" ;
}
return 0;
}
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
import java.util.Scanner;
public class Main
{
public static boolean isPalindromePossible(String input)
{
int length = input.length();
int diffCount = 0;
int i = 0;
char[][] diff = new char[2][2];
while (i < length / 2)
{
if (input.charAt(i) != input.charAt(length - i - 1))
{
if (diffCount == 2)
{
return false;
}
diff[diffCount][0] = input.charAt(i);
diff[diffCount][1] = input.charAt(length - i - 1);
diffCount++;
}
i++;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
}
if (diffCount == 0)
{
return true;
}
else if (diffCount == 1)
{
char midChar = input.charAt(i);
if (length % 2 != 0 && (diff[0][0] == midChar || diff[0][1] == midChar))
{
return true;
}
}
else if (diffCount == 2)
{
if ((diff[0][0] == diff[1][0] && diff[0][1] == diff[1][1]) ||
(diff[0][0] == diff[1][1] && diff[0][1] == diff[1][0]))
{
return true;
}
}
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
return false;
}
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
String input = scanner.next();
if (isPalindromePossible(input))
{
System.out.println("True");
}
else
{
System.out.println("False");
}
}
}
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
def isPalindromePossible(input: str) -> bool:
length = len(input)
diffCount = 0
i = 0
diff = [['0'] * 2] * 2
while i < length // 2:
if input[i] != input[length - i - 1]:
if diffCount == 2:
return False
diff[diffCount][0] = input[i]
diff[diffCount][1] = input[length - i - 1]
diffCount += 1
i += 1
if diffCount == 0:
return True
elif diffCount == 1:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
midChar = input[i]
if length % 2 != 0 and (diff[0][0] == midChar
or diff[0][1] == midChar):
return True
elif diffCount == 2:
if (diff[0][0] == diff[1][0] and diff[0][1] == diff[1][1]) or (
diff[0][0] == diff[1][1] and diff[0][1] == diff[1][0]):
return True
return False
str = input()
print(isPalindromePossible(str))
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
QUESTION NO : 54
Given a positive integer number N. the task is to find the number of ways in
which the given number can be represented as the product of two distinct
numbers.
Example 1
Input:
14
Output:
2
Explanation:
14 can be represented as 1 * 14 and 2 * 7
QUESTION NO : 54
Example 2
Input :
16
Output :
2
Explanation :
16 can be represented as 1*16 and 2 * 8
Note
4*4 is not valid way because both the numbers are same.
#include <stdio.h>
int main()
{
int n;
scanf("%d", &n);
int count = 0;
for (int i = 1; i*i <=n ; i++)
{
if (n % i == 0 && n / i != i)
{
count++;
}
}
printf("%dn", count);
return 0;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>
using namespace std;
int main()
{
int n;
cin >> n;
int count = 0;
for (int i = 1; i * i <= n; i++)
{
if (n % i == 0 && n / i != i)
{
count++;
}
}
cout << count;
return 0;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int count = 0;
for (int i = 1; i * i <= n; i++)
{
if (n % i == 0 && n / i != i)
{
count++;
}
}
System.out.println(count);
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import math
n = int(input())
count = 0
for i in range (1, int(math.sqrt(n))):
if n % i == 0 and n//i != i:
count = count + 1
print(count)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
QUESTION NO : 55
Consider the series below:
{2, 1, 3, 4, 7, 11, 18, so on}
In the above series first two elements are 2 and 1 respectively and other
elements are the sum of its two immediately previous elements.
The task is to find the minimum number of elements that need to be changed
in the given array Arr to make a series as per the above statement.
For example:
Arr[] = {2, 1, 3, 4, 9, 11, 18}
In the given array 5th
element (9) needs to replace with 7 to make the correct
series.
This means there is only one element that needs to replace in the given array.
Hence the output = 1;
QUESTION NO : 55
Example 1
Input :
7
2 1 3 4 9 11 18
Output :
1
Explanation :
In the given array 5th
element (9) needs to replace with 7 to make the correct
series. This means there is only one element that needs to replace in the given
array. Hence the output = 1;
#include <stdio.h>
int main()
{
int n;
scanf("%d", &n);
int arr[n];
for (int i = 0; i < n; i++)
{
scanf("%d", &arr[i]);
}
int a = 2;
int b = 1;
int count = 0;
if (arr[0] != a)
{
count++;
}
if (arr[1] != b)
{
count++;
}
for (int i = 2; i < n; i++)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
{
int c = a + b;
a = b;
b = c;
if (arr[i] != c)
{
count++;
}
}
printf("%dn", count);
return 0;
}
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#include <iostream>
#include <vector>
using namespace std;
int main()
{
int n;
cin >> n;
vector<int> arr(n);
for (int i = 0; i < n; i++)
{
cin >> arr[i];
}
int a = 2;
int b = 1;
int count = 0;
if (arr[0] != a)
{
count++;
}
if (arr[1] != b)
{
count++;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
}
for (int i = 2; i < n; i++)
{
int c = a + b;
a = b;
b = c;
if (arr[i] != c)
{
count++;
}
}
cout << count;
return 0;
}
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
import java.util.Scanner;
import java.util.ArrayList;
import java.util.List;
public class Main
{
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
List<Integer> arr = new ArrayList<>();
for (int i = 0; i < n; i++)
{
arr.add(scanner.nextInt());
}
int a = 2;
int b = 1;
int count = 0;
if (arr.get(0) != a)
{
count++;
}
if (arr.get(1) != b)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
{
count++;
}
for (int i = 2; i < n; i++)
{
int c = a + b;
a = b;
b = c;
if (arr.get(i) != c)
{
count++;
}
}
System.out.println(count);
}
}
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
n = int(input())
arr = list(map(int, input().strip().split()))
a = 2
b = 1
count = 0
if arr[0] != a:
count = count + 1
if arr[1] != b:
count = count + 1
for i in range(2, n):
c = a + b
a = b
b = c
if arr[i] != c:
count = count + 1
print(count)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
QUESTION NO : 56
A group of friends are playing cards. Only numeric cards are being used,
along with the joker card (equivalent to 0) and the symbols in the cards are
not taken into account.
Each player will receive a set of cards. The rule of the game is to rearrange the
set of cards to the possible lowest number sequence. The player with the set
of cards forming the smallest number wins the game. The number sequence
of the cards should not start with a joker card. The task is to write a program
for developing the logic of the game considering the set of cards as a number.
The output will be the lowest possible number that can be formed, not
beginning with 0.
QUESTION NO : 56
Example 1
Input :
34201
Output :
10234
Explanation :
The lowest number formation by rearranging the digits of the number 34201
and not starting with a 0 will be 10234. Hence the output is 10234
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char* smallest(char* lst, int length)
{
int i;
char tmp;
for (i = 0; i < length; i++)
{
if (lst[i] != '0')
{
tmp = lst[i];
break;
}
}
memmove(&lst[i], &lst[i + 1], (length - i) * sizeof(char));
lst[length - 1] = '0';
char* result = (char*)malloc((length + 1) * sizeof(char));
sprintf(result, "%c%s", tmp, lst);
return result;
}
int main()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
{
int n;
scanf("%d", &n);
char lst[12];
sprintf(lst, "%d", n);
int length = strlen(lst);
qsort(lst, length, sizeof(char), strcmp);
char* result = smallest(lst, length);
printf("%sn", result);
free(result);
return 0;
}
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
string smallest(string lst)
{
char tmp;
int length = lst.length();
for (int i = 0; i < length; i++)
{
if (lst[i] != '0')
{
tmp = lst[i];
lst.erase(i, 1);
break;
}
}
string result = tmp + lst;
return result;
}
int main()
{
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
int n;
cin >> n;
string lst = to_string(n);
int length = lst.length();
sort(lst.begin(), lst.end());
string result = smallest(lst);
cout << result << endl;
return 0;
}
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
import java.util.Scanner;
import java.util.Arrays;
public class Main
{
public static String smallest(String lst)
{
char tmp = ' ';
int length = lst.length();
for (int i = 0; i < length; i++)
{
if (lst.charAt(i) != '0')
{
tmp = lst.charAt(i);
lst = lst.substring(0, i) + lst.substring(i + 1);
break;
}
}
String result = tmp + lst;
return result;
}
public static void main(String[] args)
{
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
String lst = String.valueOf(n);
int length = lst.length();
char[] lstChars = lst.toCharArray();
Arrays.sort(lstChars);
lst = new String(lstChars);
String result = smallest(lst);
System.out.println(result);
}
}
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
def smallest(lst):
for i, n in enumerate(lst):
if n != '0':
tmp = lst.pop(i)
break
return str(tmp) + ''.join(lst)
if __name__ == '__main__':
n = int(input())
lst = list(str(n))
lst.sort()
print(smallest(lst))
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
QUESTION NO : 57
Mr. Rao is relocating from place A to B. the moving truck has a maximum
capacity C. there are N items in the house where each item has a
corresponding value (vi) and weight (Wi). Mr. Rao has to carry only the most
valuable items whose total weight does not exceed the capacity of the truck.
The task here is to find those items (single or combination of items) whose
total value (v) will be the maximum and their corresponding weight (w) will not
exceed truck capacity ( C ) here
N = no. of items
C – maximum capacity of the truck, an integer value
W[0 to N-1] – An array consisting weight of each item
V[0 to N-1] – An array consisting value of each item.
QUESTION NO : 57
Example 1
Input:
4 -> Value of N
80 -> Value of C
10 45 60 90 -> Elements of array V[]
15 20 30 40 -> Elements of array W[]
Output:
150
#include <stdio.h>
int max(int a, int b)
{
return (a > b) ? a : b;
}
int knapSack(int W, int wt[], int val[], int n)
{
if (n == 0 || W == 0)
{
return 0;
}
if (wt[n - 1] > W)
{
return knapSack(W, wt, val, n - 1);
}
else
{
return max(val[n - 1] + knapSack(W - wt[n - 1], wt, val, n - 1),
knapSack(W, wt, val, n - 1));
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
int main()
{
int N, C;
scanf("%d", &N);
scanf("%d", &C);
int val[N];
int wt[N];
for (int i = 0; i < N; i++)
{
scanf("%d", &val[i]);
}
for (int i = 0; i < N; i++)
{
scanf("%d", &wt[i]);
}
int result = knapSack(C, wt, val, N);
printf("%dn", result);
return 0;
}
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#include <iostream>
using namespace std;
int max(int a, int b)
{
return (a > b) ? a : b;
}
int knapSack(int W, int wt[], int val[], int n)
{
if (n == 0 || W == 0)
{
return 0;
}
if (wt[n - 1] > W)
{
return knapSack(W, wt, val, n - 1);
}
else
{
return max(val[n - 1] + knapSack(W - wt[n - 1], wt, val, n - 1),
knapSack(W, wt, val, n - 1));
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
}
int main()
{
int N, C;
cin >> N >> C;
int val[N];
int wt[N];
for (int i = 0; i < N; i++)
{
cin >> val[i];
}
for (int i = 0; i < N; i++)
{
cin >> wt[i];
}
int result = knapSack(C, wt, val, N);
cout << result << endl;
return 0;
}
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
import java.util.Scanner;
public class Main
{
public static int max(int a, int b)
{
return (a > b) ? a : b;
}
public static int knapSack(int W, int[] wt, int[] val, int n)
{
if (n == 0 || W == 0)
{
return 0;
}
if (wt[n - 1] > W)
{
return knapSack(W, wt, val, n - 1);
}
else
{
return max(val[n - 1] + knapSack(W - wt[n - 1], wt, val, n - 1),
knapSack(W, wt, val, n - 1));
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
}
}
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
int N = scanner.nextInt();
int C = scanner.nextInt();
int[] val = new int[N];
int[] wt = new int[N];
for (int i = 0; i < N; i++)
{
val[i] = scanner.nextInt();
}
for (int i = 0; i < N; i++)
{
wt[i] = scanner.nextInt();
}
int result = knapSack(C, wt, val, N);
System.out.println(result);
}
}
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
def knapSack(W, wt, val, n):
if n == 0 or W == 0:
return 0
if (wt[n-1] > W):
return knapSack(W, wt, val, n-1)
else:
return max(
val[n-1] + knapSack(
W-wt[n-1], wt, val, n-1),
knapSack(W, wt, val, n-1))
N = int(input())
C = int(input())
val = list(map(int, input().strip().split()))
Wt = list(map(int, input().strip().split()))
print (knapSack(C, Wt, val, N))
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
QUESTION NO : 58
Given two non-negative integers n1 and n2, where n1 < n2. The task is to find
the total number of integers in the range interval [n1, n2] (both inclusive)
which have no repeated digits.
For example:
Suppose n1 = 11 and n2 = 15
There is the number 11, which has repeated digits, but 12, 13, 14 and 15 have
no repeated digits. So, the output is 4.
QUESTION NO : 58
Example 1
Input :
11
15
Output :
4
Example 2
Input :
101
200
Output :
72
#include <stdio.h>
int repeated_digit(int n)
{
int a[10] = {0};
while (n != 0)
{
int d = n % 10;
if (a[d] == 1)
{
return 0;
}
a[d] = 1;
n = n / 10;
}
return 1;
}
int calculate(int L, int R)
{
int answer = 0;
for (int i = L; i <= R; i++)
{
answer = answer + repeated_digit(i);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
}
return answer;
}
int main()
{
int L, R;
scanf("%d", &L);
scanf("%d", &R);
int result = calculate(L, R);
printf("%dn", result);
return 0;
}
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#include <iostream>
using namespace std;
int repeated_digit(int n)
{
int a[10] = {0};
while (n != 0)
{
int d = n % 10;
if (a[d] == 1)
{
return 0;
}
a[d] = 1;
n = n / 10;
}
return 1;
}
int calculate(int L, int R)
{
int answer = 0;
for (int i = L; i <= R; i++)
{
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
answer = answer + repeated_digit(i);
}
return answer;
}
int main()
{
int L, R;
cin >> L >> R;
int result = calculate(L, R);
cout << result << endl;
return 0;
}
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
import java.util.Scanner;
public class Main
{
public static int repeated_digit(int n)
{
int[] a = new int[10];
while (n != 0)
{
int d = n % 10;
if (a[d] == 1)
{
return 0;
}
a[d] = 1;
n = n / 10;
}
return 1;
}
public static int calculate(int L, int R)
{
int answer = 0;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
for (int i = L; i <= R; i++)
{
answer = answer + repeated_digit(i);
}
return answer;
}
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
int L = scanner.nextInt();
int R = scanner.nextInt();
int result = calculate(L, R);
System.out.println(result);
}
}
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
def repeated_digit(n):
a = []
while n != 0:
d = n % 10
if d in a:
return 0
a.append(d)
n = n // 10
return 1
def calculate(L, R):
answer = 0
for i in range(L, R + 1):
answer = answer + repeated_digit(i)
return answer
L = int(input())
R = int(input())
print(calculate(L, R))
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
QUESTION NO : 59
Given a sentence str. The task is to find whether the given sentence contains
all letters of the English alphabet (a to z or A to Z). If it does not, then print all
missing letters of the alphabet, otherwise print 0.
Note
All characters in the given sentence should be treated as case insensitive,
which means that ‘A’ and ‘a’ are to be treated as the same.
The output should be in alphabetic order
The output should contain only lowercase alphabets
If none of the letters are missing, print 0 as output
QUESTION NO : 59
Example 1
Input :
The four boxing wizard starts over the quickly.
Output :
jmp
Explanation :
“The four boxing wizard starts over the quickly” does not contain all the letters
from ‘a’ to ‘z’ or ‘A’ to ‘Z’ as ‘j’, ‘m’ and ‘p’ are missing.
#include <stdio.h>
#include <ctype.h>
#include <stdbool.h>
int main()
{
char str[100];
fgets(str, sizeof(str), stdin);
// Convert the string to lowercase
for (int i = 0; str[i]; i++)
{
str[i] = tolower(str[i]);
}
bool present[26] = {false}; // Array to track the presence of letters
// Mark the presence of each letter in the string
for (int i = 0; str[i]; i++)
{
if (isalpha(str[i]))
{
int index = str[i] - 'a';
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
present[index] = true;
}
}
// Print the missing letters
for (int i = 0; i < 26; i++)
{
if (!present[i])
{
char missingLetter = i + 'a';
printf("%c", missingLetter);
}
}
return 0;
}
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#include <iostream>
#include <cctype>
#include <vector>
using namespace std;
int main() {
string str;
getline(cin, str);
// Convert the string to lowercase
for (char& c : str) {
c = tolower(c);
}
vector<bool> present(26, false); // Vector to track the presence of letters
// Mark the presence of each letter in the string
for (char c : str) {
if (isalpha(c)) {
int index = c - 'a';
present[index] = true;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
}
}
// Print the missing letters
for (int i = 0; i < 26; i++) {
if (!present[i]) {
char missingLetter = i + 'a';
cout << missingLetter;
}
}
return 0;
}
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String str = scanner.nextLine();
// Convert the string to lowercase
str = str.toLowerCase();
boolean[] present = new boolean[26]; // Array to track the presence of letters
// Mark the presence of each letter in the string
for (char c : str.toCharArray()) {
if (Character.isLetter(c)) {
int index = c - 'a';
present[index] = true;
}
}
// Print the missing letters
for (int i = 0; i < 26; i++) {
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
if (!present[i]) {
char missingLetter = (char) (i + 'a');
System.out.print(missingLetter);
}
}
}
}
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
str = input()
str = str.lower()
for i in range (0, 26):
t = chr(97+i)
if t not in str:
print (t, end='')
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
QUESTION NO : 60
An accountant in a firm has a serious issue with numbers. He types the
numbers in a reverse manner. Suppose he has to enter 123, he enters the
number 321. He has the habit of reading numbers from right to left.
The boss became aware of this only after he found out at the end of the billing
month when he had to file the tax. He has to correct al the numbers by
reentering each number from right to left. This gives the corrected number.
Given a number N, help the boss find out the corrected numbers. Display the
corrected numbers as output. Also ignore any 0’s at the end of the number.
Note
The corrected numbers should be only 16-bit signed integers. If the output
(the corrected number is outside the range display “Wrong value”.
QUESTION NO : 60
Example 1
Input :
-4512
Output :
-2154
Explanation :
From the inputs given below
N = -4512
The correct number would be from right to left which is 2154 and the sign is
retained.
Hence the outpt is -2154
QUESTION NO : 60
Example 2
Input :
500
Output :
5
Explanation :
From the inputs given above:
N = 500
The correct number would be from right to left which is 005 which can be
displayed as 5.
Hence the output is 5.
#include <stdio.h>
#include <stdbool.h>
int main()
{
int n;
scanf("%d", &n);
int temp = n;
if (n >= -32786 && n <= 32767)
{
if (n < 0)
{
n = n * -1;
}
int rev = 0;
while (n != 0)
{
int rem = n % 10;
rev = rev * 10 + rem;
n = n / 10;
}
if (temp < 0)
{
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
printf("%dn", rev * -1);
}
else
{
printf("%dn", rev);
}
}
else
{
printf("Wrong valuen");
}
return 0;
}
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#include <iostream>
using namespace std;
int main()
{
int n;
cin >> n;
int temp = n;
if (n >= -32786 && n <= 32767)
{
if (n < 0)
{
n = n * -1;
}
int rev = 0;
while (n != 0)
{
int rem = n % 10;
rev = rev * 10 + rem;
n = n / 10;
}
if (temp < 0)
{
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
cout << rev * -1 << std::endl;
}
else
{
cout << rev << std::endl;
}
}
else
{
cout << "Wrong value" << std::endl;
}
return 0;
}
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int temp = n;
if (n >= -32786 && n <= 32767)
{
if (n < 0)
{
n = n * -1;
}
int rev = 0;
while (n != 0)
{
int rem = n % 10;
rev = rev * 10 + rem;
n = n / 10;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
if (temp < 0)
{
System.out.println(rev * -1);
}
else
{
System.out.println(rev);
}
}
else
{
System.out.println("Wrong value");
}
}
}
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
n = int(input())
temp = n
if (n >= -32786 and n <= 32767):
if(n < 0):
n = n * -1
rev = 0
while(n != 0):
rem = n % 10
rev = rev * 10 + rem
n = n // 10
if(temp < 0):
print(rev * -1 )
else:
print(rev)
else:
print("Wrong value")
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
THANK YOU
Ad

More Related Content

Similar to TCS_Digital_Advanced_Coding_Student copy.pptx (20)

Unit 2
Unit 2Unit 2
Unit 2
TPLatchoumi
 
Design and Analysis of algorithms
Design and Analysis of algorithmsDesign and Analysis of algorithms
Design and Analysis of algorithms
Dr. Rupa Ch
 
Linked lists - Exercises
Linked lists - ExercisesLinked lists - Exercises
Linked lists - Exercises
Eleonora Ciceri
 
Unitii string
Unitii stringUnitii string
Unitii string
Sowri Rajan
 
Problem 2.19. How much time is required to add or subtract two large.pdf
Problem 2.19. How much time is required to add or subtract two large.pdfProblem 2.19. How much time is required to add or subtract two large.pdf
Problem 2.19. How much time is required to add or subtract two large.pdf
JUSTSTYLISH3B2MOHALI
 
Unit ii data structure-converted
Unit  ii data structure-convertedUnit  ii data structure-converted
Unit ii data structure-converted
Shri Shankaracharya College, Bhilai,Junwani
 
Solution Manual for Data Structures and Algorithm Analysis in C++, 4/E 4th Ed...
Solution Manual for Data Structures and Algorithm Analysis in C++, 4/E 4th Ed...Solution Manual for Data Structures and Algorithm Analysis in C++, 4/E 4th Ed...
Solution Manual for Data Structures and Algorithm Analysis in C++, 4/E 4th Ed...
linarasivani50
 
Multi dimensional array
Multi dimensional arrayMulti dimensional array
Multi dimensional array
Rajendran
 
Lecture 02: Preliminaries of Data structure
Lecture 02: Preliminaries of Data structureLecture 02: Preliminaries of Data structure
Lecture 02: Preliminaries of Data structure
Nurjahan Nipa
 
Analysis of algorithms
Analysis of algorithms Analysis of algorithms
Analysis of algorithms
MUSAIDRIS15
 
C aptitude scribd
C aptitude scribdC aptitude scribd
C aptitude scribd
Amit Kapoor
 
time_complexity_list_02_04_2024_22_pages.pdf
time_complexity_list_02_04_2024_22_pages.pdftime_complexity_list_02_04_2024_22_pages.pdf
time_complexity_list_02_04_2024_22_pages.pdf
SrinivasaReddyPolamR
 
Stacks.ppt
Stacks.pptStacks.ppt
Stacks.ppt
OliverKane3
 
Stacks.ppt
Stacks.pptStacks.ppt
Stacks.ppt
OliverKane3
 
Array
ArrayArray
Array
Vivian Chia En Chiang
 
First session _Cracking the coding interview.pptx
First session _Cracking the coding interview.pptxFirst session _Cracking the coding interview.pptx
First session _Cracking the coding interview.pptx
ZilvinasAleksa
 
Maharishi University of Management (MSc Computer Science test questions)
Maharishi University of Management (MSc Computer Science test questions)Maharishi University of Management (MSc Computer Science test questions)
Maharishi University of Management (MSc Computer Science test questions)
Dharma Kshetri
 
Basics of Python and Numpy jfhfkfff.pptx
Basics of Python and Numpy jfhfkfff.pptxBasics of Python and Numpy jfhfkfff.pptx
Basics of Python and Numpy jfhfkfff.pptx
24bec055
 
UNIT-1.docx Design and Analysis of Algorithm
UNIT-1.docx Design and Analysis of AlgorithmUNIT-1.docx Design and Analysis of Algorithm
UNIT-1.docx Design and Analysis of Algorithm
swethajosephsastry
 
Solution Manual for Data Structures and Algorithm Analysis in C++, 4/E 4th Ed...
Solution Manual for Data Structures and Algorithm Analysis in C++, 4/E 4th Ed...Solution Manual for Data Structures and Algorithm Analysis in C++, 4/E 4th Ed...
Solution Manual for Data Structures and Algorithm Analysis in C++, 4/E 4th Ed...
adrariaicy
 
Design and Analysis of algorithms
Design and Analysis of algorithmsDesign and Analysis of algorithms
Design and Analysis of algorithms
Dr. Rupa Ch
 
Linked lists - Exercises
Linked lists - ExercisesLinked lists - Exercises
Linked lists - Exercises
Eleonora Ciceri
 
Problem 2.19. How much time is required to add or subtract two large.pdf
Problem 2.19. How much time is required to add or subtract two large.pdfProblem 2.19. How much time is required to add or subtract two large.pdf
Problem 2.19. How much time is required to add or subtract two large.pdf
JUSTSTYLISH3B2MOHALI
 
Solution Manual for Data Structures and Algorithm Analysis in C++, 4/E 4th Ed...
Solution Manual for Data Structures and Algorithm Analysis in C++, 4/E 4th Ed...Solution Manual for Data Structures and Algorithm Analysis in C++, 4/E 4th Ed...
Solution Manual for Data Structures and Algorithm Analysis in C++, 4/E 4th Ed...
linarasivani50
 
Multi dimensional array
Multi dimensional arrayMulti dimensional array
Multi dimensional array
Rajendran
 
Lecture 02: Preliminaries of Data structure
Lecture 02: Preliminaries of Data structureLecture 02: Preliminaries of Data structure
Lecture 02: Preliminaries of Data structure
Nurjahan Nipa
 
Analysis of algorithms
Analysis of algorithms Analysis of algorithms
Analysis of algorithms
MUSAIDRIS15
 
C aptitude scribd
C aptitude scribdC aptitude scribd
C aptitude scribd
Amit Kapoor
 
time_complexity_list_02_04_2024_22_pages.pdf
time_complexity_list_02_04_2024_22_pages.pdftime_complexity_list_02_04_2024_22_pages.pdf
time_complexity_list_02_04_2024_22_pages.pdf
SrinivasaReddyPolamR
 
First session _Cracking the coding interview.pptx
First session _Cracking the coding interview.pptxFirst session _Cracking the coding interview.pptx
First session _Cracking the coding interview.pptx
ZilvinasAleksa
 
Maharishi University of Management (MSc Computer Science test questions)
Maharishi University of Management (MSc Computer Science test questions)Maharishi University of Management (MSc Computer Science test questions)
Maharishi University of Management (MSc Computer Science test questions)
Dharma Kshetri
 
Basics of Python and Numpy jfhfkfff.pptx
Basics of Python and Numpy jfhfkfff.pptxBasics of Python and Numpy jfhfkfff.pptx
Basics of Python and Numpy jfhfkfff.pptx
24bec055
 
UNIT-1.docx Design and Analysis of Algorithm
UNIT-1.docx Design and Analysis of AlgorithmUNIT-1.docx Design and Analysis of Algorithm
UNIT-1.docx Design and Analysis of Algorithm
swethajosephsastry
 
Solution Manual for Data Structures and Algorithm Analysis in C++, 4/E 4th Ed...
Solution Manual for Data Structures and Algorithm Analysis in C++, 4/E 4th Ed...Solution Manual for Data Structures and Algorithm Analysis in C++, 4/E 4th Ed...
Solution Manual for Data Structures and Algorithm Analysis in C++, 4/E 4th Ed...
adrariaicy
 

Recently uploaded (20)

RCM-billing in medical coding0000 1.pptx
RCM-billing in medical coding0000 1.pptxRCM-billing in medical coding0000 1.pptx
RCM-billing in medical coding0000 1.pptx
liajohn0808
 
COMPRESSION MODELSCOMPRESSION MODELSCOMPRESSION MODELS
COMPRESSION MODELSCOMPRESSION MODELSCOMPRESSION MODELSCOMPRESSION MODELSCOMPRESSION MODELSCOMPRESSION MODELS
COMPRESSION MODELSCOMPRESSION MODELSCOMPRESSION MODELS
johncena77770789
 
remakingyourselfpresentation-250430095415-6476ade1.pptx
remakingyourselfpresentation-250430095415-6476ade1.pptxremakingyourselfpresentation-250430095415-6476ade1.pptx
remakingyourselfpresentation-250430095415-6476ade1.pptx
lakhmanpindariya9176
 
Introduction on Speaking skills Power Point
Introduction on Speaking skills Power PointIntroduction on Speaking skills Power Point
Introduction on Speaking skills Power Point
helenswarna
 
Stakeholders Management GT 11052021.cleaned.pptx
Stakeholders Management GT 11052021.cleaned.pptxStakeholders Management GT 11052021.cleaned.pptx
Stakeholders Management GT 11052021.cleaned.pptx
SaranshJeena
 
LCL216_2024-2_WEEKS 4 & 5_IF CLAUSES (1).pdf
LCL216_2024-2_WEEKS 4 & 5_IF CLAUSES (1).pdfLCL216_2024-2_WEEKS 4 & 5_IF CLAUSES (1).pdf
LCL216_2024-2_WEEKS 4 & 5_IF CLAUSES (1).pdf
rafaelsago2015
 
SHIPPING CONTAINdccdcdERS BC (2).pdf.pptx
SHIPPING CONTAINdccdcdERS BC (2).pdf.pptxSHIPPING CONTAINdccdcdERS BC (2).pdf.pptx
SHIPPING CONTAINdccdcdERS BC (2).pdf.pptx
ArshjotSingh30
 
Sample animal revalidation protocol for resaecrh based.pptx
Sample animal revalidation protocol for resaecrh based.pptxSample animal revalidation protocol for resaecrh based.pptx
Sample animal revalidation protocol for resaecrh based.pptx
azeemccras
 
巴利亚多利德大学毕业证书学校原版文凭补办UVa成绩单办本科成绩单
巴利亚多利德大学毕业证书学校原版文凭补办UVa成绩单办本科成绩单巴利亚多利德大学毕业证书学校原版文凭补办UVa成绩单办本科成绩单
巴利亚多利德大学毕业证书学校原版文凭补办UVa成绩单办本科成绩单
xule9cv6nd
 
When Is the Best Time to Use Job Finding Apps?
When Is the Best Time to Use Job Finding Apps?When Is the Best Time to Use Job Finding Apps?
When Is the Best Time to Use Job Finding Apps?
SnapJob
 
RightShip-Inspection-Maritime-Safety-Simplified.pptx
RightShip-Inspection-Maritime-Safety-Simplified.pptxRightShip-Inspection-Maritime-Safety-Simplified.pptx
RightShip-Inspection-Maritime-Safety-Simplified.pptx
ultronmeg
 
Green Colorful House Simple Illustration Presentation.pdf.pdf
Green Colorful House Simple Illustration Presentation.pdf.pdfGreen Colorful House Simple Illustration Presentation.pdf.pdf
Green Colorful House Simple Illustration Presentation.pdf.pdf
RhyzCharmSolis
 
material-17438335 to the third floor in 47-gsms.pptx
material-17438335 to the third floor in 47-gsms.pptxmaterial-17438335 to the third floor in 47-gsms.pptx
material-17438335 to the third floor in 47-gsms.pptx
JyotirmayNirankari
 
CHAPTER 7 - Foreign Direct Investment.pptx
CHAPTER 7 - Foreign Direct Investment.pptxCHAPTER 7 - Foreign Direct Investment.pptx
CHAPTER 7 - Foreign Direct Investment.pptx
72200337
 
SAFETY BRIEFING.........................
SAFETY BRIEFING.........................SAFETY BRIEFING.........................
SAFETY BRIEFING.........................
BalaChandran458212
 
Pixida, Simplifying Success in Germany, the USA, Brazil, China and Portugal
Pixida, Simplifying Success in Germany, the USA, Brazil, China and PortugalPixida, Simplifying Success in Germany, the USA, Brazil, China and Portugal
Pixida, Simplifying Success in Germany, the USA, Brazil, China and Portugal
TechMeetups
 
Software Development Business Plan1.pptx
Software Development Business Plan1.pptxSoftware Development Business Plan1.pptx
Software Development Business Plan1.pptx
vkprintingsolution
 
Huckel_MO_Theory_Colorful_Presentation (1).pptx
Huckel_MO_Theory_Colorful_Presentation (1).pptxHuckel_MO_Theory_Colorful_Presentation (1).pptx
Huckel_MO_Theory_Colorful_Presentation (1).pptx
study2022bsc
 
Top Business Schools in Delhi For Quality Education
Top Business Schools in Delhi For Quality EducationTop Business Schools in Delhi For Quality Education
Top Business Schools in Delhi For Quality Education
top10privatecolleges
 
History of Entomology and current updates of entomology.pptx
History of Entomology and current updates of entomology.pptxHistory of Entomology and current updates of entomology.pptx
History of Entomology and current updates of entomology.pptx
Neelesh Raipuria
 
RCM-billing in medical coding0000 1.pptx
RCM-billing in medical coding0000 1.pptxRCM-billing in medical coding0000 1.pptx
RCM-billing in medical coding0000 1.pptx
liajohn0808
 
COMPRESSION MODELSCOMPRESSION MODELSCOMPRESSION MODELS
COMPRESSION MODELSCOMPRESSION MODELSCOMPRESSION MODELSCOMPRESSION MODELSCOMPRESSION MODELSCOMPRESSION MODELS
COMPRESSION MODELSCOMPRESSION MODELSCOMPRESSION MODELS
johncena77770789
 
remakingyourselfpresentation-250430095415-6476ade1.pptx
remakingyourselfpresentation-250430095415-6476ade1.pptxremakingyourselfpresentation-250430095415-6476ade1.pptx
remakingyourselfpresentation-250430095415-6476ade1.pptx
lakhmanpindariya9176
 
Introduction on Speaking skills Power Point
Introduction on Speaking skills Power PointIntroduction on Speaking skills Power Point
Introduction on Speaking skills Power Point
helenswarna
 
Stakeholders Management GT 11052021.cleaned.pptx
Stakeholders Management GT 11052021.cleaned.pptxStakeholders Management GT 11052021.cleaned.pptx
Stakeholders Management GT 11052021.cleaned.pptx
SaranshJeena
 
LCL216_2024-2_WEEKS 4 & 5_IF CLAUSES (1).pdf
LCL216_2024-2_WEEKS 4 & 5_IF CLAUSES (1).pdfLCL216_2024-2_WEEKS 4 & 5_IF CLAUSES (1).pdf
LCL216_2024-2_WEEKS 4 & 5_IF CLAUSES (1).pdf
rafaelsago2015
 
SHIPPING CONTAINdccdcdERS BC (2).pdf.pptx
SHIPPING CONTAINdccdcdERS BC (2).pdf.pptxSHIPPING CONTAINdccdcdERS BC (2).pdf.pptx
SHIPPING CONTAINdccdcdERS BC (2).pdf.pptx
ArshjotSingh30
 
Sample animal revalidation protocol for resaecrh based.pptx
Sample animal revalidation protocol for resaecrh based.pptxSample animal revalidation protocol for resaecrh based.pptx
Sample animal revalidation protocol for resaecrh based.pptx
azeemccras
 
巴利亚多利德大学毕业证书学校原版文凭补办UVa成绩单办本科成绩单
巴利亚多利德大学毕业证书学校原版文凭补办UVa成绩单办本科成绩单巴利亚多利德大学毕业证书学校原版文凭补办UVa成绩单办本科成绩单
巴利亚多利德大学毕业证书学校原版文凭补办UVa成绩单办本科成绩单
xule9cv6nd
 
When Is the Best Time to Use Job Finding Apps?
When Is the Best Time to Use Job Finding Apps?When Is the Best Time to Use Job Finding Apps?
When Is the Best Time to Use Job Finding Apps?
SnapJob
 
RightShip-Inspection-Maritime-Safety-Simplified.pptx
RightShip-Inspection-Maritime-Safety-Simplified.pptxRightShip-Inspection-Maritime-Safety-Simplified.pptx
RightShip-Inspection-Maritime-Safety-Simplified.pptx
ultronmeg
 
Green Colorful House Simple Illustration Presentation.pdf.pdf
Green Colorful House Simple Illustration Presentation.pdf.pdfGreen Colorful House Simple Illustration Presentation.pdf.pdf
Green Colorful House Simple Illustration Presentation.pdf.pdf
RhyzCharmSolis
 
material-17438335 to the third floor in 47-gsms.pptx
material-17438335 to the third floor in 47-gsms.pptxmaterial-17438335 to the third floor in 47-gsms.pptx
material-17438335 to the third floor in 47-gsms.pptx
JyotirmayNirankari
 
CHAPTER 7 - Foreign Direct Investment.pptx
CHAPTER 7 - Foreign Direct Investment.pptxCHAPTER 7 - Foreign Direct Investment.pptx
CHAPTER 7 - Foreign Direct Investment.pptx
72200337
 
SAFETY BRIEFING.........................
SAFETY BRIEFING.........................SAFETY BRIEFING.........................
SAFETY BRIEFING.........................
BalaChandran458212
 
Pixida, Simplifying Success in Germany, the USA, Brazil, China and Portugal
Pixida, Simplifying Success in Germany, the USA, Brazil, China and PortugalPixida, Simplifying Success in Germany, the USA, Brazil, China and Portugal
Pixida, Simplifying Success in Germany, the USA, Brazil, China and Portugal
TechMeetups
 
Software Development Business Plan1.pptx
Software Development Business Plan1.pptxSoftware Development Business Plan1.pptx
Software Development Business Plan1.pptx
vkprintingsolution
 
Huckel_MO_Theory_Colorful_Presentation (1).pptx
Huckel_MO_Theory_Colorful_Presentation (1).pptxHuckel_MO_Theory_Colorful_Presentation (1).pptx
Huckel_MO_Theory_Colorful_Presentation (1).pptx
study2022bsc
 
Top Business Schools in Delhi For Quality Education
Top Business Schools in Delhi For Quality EducationTop Business Schools in Delhi For Quality Education
Top Business Schools in Delhi For Quality Education
top10privatecolleges
 
History of Entomology and current updates of entomology.pptx
History of Entomology and current updates of entomology.pptxHistory of Entomology and current updates of entomology.pptx
History of Entomology and current updates of entomology.pptx
Neelesh Raipuria
 
Ad

TCS_Digital_Advanced_Coding_Student copy.pptx

  • 2. Topic/Course Sub-Topic (Example: name of college) TCS Digital Advanced Coding
  • 4. question 1 Ayush is working on a strange algorithm where he wants to convert a string from A to B, both the strings of equal length N. Below are the rules which can be performed to convert a string. String A and B are of equal length Both of them are in lower case Choose a subset X from the string A, between the index 1 and N. Let ‘s’ be the letter which alphabetically comes before all other letters in the subset. Let ‘s’ be called the ‘smallest element’ in the subset. Replace all the elements of subset with the letter ‘s’
  • 5. question 1 Find the minimum number of moves which is required to perform the conversion. If it is not possible to convert the string from A to b then return -1 Let us try to understand it with and examples Suppose there are 2 strings A = abcab B = aabab Operation 1: Now we have chosen a subset S, let us say we have taken index 2,3,5 from A
  • 6. question 1 Then the subset S becomes [bcb] Next, we have to choose the smallest element , 6041 here, which is b here in b & c Next, we have to replace all the other elements in subset with this element. So ‘b’ with replace everything in [bcb]. which becomes [bbb]. Now we will place all the respective elements back to their respective index. This will update the original string as [abbab] Operation 2: Original string [abbab] Now we have chosen a subset S, let say we have taken a index 1,2,4 from A
  • 7. question 1 Then the subset become [aba] Next, we have to choose the smallest element, which is here in a & b. Next, we have to replace the smallest with all the other elements in subset. So ‘a’ will replace everything in [aba] Now we will place all the respective elements back to their respective index. This will update the original string as [aabab] This is exactly same as String B Hence it is possible to convert string A to B, with 2 operations. So, the answer is 2.
  • 8. question 1 Example 1: Input: 2-> Input integer, N de-> input string, A cd-> Input string, B Output: -1 Explanation: In the above example we can clearly see that there is an alphabet in A which is completely different from B. hence it is not possible to convert A to B So the answer is -1
  • 9. question 1 Example 2: Input: 4-> input integer, N abab-> input string, A abaa-> input string A Output: 1 -> Output Explanation: Operation 1: Now we have chosen a subset S, let say we have taken index 3,4 from A then the Subset S becomes [ab]
  • 10. question 1 Next, we have to choose the smallest element, which is a here in a & b Next, we have to replace the smallest with all the other elements in subset. So ‘a’ will replace everything in [abl, which becomes [aa] Now we will place all the respective elements back to their respective index. This will update the original string as [abaa] This is exactly same as String B Hence it is possible to convert string A to B. with 1 operation. So, the answer is 1. Constraints: 1<=N<=1000 N integer Only lower case letters of the English alphabet Length of A,B = N
  • 11. question 1 The input format for testing First Input-Accept value of Integer, N. Second Input-Accept value of string, A (Next Line) Third Input-Accept value of string, B(Next Line) Additional messages in output will cause the failure of test cases The Output format for testing The output is an integer as per above logic. (Check the output in Example 1, Example 21 Additional messages in output will cause the failure of test cases
  • 12. #include <stdio.h> #include <stdlib.h> #include <string.h> void transformString(char* str1, char* str2) { int N = strlen(str1); int convChar[26][N]; int convCharSize[26] = { 0 }; int str1array[26][N]; int str1arraySize[26] = { 0 }; int convertMap[N]; // Initialize convertMap for (int i = 0; i < N; i++) { convertMap[i] = -1; } // Filling str1array and convChar for (int i = 0; i < N; i++) { str1array[str1[i] - 'a'][str1arraySize[str1[i] - 'a']++] = i; } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 13. for (int i = 0; i < N; i++) { // Not possible to convert if (str1[i] < str2[i]) { printf("-1n"); return; } else if (str1[i] == str2[i]) { continue; } else { int index = str2[i] - 'a'; convChar[index][convCharSize[index]++] = i; convertMap[i] = str2[i]; } } // Calculate result int ret = 0; int retv[N][N]; int retvSize = 0; 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 14. for (int i = 25; i >= 0; i--) { int* v = convChar[i]; int vSize = convCharSize[i]; if (vSize == 0) continue; ret++; int* v1 = str1array[i]; int v1Size = str1arraySize[i]; if (v1Size == 0) { printf("-1n"); return; } int isScompleted = 0; for (int j = 0; j < v1Size; j++) { if (convertMap[v1[j]] != -1) { char a = convertMap[v1[j]]; 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 15. if (a > i + 'a') continue; else { v[vSize++] = v1[j]; isScompleted = 1; memcpy(retv[retvSize++], v, vSize * sizeof(int)); break; } } else { v[vSize++] = v1[j]; isScompleted = 1; memcpy(retv[retvSize++], v, vSize * sizeof(int)); break; } } if (!isScompleted) { printf("-1n"); return; } } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 16. printf("%dn", ret); } int main() { int N; char A[1000], B[1000]; // Read the input values scanf("%d", &N); scanf("%s", A); scanf("%s", B); transformString(A, B); return 0; } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 17. #include <bits/stdc++.h> using namespace std; void transformString(string str1,string str2) { int N = str1.length(); vector<int> convChar[26]; vector<int> str1array[26]; // Initialize both arrays for (int i = 0; i < 26; i++) { vector<int> v; convChar[i] = v; str1array[i] = v; } // Stores the index of character map<int, char> convertMap; // Filling str1array, convChar // and hashmap convertMap. for (int i = 0; i < N; i++) { str1array[str1[i] - 'a'].push_back(i); } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 18. for (int i = 0; i < N; i++) { // Not possible to convert if (str1[i] < str2[i]) { cout << -1 << endl; return; } else if (str1[i] == str2[i]) continue; else { convChar[str2[i] - 'a'].push_back(i); convertMap[i] = str2[i]; } } // Calculate result // Initializing return values int ret = 0; vector<vector<int> > retv; // Iterating the character from // the end 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 19. for (int i = 25; i >= 0; i--) { vector<int> v = convChar[i]; if (v.size() == 0) continue; // Increment the number of // operations ret++; vector<int> v1 = str1array[i]; // Not possible to convert if (v1.size() == 0) { cout << -1 << endl; return; } // to check whether the final // element has been added // in set S or not. bool isScompleted = false; for (int j = 0; j < v1.size(); j++) { 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 20. if (convertMap.find(v1[j]) != convertMap.end()) { char a = convertMap[v1[j]]; // Already converted then // then continue if (a > i + 'a') continue; else { v.push_back(v1[j]); isScompleted = true; retv.push_back(v); break; } } else { v.push_back(v1[j]); isScompleted = true; retv.push_back(v); 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 21. } } // Not possible to convert if (!isScompleted) { cout << -1 << endl; return; } } // Print the result cout << ret << endl; } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 22. int main() { int N; string A, B; // Read the input values cin >> N; cin >> A; cin >> B; transformString(A, B); return 0; } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 23. import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Scanner; public class Main { public static void transformString(String str1, String str2) { int N = str1.length(); List<Integer>[] convChar = new ArrayList[26]; List<Integer>[] str1array = new ArrayList[26]; // Initialize both arrays for (int i = 0; i < 26; i++) { convChar[i] = new ArrayList<>(); str1array[i] = new ArrayList<>(); } // Stores the index of character Map<Integer, Character> convertMap = new HashMap<>(); 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 24. // Filling str1array, convChar and hashmap convertMap. for (int i = 0; i < N; i++) { str1array[str1.charAt(i) - 'a'].add(i); } for (int i = 0; i < N; i++) { // Not possible to convert if (str1.charAt(i) < str2.charAt(i)) { System.out.println(-1); return; } else if (str1.charAt(i) == str2.charAt(i)) { continue; } else { convChar[str2.charAt(i) - 'a'].add(i); convertMap.put(i, str2.charAt(i)); } } // Calculate result // Initializing return values int ret = 0; List<List<Integer>> retv = new ArrayList<>(); 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 25. // Iterating the character from the end for (int i = 25; i >= 0; i--) { List<Integer> v = convChar[i]; if (v.size() == 0) continue; // Increment the number of operations ret++; List<Integer> v1 = str1array[i]; // Not possible to convert if (v1.size() == 0) { System.out.println(-1); return; } // to check whether the final element has been added in set S or not. boolean isScompleted = false; 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 26. for (int j = 0; j < v1.size(); j++) { // Check if v1[j] is present in hashmap or not if (convertMap.containsKey(v1.get(j))) { char a = convertMap.get(v1.get(j)); // Already converted then continue if (a > i + 'a') continue; else { v.add(v1.get(j)); isScompleted = true; retv.add(v); break; } } else { v.add(v1.get(j)); isScompleted = true; retv.add(v); break; } } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 27. // Not possible to convert if (!isScompleted) { System.out.println(-1); return; } } // Print the result System.out.println(ret); } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int N = scanner.nextInt(); String A = scanner.next(); String B = scanner.next(); transformString(A, B); } } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 28. def transformString(str1, str2): N = len(str1) convChar = [[] for _ in range(26)] str1array = [[] for _ in range(26)] # Initialize both arrays convertMap = {} # Filling str1array, convChar and hashmap convertMap. for i in range(N): str1array[ord(str1[i]) - ord('a')].append(i) for i in range(N): # Not possible to convert if str1[i] < str2[i]: print(-1) return elif str1[i] == str2[i]: continue else: convChar[ord(str2[i]) - ord('a')].append(i) convertMap[i] = str2[i] 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 29. # Calculate result # Initializing return values ret = 0 retv = [] # Iterating the character from the end for i in range(25, -1, -1): v = convChar[i] if len(v) == 0: continue # Increment the number of operations ret += 1 v1 = str1array[i] # Not possible to convert if len(v1) == 0: print(-1) return # to check whether the final element has been added in set S or not. isScompleted = False 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 30. for j in range(len(v1)): # Check if v1[j] is present in hashmap or not if v1[j] in convertMap: a = convertMap[v1[j]] # Already converted then continue if a > chr(i + ord('a')): continue else: v.append(v1[j]) isScompleted = True retv.append(v) break else: v.append(v1[j]) isScompleted = True retv.append(v) break # Not possible to convert if not isScompleted: print(-1) return 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 31. # Print the result print(ret) # Read the input values N = int(input()) A = input() B = input() transformString(A, B) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 32. question 2 A boy enters a stationery shop. There are N number of pencils and M number of erasers available in the shop. But the boy's mother insists that he can buy only P number of pencils and E number of erasers. The task here is to find the number of ways the boy can choose 'P' pencils and 'E' erasers from the available N and M pencils & erasers respectively. Note: The boy can choose in any order. N-number of pencils available in the shop M-number of erasers available in the shop P-number of pencils he can choose to buy from N E-number of erasers he can choose to buy from M Example 1:
  • 33. question 2 Input: 3 Value of N M 1 Value of M W 2 Value of P X 1 Value of E Y Output: 3 Number of ways we can choose Explanation 1 From the input given above 1st way of selecting: Select 1st and 2nd pencils, 1 eraser 2nd way of selecting:
  • 34. question 2 Select 2nd and 3rd pencils, 1 eraser 1st way of selecting: Select 1st and 3rd pencils, 1 eraser The Possible number of ways selecting 2 pencils and 1 eraser is 3 Hence the output is 3. Example 2 Input: 5->Value of N 3->Value of M 5->Value of P 3->Value of E Output:
  • 35. question 2 ->.Number of ways we can choose Explanation 2 From the input given above: 1st way of selecting: Select 1,2,3,4,5 Pencils and 1,2,3 erasers There is only one possible way of selecting 5 pencils and 3 Hence, the output is 1. Constarins: 0<N<<=50 0<M<=50 0<=P<=50 0<=E<=50
  • 36. question 2 The Input format for testing The candidate has to write the code to accept 4 input(s). First Input - Accept value for N(Positive integer number) Second Input-Accept value for M(Positive integer number) Third input Accept value for P(Positive integer number) Fourth input Accept value for E(Positive integer number) The Output format for testing The output should be a positive integer number or print the message (if any) given in the problem statement (Check the output in Example 1, Example 2)
  • 37. #include <stdio.h> // Function to calculate the factorial of a number int factorial(int n) { int fact = 1; for (int i = 1; i <= n; i++) { fact *= i; } return fact; } // Function to calculate the number of ways to choose 'P' pencils and 'E' erasers int countWaysToChoose(int N, int M, int P, int E) { // Calculate the number of ways to choose 'P' pencils int waysToChoosePencils = factorial(N) / (factorial(P) * factorial(N - P)); // Calculate the number of ways to choose 'E' erasers int waysToChooseErasers = factorial(M) / (factorial(E) * factorial(M - E)); 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 38. // Calculate the total number of ways int totalWays = waysToChoosePencils * waysToChooseErasers; return totalWays; } int main() { int N, M, P, E; scanf("%d %d %d %d", &N, &M, &P, &E); int ways = countWaysToChoose(N, M, P, E); printf("%dn", ways); return 0; } 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
  • 39. #include <iostream> using namespace std; // Function to calculate the factorial of a number int factorial(int n) { int fact = 1; for (int i = 1; i <= n; i++) { fact *= i; } return fact; } // Function to calculate the number of ways to choose 'P' pencils and 'E' erasers int countWaysToChoose(int N, int M, int P, int E) { // Calculate the number of ways to choose 'P' pencils int waysToChoosePencils = factorial(N) / (factorial(P) * factorial(N - P)); // Calculate the number of ways to choose 'E' erasers int waysToChooseErasers = factorial(M) / (factorial(E) * factorial(M - E)); // Calculate the total number of ways 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 40. E)); // Calculate the total number of ways int totalWays = waysToChoosePencils * waysToChooseErasers; return totalWays; } int main() { int N, M, P, E; cin >> N >> M >> P >> E; int ways = countWaysToChoose(N, M, P, E); cout << ways; return 0; } 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
  • 41. import java.util.Scanner; public class Main { // Function to calculate the factorial of a number public static int factorial(int n) { int fact = 1; for (int i = 1; i <= n; i++) { fact *= i; } return fact; } // Function to calculate the number of ways to choose 'P' pencils and 'E' erasers public static int countWaysToChoose(int N, int M, int P, int E) { // Calculate the number of ways to choose 'P' pencils int waysToChoosePencils = factorial(N) / (factorial(P) * factorial(N - P)); // Calculate the number of ways to choose 'E' erasers 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 42. int waysToChooseErasers = factorial(M) / (factorial(E) * factorial(M - E)); // Calculate the total number of ways int totalWays = waysToChoosePencils * waysToChooseErasers; return totalWays; } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int N = scanner.nextInt(); int M = scanner.nextInt(); int P = scanner.nextInt(); int E = scanner.nextInt(); int ways = countWaysToChoose(N, M, P, E); System.out.println(ways); } } 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
  • 43. # Function to calculate the factorial of a number def factorial(n): fact = 1 for i in range(1, n+1): fact *= i return fact # Function to calculate the number of ways to choose 'P' pencils and 'E' erasers def countWaysToChoose(N, M, P, E): # Calculate the number of ways to choose 'P' pencils waysToChoosePencils = factorial(N) // (factorial(P) * factorial(N - P)) # Calculate the number of ways to choose 'E' erasers waysToChooseErasers = factorial(M) // (factorial(E) * factorial(M - E)) # Calculate the total number of ways totalWays = waysToChoosePencils * waysToChooseErasers return totalWays # Main function def main(): N = int(input()) M = int(input()) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 44. P = int(input()) E = int(input()) ways = countWaysToChoose(N, M, P, E) print(ways) # Call the main function main() 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
  • 45. question 3 Question: 3 One day Bob is playing Zombie World video game. In Zombie World game each round will contain N zombies and each zombie's energy is Zi (where 1<=i<=N). Bob will start the round with B energy. In order to move to the next level Bob need to kill all the N zombie's but Bob can select any one among N Zombie's. If energy of Bob (B) is less than Zombie energy (Zi) then Bob will die and lose the round else Bob will won, during the fighting with zombie, Bob will lose his energy by (Zi%2)+(Zi/2). At any point of game Bob will play optimally. Now your task is to find out whether Bob can reach to the next level or
  • 46. question 3 not.Input FormatThe first line of input contain B and N, where B is the energy of Bob and N is the number of ZombiesThe second line of input contain Zi, where Zi is a list containing energy of zombies separated by spaceOutput FormatPrint "YES" or "NO" depending upon whether Bob can reach the next level or not. Constraints 1<=N<=10^41<=B<=10^91<=Zi<=10^5 Sample Test Case : Input: 35 3 5 9 6 Output: YES
  • 47. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 #include<stdio.h> void swap(int* xp, int* yp) { int temp = *xp; *xp = *yp; *yp = temp; } // Function to perform Selection Sort void sort(long int arr[], long int n) { int i, j, min_idx; // One by one move boundary of unsorted subarray for (i = 0; i < n - 1; i++) { // Find the minimum element in unsorted array min_idx = i; for (j = i + 1; j < n; j++) if (arr[j] < arr[min_idx]) min_idx = j; // Swap the found minimum element // with the first element swap(&arr[min_idx], &arr[i]); } } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 48. int main(){ long int b,n; scanf("%ld%ld",&b,&n); long int z[n]; for(long int i=0;i<n;i++) scanf("%ld",&z[i]); sort(z, n); for(long int i=0;i<n;i++) b-=(z[i]%2)+(z[i]/2); if(b<0) printf("NO"); else printf("YES"); } 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
  • 49. #include <algorithm> #include<iostream> using namespace std; int main(){ long int b,n; cin>>b>>n; long int z[n]; for(long int i=0;i<n;i++) cin>>z[i]; sort(z, z+n); for(long int i=0;i<n;i++) b-=(z[i]%2)+(z[i]/2); if(b<0) cout<<"NO"; else cout<<"YES"; } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 50. import java.util.Scanner; import java.util.Arrays; class Main{ public static void main(String args[]) { Scanner sc = new Scanner(System.in); long b; b = sc.nextLong(); int n = sc.nextInt(); long z[]= new long[n]; for(int i=0;i<n;i++) z[i]=sc.nextLong(); Arrays.sort(z); for(int i=0;i<n;i++) b-=(z[i]%2)+(z[i]/2); if(b<0) System.out.print("NO"); else System.out.print("YES"); } } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 51. b ,n= [int(x) for x in input().split()] z = [int(x) for x in input().split()] z.sort() for i in range(n): b-=(z[i]%2)+(z[i]/2) if(b<0): print("NO") else: print("YES") 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 52. question 4 Alice and Bob are batch mates and Alice got placed in a well-reputed product- based company and his friend Bob is demanding a pizza party from him. Alice is ready for giving party and he ordered N pizzas from the nearest restaurant. Now pizzas can have at most K different flavors (It is not necessary that there should be one pizza of each flavor), numbered from 1 to K such that ⅈ^th pizza can have Ai flavor (1 <= Ai <=k). Bob is on dieting, and he can only eat pizza of at most k-1 flavors but he can eat as many pizzas of ith flavor and he wanted to choose maximum possible pizzas which are in contiguous sequence to one another such that all pizzas in sequence has atmost k-1 flavors. For example 6 2 -> here 6 is the number pizzas of and 2 is number of distinct flavors 1 1 1 2 2 1 -> ith pizza has flavor ai
  • 53. question 4 Example 1: Input 6 2 -> Size of input Array and K distinct flavors 1 1 1 2 2 1 -> input array (N Different pizza flavors ) Output 3 Explanation Maximum length subarray with at most k-1 distinct flavors is 3 and sub array is 1 1 1
  • 54. question 4 Example 2: Input: 5 3 -> Size of inputs Arrays and K distinct flavors 1 1 2 2 1 -> input array (N Different Pizza Flavors) Output 5 Explanation Since N pizza in total has only 2 flavors so bob can eat all pizza so maximum length of subarray with at most k-1 distinct flavors is 5
  • 55. question 4 Constraints 1<N<100000>Size of Array 2<K<100000> Number of different flavors 1<A[i]<100000> Value of ith flavor 0 base indexing The Input format for testing The candidate has to write the code to accept 2 inputs. First Input: It will contain two integer N and K Second Input: It will contain a N integer separated by space. Output format for testing The output will contain a single line containing an integer denoting maximum possible length of subarray.
  • 56. question 4 Additional messages in output will cause the failure of test cases. Instructions: System doesn't allow any kind of hard coded input value/values. Written program code by the candidate will be verified against the inputs which are supplied from the system
  • 57. #include <stdio.h> int main() { int n, k; scanf("%d %d", &n, &k); int arr[n]; for (int i = 0; i < n; i++) { scanf("%d", &arr[i]); } int maxcount = 0; for (int i = 0; i < n; i++) { int count = 0; while (i < n && arr[i] <= k - 1) { count++; i++; } maxcount = (count > maxcount) ? count : maxcount; } printf("%dn", maxcount); return 0; } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 58. #include <iostream> using namespace std; int main() { int n, k; cin >> n >> k; int arr[n]; for (int i = 0; i < n; i++) { cin >> arr[i]; } int maxcount = 0; for (int i = 0; i < n; i++) { int count = 0; while (i < n && arr[i] <= k - 1) { count++; i++; } maxcount = (count > maxcount) ? count : maxcount; } cout << maxcount << endl; return 0; } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 59. import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); int k = scanner.nextInt(); int[] arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = scanner.nextInt(); } int maxcount = 0; for (int i = 0; i < n; i++) { int count = 0; while (i < n && arr[i] <= k - 1) { count++; i++; } maxcount = Math.max(count, maxcount); } System.out.println(maxcount); scanner.close(); }} 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 60. n,k=map(int,input().split()) arr=list(map(int,input().split())) maxcount=0 for i in range(n): count=0 while i<n and arr[i]<=k-1: count+=1 i+=1 maxcount=max(maxcount, count) print(maxcount) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 61. question 5 Alice had to go to play with his friends. But his brother is not leaving. So, he thought to ask a question so that in the mean time he can go. So , the problem is as follows: He will be given numbers n,m and k. Calculate T. (T = (nm)/k) His brother has to find the three coordinates of the XY plane (2D points) such that the area of the triangle formed by those points should be equal to T. If there is any solution print YES. else NO. NOTE: 1 x1,y1, x2,y2, x3, y3 109 ≤ ≤ Example 1: Input: 4 3 3
  • 62. question 5 Output: YES Explanation: One possible way is (1,0), (2,3) and (4,1) are the points where there area is equal to T. Example - 2: Input: 4 4 7 Output. NO
  • 63. question 5 Constraints: 1 n,m 109 ≤ ≤ 2 k 109 ≤ ≤ The input format for testing: •The first line represents the n, m and k, each separated by a space. The Output format for testing: •Print YES if there is any solution else NO Instructions: •The system does not allow any kind of hard- coded input value/ values. •Written program code by the candidate will be verified against the inputs which are supplied from the system.
  • 64. #include <stdio.h> #include <math.h> char* check_triangle_area(int n, int m, int k) { double T = (double)(n * m) / k; for (int x1 = 1; x1 <= n; x1++) { for (int y1 = 0; y1 <= m; y1++) { for (int x2 = 0; x2 <= n; x2++) { for (int y2 = 0; y2 <= m; y2++) { double area = 0.5 * fabs(x1 * (y2 - y1) + x2 * (y1 - 0) + n * (0 - y2)); if (area == T) { return "YES"; } } } } } return "NO"; } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 65. int main() { int n, m, k; scanf("%d %d %d", &n, &m, &k); char* result = check_triangle_area(n, m, k); printf("%sn", result); return 0; }
  • 66. #include <iostream> #include <cmath> using namespace std; string check_triangle_area(int n, int m, int k) { double T = static_cast<double>(n * m) / k; for (int x1 = 1; x1 <= n; x1++) { for (int y1 = 0; y1 <= m; y1++) { for (int x2 = 0; x2 <= n; x2++) { for (int y2 = 0; y2 <= m; y2++) { double area = 0.5 * abs(x1 * (y2 - y1) + x2 * (y1 - 0) + n * (0 - y2)); if (area == T) { return "YES"; } } } } } return "NO"; } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 67. int main() { int n, m, k; cin >> n >> m >> k; string result = check_triangle_area(n, m, k); cout << result << endl; return 0; }
  • 68. import java.util.Scanner; public class Main { static String checkTriangleArea(int n, int m, int k) { double T = (double) (n * m) / k; for (int x1 = 1; x1 <= n; x1++) { for (int y1 = 0; y1 <= m; y1++) { for (int x2 = 0; x2 <= n; x2++) { for (int y2 = 0; y2 <= m; y2++) { double area = 0.5 * Math.abs(x1 * (y2 - y1) + x2 * (y1 - 0) + n * (0 - y2)); if (area == T) { return "YES"; } } } } } return "NO"; } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 69. public static void main(String[] args) { Scanner scanner = new Scanner(System.in); long n = scanner.nextLong(); long m = scanner.nextLong(); long k = scanner.nextLong(); if (!isTrianglePossible(n, m, k)) System.out.println("NO"); } }
  • 70. def check_triangle_area(n, m, k): T = (n * m) / k for x1 in range(1, n + 1): for y1 in range(m + 1): for x2 in range(n + 1): for y2 in range(m + 1): area = 0.5 * abs(x1 * (y2 - y1) + x2 * (y1 - 0) + n * (0 - y2)) if area == T: return "YES“ return "NO“ if _name_ == "_main_": n, m, k = map(int, input().split()) result = check_triangle_area(n, m, k) print(result) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 71. question 6 You have given n piles in which each pile contains some numbers of stones/coins and you have also given the information about who can made the first move from player 1 and 2. In each turn, a player can choose only one pile and remove any number of stones (at least one) from that pile. The player who cannot move is considered to lose the game (i.e., one who take the last stone is the winner). ” Input Format : First line will contain two integers n and t - number of piles and who will made the first move first or 2nd player (if t is 1 then 1st player will start game otherwise 2nd player will start the game) (1 <= n <= 10^5, 1 <= t <= 2). Second line will contain n space separated integers (1 <= a[i] <= 100000).
  • 72. question 6 Output Format : Print 1 if player 1 will win otherwise print 2. Sample Input 1: 3 1 3 4 5 Sample Output 1: 1 Sample Input 2: 3 2 3 4 5 Sample Output 2: 2
  • 73. #include <stdio.h> #define int long long #define COMPUTER 1 #define HUMAN 2 int calculateNimSum(int piles[], int n) { int i, nimsum = piles[0]; for (i = 1; i < n; i++) nimsum = nimsum ^ piles[i]; return nimsum; } void knowWinnerBeforePlaying(int piles[] , int n, int whoseTurn) { if (calculateNimSum(piles, n) ! = 0) { if (whoseTurn == COMPUTER) printf("1"); else printf("2"); } else { if (whoseTurn == COMPUTER) printf("2"); else printf("1"); } } int main() { int n, turn; scanf("%lld %lld", &n, &turn); int piles[n]; for (int i = 0; i < n; i++) scanf("%lld", &piles[i]); knowWinnerBeforePlaying(piles, n, t urn); return 0; }
  • 74. using namespace std; #define int long long #define COMPUTER 1 #define HUMAN 2 int calculateNimSum(int piles[], int n) { int i, nimsum = piles[0]; for (i = 1; i<n; i++) nimsum = nimsum ^ piles[i]; return(nimsum); } void knowWinnerBeforePlaying(int piles[] , int n, int whoseTur n) { if (calculateNimSum(piles, n) != 0) { if (whoseTurn == COMPUTER) cout << 1; else cout << 2; } else { if (whoseTurn == COMPUTER) cout << 2; else cout << 1; } return; } signed main() { int n, turn; cin >> n >> turn; int piles[n]; for(int i = 0; i < n; i+ +) cin >> piles[i]; knowWinnerBeforePlaying(piles, n, t urn); return(0); }
  • 75. import java.util.Scanner; public class Main{ public static long calculateNimSum(l ong[] piles, int n) { long nimsum = piles[0]; for (int i = 1; i < n; i++) { nimsum = nimsum ^ piles[i]; } return nimsum; } public static void knowWinnerBeforeP laying(long[] piles, int n, int whoseTur n) { if (calculateNimSum(piles, n) ! = 0) { if (whoseTurn == 1) { System.out.print("1"); } else { System.out.print("2"); } } else { if (whoseTurn == 1) { System.out.print("2"); } else { System.out.print("1"); } } } public static void main(String[] ar gs) { Scanner scanner = new Scanner(S ystem.in); int n = scanner.nextInt(); int turn = scanner.nextInt(); long[] piles = new long[n]; for (int i = 0; i < n; i++) { piles[i] = scanner.nextLong (); } knowWinnerBeforePlaying(piles, n, turn); scanner.close(); }
  • 76. def calculateNimSum(piles, n): nimsum = piles[0] for i in range(1, n): nimsum = nimsum ^ piles[i] return nimsum def knowWinnerBeforePlaying(piles, n, wh oseTurn): if calculateNimSum(piles, n) != 0: if whoseTurn == 1: print("1", end="") else: print("2", end="") else: if whoseTurn == 1: print("2", end="") else: print("1", end="") if __name__ == "__main__": n, turn = map(int, input().split()) piles = list(map(int, input().split ())) knowWinnerBeforePlaying(piles, n, t urn)
  • 77. question 7 A man wants to do rock climbing and reach the top of a steep peak. There is 'N' number of Convenient rocks on the mountain which the mountaineer can step onto to reach the peak a little easily. The initial position/rock on which the rock climber is standing currently is denoted as 'I'. From each rock, the person can skip utmost 'X' rocks. The task here is to find the number of ways a mountaineer can climb to reach the peak. Example 1: Input: 6-> Value of N 3-> Value of I 2-> Value of X Output: 3-> Number of ways he can reach the peak
  • 78. #include <stdio.h> int countClimbingWays(int N, int I, int X) { int ways[N + 1]; ways[I] = 1; ways[I - 1] = 1; for (int i = I + 1; i <= N; i++) { ways[i] = 0; for (int j = 1; j <= X && i - j >= I; j++) { ways[i] += ways[i - j]; } } return ways[N]; } int main() { int N, I, X; scanf("%d", &N); 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 scanf("%d", &I); scanf("%d", &X); int numWays = countClimbingWays(N, I, X); printf("%dn", numWays); return 0; } 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
  • 79. #include <iostream> using namespace std; int countClimbingWays(int N, int I, int X) { int ways[N + 1]; ways[I] = 1; ways[I - 1] = 1; for (int i = I + 1; i <= N; i++) { ways[i] = 0; for (int j = 1; j <= X && i - j >= I; j++) { ways[i] += ways[i - j]; } } return ways[N]; } int main() { int N, I, X; 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 cin >> N; cin >> I; cin >> X; int numWays = countClimbingWays(N, I, X); cout <<numWays; return 0; } 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
  • 80. import java.util.Scanner; public class Main { public static int countClimbingWays(int N, int I, int X) { int[] ways = new int[N + 1]; ways[I] = 1; ways[I - 1] = 1; for (int i = I + 1; i <= N; i++) { ways[i] = 0; for (int j = 1; j <= X && i - j >= I; j++) { ways[i] += ways[i - j]; } } return ways[N]; 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int N, I, X; N = scanner.nextInt(); I = scanner.nextInt(); X = scanner.nextInt(); int numWays = countClimbingWays(N, I, X); System.out.println(numWays); } } 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
  • 81. def countClimbingWays(N, I, X): ways = [0] * (N + 1) ways[I] = 1 ways[I - 1] = 1 for i in range(I + 1, N + 1): ways[i] = 0 for j in range(1, X + 1): if i - j >= I: ways[i] += ways[i - j] return ways[N] N = int(input()) I = int(input()) X = int(input()) numWays = countClimbingWays(N, I, X) print(numWays) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
  • 82. question 8 An event management company has come up with a unique idea of printing their event tickets. Based on the ticket number combination (str1), the visitor is directed towards a particular class of audience. The task is to create a program/application to fetch the ticket number based on the following conditions: Any occurrences of digits EF and G should be deleted. The characters EF should be in the same format. Input format The candidate has to write the code to accept 1 input(s). First Input -Accept value for str1 which is a string consisting of numbers and uppercase alphabets without any spaces Output format
  • 83. question 8 The output should be a string without any spaces (Check the output in Example 1 and Example 2) Additional messages in output will cause the failure of test cases. Constraints Str ((A,Z),(0-9)) No spaces and special characters allowed. Only uppercase alphabets in the input string Example 1: Input: 4523EF58G -> A value of STR1
  • 84. question 8 Output : 452358 -> A after removal of characters EF and G Example 2: Input: E12F35G58 -> A value of STR1 Output : E12F3558 -> A after removal of characters “G” Explanation: In the above example, characters E and F are not together So, they won't be deleted. The output will be with only character G removed.
  • 85. #include <stdio.h> #include <stdlib.h> #include <string.h> char* removeCharacters(const char* str) { char* result = (char*)malloc(strlen(str) + 1); int resultIndex = 0; int isEF = 0; for (int i = 0; str[i] != '0'; i++) { if (str[i] == 'E' && !isEF) { isEF = 1; } else if (isEF && str[i] == 'F') { isEF = 0; 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 } else if (str[i] != 'G') { result[resultIndex++] = str[i]; } } result[resultIndex] = '0'; return result; } int main() { char ticketNumber[100]; scanf("%s", ticketNumber); char* modifiedTicketNumber = removeCharacters(ticketNumber); printf("%sn", modifiedTicketNumber); free(modifiedTicketNumber); return 0; } 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
  • 86. #include <iostream> #include <string> using namespace std; string removeCharacters(const string& str) { string result; bool isEF = false; for (char ch : str) { if (ch == 'E' && !isEF) { isEF = true; } else if (isEF && ch == 'F') { isEF = false; } else if (ch != 'G') { result.push_back(ch); } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 } return result; } int main() { string ticketNumber; cin >> ticketNumber; string modifiedTicketNumber = removeCharacters(ticketNumber); cout << modifiedTicketNumber << "n"; return 0; } 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
  • 87. import java.util.Scanner; public class Main { public static String removeCharacters(String str) { StringBuilder result = new StringBuilder(); boolean isEF = false; for (char ch : str.toCharArray()) { if (ch == 'E' && !isEF) { isEF = true; } else if (isEF && ch == 'F') { isEF = false; } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 else if (ch != 'G') { result.append(ch); } } return result.toString(); } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); String ticketNumber = scanner.nextLine(); String modifiedTicketNumber = removeCharacters(ticketNumber); System.out.println(modifiedTicketNumber ); } } 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
  • 88. def remove_characters(ticket_number): result = "" is_ef = False for ch in ticket_number: if ch == 'E' and not is_ef: is_ef = True elif is_ef and ch == 'F': is_ef = False elif ch != 'G': result += ch return result def main(): ticket_number = input() modified_ticket_number = remove_characters(ticket_number) print(modified_ticket_number) main() 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
  • 89. question 9 The person is travelling from place A to place B. He will take 12 hours to reach the destination by roads. As the person starts his journey, he has to note the current time in hours H and minutes M ( non negative integer input ).The task is to find the time left for him to reach the destination (output).If current time (hours or minutes) is a value exceeding 24 hours, the output should be a negative integer value, representing total exceeded hours and minutes (See the Example 3). Input format The candidate has to write the code to accept two inputs separated by a new line. First Input Accept value for hours which is H. Second Input- Accept value for minutes which is M. Output format
  • 90. question 9 The output should be time in 24 hour format (Check the output in Example 1 and 2 above). The hours and minutes should be separated by "::" without any additional space(See the output in examples). Additional messages in output will cause the failure of test cases. Constraints: 0<H<=100 0<M<=60 Example 1: Input: 14 value of H i.e Hours 20 value of M i.e Minutes
  • 91. question 9 Output: 9::40 Time left to reach the destination Example 2: Input: 1 value of H i.e Hours 15 value of M i.e Minutes Output: 22::45 Time left to reach the destination Example 3: Input: 30 value of H i.e Hours 5 value of M i.e Minutes Output: -6::5 Time left to reach the destination
  • 92. #include <stdio.h> int main() { int H, M; scanf("%d", &H); scanf("%d", &M); // Convert hours to minutes int currentTotalMinutes = H * 60 + M; // Calculate time left in minutes int timeLeftMinutes = 24 * 60 - currentTotalMinutes; // Convert time left to hours and minutes int timeLeftHours = timeLeftMinutes / 60; int timeLeftMins = timeLeftMinutes % 60; printf("%02d::%02dn", timeLeftHours, timeLeftMins); return 0; } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 93. #include <bits/stdc++.h> using namespace std; int main() { int H, M; cin >> H; cin >> M; // Convert hours to minutes int currentTotalMinutes = H * 60 + M; // Calculate time left in minutes int timeLeftMinutes = 24 * 60 - currentTotalMinutes; // Convert time left to hours and minutes int timeLeftHours = timeLeftMinutes / 60; int timeLeftMins = timeLeftMinutes % 60; cout << setfill('0') << setw(2) << timeLeftHours << "::" << setfill('0') << setw(2) << timeLeftMins; return 0; } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 94. import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int H, M; H = scanner.nextInt(); M = scanner.nextInt(); // Convert hours to minutes int currentTotalMinutes = H * 60 + M; // Calculate time left in minutes int timeLeftMinutes = 24 * 60 - currentTotalMinutes; // Convert time left to hours and minutes int timeLeftHours = timeLeftMinutes / 60; int timeLeftMins = timeLeftMinutes % 60; System.out.printf("%02d::%02d", timeLeftHours, timeLeftMins); scanner.close(); } } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 95. H = int(input()) M = int(input()) # Calculate total minutes currentTotalMinutes = H * 60 + M # Check if current time exceeds 24 hours if currentTotalMinutes > 24 * 60: timeExceededMinutes = currentTotalMinutes - (24 * 60) timeExceededHours = timeExceededMinutes // 60 timeExceededMinutes %= 60 print("-{}::-{:02d}".format(timeExceededHours, timeExceededMinutes)) else: # Calculate time left in minutes timeLeftMinutes = 24 * 60 - currentTotalMinutes # Calculate time left hours and minutes timeLeftHours = timeLeftMinutes // 60 timeLeftMinutes %= 60 # Format and print the output print("{:02d}::{:02d}".format(timeLeftHours, timeLeftMinutes)) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 96. question 10 A shopkeeper in a nearby town always starts a business ₹0. He never uses the previous days money for transaction. Any item in his shop costs ₹30.There are N number of customers waiting in the queue to buy items. A customer can buy any number of items but worth only ₹30.The customer can transact with shopkeeper only with the denominations ₹30,₹60,₹120.The task here is to find the transaction between the shopkeeper and customer is possible. The customer should be able to buy the item. The amount each customer uses for his transaction is given as array elements . The shopkeeper should be able to return the exact change. Display ‘Transaction Successful’ on the successful transaction with all the customers in the queue. Display ‘Transaction failed’ on the unsuccessful transaction with any one customer in the queue.
  • 97. question 10 Example 1 Sample Input: 3 -> value of N 30 30 60->a[] ,Elements a[0] to a[N-1],where input of each element is seperated by a new line. Sample Output: Transaction successful.
  • 98. #include <stdio.h> int isTransactionPossible(int a[], int N) { int change30 = 0; int change60 = 0; int change120 = 0; for (int i = 0; i < N; i++) { if (a[i] == 30) { // If customer pays ₹30, no change required change30++; } else if (a[i] == 60) { // If customer pays ₹60, return ₹30 change if available if (change30 > 0) { change30--; } else { 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 99. return 0; } change60++; } else if (a[i] == 120) { // If customer pays ₹120, return ₹90 change if available if (change30 > 0 && change60 > 0) { change30--; change60--; } else if (change30 >= 3) { change30 -= 3; } else { return 0; } change120++; } 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
  • 100. } return 1; } int main() { int N; scanf("%d", &N); int a[N]; for (int i = 0; i < N; i++) { scanf("%d", &a[i]); } if (isTransactionPossible(a, N)) { printf("Transaction successful"); } else { printf("Transaction failed"); } return 0; 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
  • 101. #include <iostream> using namespace std; bool isTransactionPossible(int a[], int N) { int change30 = 0; int change60 = 0; int change120 = 0; for (int i = 0; i < N; i++) { if (a[i] == 30) { // If customer pays ₹30, no change required change30++; } else if (a[i] == 60) { // If customer pays ₹60, return ₹30 change if available if (change30 > 0) { change30--; } else 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 102. { return false; } change60++; } else if (a[i] == 120) { // If customer pays ₹120, return ₹90 change if available if (change30 > 0 && change60 > 0) { change30--; change60--; } else if (change30 >= 3) { change30 -= 3; } else { return false; } change120++; 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
  • 103. } return true; } int main() { int N; cin >> N; int a[N]; for (int i = 0; i < N; i++) { cin >> a[i]; } if (isTransactionPossible(a, N)) { cout << "Transaction successful" << endl; } else { cout << "Transaction failed" << endl; } return 0; 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
  • 104. import java.util.Scanner; public class Main { public static int isTransactionPossible(int[] a, int N) { int change30 = 0; int change60 = 0; int change120 = 0; for (int i = 0; i < N; i++) { if (a[i] == 30) { // If customer pays ₹30, no change required change30++; } else if (a[i] == 60) { // If customer pays ₹60, return ₹30 change if available if (change30 > 0) { change30--; } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 105. else { return 0; } change60++; } else if (a[i] == 120) { // If customer pays ₹120, return ₹90 change if available if (change30 > 0 && change60 > 0) { change30--; change60--; } else if (change30 >= 3) { change30 -= 3; } else { return 0; } 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
  • 106. change120++; } } return 1; } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int N = scanner.nextInt(); int[] a = new int[N]; for (int i = 0; i < N; i++) { a[i] = scanner.nextInt(); } if (isTransactionPossible(a, N) == 1) { System.out.println("Transaction successful"); } else { System.out.println("Transaction failed"); } 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
  • 108. def is_transaction_possible(a, N): change30 = 0 change60 = 0 change120 = 0 for i in range(N): if a[i] == 30: # If customer pays ₹30, no change required change30 += 1 elif a[i] == 60: # If customer pays ₹60, return ₹30 change if available if change30 > 0: change30 -= 1 else: return 0 change60 += 1 elif a[i] == 120: # If customer pays ₹120, return ₹90 change if available if change30 > 0 and change60 > 0: change30 -= 1 change60 -= 1 elif change30 >= 3: change30 -= 3 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 109. else: return 0 change120 += 1 return 1 N = int(input()) a = [] for i in range(N): a.append(int(input())) if is_transaction_possible(a, N) == 1: print("Transaction successful") else: print("Transaction failed") 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
  • 110. Set B
  • 111. question 11 Given a string in which the same character occurs in many consecutive character elements. Your task is to find the characters that have even frequency and are consecutive. Display the sum of every frequency count( For even frequency only) Example 1: Sample Input: aaabbaccccdd Sample Output: 8 Example 2 Sample Input: vdkkmmmnn Sample Output: 4
  • 112. #include <stdio.h> #include <string.h> int findSumOfEvenFrequency(char str[]) { int sum = 0; int count = 1; for (int i = 1; i < strlen(str); i++) { if (str[i] == str[i - 1]) { count++; } else { if (count % 2 == 0) { sum += count; } count = 1; } } // Check the count of the last character sequence 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 113. if (count % 2 == 0) { sum += count; } return sum; } int main() { char input[100]; scanf("%s", input); int result = findSumOfEvenFrequency(input); printf("%dn", result); return 0; } 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
  • 114. #include <iostream> using namespace std; int findSumOfEvenFrequency(string str) { int sum = 0; int count = 1; for (int i = 1; i < str.length(); i++) { if (str[i] == str[i - 1]) { count++; } else { if (count % 2 == 0) { sum += count; } count = 1; } } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 115. // Check the count of the last character sequence if (count % 2 == 0) { sum += count; } return sum; } int main() { string input; cin >> input; int result = findSumOfEvenFrequency(input); cout << result << endl; return 0; } 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
  • 116. import java.util.Scanner; public class Main { public static int findSumOfEvenFrequency(String str) { int sum = 0; int count = 1; for (int i = 1; i < str.length(); i++) { if (str.charAt(i) == str.charAt(i - 1)) { count++; } else { if (count % 2 == 0) { sum += count; } count = 1; } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 117. } // Check the count of the last character sequence if (count % 2 == 0) { sum += count; } return sum; } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); String input = scanner.next(); int result = findSumOfEvenFrequency(input); System.out.println(result); } } 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
  • 118. def find_sum_of_even_frequency(string): sum = 0 count = 1 for i in range(1, len(string)): if string[i] == string[i - 1]: count += 1 else: if count % 2 == 0: sum += count count = 1 # Check the count of the last character sequence if count % 2 == 0: sum += count return sum input_str = input() result = find_sum_of_even_frequency(input_str) print(result) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 119. question 12 Given N Rupees. A liter plastic bottle of milk costs R1 Rupees and a liter of the glass bottle of milk costs R2 Rupees. But the empty glass bottle after buying can be exchanged for R3 Rupees. Find the maximum liters of milk which can be bought with N Rupees. Example-1: Input: 10 Value of N → 11 Value of R1 i.e. price of plastic bottle → 9 Value of R2 i.e. price of glass bottle → 8 Value of R3 i.e. price of empty glass bottle → Output: 2
  • 120. #include <stdio.h> int max(int a, int b) { return (a > b) ? a : b; } void maxLitres(int budget, int plastic, int glass, int refund) { if (glass - refund < plastic) { int ans = max((budget - refund) / (glass - refund), 0); budget -= ans * (glass - refund); ans += budget / plastic; printf("%dn", ans); } else { printf("%dn", budget / plastic); } } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 121. int main() { int budget, plastic, glass, refund; scanf("%d", &budget); scanf("%d", &plastic); scanf("%d", &glass); scanf("%d", &refund); maxLitres(budget, plastic, glass, refund); return 0; } 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
  • 122. #include<bits/stdc++.h> using namespace std; void maxLitres(int budget, int plastic, int glass , int refund) { if (glass - refund < plastic) { int ans = max((budget - refund) / (glass - r efund), 0); budget -= ans * (glass - refund); ans += budget / plastic; cout << ans << endl; } else cout << (budget / plastic) << endl; } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 int main() { int budget, plastic, glass, refund; cin >> budget; cin >> plastic; cin >> glass; cin >> refund; maxLitres(budget, plastic, glass, refund); return 0; } 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
  • 123. import java.util.Scanner; public class Main { public static int max(int a, int b) { return (a > b) ? a : b; } public static void maxLitres(int budget, int plastic, int glass, int refund) { if (glass - refund < plastic) { int ans = max((budget - refund) / (glass - refund), 0); budget -= ans * (glass - refund); ans += budget / plastic; System.out.println(ans); } else { System.out.println(budget / plastic); } } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 124. public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int budget = scanner.nextInt(); int plastic = scanner.nextInt(); int glass = scanner.nextInt(); int refund = scanner.nextInt(); maxLitres(budget, plastic, glass, refund); } } 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
  • 125. def maxLitres(budget, plastic, glass, refund): if glass - refund < plastic: ans = max((budget - refund) // (glass - refund), 0) budget -= ans * (glass - refund) ans += budget // plastic print(ans) else: print(budget // plastic) budget = int(input()) plastic = int(input()) glass = int(input()) refund = int(input()) maxLitres(budget, plastic, glass, refund) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 126. question 13 I guess you all remember that number game where you used to ask your friend to choose a number, then multiply it by some number, then add by some number, and after doing multiple operations, then the answer. And you were successfully able to find that initial number that was chosen by your friend the be02ginning of the game. We are going to make something similar to this. So, you asked your friend to choose a number N, and multiply it by a given number A. Next, your friend has to choose a divisor of N, let's say 'Z', and add it to the above product. Now the final result becomes a number say X. If we frame it as an equation, it can be represented as X = AN So, now you know the value of A and X. Your task is to find the number N, which was chosen by your friend. The values of N can be multiple, You have to print all the possible values separated by SPACE. If there is no valid value of N, then reply None. This means your friend didn't give you the correct reply.
  • 127. question 13 Let us try to understand it with an example. Consider you have given a value of A = 3 and finally received the output value x = 35 Putting the values in equation X=A*N+Z,we get: 35-3*N+Z, and Z is one of the divisors of N. With a smaller number like 1 or 2, this is not possible. So, we will start with some bigger numbers such as N = 8 Then Z can be 2 or 4 or 8, but in that case, the result will be even, but the answer is odd. So, we move to the next value 9. With N = 9 ,Z can be 3putting this in the equation: 35 =3*N+Z, and Z is one of the divisors of N. 3*9+3 = 30 which doesn't matches with 35. So, we move to the next integer. With N = 10 , Z can be 2 or 5, putting this in the equation: 35=3*N+Z With Z = 2
  • 128. question 13 3 + 10 + 2 = 32 still not equal to 35. With z = 5 3*10 + 5 = 35 , still now equal to 35. So, one of the values of N is 10. Likewise, if we proceed, we cannot find any other value which could satisfy the above conditions. So, the output is only 10. Example 1: Input: 50 5 -> Input integer, A, X Output: None ->Output
  • 129. question 13 Input format: First Input Accept value of Integer A. Second Input-Accept value of Integer, K (Next Line). Output format :
  • 130. question 13 The output are either None or integers values (separated by space) value as per above logic. (Check the output in Example 1, Example 2). Additional messages in output will cause the failure of test cases. Constraints: 1 <= xx = 1000000 1 <= A <= X Only positive integer values
  • 131. #include <stdio.h> int isDivisor(int number, int divisor) { return number % divisor == 0; } int main() { // Get user inputs int X, A; scanf("%d", &X); scanf("%d", &A); for (int N = 1; N <= X; N++) { for (int Z = 1; Z <= N; Z++) { if (X == A * N + Z && isDivisor(N, Z)) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 { printf("%d", N); // Exit the loops as the equation is satisfi ed return 0; } } } printf("None"); // If no values of N and Z sat isfy the equation return 0; } 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
  • 132. #include <iostream> using namespace std; bool isDivisor(int number, int divisor) { return number % divisor == 0; } int main() { // Get user inputs int X, A; cin >> X; cin >> A; for (int N = 1; N <= X; N++) { for (int Z = 1; Z <= N; Z++) { 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 if (X == A * N + Z && isDivisor(N, Z)) { cout << N; // Exit the loops as the equation is satisfi ed return 0; } } } cout << "None"; // If no values of N and Z s atisfy the equation return 0; } 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
  • 133. import java.util.Scanner; public class Main { public static boolean isDivisor(int number, i nt divisor) { return number % divisor == 0; } public static void main(String[] args) { // Get user inputs Scanner scanner = new Scanner(System.i n); int X = scanner.nextInt(); int A = scanner.nextInt(); scanner.close(); 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 for (int N = 1; N <= X; N++) { for (int Z = 1; Z <= N; Z++) { if (X == A * N + Z && isDivisor(N, Z)) { System.out.print(N); // Exit the loops as the equation is satisfied return; } } } System.out.print("None"); // If no values of N and Z satisfy the equation } } 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
  • 134. def isDivisor(number, divisor): return number % divisor == 0 X, A = map(int, input().split()) for N in range(1, X+1): for Z in range(1, N+1): if X == A * N + Z and isDivisor(N, Z): print(N) exit() print("None") 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 135. QUESTION 14 In the city of Tasgi, the array of competition is going on.You have been invited to the game is as follows: You are given an array A of size N. The array is called good if and only if an integer 1 k N. Such that a1 < ≤ ≤ a2<….. <ak and ak >ak+1 > ak+2 >> aN. You can do the following operation. i.e., select any index (i) such that ai > 0 and decrease the ai by 1. (ie., a¡= a¡-1) The prize money for winners in that competition is 1 million dollars. So, You want to win. Print Yes if it is possible to make an array good by using operation as many times you want else No Example - 1: Input: 6 ->N(number of elements of an array) 100 11 15 9 7 8 ->N elements of an array
  • 136. QUESTION 14 Output: Yes Explanation: We can transform the array into [3.11.15,9.74] (decrease the first element 97 times and decrease the last element 4 times). It is good because 3<11<15 and 15>9>7>4 Example 2: Input: 3 12 10 8 Output: Yes
  • 137. #include <stdio.h> int isGoodArray(int* nums, int n) { int maxNum = nums[0]; int minNum = nums[n - 1]; for (int i = 1; i < n; i++) { if (nums[i] >= maxNum || nums[i] <= minNum) { return 0; } maxNum = nums[i]; } return 1; } int main() { int N; 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 scanf("%d", &N); int nums[N]; for (int i = 0; i < N; i++) { scanf("%d", &nums[i]); } int first = nums[0]; int last = nums[N - 1]; if (first > last) { printf("Yesn"); } else { if (isGoodArray(nums, N)) { printf("Yesn"); } else { printf("Non"); } 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
  • 138. #include <iostream> #include <vector> using namespace std; bool isGoodArray(vector<int>& nums) { int n = nums.size(); int maxNum = nums[0]; int minNum = nums[n - 1]; for (int i = 1; i < n; i++) { if (nums[i] >= maxNum || nums[i] <= minNum) { return false; } maxNum = nums[i]; } return true; } int main() { 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 cin >> N; vector<int> nums(N); for (int i = 0; i < N; i++) { cin >> nums[i]; } int first = nums[0]; int last = nums[N - 1]; if (first > last) { cout << "Yes" << endl; } else { cout << "No" << endl; } return 0; } 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
  • 139. import java.util.Scanner; public class Main { public static boolean isGoodArray(int[] nums, int n) { int maxNum = nums[0]; int minNum = nums[n - 1]; for (int i = 1; i < n; i++) { if (nums[i] >= maxNum || nums[i] <= minNum) { return false; } maxNum = nums[i]; } return true; } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int N = scanner.nextInt(); int[] nums = new int[N]; for (int i = 0; i < N; i++) { nums[i] = scanner.nextInt(); } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 140. int first = nums[0]; int last = nums[N - 1]; if (first > last) { System.out.println("Yes"); } else { if (isGoodArray(nums, N)) { System.out.println("Yes"); } else { System.out.println("No"); } } } } 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
  • 141. def is_good_array(nums): max_num = nums[0] min_num = nums[-1] for num in nums[1:]: if num >= max_num or num <= min_num: return False max_num = num return True N = int(input()) nums = list(map(int, input().split())) first = nums[0] last = nums[-1] if first > last: print("Yes") else: if is_good_array(nums): print("Yes") else: print("No") 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 142. QUESTION 15 The lanes of the city market are very narrow and always bustling with crowds. There is no space for parking 2 or 4 wheelers. To solve this problem the officials of the area have converted a nearby open space into parking area. Vehicles can be parked in 2 separate lanes. There is space for N number of vehicles in each lane. Every parked vehicle has a specific amount of fuel in the tank. The amount of fuel in which each vehicle is represented by following series : Lane 1 : b, b+a, b+2a…..b+(n-1)a Lane 2 : d,d+c, d+2c,…..d+(n-1)c The above two series will have the same value at some point in series. The task here is to find the value which will be the same in both series. Also, display a message as “No same amount of fuel found” if there is no value that is the same in both the series. Note: Values a, b, c, d in the series non zero values
  • 143. QUESTION 15 Example 1 : Input : 50 ->Value of N 20 ->Value of a 2 ->Value of b 9 -> Value of c 19->Value of d Output : 82 ->same value in both the series Explanation: from the table we can deduce the output is 82
  • 144. QUESTION 15 LANE 1 SERIES LANE 2 SERIES b 2 d 28 b+a 22 d+a 37 b+2a 42 d+2a 46 b+3a 62 d+3a 55 b+4a 82 d+4a 64 b+5a 102 d+5a 73 b+6a 122 d+6a 82 b+7a 142 d+7a 91 b+(n-1)a 982 d+(n-1)d 460
  • 145. QUESTION 15 Example 2 : Input : 9 >Value of N 2 ->Value of a 2 ->Value of b 10->Value of c 15 -> Value of d Output : No same amount of fuel found Explanation:
  • 146. QUESTION 15 LANE 1 SERIES LANE 2 SERIES b 2 d+c 25 b+a 4 d+2c 35 b+2a 6 d+3c 45 b+3a 8 d+4c 55 b+4a 10 d+5c 65 b+5a 12 d+6c 75 b+6a 14 d+7c 85 b+7a 16 d+8c 95 b+8a 18
  • 147. #include <stdio.h> int findCommonFuel(int N, int a, int b, int c, int d) { for (int i = 0; i < N; i++) { int fuelInLane1 = b + (a * i); for (int j = 0; j < N; j++) { int fuelInLane2 = d + (c * j); if (fuelInLane1 == fuelInLane2) { return fuelInLane1; } } } return -1; // No same amount of fuel found } int main() { int N, a, b, c, d; scanf("%d", &N); scanf("%d", &a); 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 148. scanf("%d", &c); scanf("%d", &d); int commonFuel = findCommonFuel(N, a, b, c, d); if (commonFuel == -1) { printf("No same amount of fuel foundn"); } else { printf("%d",commonFuel); } return 0; } 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
  • 149. #include <iostream> using namespace std; int findCommonFuel(int N, int a, int b, int c, int d) { for (int i = 0; i < N; i++) { int fuelInLane1 = b + (a * i); for (int j = 0; j < N; j++) { int fuelInLane2 = d + (c * j); if (fuelInLane1 == fuelInLane2) { return fuelInLane1; } } } return -1; // No same amount of fuel found } int main() { int N, a, b, c, d; cin >> N; 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 150. cin >> a; cin >> b; cin >> c; cin >> d; int commonFuel = findCommonFuel(N, a, b, c, d); if (commonFuel == -1) { cout << "No same amount of fuel found" << endl; } else { cout << commonFuel; } return 0; } 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
  • 151. import java.util.Scanner; public class Main { public static int findCommonFuel(int N, int a, int b, int c, int d) { for (int i = 0; i < N; i++) { int fuelInLane1 = b + (a * i); for (int j = 0; j < N; j++) { int fuelInLane2 = d + (c * j); if (fuelInLane1 == fuelInLane2) { return fuelInLane1; } } } return -1; // No same amount of fuel found } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int N = scanner.nextInt(); 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 152. int b = scanner.nextInt(); int c = scanner.nextInt(); int d = scanner.nextInt(); int commonFuel = findCommonFuel(N, a, b, c, d); if (commonFuel == -1) { System.out.println("No same amount of fuel found"); } else { System.out.println(commonFuel); } } } 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
  • 153. def find_common_fuel(N, a, b, c, d): for i in range(N): fuel_in_lane1 = b + (a * i) for j in range(N): fuel_in_lane2 = d + (c * j) if fuel_in_lane1 == fuel_in_lane2: return fuel_in_lane1 return -1 # No same amount of fuel found N = int(input()) a = int(input()) b = int(input()) c = int(input()) d = int(input()) common_fuel = find_common_fuel(N, a, b, c, d) if common_fuel == -1: print("No same amount of fuel found") else: print(common_fuel) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 154. question 16 jack is a sports teacher at St. Patrick’s School. He makes games not only to make the student fit, but also smart .So, he lined up all the N number of students in his class. At each position he has fixed a board with the integer number printed on it. Each of the numbers are unique and are in exactly the range of N. Let us say there are 10 students, then the boards will be printed with numbers from 1 to 10 in a random order given by the sequence A[]. As a rule, all students wear a jersey with their numbers printed on it. So, if there are N students, each will have a number, just like a football team. Now, in the beginning, all the students will stand as per the increasing order of their jersey numbers, from left to right. The only difference will be their respective board number which is placed at their respective location. The board location is fixed and cannot be changed. We can consider the arrangement as below. Suppose there are 5 students, and the board is placed in the order of [23154]
  • 155. question 16 Board-2, 3, 1, 5,4 Student's Jersey-1,2,3,4,5 Now the game begins. •After every beat of the drum, each student will have to move to that location (index), where his board is pointing to. In the above case student with jersey #1 is standing with board #2, so now he will have to move to location #2. Similarly, all the other students will do. So after first beat of the drum, the alignment will be: Board 2, 3, 1, 5, 4 Student's Jersey --3. 1, 2, 5.4 Jersey #1 has moved to Index2. Jersey #2 has moved to Index 3. Jersey #3 has moved to index 1. Jersey #4 has moved to index 5. Jersey #5 has moved to Index 4.
  • 156. question 16 Now again with the next beat of the drum, same task as shown below: Board - 2, 3, 1, 5, 4 Student's Jersey-2,3,1,4,5 Jersey #3 has moved to index 2. Jersey #1 has moved to index 3. Jersey #2 has moved to index 1. Jersey #5 has moved to index 5. Jersey #4 has moved to index 4. This keeps going on and on, until all the students are back the way they were at the beginning. So ,after 6 beats of the drum, all the students will be aligned the same way as before. Given N and the order of board of the respective positions, find the number of beats required to bring back the students to their original position. So ,for the above case the answer is 6.
  • 157. question 16 Example 1: Input: 3 ->Input integer, N 1 2 3->Input integer 9[] board alignment Output: 1->Output Explanation: All the students will be standing as below,with the board positions: Board-1,2,3 Student jersey- 1,2,3 After first beat of drum: Jersey #1 has moved to index 1.
  • 158. #include <stdio.h> #include <stdlib.h> int main() { int n; scanf("%d", &n); int* B = (int*)malloc(n * sizeof(int)); for (int i = 0; i < n; i++) { scanf("%d", &B[i]); } int* arr = (int*)malloc(n * sizeof(int)); for (int i = 0; i < n; i++) { arr[i] = i + 1; } int ans = 0; int* original_arr = (int*)malloc(n * sizeof(int)); for (int i = 0; i < n; i++) { original_arr[i] = arr[i]; } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 159. while (1) { ans++; int* ar = (int*)malloc(n * sizeof(int)); for (int i = 0; i < n; i++) { ar[i] = arr[B[i] - 1]; } int isEqual = 1; for (int i = 0; i < n; i++) { if (ar[i] != original_arr[i]) { isEqual = 0; break; } } if (isEqual) { free(ar); break; } 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
  • 160. free(arr); arr = ar; } printf("%dn", ans); free(B); free(arr); free(original_arr); return 0; } 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
  • 161. #include <iostream> #include <vector> #include <algorithm> using namespace std; int main() { int n; cin >> n; vector<int> B(n); for (int i = 0; i < n; i++) { cin >> B[i]; } vector<int> arr(n); for (int i = 0; i < n; i++) { arr[i] = i + 1; } int ans = 0; vector<int> original_arr = arr; // Store the original arrangement while (true) { 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 162. ans++; vector<int> ar(n); for (int i = 0; i < n; i++) { ar[i] = arr[B[i] - 1]; } if (ar == original_arr) { break; } arr = ar; } cout << ans << endl; return 0; } 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
  • 163. import java.util.ArrayList; import java.util.List; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); List<Integer> B = new ArrayList<>(); for (int i = 0; i < n; i++) { B.add(scanner.nextInt()); } List<Integer> arr = new ArrayList<>(); for (int i = 0; i < n; i++) { arr.add(i + 1); } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 164. int ans = 0; List<Integer> originalArr = new ArrayList<>(arr); // Store the original arrangement while (true) { ans++; List<Integer> ar = new ArrayList<>(); for (int i = 0; i < n; i++) { ar.add(arr.get(B.get(i) - 1)); } if (ar.equals(originalArr)) { break; } arr = new ArrayList<>(ar); } System.out.println(ans); } 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
  • 165. n = int(input()) B = list(map(int, input().split())) arr = list(range(1, n+1)) ans = 0 while True: ans += 1 ar = [None] * n for i in range(n): ar[i] = arr[B[i] - 1] if ar == sorted(ar): break arr = ar print(ans) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 166. question 17 Joe is playing a game where there are N group of balloons. He is given a gun which can shoot one round per minute. For each round it can hit 1 balloon in K groups each.If the group has zero balloons left, then we say that particular group is destroyed completely, and it would not be counted. The gun is deactivated if the number of groups falls below K. Find the maximum number of minutes the gun will be activated based on the above factors. Let us try to understand it with an example. Let say there are N groups N=5 and K = 3 means if there are less than 3 groups the gun will be de-activated. In order to stay in the game for longer time, he will play optimally. Also note that the K group may be formed arbitrary selecting K members from N groups. Each of the 5 groups has below number of balloons : B = [4,3,5,6,7]
  • 167. question 17 So, in the beginning this is the configuration of all groups with their respective balloons: 4 3 5 6 7 Below the timeline: Minute 1: the gun takes 1 shot and it will hit 1 balloon in k=3 groups, now the configuration of each group will be: 4 3 3 4 5 6 Minute 2: the gun takes 1 shot and it will hit 1 balloon in K =3 group, now the configuration of each group will be: 4 3 3 4 5 Minute 3: the gun takes 1 shot a -3 group, now the configuration of each group will be 4 3 2 3 4 Minute 4: the gun takes 1 shot and it will hit 1 balloon in K =3 group, now the configuration of each group will be: 3 3 2 2 3 Minute 5:the gun takes 1 shot and it will hit 1 balloon in K =3 group, the configuration of each group will be: 3 3 1 1 2. Minute 6: the gun takes 1 shot and it will hit 1 balloon in K =3 group, now the configuration of each group will be: 22 1 1 1
  • 168. question 17 Minute 7: the gun takes 1 shot and it will hit 1 balloon in K=3 group, now the configuration of each group will be 1 1 0 1 1 Minute 8: the gun takes 1 shot and it will hit 1 balloon in K =3 group, now the configuration of each group will be:0 0 0 0 1 Now there are less than K-3 groups, other have lost all their balloons. And the maximum time Joe was busy was 8 minutes. So, the final answer is 8 The input format for testing: First Input-Accept value of Integer, N Second Input -Accept value of Integer, K (Next Line) Next 'N' Lines-Elements of sequence B The Output format for testing:
  • 169. question 17 The output is an integer value as per above logic (Check the output in Example 1, Example 2) Additional messages in output will cause the failure of test cases. Constraints: 1<= N<=1000 1 <= K<=N 1<=B[]<=100000 Only integer values Example 1: Input: 2-> Input integer N 2-> Input integer 2 -> Input integer, B[] 3 ->Input integer, B
  • 170. question 17 Output: 2 ->output Explanation: In the above example, there are K=2 groups whicha gun can fire at a time. Initial configuration of each groups : 2 3 Minute 1: the gun takes 1 shot and it will hit 1 balloon in k -2 groups, now the configuration of each group will be: 1 2 Minute 2: the gun takes 1 shot and it will hit 1 balloon in K -2 group, now the configuration of each group will be: 0 1 Now there are less than K-2 groups, other have lost all their balloons. And the maximum time Joe was busy was 2 minutes. Example 2:
  • 171. question 17 Input: 5-> Input integer N 3-> Input integer K 4 -> Input integer, B[] 3 ->Input integer, B[] 5 ->Input integer, B[] 6 ->Input integer, B[] 7 ->Input integer, B[] Output: 8 ->output
  • 172. #include <stdio.h> #include <stdlib.h> int compare(const void *a, const void *b) { return (*(int*)b - *(int*)a); } int getMaxActiveTime(int N, int K, int* balloons) { qsort(balloons, N, sizeof(int), compare); int minutes = 0; int remainingGroups = N; while (remainingGroups >= K) { for (int i = 0; i < K; i++) { balloons[i] -= 1; if (balloons[i] == 0) { remainingGroups--; } } minutes++; 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 173. qsort(balloons, N, sizeof(int), compare); } return minutes; } int main() { int N, K; scanf("%d %d", &N, &K); int* balloons = (int*)malloc(N * sizeof(int)); for (int i = 0; i < N; i++) { scanf("%d", &balloons[i]); } int result = getMaxActiveTime(N, K, balloons); printf("%dn", result); free(balloons); return 0; } 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
  • 174. #include <iostream> #include <vector> #include <algorithm> using namespace std; int getMaxActiveTime(int N, int K, vector<int>& balloons) { sort(balloons.rbegin(), balloons.rend()); // Sort balloons in descending order int minutes = 0; int remainingGroups = N; while (remainingGroups >= K) { for (int i = 0; i < K; i++) { balloons[i] -= 1; // Shoot one balloon in K groups if (balloons[i] == 0) { remainingGroups--; // Reduce the count of remaining groups } } minutes++; // Increment the minutes sort(balloons.rbegin(), balloons.rend()); // Sort balloons again } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 175. return minutes; } int main() { int N, K; cin >> N >> K; vector<int> balloons(N); for (int i = 0; i < N; i++) { cin >> balloons[i]; } int result = getMaxActiveTime(N, K, balloons); cout << result << endl; return 0; } 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
  • 176. import java.util.*; public class Main { public static int getMaxActiveTime(int N, int K, List<Integer> balloons) { Collections.sort(balloons, Collections.reverseOrder()); // Sort balloons in descending order int minutes = 0; int remainingGroups = N; while (remainingGroups >= K) { for (int i = 0; i < K; i++) { int balloon = balloons.get(i) - 1; // Shoot one balloon in K groups balloons.set(i, balloon); if (balloon == 0) { remainingGroups--; // Reduce the count of remaining groups } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 177. minutes++; // Increment the minutes Collections.sort(balloons, Collections.reverseOrder()); // Sort balloons again } return minutes; } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int N = scanner.nextInt(); int K = scanner.nextInt(); List<Integer> balloons = new ArrayList<>(); for (int i = 0; i < N; i++) { balloons.add(scanner.nextInt()); } int result = getMaxActiveTime(N, K, balloons); System.out.println(result); } } 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
  • 178. def get_max_active_time(N, K, balloons): balloons.sort(reverse=True) # Sort balloons in descending order minutes = 0 remaining_groups = N while remaining_groups >= K: for i in range(K): balloon = balloons[i] - 1 # Shoot one balloon in K groups balloons[i] = balloon if balloon == 0: remaining_groups -= 1 # Reduce the count of remaining groups minutes += 1 # Increment the minutes balloons.sort(reverse=True) # Sort balloons again return minutes N = int(input()) K = int(input()) balloons = [] for _ in range(N): balloons.append(int(input())) result = get_max_active_time(N, K, balloons) print(result) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 179. question 18 Mike came up with a new way of sorting a string. What he does is he takes all the unique alphabets from the string and sorts it in that order. Let say there is a string "apple", now it contains a p l e as distinct alphabets. He sorts the string apple based on his own keys let say eapl. So, first all "e" will be picked from the string "apple", and then all "a", and so on till "T". Hence the final sorted word becomes "eappl". The Input format for testing The candidate has to write the code to accept 2 input(s) •First Input - Accept value for input string. •First Input - Accept value for input key. The Output format for testing
  • 180. question 18 •The output should be a sorted string based on the input key given by the user as mentioned in the above criteria. (Check the output in Example 1, Example 2) •Additional messages in output will cause the failure of test cases. Constraints: 0<length(input String)<=50 Input key should contain all the alphabets of inputstrings No duplicates in input keys. Example 1: Input: apple->Input string eapl -> Input string, sorting key value
  • 181. question 18 Output: eappl->output string with sorted value based on the user keys. Explanation: The input by the user is "apple” and the key is "eapl". So, as per the key, all "e" has to be sorted first. Then all the a's and the all the p's, and finally all the 1’s .Note that here we have 2 p's so they will be sorted together in the output. Putting everything together the final string comes as “eappl” Example 2: Input: welcome ->input string lowmec -> input string,sorting key value
  • 182. question 18 Output: lowmeec ->output string with sorted value based on the user keys. Explanation: The input by the user is “welcome” and the key is “lowmec". So, as per the key, all 1’s has to be sorted first,then all the 0's and then all the w's and then all the m's ,the all the e's, and finally all the c’s .Note that here we have 2 p's so they will be sorted together in the output. Putting everything together the final string comes as “lowmeec”
  • 183. #include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> char* sortString(const char* input, const char* key) { size_t len = strlen(input); char* sortedString = malloc((len + 1) * sizeof(char)); strcpy(sortedString, input); for (int i = 0; i < len; i++) { for (int j = i + 1; j < len; j++) { char a = tolower(sortedString[i]); char b = tolower(sortedString[j]); const char* indexA = strchr(key, a); const char* indexB = strchr(key, b); if (indexA != NULL && indexB != NULL && indexA > indexB) { char temp = sortedString[i]; 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 184. sortedString[i] = sortedString[j]; sortedString[j] = temp; } } } return sortedString; } int main() { char input[100]; char key[100]; scanf("%s %s", input, key); char* sortedString = sortString(input, key); printf("%sn", sortedString); free(sortedString); return 0; } 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
  • 185. #include <iostream> #include <string> using namespace std; string sortString(const string& input, const string& key) { string sortedString = input; // Sort the string using the key as the custom sorting criterion for (int i = 0; i < sortedString.length(); i++) { for (int j = i + 1; j < sortedString.length(); j++) { char a = tolower(sortedString[i]); char b = tolower(sortedString[j]); size_t indexA = key.find(a); size_t indexB = key.find(b); if (indexA > indexB) { swap(sortedString[i], sortedString[j]); } } } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 186. return sortedString; } int main() { string input, key; cin >> input >> key; string sortedString = sortString(input, key); cout << sortedString << endl; return 0; } 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
  • 187. import java.util.Scanner; public class Main { public static String sortString(String input, String key) { char[] sortedString = input.toCharArray(); // Sort the string using the key as the custom sorting criterion for (int i = 0; i < sortedString.length; i++) { for (int j = i + 1; j < sortedString.length; j++) { char a = Character.toLowerCase(sortedString[i]); char b = Character.toLowerCase(sortedString[j]); int indexA = key.indexOf(a); int indexB = key.indexOf(b); if (indexA > indexB) { char temp = sortedString[i]; sortedString[i] = sortedString[j]; sortedString[j] = temp; } } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 188. return new String(sortedString); } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); String input = scanner.next(); String key = scanner.next(); String sortedString = sortString(input, key); System.out.println(sortedString); } 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
  • 189. def sort_string(input_str, key): sorted_str = list(input_str) # Sort the string using the key as the custom sorting criterion for i in range(len(sorted_str)): for j in range(i + 1, len(sorted_str)): a = sorted_str[i].lower() b = sorted_str[j].lower() index_a = key.find(a) index_b = key.find(b) if index_a > index_b: sorted_str[i], sorted_str[j] = sorted_str[j], sorted_str[i] return ''.join(sorted_str) input_str = input() key = input() sorted_string = sort_string(input_str, key) print(sorted_string) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 190. question 19 Mikes likes to play with numbers. His friends are also good with numbers and often plays mathematical games. They made a small game where they will spell the last digit of a factorial of a number other than 0. Let say the given number is 5, so 5! (5 factorial) will be 5 *4* 3* 2* 1= 120. Here 0 is the last digit. But, we don't want 0, we want a number other than 0. Then the last digit is 2. This is what we have to output Example 1: Input 5 ->Input number Output 2->last non-zero digit
  • 191. question 19 Explanation: Input number is 5, so 5!=120. The last nonzero digit is 2. And this is the output. Example 2 Input: 9-> Input number. Output: 8-> last non-zero digit Explanation: Input number is 9, so 9!=362880. The last nonzero digit is 8. And this is the output.
  • 192. question 19 Constraints: •1<=input number<105 •Only integers The candidate has to write the code to accept 2 input(s) •First input-Accept the value of integer The output format for testing •The output is the last nonzero digit, of a factorial of the input number (Checks the output in Example 1, Example 2). Additional messages in output will cause the failure of test cases. Instructions •System doesn’t allow any kind of hard coded input. •Written program cade by the candidate will be verified against inputs which are supplied from the system.
  • 193. #include <stdio.h> //Recursive function to calculate the factorial int fact(int n) { if(n <= 1) //Base Condition return 1; return n*fact(n-1); } int main() { int n; scanf("%d",&n); int factorial = fact(n); while(factorial%10==0) { factorial /= 10; } printf("%d",factorial%10); } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 194. #include <iostream> using namespace std; int fact(int n) { if (n <= 1) // Base Condition return 1; return n * fact(n - 1); } int main() { int n; cin>>n; int factorial = fact(n); while (factorial % 10 == 0) { factorial /= 10; } cout << factorial % 10; return 0; } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 195. import java.util.Scanner; public class Main { // Recursive function to calculate the factorial public static int fact(int n) { if (n <= 1) // Base Condition return 1; return n * fact(n - 1); } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); int factorial = fact(n); while (factorial % 10 == 0) { factorial /= 10; } System.out.println(factorial % 10); } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 196. def fact(n): if n <= 1: # Base Condition return 1 return n * fact(n - 1) n = int(input()) factorial = fact(n) while factorial % 10 == 0: factorial //= 10 print(factorial % 10) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 197. sortedString[i] = sortedString[j]; sortedString[j] = temp; } } } return sortedString; } int main() { char input[100]; char key[100]; scanf("%s %s", input, key); char* sortedString = sortString(input, key); printf("%sn", sortedString); free(sortedString); return 0; } 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
  • 198. question 20 Raju is a traveller and travels to many different places around the world. This time he went to an island that had its own currency. They only have 2 coin system currency. They call Aana, and these are coins. So in this islands they have either 1-Aana or 2- Aana. Just like all the other coins these Aana also have their heads and tails. Also, while paying anything to the shopkeeper here, you have tofollow their ritual and ritual says, •There is a wooden board at each shop where a customer places the coins in a squences while paying to shopkeeper. •You should always place the coin on a wooden board just like a squences. •The first coin in the sequence should always be facing the side of head. Now your task is to find out in how many ways he can pay the shopkeeper here, given some Xamount. The answer can be huge, so you can give an output with module 109+7. Let us try understand it with an example.
  • 199. question 20 Consider that Raj has to pay 2 cents to the shopkeeper, so X=10. He can pay it as either 2coins of 1-Aana or 1coin of 2-Aana. 2coins of 1-Aana can be given as below: •First coin placed as H, other coin can be as H(heads). •First coin placed as H, other coin be as T(tails). 1coin of 2-Aana can be given as below: •Firstcoin placed as H. •No other combination for 2-Aana coin can exists. Hence total of 3 different combinations can exist to pay a sum of 3-Aana value. Hence the answer is 3. Given X, find out different number of ways in which Raj can pay to the shopkeeper. Example 1: Input: 1->Input integer, X
  • 200. question 20 Output: 1->output Explanation: If the amount which we have to pay is just 1, then we can pay it with just one coin, which 1-Aana and the combination for it will be just 1-H Hence the answer is 1. Example 2: Input: 2->Input integer, Output: 3->Output
  • 201. question 20 Explanation: In this scenario where, he need to pay 2-Aana to the shopkeeper, he can pay it as either 2 coins of 1-Aana or one coin of 2-Aana 2 coin of 1-Aana can be given as below: •First coin placed as H, other coins can be as H(heads) •First coin placed as H, other coins can be as T(tails) 1 coin of 2-Aana can be given as below: •First coin placed as H.
  • 202. #include <stdio.h> #include <stdlib.h> #define MOD 1000000007 int countPaymentWays(int X) { if (X == 1) return 1; if (X == 2) return 3; int* dp = (int*)malloc((X + 1) * sizeof(int)); dp[0] = 1; dp[1] = 1; dp[2] = 3; for (int i = 3; i <= X; i++) { dp[i] = (dp[i - 1] + dp[i - 2]) % MOD; } int ways = dp[X]; free(dp); return ways; } int main() 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 203. { int X; scanf("%d", &X); int ways = countPaymentWays(X); printf("%dn", ways); return 0; } 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
  • 204. #include <iostream> #include <vector> using namespace std; const int MOD = 1e9 + 7; int countPaymentWays(int X) { if (X == 1) return 1; if (X == 2) return 3; vector<int> dp(X + 1, 0); dp[0] = 1; dp[1] = 1; dp[2] = 3; for (int i = 3; i <= X; i++) { dp[i] = (dp[i - 1] + dp[i - 2]) % MOD; } return dp[X]; } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 205. int main() { int X; cin >> X; int ways = countPaymentWays(X); cout <<ways; return 0; } 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
  • 206. import java.util.Scanner; public class Main { private static final int MOD = 1000000007; public static int countPaymentWays(int X) { if (X == 1) return 1; if (X == 2) return 3; int[] dp = new int[X + 1]; dp[0] = 1; dp[1] = 1; dp[2] = 3; for (int i = 3; i <= X; i++) { dp[i] = (dp[i - 1] + dp[i - 2]) % MOD; } return dp[X]; } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 207. public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int X = scanner.nextInt(); int ways = countPaymentWays(X); System.out.println(ways); } } 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
  • 208. MOD = 1000000007 def countPaymentWays(X): if X == 1: return 1 if X == 2: return 3 dp = [0] * (X + 1) dp[0] = 1 dp[1] = 1 dp[2] = 3 for i in range(3, X + 1): dp[i] = (dp[i - 1] + dp[i - 2]) % MOD return dp[X] X = int(input()) ways = countPaymentWays(X) print(ways) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 209. Set C
  • 210. question 21 A game company has designed an online lottery game. Bingo, in this game, N number cards are displayed. Each card has a value on it. The value can be negative or positive. The player must choose two cards. To win one game, the product of the values of the two cards must be maximum value possible for any pair of cards in the display. The winning amoint will be the sum of the two cards chosen by the player. Write an algorithm to find the winning amount as the sum of the value of the cards whose product value is maximum. Input The second line consists of N space-separated integers - val1, val2....., valN representing the values on the cards. Output Print an integer representing the sum of the values of the two cards whose product value is maximum.
  • 211. question 21 Constraints 0 < numCards < 106 -106 < vali < 106 0 < i < numCards Example Input: 7 9 -3 8 -6 -7 8 10 Output: 19 Explanation: The maximum product of the values of is 90, i.e. 9*10. So the sum of the values of the selected cards is 19.
  • 212. #include <stdio.h> int main() { int numCustomers; scanf("%d", &numCustomers); int balance[numCustomers]; for (int i = 0; i < numCustomers; i++) { scanf("%d", &balance[i]); } int product = 0; // smallest product int sum = 0; // sum of two balance values whose product is the smallest for (int i = 0; i < numCustomers - 1; i++) { for (int j = i + 1; j < numCustomers; j++) { if (balance[i] * balance[j] > product) { product = balance[i] * balance[j]; sum = balance[i] + balance[j]; } } }// display output printf("%dn", sum); return 0; } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 213. #include <iostream> #include <vector> int main() { int numCustomers; std::cin >> numCustomers; std::vector<int> balance(numCustomers); for (int i = 0; i < numCustomers; i++) { std::cin >> balance[i]; } int product = 0; // smallest product int sum = 0; // sum of two balance values whose product is the smallest for (int i = 0; i < numCustomers - 1; i++) { for (int j = i + 1; j < numCustomers; j++) { if (balance[i] * balance[j] > product) { product = balance[i] * balance[j]; sum = balance[i] + balance[j]; } } } // display output std::cout << sum << std::endl; return 0; } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 214. import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scan = new Scanner(System.in); int numCustomers = scan.nextInt(); int[] balance = new int[numCustomers]; for(int i=0; i<numCustomers; i++) { balance[i] = scan.nextInt(); } int product = 0;//smallest product int sum=0; //sum of 2 balance values whose product is the smallest for(int i=0; i<numCustomers-1; i++) { for(int j=i+1; j<numCustomers; j++) { if(balance[i]*balance[j] > product) { product = balance[i] * balance[j]; sum = balance[i] + balance[j]; } } } //display output System.out.println(sum); } } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 215. numCustomers = int(input()) balance = [] for _ in range(numCustomers): balance.append(int(input())) product = 0 # smallest product sum_values = 0 # sum of two balance values whose product is the smallest for i in range(numCustomers - 1): for j in range(i + 1, numCustomers): if balance[i] * balance[j] > product: product = balance[i] * balance[j] sum_values = balance[i] + balance[j] # display output print(sum_values) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 216. question 22 A new medicine named "Medio-cine" is out in the market which helps in treating auto-immune diseases in humans. These are very common in 0-10 year old kids or greater than or equal to 81 year old senior citizens. Both these age groups are considered at a very high risk. The government wants to distribute the medicine as soon as possible among all age groups. There is only one(1) political center from where this medicine is distributed. In a single day we cannot provide to both high risk and non high risk age groups.Each person requires only one capsule and there can be L capsules distributed in a day. The high risk humans are supposed to be considered first.There are 'N' humans and 'L' capsules per day. Find the minimum number of days required to medicate all the N humans. Input format
  • 217. question 22 Input format First Line: Contains a Positive Integer denoting N and L denoting number of medicines. Next line Contains N elements of the array A space separated denoting age. Constraints: 1<=N<10000 1<=L=1000 1<=A[i]=1000 Example 1: Input: 5 2 -> N, L 11 81 27 72 79 -> array A (age of N humans respectively)
  • 218. question 22 Output: 3 Days Explanation: At max 2 can be medicated on a single day One of the optimal solution is 81 on day 11,27 and 72 on day 2. Remaining on day 3 Example 2: Input: 11 1 10 10 10 10 14 15 57 38 49 28 32 Output: 11 Explanation: At max 1 can be medicated on a single day
  • 219. #include <stdio.h> #include <stdlib.h> int compare(const void *a, const void *b) { return (*(int*)a - *(int*)b); } int minimumDays(int N, int L, int *ages) { qsort(ages, N, sizeof(int), compare); // Sort the ages in ascending order int highRiskCount = 0; int nonHighRiskCount = 0; // Count the number of high-risk and non-high-risk individuals for (int i = 0; i < N; i++) { if (ages[i] <= 10 || ages[i] >= 81) { highRiskCount++; } else { nonHighRiskCount++; } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 220. } int days = 0; while (highRiskCount > 0 || nonHighRiskCount > 0) { int capsules = L; // Number of capsules available for the day // Distribute capsules to high-risk individuals first while (capsules > 0 && highRiskCount > 0) { capsules--; highRiskCount--; } // Distribute capsules to non-high-risk individuals while (capsules > 0 && nonHighRiskCount > 0) { capsules--; nonHighRiskCount--; } days++; // Increment the number of days } return days; } 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
  • 221. int main() { int N, L; scanf("%d %d", &N, &L); int *ages = (int*)malloc(N * sizeof(int)); for (int i = 0; i < N; i++) { scanf("%d", &ages[i]); } int result = minimumDays(N, L, ages); printf("%d Daysn", result); free(ages); return 0; } 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
  • 222. #include <iostream> #include <vector> #include <algorithm> int minimumDays(int N, int L, std::vector<int>& ages) { std::sort(ages.begin(), ages.end()); // Sort the ages in ascending order int highRiskCount = 0; int nonHighRiskCount = 0; // Count the number of high-risk and non-high-risk individuals for (int i = 0; i < N; i++) { if (ages[i] <= 10 || ages[i] >= 81) { highRiskCount++; } else { nonHighRiskCount++; } } int days = 0; while (highRiskCount > 0 || nonHighRiskCount > 0) { int capsules = L; // Number of capsules available for the day 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 223. // Distribute capsules to high-risk individuals first while (capsules > 0 && highRiskCount > 0) { capsules--; highRiskCount--; } // Distribute capsules to non-high-risk individuals while (capsules > 0 && nonHighRiskCount > 0) { capsules--; nonHighRiskCount--; } days++; // Increment the number of days } return days; } int main() { int N, L; std::cin >> N >> L; 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
  • 224. std::vector<int> ages(N); for (int i = 0; i < N; i++) { std::cin >> ages[i]; } int result = minimumDays(N, L, ages); std::cout << result << " Days" << std::endl; return 0; } 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
  • 225. import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Scanner; public class Main { public static int minimumDays(int N, int L, List<Integer> ages) { Collections.sort(ages); // Sort the ages in ascending order int highRiskCount = 0; int nonHighRiskCount = 0; // Count the number of high-risk and non-high-risk individuals for (int i = 0; i < N; i++) { if (ages.get(i) <= 10 || ages.get(i) >= 81) { highRiskCount++; } else { nonHighRiskCount++; } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 226. } int days = 0; while (highRiskCount > 0 || nonHighRiskCount > 0) { int capsules = L; // Number of capsules available for the day // Distribute capsules to high-risk individuals first while (capsules > 0 && highRiskCount > 0) { capsules--; highRiskCount--; } // Distribute capsules to non-high-risk individuals while (capsules > 0 && nonHighRiskCount > 0) { capsules--; nonHighRiskCount--; } days++; // Increment the number of days } return days; } public static void main(String[] args) 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
  • 227. { Scanner scanner = new Scanner(System.in); int N = scanner.nextInt(); int L = scanner.nextInt(); List<Integer> ages = new ArrayList<>(); for (int i = 0; i < N; i++) { ages.add(scanner.nextInt()); } int result = minimumDays(N, L, ages); System.out.println(result + " Days"); } } 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
  • 228. def minimum_days(N, L, ages): ages.sort() # Sort the ages in ascending order high_risk_count = 0 non_high_risk_count = 0 # Count the number of high-risk and non-high-risk individuals for age in ages: if age <= 10 or age >= 81: high_risk_count += 1 else: non_high_risk_count += 1 days = 0 while high_risk_count > 0 or non_high_risk_count > 0: capsules = L # Number of capsules available for the day # Distribute capsules to high-risk individuals first while capsules > 0 and high_risk_count > 0: capsules -= 1 high_risk_count -= 1 # Distribute capsules to non-high-risk individuals while capsules > 0 and non_high_risk_count > 0: capsules -= 1 non_high_risk_count -= 1 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 229. days += 1 # Increment the number of days return days N, L = map(int, input().split()) ages = list(map(int, input().split())) result = minimum_days(N, L, ages) print(result, "Days") 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
  • 230. question 23 Jack and Jill went to a carnival, there are many games counter in the carnival. And if you win you may get good prizes. One of the games there was Check-and-win. The game was simple but a bit tricky. Below are the rules of the game: • There will be a strip with N integers mentioned on it. •Each player will get their respective number strips.Each time one player has to pick a number from the strip. The index chosen by the one player cannot be used further in the game. We will understand more in below example. •The next player has to pick a number from another index from their respective strip. Once that index is used, it won't be used again in the game by either of the payers. • At the end of the when all the indexes are checked. The sum will be calculated for each player. • The player with the maximum sum will be the winner.
  • 231. question 23 Jack decided a rule, that he will always start first. Print Jack if he wins, or Jill when Jill wins. If there is a tie, print Tie. Considering that both the players are playing optimally. find the output. Let us try to understand it with an example. Consider the strip of 3 integers. Means N = 3. Respective strip for Jack and Jill is as follows: JK: [134] JL: (531) The rule says that Jack always plays first. Step 1: Jack plays first and chooses the largest element his number-strip JK[3] = 4. Now index 3 is checked. Step 2: Jill plays next, now she has to find the largest number among index 1 and 2. Within these 2 indices she has the largest number at index 1. So, she chooses JL[1] Now index 1 is checked.
  • 232. question 23 Step 3: Its Jack's turn now, and the only index left is 2. So, he chooses JK[2] Sum of each: Jack : 4 + 3 =7 jill :5 Clearly jack wins. Hence the answer is jack. Input format First Input -Accept value of Integer, N. Next 'N' Lines-Elements of sequence JK[] Next 'N' Lines-Elements of sequence JI[] Output format
  • 233. question 23 Step 3: Its Jack's turn now, and the only index left is 2. So, he chooses JK[2] Sum of each: Jack : 4 + 3 =7 jill :5 Clearly jack wins. Hence the answer is jack. Input format First Input -Accept value of Integer, N. Next 'N' Lines-Elements of sequence JK[] Next 'N' Lines-Elements of sequence JI[] Output format
  • 234. question 23 The output is an integer value as per above logic. (Check the output in Example 1, Example 2). additional messages in output will cause the failure of test cases. Constraints 1<=N<=1000 1 <= Jk[], JL[]<=10000 Only integer values Example 1: Input: 2 ->Input integer , N 1 1->Input integer , Jk[] 2 2->Input integer , JL[]
  • 235. question 23 Output: Jill->output Explanation: Step 1: Jack plays first and chooses the largest element from his number-strip JK[1]=1 Now index 1 is checked. step 2: Jill plays next, now she has to find the largest number only present at index 2. So, she chooses JL[2] Now index 2 is checked. Sum of each: Jack=1 Jill=2 Clearly jill wins. Hence the answer is jill
  • 236. question 23 Example 2: Input: 4-> Input integer , N 1 2 3 4->Input integer , Jk[] 4 3 2 1->Input integer , JL[] Output: Tie->output Explanation: Step 1: Jack plays first and chooses the largest element from his number-strip JK[4] =4 Now index 4 is checked. Step 2: Jill plays next, now she has to find the largest number among index 1, 2 and 3, So he chooses JL[1] = 4. Now index 1 is checked.
  • 237. question 23 Step 3: jack plays next and now he has to find the large number among index 2 and 3. JK[3] =3 Now index 3 is checked. Step 4: Jill plays next, now she has to find the largest number only present at index 2. So, he chooses JL[2] = 3 Now index 2 is checked. All indices are checked now. Sum of each
  • 238. #include <stdio.h> #include <stdbool.h> char* findWinner(int N, int JK[], int JL[]) { bool checked[N + 1]; for (int i = 0; i <= N; i++) { checked[i] = false; } int jackSum = 0, jillSum = 0; for (int i = 0; i < N; i++) { int maxJK = -1, maxJL = -1; // Find the maximum available number for Jack for (int j = 0; j < N; j++) { if (!checked[j] && JK[j] > maxJK) { maxJK = JK[j]; } } // Mark the chosen index as checked 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 239. for (int j = 0; j < N; j++) { if (JK[j] == maxJK) { checked[j] = true; break; } } // Find the maximum available number for Jill for (int j = 0; j < N; j++) { if (!checked[j] && JL[j] > maxJL) { maxJL = JL[j]; } } // Mark the chosen index as checked for (int j = 0; j < N; j++) { if (JL[j] == maxJL) { checked[j] = true; 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
  • 240. } } // Calculate the sum for each player jackSum += maxJK; jillSum += maxJL; } // Determine the winner if (jackSum > jillSum) { return "Jack"; } else if (jillSum > jackSum) { return "Jill"; } else { return "Tie"; } } int main() 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
  • 241. { int N; scanf("%d", &N); int JK[N], JL[N]; for (int i = 0; i < N; i++) { scanf("%d", &JK[i]); } for (int i = 0; i < N; i++) { scanf("%d", &JL[i]); } char* winner = findWinner(N, JK, JL); printf("%sn", winner); return 0; } 67 68 69 70 71 72 73 74 75 76 78 79 80 81 82 83 84 85 86 87 88 89
  • 242. #include <iostream> #include <vector> #include <algorithm> using namespace std; string findWinner(int N, vector<int>& JK, vector<int>& JL) { vector<bool> checked(N + 1, false); // To keep track of checked indices int jackSum = 0, jillSum = 0; for (int i = 0; i < N; i++) { int maxJK = -1, maxJL = -1; // Find the maximum available number for Jack for (int j = 0; j < N; j++) { if (!checked[j] && JK[j] > maxJK) { maxJK = JK[j]; } } // Mark the chosen index as checked for (int j = 0; j < N; j++) { 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 243. if (JK[j] == maxJK) { checked[j] = true; break; } } // Find the maximum available number for Jill for (int j = 0; j < N; j++) { if (!checked[j] && JL[j] > maxJL) { maxJL = JL[j]; } } // Mark the chosen index as checked for (int j = 0; j < N; j++) { if (JL[j] == maxJL) { checked[j] = true; break; } 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
  • 244. } // Calculate the sum for each player jackSum += maxJK; jillSum += maxJL; } // Determine the winner if (jackSum > jillSum) { return "Jack"; } else if (jillSum > jackSum) { return "Jill"; } else { return "Tie"; } } int main() { int N; 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
  • 245. cin >> N; vector<int> JK(N), JL(N); for (int i = 0; i < N; i++) { cin >> JK[i]; } for (int i = 0; i < N; i++) { cin >> JL[i]; } string winner = findWinner(N, JK, JL); cout << winner << endl; return 0; } 67 68 69 70 71 72 73 74 75 76 78 79 80 81 82 83 84 85 86 87 88 89
  • 246. import java.util.Scanner; public class Main { public static String findWinner(int N, int[] JK, int[] JL) { boolean[] checked = new boolean[N + 1]; int jackSum = 0, jillSum = 0; for (int i = 0; i <= N; i++) { checked[i] = false; } for (int i = 0; i < N; i++) { int maxJK = -1, maxJL = -1; // Find the maximum available number for Jack for (int j = 0; j < N; j++) { if (!checked[j] && JK[j] > maxJK) { maxJK = JK[j]; } } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 247. // Mark the chosen index as checked for (int j = 0; j < N; j++) { if (JK[j] == maxJK) { checked[j] = true; break; } } // Find the maximum available number for Jill for (int j = 0; j < N; j++) { if (!checked[j] && JL[j] > maxJL) { maxJL = JL[j]; } } // Mark the chosen index as checked for (int j = 0; j < N; j++) { if (JL[j] == maxJL) { 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
  • 248. checked[j] = true; break; } } // Calculate the sum for each player jackSum += maxJK; jillSum += maxJL; } // Determine the winner if (jackSum > jillSum) { return "Jack"; } else if (jillSum > jackSum) { return "Jill"; } else { return "Tie"; } } 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
  • 249. public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int N = scanner.nextInt(); int[] JK = new int[N]; int[] JL = new int[N]; for (int i = 0; i < N; i++) { JK[i] = scanner.nextInt(); } for (int i = 0; i < N; i++) { JL[i] = scanner.nextInt(); } String winner = findWinner(N, JK, JL); System.out.println(winner); } } 67 68 69 70 71 72 73 74 75 76 78 79 80 81 82 83 84 85 86 87 88 89
  • 250. def findWinner(N, JK, JL): checked = [False] * (N + 1) jackSum = 0 jillSum = 0 for i in range(N): maxJK = -1 maxJL = -1 # Find the maximum available number for Jack for j in range(N): if not checked[j] and JK[j] > maxJK: maxJK = JK[j] # Mark the chosen index as checked for j in range(N): if JK[j] == maxJK: checked[j] = True break # Find the maximum available number for Jill for j in range(N): if not checked[j] and JL[j] > maxJL: maxJL = JL[j] # Mark the chosen index as checked 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 251. for j in range(N): if JL[j] == maxJL: checked[j] = True break # Calculate the sum for each player jackSum += maxJK jillSum += maxJL # Determine the winner if jackSum > jillSum: return "Jack" elif jillSum > jackSum: return "Jill" else: return "Tie" N = int(input()) JK = list(map(int, input().split())) JL = list(map(int, input().split())) winner = findWinner(N, JK, JL) print(winner) 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 for j in range(N): if JL[j] == maxJL: checked[j] = True break # Calculate the sum for each player jackSum += maxJK jillSum += maxJL # Determine the winner if jackSum > jillSum: return "Jack" elif jillSum > jackSum: return "Jill" else: return "Tie" N = int(input()) JK = list(map(int, input().split())) JL = list(map(int,
  • 252. question 24 You are given a non-negative integer num`. You will also be given an array `Digits of size exactly 10 where each element of the array will be between 0-9 inclusive. You can perform the following operation on the given integer ‘num’ at most once. You can select a continuous part of ‘num’ and name it ‘x’. For each digit ‘D’ in the number ‘x’, you can change it to digits [D] (consider 0-based indexing). You need to convert the given integer ‘num’ to a maximum possible number after performing the given operation at most once. Example 1:
  • 253. question 24 Input: 132 -> ‘num’ 9 8 1 2 7 6 5 4 0 3 -> Elements of Array`Digits (Size of Array 'Digits is always 10 and elements of the array are space separated) Output: 832 Explanation: You can change the first digit from 1 to 8, then the final number will be 832. Digit 3 can be mapped to 2, but it will change 832 to 822 which is lesser. So, 832 is the maximum number possible.
  • 254. question 24 Example 2: Input: 021 -> ‘num’ 9435721906 -> Elements of Array ‘Digits’ (size of Array ‘digits’ is always 10 and Elements of the array are space separated) Output: 934 Explanation: You can change the first digit from 0 to 9, then the number will be 921. Then you can change the digit from 2 to 3 the number will be 931.
  • 255. question 24 Then you can change the digit from 1 to 4 the number will be 934. Show 934 is the maximum number possible. Constraints: •0<=num<=10100 •0<=Digits[i]<=9, for all valid i(0<=i<10) •Digit Length ==10 •Integer ‘num’ can contain zeros at the start. (For example, ‘012’ is also a valid input) The Input format for testing: •First line: Contains a non negative integer ‘num’ •Second line: contention array ‘Digits’ of size 10 (All elements of the array are space separated)
  • 256. question 24 The output format for testing: •Output a single integer denoting the maximum possible integer after performing some operations on the given integer ‘num’ •(Number of digits in the output should be the same as the number of digits in the input ‘num’) Instructions: •The system does not allow any kind of hard coded input value/ values. •Written programme code by the candidate will be verified against the inputs which are supplied from the system.
  • 257. #include <stdio.h> #include <stdlib.h> #include <string.h> int main() { char num[100]; scanf("%s", num); int digits[10]; for (int i = 0; i < 10; i++) { scanf("%d", &digits[i]); } int length = strlen(num); for (int i = 0; i < length; i++) { int digit = num[i] - '0'; if (digit < digits[digit]) { num[i] = digits[digit] + '0'; } else if (digit > digits[digit]) { 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 259. #include <iostream> #include <vector> using namespace std; int main() { string num; cin >> num; vector<int> digits(10); for (int i = 0; i < 10; i++) { cin >> digits[i]; } for (int i = 0; i < num.length(); i++) { int digit = num[i] - '0'; if (digit < digits[digit]) { num[i] = digits[digit] + '0'; } else if (digit > digits[digit]) { break; 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 260. } } cout << num << endl; return 0; } 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
  • 261. import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); String num = scanner.nextLine(); int[] digits = new int[10]; for (int i = 0; i < 10; i++) { digits[i] = scanner.nextInt(); } int length = num.length(); for (int i = 0; i < length; i++) { int digit = Character.getNumericValue(num.charAt(i)); if (digit < digits[digit]) { char[] numArray = num.toCharArray(); numArray[i] = (char) (digits[digit] + '0'); num = String.valueOf(numArray); } else if (digit > digits[digit]) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 263. num = input() digits = list(map(int, input().split())) for i in range(len(num)): digit = int(num[i]) if digit < digits[digit]: num = num[:i] + str(digits[digit]) + num[i+1:] elif digit > digits[digit]: break print(num) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 264. question 25 You are in the Marvel Universe and Doctor strange has to defend a little girl named ‘America’ from the scarlet witch. The Scarlet witch is really strong thus Doctor strange has assembled an army of ‘n’ magicians to fight her. She throws magical red balls toward her enemy to get rid of him. Each magician in Doctor Strange's army has some strength denoted by 'Pi' element in an array. The scarlet witch has the power to fire any number of magical red balls at the same time in her single attack. She can do 'q' number of attacks. The opponent can stand against her till he has strength. One magical red ball decreases strength by 1. I.e., if a person has the strength of 2 and she throws 1 magical ball in her first attack then his strength becomes 1 and he is saved. But if she threw one more then he would die. But this is the point where the twist comes,
  • 265. question 25 Doctor Strange is not weak, he has a darkhold. When all the magicians of Doctor Strange's army die, he with the help of his magic and darkhold, revives them all and they stand up again for fighting. i.e., if at the second all his magicians die then at the end of that i second all his magicians will stand up again for fighting. You are Doctor Strange’s assistant cell him how many magicians are left alive for fighting at the end of each attack by the Scarlet witch note that, as soon as all the magicians die, Doctor Strange will instantaneously make them alive. Example 1: Input: 10 3 ->Number of magicians in Doctor strange army and the number of attacks by the scarlet witch space- separated.
  • 266. question 25 1 1 1 1 1 1 1 1 1 1 -> strength of each soldier in the army 10 10 5 -> Number of magical red balls fired by the scarlet witch in her each attack Output: 10 10 5 -> The respective numbers (space-separated) of magicians left alive after each attack of the scarlet witch Explanation: Here there will be 3 attacks.The scenario will be as follows : Attack 1: All 10 magicians die and as soon as all magicians die, they are brought back to life again, thus at end of the 1st attack 10 magicians are alive again.
  • 267. question 25 Attack 2: Same Scenario Attack 3: 5 magicians die, thus 5 are left. Example 2: Input: 5 2 -> Number of magicians in doctor strange army and the number of attacks by the scarlet witch space-separated. 1 2 1 1 1 -> Strength of each soldier in the army 2 3 -> Number of magical red balls fired by the scarlet witch in her each attack Output: 4 1 -> The respective numbers(space-separated) of magicians left alive after each attack of the scarlet witch
  • 268. question 25 Explanation: Here there will be 2 attacks.The scenario will be as follows : Attack 1: Only 1 magician die and second one’s strength will be decreased to 1,thus army’s condition is – 1 1 1 1 Attack 2: Here in the second attack next three magicians die and only 1 left.
  • 269. #include <stdio.h> #include <stdlib.h> int main() { int n, q; scanf("%d %d", &n, &q); int* strength = (int*)malloc(n * sizeof(int)); for (int i = 0; i < n; i++) { scanf("%d", &strength[i]); } int* balls = (int*)malloc(q * sizeof(int)); for (int i = 0; i < q; i++) { scanf("%d", &balls[i]); } int* magicians = (int*)malloc(n * sizeof(int)); for (int i = 0; i < n; i++) { magicians[i] = 1; // Initialize all magicians as alive } for (int i = 0; i < q; i++) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 270. { int ballsThrown = balls[i]; int alive = 0; // Number of magicians alive after each attack for (int j = 0; j < n; j++) { if (magicians[j] > 0) { if (ballsThrown >= strength[j]) { ballsThrown -= strength[j]; magicians[j] = 0; // Mark magician as dead } else { alive++; // Magician survives the attack strength[j] -= ballsThrown; // Decrease magician's strength ballsThrown = 0; // All balls are used } } } if (alive == 0) { 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
  • 271. for (int j = 0; j < n; j++) { magicians[j] = 1; // Revive all magicians } alive = n; } printf("%d ", alive); } printf("n"); free(strength); free(balls); free(magicians); return 0; } 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
  • 272. #include <iostream> #include <vector> using namespace std; int main() { int n, q; cin >> n >> q; vector<int> strength(n); for (int i = 0; i < n; i++) { cin >> strength[i]; } vector<int> balls(q); for (int i = 0; i < q; i++) { cin >> balls[i]; } vector<int> magicians(n, 1); // Initialize all magicians as alive for (int i = 0; i < q; i++) { int ballsThrown = balls[i]; int alive = 0; // Number of magicians alive after each attack 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 273. for (int j = 0; j < n; j++) { if (magicians[j] > 0) { if (ballsThrown >= strength[j]) { ballsThrown -= strength[j]; magicians[j] = 0; // Mark magician as dead } else { alive++; // Magician survives the attack strength[j] -= ballsThrown; // Decrease magician's strength ballsThrown = 0; // All balls are used } } } if (alive == 0) { for (int j = 0; j < n; j++) { 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
  • 274. magicians[j] = 1; // Revive all magicians } alive = n; } cout << alive << " "; } cout <<endl; return 0; } 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
  • 275. import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); int q = scanner.nextInt(); int[] strength = new int[n]; for (int i = 0; i < n; i++) { strength[i] = scanner.nextInt(); } int[] balls = new int[q]; for (int i = 0; i < q; i++) { balls[i] = scanner.nextInt(); } int[] magicians = new int[n]; for (int i = 0; i < n; i++) { magicians[i] = 1; // Initialize all magicians as alive 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 276. for (int i = 0; i < q; i++) { int ballsThrown = balls[i]; int alive = 0; // Number of magicians alive after each attack for (int j = 0; j < n; j++) { if (magicians[j] > 0) { if (ballsThrown >= strength[j]) { ballsThrown -= strength[j]; magicians[j] = 0; // Mark magician as dead } else { alive++; // Magician survives the attack strength[j] -= ballsThrown; // Decrease magician's strength ballsThrown = 0; // All balls are used } } } 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
  • 277. if (alive == 0) { for (int j = 0; j < n; j++) { magicians[j] = 1; // Revive all magicians } alive = n; } System.out.print(alive + " "); } System.out.println(); scanner.close(); } } 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
  • 278. n, q = map(int, input().split()) strength = list(map(int, input().split())) balls = list(map(int, input().split())) magicians = [1] * n for i in range(q): ballsThrown = balls[i] alive = 0 for j in range(n): if magicians[j] > 0: if ballsThrown >= strength[j]: ballsThrown -= strength[j] magicians[j] = 0 else: alive += 1 strength[j] -= ballsThrown ballsThrown = 0 if alive == 0: magicians = [1] * n alive = n print(alive, end=' ') print() 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 279. QUESTION NO : 26 Your friend had a child. You wanted to give him a nice nickname of length N and k length repetitive by modifying his real name S of length N. The nickname is called nice if and only if the S is a palindrome and the S has a period of k. (Here period nothing but repetition of the substring for every k intervals i.e.. S1 to k=S(k+1) to (2*k) =. .. . .= S(x*k+1) to N. Here you will be given string S length N and k where N % k=0. To make a nickname nice, you can use the following operation. The operation follows: You can choose any index (i) of the string S and change the ith letter with some other letter. Find the minimum number of operations required to convert string S to a nice nickname.
  • 280. QUESTION NO : 26 Example - 1: Input: 8 2 ------> N (length of the string) and Abaacbaa ------> String S. Output: 3 Explanation: One possible solution is aaaaaaaa. so that we can get the minimum number of operations required to convert S to a nice nick name.
  • 281. QUESTION NO : 26 Example - 2: Input: 10 2 Aabcbaacba Output: 5 Constraints: 1<=N<=105 1<=N and N%k=0 The input format for testing: The first line represents the N and K. The second line represents the string S.
  • 282. QUESTION NO : 26 The output format for testing: Print the minimum number of operations required to convert the string S to a nice nickname. Instructions: The system does not allow any kind of hard coded input
  • 283. import java.util.Scanner; public class Main { public static int minOperationsForNiceNickname(int N, int k, String S) { int operations = 0; for (int i = 0; i < k / 2; i++) { int[] freq = new int[26]; // Count the frequency of characters at indices i and (k - i - 1) for (int j = i; j < N; j += k) { freq[S.charAt(j) - 'a']++; freq[S.charAt(j + (k - 2 * i - 1)) - 'a']++; } int maxFreq = 0; int totalFreq = 0; // Find the most frequent character and calculate the total frequency for (int f : freq) { maxFreq = Math.max(maxFreq, f); totalFreq += f; 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 284. } // Subtract the most frequent character's frequency from the total frequency operations += totalFreq - maxFreq; } return operations; } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int N = scanner.nextInt(); int k = scanner.nextInt(); String S = scanner.next(); int minOperations = minOperationsForNiceNickname(N, k, S); System.out.println(minOperations); } } 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
  • 285. #include <stdio.h> #include <string.h> int minOperationsForNiceNickname(int N, int k, const char* S) { int operations = 0; for (int i = 0; i < k / 2; i++) { int freq[26] = {0}; // Count the frequency of characters at indices i and (k - i - 1) for (int j = i; j < N; j += k) { freq[S[j] - 'a']++; freq[S[j + (k - 2 * i - 1)] - 'a']++; } int maxFreq = 0; int totalFreq = 0; // Find the most frequent character and calculate the total frequency for (int f = 0; f < 26; f++) { maxFreq = (freq[f] > maxFreq) ? freq[f] : maxFreq; totalFreq += freq[f]; } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 286. // Subtract the most frequent character's frequency from the total frequency operations += totalFreq - maxFreq; } return operations; } int main() { int N, k; scanf("%d %d", &N, &k); char S[N + 1]; scanf("%s", S); int minOperations = minOperationsForNiceNickname(N, k, S); printf("%dn", minOperations); return 0; } 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
  • 287. #include <iostream> #include <string> #include <vector> using namespace std; int minOperationsForNiceNickname(int N, int k, const string& S) { int operations = 0; for (int i = 0; i < k / 2; i++) { vector<int> freq(26, 0); // Count the frequency of characters at indices i and (k - i - 1) for (int j = i; j < N; j += k) { freq[S[j] - 'a']++; freq[S[j + (k - 2 * i - 1)] - 'a']++; } int maxFreq = 0; int totalFreq = 0; // Find the most frequent character and calculate the total frequency for (int f : freq) { maxFreq = max(maxFreq, f); 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 288. totalFreq += f; } // Subtract the most frequent character's frequency from the total frequency operations += totalFreq - maxFreq; } return operations; } int main() { int N, k; cin >> N >> k; string S; cin >> S; int minOperations = minOperationsForNiceNickname(N, k, S); cout << minOperations << endl; return 0; } 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
  • 289. def min_operations_for_nice_nickname(N, k, S): operations = 0 for i in range(k // 2): freq = [0] * 26 # Count the frequency of characters at indices i and (k - i - 1) for j in range(i, N, k): freq[ord(S[j]) - ord('a')] += 1 freq[ord(S[j + (k - 2 * i - 1)]) - ord('a')] += 1 max_freq = 0 total_freq = 0 # Find the most frequent character and calculate the total frequency for f in freq: max_freq = max(max_freq, f) total_freq += f #Subtract the most frequent character's frequency from the total frequency operations += total_freq - max_freq return operations N, k = map(int, input().split()) S = input() min_operations = min_operations_for_nice_nickname(N, k, S) print(min_operations) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 290. QUESTION NO : 27 Ria likes to play a number game always. Today she decided to find the largest number that can be made using all of the digits of the given input(Non negative integer) value N. Example 1: Input : 3675092 -> value of N Output: 9765320 Example 2 : Input: 2856 -> value of N Output: 8652
  • 291. QUESTION NO : 27 Note: Since, input value, N accepts integer value only, hence digit 0 that comes before the first non-zero digit should not take into consideration of input. Constraints: 1<N<10000000 The input format for testing: The candidate has to write the court to accept a positive integer number.
  • 292. #include <stdio.h> #include <stdlib.h> #include <string.h> int compare(const void *a, const void *b) { return (*(char*)b - *(char*)a); } char* largestNumber(int N) { char numStr[12]; sprintf(numStr, "%d", N); qsort(numStr, strlen(numStr), sizeof(char), compare); return strdup(numStr); } int main() { int N; scanf("%d", &N); char* largestNum = largestNumber(N); printf("%sn", largestNum); free(largestNum); return 0; } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 293. #include <algorithm> using namespace std; bool compare(char a, char b) { return a > b; } string largestNumber(int N) { string numStr = to_string(N); sort(numStr.begin(), numStr.end(), compare); return numStr; } int main() { int N; cin >> N; string largestNum = largestNumber(N); cout << largestNum << endl; return 0; } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 294. import java.util.Arrays; import java.util.Scanner; public class Main { public static String largestNumber(int N) { String numStr = Integer.toString(N); char[] numArr = numStr.toCharArray(); Arrays.sort(numArr); StringBuilder sb = new StringBuilder(); for (int i = numArr.length - 1; i >= 0; i--) { sb.append(numArr[i]); } return sb.toString(); } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int N = scanner.nextInt(); String largestNum = largestNumber(N); System.out.println(largestNum); }} 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 295. def largestNumber(N): numStr = str(N) numArr = list(numStr) numArr.sort(reverse=True) largestNum = ''.join(numArr) return largestNum N = int(input()) largestNum = largestNumber(N) print(largestNum) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 296. QUESTION NO : 28 Rahul, a mathematical genius will be given a positive number N and he needs to reduce it to 0 (zero) by following operations mentioned as under: Take one of the divisors of N – which is different from N itself and subtract it from N. Perform the above operation till the original number is reduced to 0 (zero). The task here is to find the minimum number of steps Rahul needs to perform such that N is reduced to 0 (zero) Note: If the N is 1 during the operation, then in order to reduce 1 to 0 (zero) subtract 1 from it. It is shown in the following examples
  • 297. QUESTION NO : 28 Example 1 Input 5 Output 4 Explanation Divisors of 5 are 1, 5 but you cannot subtract 5 so then subtract 1 from 5 The reduced number is 5-1 = 4 Divisors of 4 are 1, 2 and 4 but you cannot subtract 4 so reduce it by 2, after reducing it by 2, number becomes 4 – 2 = 2 Divisor of 2 are 1, 2 and after reducing it by 1, number becomes 2 – 1 = 1 You can subtract 1 by 1 and then the number becomes 0. So for N = 5, the minimum number of steps are 4.
  • 298. QUESTION NO : 28 Example 2 Input 8 Output 4 Explanation In first step, subtract 4 from 8, number becomes 8 – 4 = 4 In second step, subtract 2 from 4, number becomes 4 – 2 = 2 In third step, subtract 1 from 2, number becomes 2 – 1 = 1 In fourth step, subtract 1 from 1, number becomes 1 – 1 = 0 Example 3 Input 6 Output 4
  • 299. #include<stdio.h> int fun(int n) { int count = 0; int fact = 1; while(n != 0) { for(int i = 1; i < n; i++) { if(n % i == 0) { fact = i; } } n = n - fact; count = count + 1; } return count; } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 300. int main() { int n; scanf("%d", &n); printf("%d", fun(n)); return 0; } 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
  • 301. #include<iostream> using namespace std; int fun(int n) { int count = 0; int fact = 1; while(n != 0) { for(int i = 1; i < n; i++) { if(n % i == 0) { fact = i; } } n = n - fact; count = count + 1; } return count; } int main() { 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 302. int n; cin >> n; cout << fun(n); return 0; } 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
  • 303. import java.util.Scanner; public class Main { public static int fun(int n) { int count = 0; int fact = 1; while (n != 0) { for (int i = 1; i < n; i++) { if (n % i == 0) { fact = i; } } n = n - fact; count = count + 1; } return count; } public static void main(String[] args) { 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 304. Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); System.out.println(fun(n)); scanner.close(); } } 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
  • 305. def fun(n): count = 0 fact = 1 while n != 0: for i in range(1, n): if n % i == 0: fact = i n = n - fact count = count + 1 return count n = int(input()) print(fun(n)) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 306. QUESTION NO : 29 Given a positive integer number N. the task is to find the number of ways in which the given number can be represented as the product of two distinct numbers. Example 1 Input 14 Output 2 Explanation 14 can be represented as 1 * 14 and 2 * 7 Example 2 Input 16 Output 2
  • 307. QUESTION NO : 29 Explanation 16 can be represented as 1*16 and 2 * 8 Note 4*4 is not valid way because both the numbers are same.
  • 308. #include <iostream> #include <cmath> using namespace std; int fun(int n) { int count = 0; for (int i = 1; i * i <= n; i++) { if (n % i == 0 && (n / i != i)) { count++; } } return count; } int main() { int n; cin >> n; cout << fun(n); return 0; } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 309. #include<stdio.h> #include<math.h> int fun(int n) { int count = 0; for(int i = 1; i*i <= n; i++) { if(n % i == 0 && (n / i != i) ) { count++; } } return count; } int main() { int n; scanf("%d", &n); printf("%d", fun(n)); return 0; } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 310. import java.util.Scanner; public class Main { public static int fun(int n) { int count = 0; for (int i = 1; i * i <= n; i++) { if (n % i == 0 && (n / i != i)) { count++; } } return count; } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); System.out.println(fun(n)); scanner.close(); } } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 311. def fun(n): count = 0 for i in range(1, int(n**0.5) + 1): if n % i == 0 and n // i != i: count += 1 return count n = int(input()) print(fun(n)) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 312. QUESTION NO : 30 Given a number N, the task is to split the Num into multiple parts in such a fashion as to find the highest product. Print the highest product value. Consider N = 4. Best: 4 = 2 + 2 and 2 * 2 = 4 Similarly for N = 6, (3 * 3) = 9 For N = 8, (2 * 3 * 3) = 18 For N = 15, (3 * 3 * 3 * 3 * 3) = 243 Constraints 1 <= N <= 100 Input format The candidate has to write the code to accept a non-negative integer number only. Output format The output should be a positive integer only.
  • 313. QUESTION NO : 30 Example 1 Input 4 Output 4 Example 2 Input Output 9 6
  • 314. #include<stdio.h> int fun(int n) { if(n == 2 || n == 3) return n-1; int res = 1; while(n > 4) { n = n - 3; res = res * 3; } return (n * res); } int main() { int n; scanf("%d", &n); printf("%d", fun(n)); return 0; } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 315. #include <iostream> using namespace std; int fun(int n) { if (n == 2 || n == 3) return n - 1; int res = 1; while (n > 4) { n = n - 3; res = res * 3; } return (n * res); } int main() { int n; cin >> n; cout << fun(n); return 0; } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 316. import java.util.Scanner; public class Main { public static int fun(int n) { if (n == 2 || n == 3) return n - 1; int res = 1; while (n > 4) { n = n - 3; res = res * 3; } return (n * res); } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); System.out.println(fun(n)); scanner.close(); }} 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 317. def fun(n): if n == 2 or n == 3: return n - 1 res = 1 while n > 4: n = n - 3 res = res * 3 return n * res n = int(input()) print(fun(n)) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 319. QUESTION NO : 31 You are at your 1(containing zeros of size N) The magic operation is nothing but in this operation, you select any index (i) in the array B and add (k to the power i) to the B[i].So, if you are able to build the A array from the B array then print YES else NO. NOTE: The array A is 0 indexed.
  • 320. QUESTION NO : 31 Example 1: Input: 3 2 ->N (length of an array A) and k (weapon) 46 54 100 ->A array of length N Output: NO Explanation: Initially B=[0,0,0] Here, we can get A[0] by applying magic operations 46 times on index 0 and 25 times on index-2, but cannot get A[1] by applying magic operations.
  • 321. #include <stdio.h> #include <stdbool.h> bool isPossibleToBuildArray(int A[], int n, int k) { int B[n]; B[0] = 1; for (int i = 1; i < n; i++) { B[i] = B[i - 1] * k; } for (int i = 0; i < n; i++) { int count = 0; int power = B[i]; while (A[i] >= power) { A[i] -= power; count++; } if (A[i] != 0 || count > 1) { return false;} 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 322. } } return true; } int main() { int n, k; scanf("%d %d", &n, &k); int A[n]; for (int i = 0; i < n; i++) { scanf("%d", &A[i]); } bool possible = isPossibleToBuildArray(A, n, k); printf("%s", possible ? "YES" : "NO"); return 0; } 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
  • 323. #include <iostream> #include <vector> #include <cmath> using namespace std; bool isPossibleToBuildArray(vector<int>& A, int k) { int n = A.size(); vector<int> B(n, 0); for (int i = 0; i < n; i++) { int power = pow(k, i); B[i] = power; } for (int i = 0; i < n; i++) { int count = 0; while (A[i] >= B[i]) { A[i] -= B[i]; count++; } if (A[i] != 0 || count > 1) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 324. { return false; } } return true; } int main() { int n, k; cin >> n >> k; vector<int> A(n); for (int i = 0; i < n; i++) { cin >> A[i]; } bool possible = isPossibleToBuildArray(A, k); cout << (possible ? "YES" : "NO"); return 0; } 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
  • 325. import java.util.Scanner; import java.util.ArrayList; class Main { public static boolean isPossibleToBuildArray(ArrayList<Integer> A, int k) { int n = A.size(); ArrayList<Integer> B = new ArrayList<Integer>(n); for (int i = 0; i < n; i++) { int power = (int) Math.pow(k, i); B.add(power); } for (int i = 0; i < n; i++) { int count = 0; while (A.get(i) >= B.get(i)) { A.set(i, A.get(i) - B.get(i)); count++; } if (A.get(i) != 0 || count > 1) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 326. { return false; } } return true; } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); int k = scanner.nextInt(); ArrayList<Integer> A = new ArrayList<Integer>(n); for (int i = 0; i < n; i++) { A.add(scanner.nextInt()); } boolean possible = isPossibleToBuildArray(A, k); System.out.println(possible ? "YES" : "NO"); scanner.close(); } } 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
  • 327. def isPossibleToBuildArray(A, k): n = len(A) B = [] for i in range(n): power = k ** i B.append(power) for i in range(n): count = 0 while A[i] >= B[i]: A[i] -= B[i] count += 1 if A[i] != 0 or count > 1: return False return True n, k = map(int, input().split()) A = list(map(int, input().split())) possible = isPossibleToBuildArray(A, k) print("YES" if possible else "NO") 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 328. QUESTION NO : 32 Ram is a very busy business man. Everyday he has to travel to different cities. There are N cities in the list(a[]) that he has to pass through to reach his destination. His destination is the last city in the list. He always starts from his home city(a[0]). The maximum distance Ram can travel when he is at city i is given by a[i]. It takes 1 unit of time each he travels from any one city to another city. His goal is to reach the destination city(a[N-1]) at the end of the day. Given N, a , the task here is to help Ram to travel from his home city to destination in the minimum amount of time. Give the time as output Note: Assume,the destination can always be reached
  • 329. QUESTION NO : 32 Example 1: Input: 5-> Value of N 2 1 2 5 3-> a[], Elements a[0] to a[N-1], where each input element is separated by new line Output: 2
  • 330. QUESTION NO : 32 Explanation: From the inputs given above: Ram starts from his home city (a[0]):2 Maximum distance Ram can travel is 2 places ahead that is Ram can either go to a[1] or a[2] Ram will go to a city at a[2] Amount of time spent is 1 unit Again he starts from a[2] Maximum distance Rankan travel is two places ahead that is Ram can either go to a[3] or a[4] Ram will go to a[4] which is the destination Amount of time spent is 1 unit.
  • 331. QUESTION NO : 32 Example 2: Input : 8-> Value of N 1 2 1 1 3 5 6 4-> a[], Elements a[0] to a[N-1] where each input element is separated by new line Output: 4
  • 332. QUESTION NO : 32 Explanation: From the inputs given above: Iran starts from his home city (a[0]):1 Maximum distance Ram can travel is 1 place ahead that is Ram can go only to a[1] Amount of time spent is 1 unit. Again he starts from a[1] Maximum distance from can travel is 2 places ahead that is Ram can either go to a[2] or a[3] Ram will go to a city at a[3]. Amount of time spent is 1 unit. Again he starts from a[3]
  • 333. QUESTION NO : 32 Maximum distance from can travel is 1 places ahead that is Ram can either go to a[4] Ram will go only to a city a[4]. Amount of time spent is 1 unit. Again he starts from a[4] Maximum distance from can travel is 3 places ahead that is Ram can either go to a[5] or a[6] or a[7]. Ram will go a to city at a[7] which is the destination. Amount of time spent is 1 unit. The total amount of time spent is 4 units. This is the least amount of time Ron has to spend to travel from source to destination. Hence, the output is 4.
  • 334. QUESTION NO : 32 Constraints: 1<N<10000000 The input format testing: The candidate has to write the code to accept a positive integer number
  • 335. #include <stdio.h> int minTime(int N, int *a) { int currMaxDist = 0; // Current maximum distance Ram can travel int minTime = 0; // Minimum time spent to reach the destination for (int i = 0; i < N - 1; i++) { if (i + a[i] > currMaxDist) { currMaxDist = i + a[i]; // Update the current maximum distance } if (currMaxDist >= N - 1) { break; // Destination reached } minTime++; // Increment the minimum time spent } return minTime; } int main() { int N; 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 336. scanf("%d", &N); int a[N]; for (int i = 0; i < N; i++) { scanf("%d", &a[i]); } int minTravelTime = minTime(N, a); printf("%dn", minTravelTime); return 0; } 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
  • 337. #include <iostream> using namespace std; int minTime(int N, int *a) { int currMaxDist = 0; // Current maximum distance Ram can travel int minTime = 0; // Minimum time spent to reach the destination for (int i = 0; i < N - 1; i++) { if (i + a[i] > currMaxDist) { currMaxDist = i + a[i]; // Update the current maximum distance } if (currMaxDist >= N - 1) { break; // Destination reached } minTime++; // Increment the minimum time spent } return minTime; } int main() 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 338. { int N; cin >> N; int a[N]; for (int i = 0; i < N; i++) { cin >> a[i]; } int minTravelTime = minTime(N, a); cout << minTravelTime << endl; return 0; } 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
  • 339. import java.util.Scanner; public class Main { public static int minTime(int N, int[] a) { int currMaxDist = 0; // Current maximum distance Ram can travel int minTime = 0; // Minimum time spent to reach the destination for (int i = 0; i < N - 1; i++) { if (i + a[i] > currMaxDist) { currMaxDist = i + a[i]; // Update the current maximum distance } if (currMaxDist >= N - 1) { break; // Destination reached } minTime++; // Increment the minimum time spent } return minTime; } public static void main(String[] args) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 340. { Scanner scanner = new Scanner(System.in); int N = scanner.nextInt(); int[] a = new int[N]; for (int i = 0; i < N; i++) { a[i] = scanner.nextInt(); } int minTravelTime = minTime(N, a); System.out.println(minTravelTime); scanner.close(); } } 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
  • 341. def minTime(N, a): currMaxDist = 0 # Current maximum distance Ram can travel minTime = 0 # Minimum time spent to reach the destination for i in range(N - 1): if i + a[i] > currMaxDist: currMaxDist = i + a[i] # Update the current maximum distance if currMaxDist >= N - 1: break # Destination reached minTime += 1 # Increment the minimum time spent return minTime N = int(input()) a = list(map(int, input().split())) minTravelTime = minTime(N, a) print(minTravelTime) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 342. QUESTION NO : 33 Rohan has a board of N*M dimensions where N is number of rows and M is number of columns. He has X number of coins numbered. They are playing a game on this with the below rule: •You need to fill the board with coins. You can fill each cell of board with a minimum of 0 coins or a maximum of X coins. •Each cell can be filled with coins between 0 to X. •For every pair of neighbor cells, the number of coins in both cells should not exceed a given number Y. Two cells are neighbor if they share a side. Your task is to find the maximum number of coins which can be filled inside the board at a particular time, considering the above mentioned condition. The Input will be: N: Number of rows M : Number of columns X : Number of coins per cell Y : Maximum sum of neighbor cells.
  • 343. QUESTION NO : 33 Example 1: Input : 2 2 5 2-> Input integer, N, M, X and Y. Output : 4->Output Explanation: In the above matrix which is 2*2. The maximum sum of neighbours can be at most 2. We can have below arrangement In the arrangement above, All the conditions satisfies •Maximum coin can be only 2. •The neighbour has at most 2 coins. Clearly the maximum coin which we can adjust in this board the are 4. Example 2: Input: 3 3 6 3->Input integers N, M, X and Y
  • 344. QUESTION NO : 33 Output: 15->Output Explanation: In the above matrix which is 3*3 the maximum sum of neighbours can be at most 3. We can have the below arrangement In the arrangement above, All the conditions satisfies •Maximum coin can be only 6. •The neighbour has at most 3 coins. Clearly the maximum coin which we can adjust in this board the are 15. Constraints: •1<=N,M<=100 •1<=X,Y<=100 •Only lowercase allowed
  • 345. QUESTION NO : 33 The input format for testing: •First input - Accept value of integer N •Second input -accept value of integer M(Next Line) •Third input -accept value of integer X (Next Line) Fourth input accept value of integer y(Next Line) The output format for testing: •The output is an integer as per above logic (check the output in example 1, example 2) •Additional message in output will cause the failure of test cases. Instructions: •System does not allow any kind of hard coded input value or values. •Return programme code by the candidate will be verified against the inputs which are supplied from the system.
  • 346. #include <stdio.h> int maxCoins(int N, int M, int X, int Y) { int maxCoins = 0; // Handle the special cases where N or M is 1 if (N == 1 || M == 1) { maxCoins = (N * M) * (X < Y ? X : Y); return maxCoins; } // Calculate the maximum number of coins based on the position on the board int diagonalSize = (X <= Y) ? X : Y; maxCoins = diagonalSize; for (int i = 2; i <= N; i++) { for (int j = 2; j <= M; j++) { if ((i % 2 == 0 && j % 2 == 0) || (i % 2 != 0 && j % 2 != 0)) { maxCoins += diagonalSize; } else 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 347. { maxCoins += (X <= Y) ? X : Y; } } } return maxCoins; } int main() { int N, M, X, Y; scanf("%d", &N); scanf("%d", &M); scanf("%d", &X); scanf("%d", &Y); int result = maxCoins(N, M, X, Y); printf("%dn", result); return 0; } 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
  • 348. #include <iostream> using namespace std; int maxCoins(int N, int M, int X, int Y) { int maxCoins = 0; // Handle the special cases where N or M is 1 if (N == 1 || M == 1) { maxCoins = (N * M) * (X < Y ? X : Y); return maxCoins; } // Calculate the maximum number of coins based on the position on the board int diagonalSize = (X <= Y) ? X : Y; maxCoins = diagonalSize; for (int i = 2; i <= N; i++) { for (int j = 2; j <= M; j++) { if ((i % 2 == 0 && j % 2 == 0) || (i % 2 != 0 && j % 2 != 0)) { maxCoins += diagonalSize; } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 349. else { maxCoins += (X <= Y) ? X : Y; } } } return maxCoins; } int main() { int N, M, X, Y; cin >> N >> M >> X >> Y; int result = maxCoins(N, M, X, Y); cout << result << endl; return 0; } 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
  • 350. import java.util.Scanner; public class Main { public static int maxCoins(int N, int M, int X, int Y) { int maxCoins = 0; // Handle the special cases where N or M is 1 if (N == 1 || M == 1) { maxCoins = (N * M) * (X < Y ? X : Y); return maxCoins; } int diagonalSize = (X <= Y) ? X : Y; maxCoins = diagonalSize; for (int i = 2; i <= N; i++) { for (int j = 2; j <= M; j++) { if ((i % 2 == 0 && j % 2 == 0) || (i % 2 != 0 && j % 2 != 0)) { 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 351. } else { maxCoins += (X <= Y) ? X : Y; } } } return maxCoins; } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int N = scanner.nextInt(); int M = scanner.nextInt(); int X = scanner.nextInt(); int Y = scanner.nextInt(); int result = maxCoins(N, M, X, Y); System.out.println(result); } } 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
  • 352. def maxCoins(N, M, X, Y): maxCoins = 0 # Handle the special cases where N or M is 1 if N == 1 or M == 1: maxCoins = (N * M) * min(X, Y) return maxCoins # Calculate the maximum number of coins based on the position on the board diagonalSize = X if X <= Y else Y maxCoins = diagonalSize for i in range(2, N + 1): for j in range(2, M + 1): if (i % 2 == 0 and j % 2 == 0) or (i % 2 != 0 and j % 2 != 0): maxCoins += diagonalSize else: maxCoins += X if X <= Y else Y return maxCoins # Get input in a single line N, M, X, Y = map(int, input().split()) result = maxCoins(N, M, X, Y) print(result) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 353. QUESTION NO : 34 You will be given a String 's' of length, 'n' and you need to find out the two longest non-intersecting subsequences of the given string ‘S’which are anagrams to each other. Formally, you need to find out two subsequences from the given string such that the last index of the first subsequence is less than the first index of second subsequence and they are anagrams to each other. Anagram Strings: Two strings are anagrams of each other if they are of the same length and each character appears in both of them the same number of times. For e.g., “time” and “mite” are anagrams. Subsequence: Any string that can be obtained by deleting zero or more characters from a given string keeping the order of characters the same. For example S =“aaababcd” Subsequences "aab" (0,1,3) and "aab" (2,4,5) are invalid. They a are anagrams but they are intersecting (i.e., the last index of first subsequence {3} is greater than the first Index of second Subsequence {2}).
  • 354. QUESTION NO : 34 Subsequences "ab" {0.3} and "ab" {4,5} are valid. They are anagrams as well as not intersecting. You need to find out the longest such subsequence. Have a look at explanations of sample examples for better understanding. String's will contain only the English lowercase letters (a-z). Example 1: Input: 11 -> n (length of string) codingisfun -> Sting ‘s’ Output: 2 Explanation: The longest possible subsequences are “in”->{3,4} and “in”->{6,10}. They are anagrams to each other as well as they are non intersecting.
  • 355. QUESTION NO : 34 Example 2: Input: 11 -> n (length of string) maharashtra ->string ‘s’ Output: 4 Explanation: The longest possible sub-sequences are ”ahar”->{1,2,3,4}and ”ahar” {5,7,9,10}. They are anagrams and non intersecting subsequences. : 1<=n<=10000 String S wiConstraintsll only contain English lowercase letters (a-z) without any other symbols.
  • 356. QUESTION NO : 34 The input format for testing: First line: Contains an integer n [length of strings] Second line: Contains string ‘s’ (of length ‘n’) The output format for testing: Output is a single integer denoting the maximum length of the string
  • 357. #include <stdio.h> #include <string.h> int max(int a, int b) { return a > b ? a : b; } int longestAnagramSubsequence(int n, char s[]) { int frequencies[26] = {0}; // Array to store the frequency of each character int dp[26][n + 1]; memset(dp, 0, sizeof(dp)); // Initialize dp array with 0 for (int i = 1; i <= n; i++) { int currChar = s[i - 1] - 'a'; frequencies[currChar]++; for (int j = 0; j < 26; j++) { dp[j][i] = dp[j][i - 1]; // Carry forward the length from previous index if (j == currChar) { 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 358. for (int k = 0; k < j; k++) { if (frequencies[j] - frequencies[k] > 0) { dp[j][i] = max(dp[j][i], dp[k][i - 1] + 1); } } } } } int maxLength = 0; // Find the maximum length among all characters for (int i = 0; i < 26; i++) { maxLength = max(maxLength, dp[i][n]); } return maxLength; } int main() { int n; char s[10001]; 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
  • 359. scanf("%d", &n); scanf("%s", s); int result = longestAnagramSubsequence(n, s); printf("%dn", result); return 0; } 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
  • 360. #include <iostream> #include <cstring> using namespace std; int max(int a, int b) { return a > b ? a : b; } int longestAnagramSubsequence(int n, char s[]) { int frequencies[26] = {0}; // Array to store the frequency of each character int dp[26][n + 1]; // dp[i][j] stores the length of the longest subsequence ending at index j memset(dp, 0, sizeof(dp)); // Initialize dp array with 0 for (int i = 1; i <= n; i++) { int currChar = s[i - 1] - 'a'; frequencies[currChar]++; for (int j = 0; j < 26; j++) { dp[j][i] = dp[j][i - 1]; // Carry forward the length from previous index if (j == currChar) { dp[j][i]++; // Increment the length for the current character 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 361. // Adjust the length based on the frequency of the character for (int k = 0; k < j; k++) { if (frequencies[j] - frequencies[k] > 0) { dp[j][i] = max(dp[j][i], dp[k][i - 1] + 1); } } } } } int maxLength = 0; // Find the maximum length among all characters for (int i = 0; i < 26; i++) { maxLength = max(maxLength, dp[i][n]); } return maxLength; } int main() { int n; 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
  • 362. char s[10001]; cin >> n; cin >> s; int result = longestAnagramSubsequence(n, s); cout << result << endl; return 0; } 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
  • 363. import java.util.Arrays; import java.util.Scanner; public class Main { public static int max(int a, int b) { return a > b ? a : b; } public static int longestAnagramSubsequence(int n, char[] s) { int[] frequencies = new int[26]; // Array to store the frequency of each character int[][] dp = new int[26][n + 1]; // dp[i][j] stores the length of the longest subsequence ending Arrays.fill(frequencies, 0); // Initialize frequencies array as 0 for (int i = 1; i <= n; i++) { int currChar = s[i - 1] - 'a'; frequencies[currChar]++; for (int j = 0; j < 26; j++) { dp[j][i] = dp[j][i - 1]; // Carry forward the length from the previous index if (j == currChar) { 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 364. dp[j][i]++; // Increment the length for the current character // Adjust the length based on the frequency of the character for (int k = 0; k < j; k++) { if (frequencies[j] - frequencies[k] > 0) { dp[j][i] = max(dp[j][i], dp[k][i - 1] + 1); } } } } } int maxLength = 0; // Find the maximum length among all characters for (int i = 0; i < 26; i++) { maxLength = max(maxLength, dp[i][n]); } return maxLength; } public static void main(String[] args) { 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
  • 365. Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); char[] s = scanner.next().toCharArray(); int result = longestAnagramSubsequence(n, s); System.out.println(result); scanner.close(); } } 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
  • 366. def max(a, b): return a if a > b else b def longestAnagramSubsequence(n, s): frequencies = [0] * 26 # Array to store the frequency of each character dp = [[0] * (n + 1) for _ in range(26)] # dp[i] [j] stores the length of the longest subsequence ending at index j with character i for i in range(1, n + 1): currChar = ord(s[i - 1]) - ord('a') frequencies[currChar] += 1 for j in range(26): dp[j][i] = dp[j][i - 1] # Carry forward the length from previous index if j == currChar: dp[j][i] += 1 # Increment the length for the current character # Adjust the length based on the frequency of the character for k in range(j): if frequencies[j] - frequencies[k] > 0: dp[j][i] = max(dp[j][i], dp[k][i - 1] + 1) maxLength = 0 # Find the maximum length among all characters for i in range(26): maxLength = max(maxLength, dp[i][n]) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 367. return maxLength n = int(input()) s = input() result = longestAnagramSubsequence(n, s) print(result) 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
  • 368. QUESTION NO : 35 Rohan was assigned a strange homework. He is always passionate about working on sequences, but this time, he finds things to be a bit messy. So, he called his friend Jack to work with him and solve the sequence problem. So, the problem states that: Consider a sequence S with N elements, all the elements are integer values. Find the number of pairs in the format of (x,y) such that the element ‘x’ has occurred in sequence S, minimum ‘y’ times. And the element ‘y’ has occurred in sequence S minimum ‘x’ times. So, x and y are the elements of S as well. Jack has to find all such combinations and return the total number of such combinations. Let us try to understand it with an example. Consider N=5, and A=[1, 2, 3, 4, 5]
  • 369. QUESTION NO : 35 The number of pairs from the above elements of the sequence can be as follows: (1,1): Can be considered as 1(x) occurred a minimum number of 1(y) number of times. (1,2): Cannot be considered as 1(x) didn’t occur a minimum of 2(y) number of times. (1,3)-(1,4)-(1,5): Similar to (1,2): Cannot be considered. (2,2)- till (2,5): Cannot be considered. We can follow other combinations as well, but none of them follows the above conditions like (1,1). Hence there is only one pair, which follows the rule. Hence the answer is 1. Example 1: Input : 5 -> Input integer, N 1 1 2 2 3 -> Input integer, S[]
  • 370. QUESTION NO : 35 Explanation: We can have the below combination: (1,1): Can be considered as 1(x) occurred a minimum of 1(y) number of times (1,2): Can be considered as 1(x) occurred at minimum of 2(y) number of times, and who has acquired a minimum of 2(y) number if times. Example 2: Input : 5 -> Input integer, N 1 2 3 4 5 ->Input integer, S[] Output : 1 -> output Explanation: In this scenario, as explained in the demo example we have only 1 pair that matches the criteria hence the answer is 1.
  • 371. QUESTION NO : 35 Constraints: 2<=N<=100000 1<=S[]<=100000 Only positive integer values The input format for testing First input -accept value of integer N Next ‘N’ Lines –Elements of sequence S[] The output format for testing: The output is an integer value as per the above logic. (Check the output in Example 1, Example 2). Additional message in output will cause the failure of test cases. Instructions: System doesn’t allow any kind of hard coded input value or values. Open programme for salaries will be verified against the input which are supplied from the system.
  • 372. #include <stdio.h> #include <stdlib.h> #define MAX_SIZE 100000 // Function to find the number of valid pairs int findValidPairs(int N, int S[]) { int frequency[MAX_SIZE + 1] = {0}; // Array to store the frequency of each ele // Calculate the frequencies of elements for (int i = 0; i < N; i++) { frequency[S[i]]++; } // Find the number of valid pairs int validPairs = 0; for (int i = 0; i < N; i++) { int x = S[i]; int y = frequency[x]; if (y >= x) { validPairs++; } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 373. } return validPairs; } int main() { int N; scanf("%d", &N); int S[MAX_SIZE]; for (int i = 0; i < N; i++) { scanf("%d", &S[i]); } int result = findValidPairs(N, S); printf("%dn", result); return 0; } 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
  • 374. #include <iostream> using namespace std; #define MAX_SIZE 100000 // Function to find the number of valid pairs int findValidPairs(int N, int S[]) { int frequency[MAX_SIZE + 1] = {0}; // Calculate the frequencies of elements for (int i = 0; i < N; i++) { frequency[S[i]]++; } // Find the number of valid pairs int validPairs = 0; for (int i = 0; i < N; i++) { int x = S[i]; int y = frequency[x]; if (y >= x) { validPairs++; } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 375. } return validPairs; } int main() { int N; cin >> N; int S[MAX_SIZE]; for (int i = 0; i < N; i++) { cin >> S[i]; } int result = findValidPairs(N, S); cout << result; return 0; } 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
  • 376. import java.util.Scanner; public class Main { public static final int MAX_SIZE = 100000; // Function to find the number of valid pairs public static int findValidPairs(int N, int[] S) { int[] frequency = new int[MAX_SIZE + 1]; // Calculate the frequencies of elements for (int i = 0; i < N; i++) { frequency[S[i]]++; } // Find the number of valid pairs int validPairs = 0; for (int i = 0; i < N; i++) { int x = S[i]; int y = frequency[x]; if (y >= x) { validPairs++; 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 377. } } return validPairs; } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int N = scanner.nextInt(); int[] S = new int[MAX_SIZE]; for (int i = 0; i < N; i++) { S[i] = scanner.nextInt(); } int result = findValidPairs(N, S); System.out.println(result); } } 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
  • 378. # Function to find the number of valid pairs def findValidPairs(N, S): frequency = [0] * (MAX_SIZE + 1) # Calculate the frequencies of elements for i in range(N): frequency[S[i]] += 1 # Find the number of valid pairs validPairs = 0 for i in range(N): x = S[i] y = frequency[x] if y >= x: validPairs += 1 return validPairs MAX_SIZE = 100000 N = int(input()) S = list(map(int, input().split())) result = findValidPairs(N, S) print(result) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 379. QUESTION NO : 36 Rohan went to a gold showroom. All the jewellery is tagged with an index on it. The indices are integers from 1 to N. He wanted to two items of jewellery for his wife. When asked for a discount on jewellery items, the store manager who is retired mathematics professor replied with an unusual response: The discount will be the number of all those elements falling between the indices (inclusive of both) of 2 items which have a prime number of divisors. Assuming that Rohan will buy 2 different pieces of jewellery, which is present at index ‘i’ and ‘j’, respectively. Find the discount percentage he will receive from the jewellery store. Input is the two indices of the respective jewellery items. Output is the integer value; which Rohan is going to receive as a discount. Let to try to understand it with an example. Let’s say Rohan picked 2 items that are present at index 10 and 15 respectively. This M means I = 10 and J = 15.
  • 380. QUESTION NO : 36 Now let us check the number of divisors for each number from 10 to 15: 10:Number of divisors are 1,2,5, and 10, total 4, and 4 is not prime. Excluded. 11 : Number of divisors are 1 and 11, total 2, 2 is prime. Included. 12 : Number of divisors are 1,2,3,4,6 and 12, total 6, 6 is not prime. Excluded. 13 : Number of divisors are 1 and 13, total 2, 2 is prime. Included. 14 : Number of divisors are 1,2,7 and 14, total 4, 4 is not prime. Excluded. 15 : Number of divisors are 1,3,5 and 15, total 4, 4 is not prime. Excluded. So, the total number of elements with a prime number of divisors is only 2 between 10 and 15. Hence the answer is 2. Example 1: Input : 10 -> Input integer, I 16 -> Input integer, j Output : 3-> output
  • 381. QUESTION NO : 36 Explanation: In the abo scenario let’s check the number of divisors for each number from 10 to 16. 10: Number of divisors are 1,2,5 and 10. Total 4 and 4 is not prime. Excluded 11: Number of divisors are 1 and 11. Total 2 and 2 is prime. Included 10: Number of divisors are 1,2,3,4,6 and 12. Total 5 and 5 is not prime. Excluded 13: Number of divisors are 1 and 13. Total 2 and 2 is prime. Included 14: Number of divisors are 1,2,7 and 14. Total 4 and 4 is not prime. Excluded 15: Number of divisors are 1,3,5 and 15. Total 4 and 4 is not prime. Excluded •Example 2: •Input : •32 -> Input integer, I •40 -> Input integer, j •Output : •1 -> output
  • 382. QUESTION NO : 36 Explanation:In the abo scenario let’s check the number of divisors for each number from 32 to 40. 32: Number of divisors are 1,2,4,8,16 and 32. Total 6 and 6 is not prime. Excluded 33: Number of divisors are 1,3,11 and 33. Total 4 and 4 is not prime. Excluded 34: Number of divisors are 1,2,17 and 34. Total 4 and 4 is not prime. Excluded 35: Number of divisors are 1,5,7 and 35. Total 4 and 4 is not prime. Excluded 36: Number of divisors are 1,2,3,4,6,9,12,18 and 36. Total 9 and 9 is not prime.Excluded 37: Number of divisors are 1 and 37. Total 2 and 2 is prime. Included. 38: Number of divisors are 1,2,19 and 38. Total 4 and 4 is not prime. Excluded 39: Number of divisors are 1,3,13 and 39. Total 4 and 4 is not prime. Excluded
  • 383. QUESTION NO : 36 Constraints: •1<=i<j<=100000 •Only integers The candidate has to write the court to accept 2 inputs: First input accept value of integer Second input accept value of integer. Instructions: •System does not allow any kind of hard coded input value/values. •Return programme code by the candidate will be verified against the inputs which are supplied from the system
  • 384. #include <stdio.h> #include <math.h> int isPrime(int n) { if (n <= 1) { return 0; } for (int i = 2; i * i <= n; i++) { if (n % i == 0) { return 0; } } return 1; } int calculateDiscount(int i, int j) { int count = 0; for (int num = i; num <= j; num++) { 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 385. int divisors = 0; for (int divisor = 1; divisor <= num; divisor++) { if (num % divisor == 0) { divisors++; } } if (isPrime(divisors)) { count++; } } return count; } int main() { int i, j; scanf("%d %d", &i, &j); int discount = calculateDiscount(i, j); printf("%dn", discount); return 0; } 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
  • 386. #include <iostream> #include <cmath> using namespace std; int isPrime(int n) { if (n <= 1) { return 0; } for (int i = 2; i * i <= n; i++) { if (n % i == 0) { return 0; } } return 1; } int calculateDiscount(int i, int j) { int count = 0; for (int num = i; num <= j; num++) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 387. { int divisors = 0; for (int divisor = 1; divisor <= num; divisor++) { if (num % divisor == 0) { divisors++; } } if (isPrime(divisors)) { count++; }} return count; } int main() { int i, j; cin >> i >> j; int discount = calculateDiscount(i, j); cout << discount; return 0; } 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
  • 388. import java.util.Scanner; public class Main { public static int isPrime(int n) { if (n <= 1) { return 0; } for (int i = 2; i * i <= n; i++) { if (n % i == 0) { return 0; } } return 1; } public static int calculateDiscount(int i, int j) { int count = 0; for (int num = i; num <= j; num++) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 389. { int divisors = 0; for (int divisor = 1; divisor <= num; divisor++) { if (num % divisor == 0) { divisors++; } } if (isPrime(divisors) == 1) { count++; } } return count; } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int i = scanner.nextInt(); int j = scanner.nextInt(); int discount = calculateDiscount(i, j); 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
  • 391. def isPrime(n): if n <= 1: return 0 for i in range(2, int(n**0.5) + 1): if n % i == 0: return 0 return 1 def calculateDiscount(i, j): count = 0 for num in range(i, j + 1): divisors = 0 for divisor in range(1, num + 1): if num % divisor == 0: divisors += 1 if isPrime(divisors) == 1: count += 1 return count i = int(input()) j=int(input()) discount = calculateDiscount(i, j) print(discount) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 392. QUESTION NO : 37 You are given an Array ‘Arr’ of ‘N’ positive integers. You need to convert the given array ‘Arr’ to Zero-Array. An Array ‘A’ is know as Zero-Array if the bitwise AND (&) of all the elements of the array is Zero. In other words, Array ‘A’ with length ‘L’ is known as Zero –Array if A[0] & A[1] & A[2]………& A[L] = 0. For example array [1,2,3]is a Zero-Array, you can perform the following move any number of times: •Choose any array elements from Array ‘Arr’, say Arr[i], and flip exactly one bit in Arr[i] (Flipping a bit means if the bit is 1 then covert it to 0 and if the bit is 0 then convert it to 1) •You need to find the minimum number of moves to convert the given array ‘Arr’ to Zero-Array .
  • 393. QUESTION NO : 37 The input format for testing First Line Contains a positive Integer N (Size of the array) Next Line Contains N space-separated positive integers The Output format for testing: The output is an integer value as per above logic. (Check the output in Example 1, Example 2). Additional messages in output will cause the failure of test cases. Constraints: N==Length of Array ‘Arr’ 1<=N<= 1000 1<=Arr[i]<= 10000, for all valid (0 <=i<=N-1)
  • 394. QUESTION NO : 37 Example 1: Input: 5 -> N (size of the array) 10 11 13 5 3 -> Array ‘Arr’ (Elements of the array will be space separated Output: 0 Explanation: The given array is already a zero Array since 10 & 11 & 13 & 5 & 3 = 0. So,minimum number of moves required are 0.
  • 395. #include <stdio.h> int main() { int N; scanf("%d", &N); // Read the size of the array int Arr[N]; for (int i = 0; i < N; i++) { scanf("%d", &Arr[i]); // Read the elements of the array } int minMoves = 0; int bitwiseAnd = Arr[0]; // Initialize the bitwise AND with the first element // Calculate the bitwise AND of all elements in the array for (int i = 1; i < N; i++) { bitwiseAnd &= Arr[i]; } // Count the number of set bits in the bitwise AND while (bitwiseAnd != 0) { if (bitwiseAnd & 1) { 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 396. minMoves++; } bitwiseAnd >>= 1; } printf("%dn", minMoves); // Print the minimum number of moves return 0; } 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
  • 397. #include <iostream> using namespace std; int main() { int N; cin >> N; // Read the size of the array int Arr[N]; for (int i = 0; i < N; i++) { cin >> Arr[i]; // Read the elements of the array } int minMoves = 0; int bitwiseAnd = Arr[0]; // Initialize the bitwise AND with the first element // Calculate the bitwise AND of all elements in the array for (int i = 1; i < N; i++) { bitwiseAnd &= Arr[i]; } // Count the number of set bits in the bitwise AND while (bitwiseAnd != 0) { if (bitwiseAnd & 1) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 398. { minMoves++; } bitwiseAnd >>= 1; } cout << minMoves; // Print the minimum number of moves return 0; } 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
  • 399. import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int N = scanner.nextInt(); // Read the size of the array int[] Arr = new int[N]; for (int i = 0; i < N; i++) { Arr[i] = scanner.nextInt(); // Read the elements of the array } int minMoves = 0; int bitwiseAnd = Arr[0]; // Calculate the bitwise AND of all elements in the array for (int i = 1; i < N; i++) { bitwiseAnd &= Arr[i]; } // Count the number of set bits in the bitwise AND while (bitwiseAnd != 0) { 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 400. if ((bitwiseAnd & 1) == 1) { minMoves++; } bitwiseAnd >>= 1; } System.out.println(minMoves); // Print the minimum number of moves } } 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
  • 401. N = int(input()) # Read the size of the array Arr = list(map(int, input().split())) # Read the elements of the array minMoves = 0 bitwiseAnd = Arr[0] # Initialize the bitwise AND with the first element # Calculate the bitwise AND of all elements in the array for i in range(1, N): bitwiseAnd &= Arr[i] # Count the number of set bits in the bitwise AND while bitwiseAnd != 0: if bitwiseAnd & 1 == 1: minMoves += 1 bitwiseAnd >>= 1 print(minMoves) # Print the minimum number of moves 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 402. QUESTION NO : 38 You are given an Array ‘Arr’ of ‘N’ positive integers. You need to convert the given array ‘Arr’ to Zero-Array. An Array ‘A’ is know as Zero-Array if the bitwise AND (&) of all the elements of the array is Zero. In other words, Array ‘A’ with length ‘L’ is known as Zero –Array if A[0] & A[1] & A[2]………& A[L] = 0. For example array [1,2,3]is a Zero-Array, you can perform the following move any number of times: •Choose any array elements from Array ‘Arr’, say Arr[i], and flip exactly one bit in Arr[i] (Flipping a bit means if the bit is 1 then covert it to 0 and if the bit is 0 then convert it to 1) •You need to find the minimum number of moves to convert the given array ‘Arr’ to Zero-Array .
  • 403. QUESTION NO : 38 The input format for testing First Line Contains a positive Integer N (Size of the array) Next Line Contains N space-separated positive integers The Output format for testing: The output is an integer value as per above logic. (Check the output in Example 1, Example 2). Additional messages in output will cause the failure of test cases. Constraints: N==Length of Array ‘Arr’ 1<=N<= 1000 1<=Arr[i]<= 10000, for all valid (0 <=i<=N-1)
  • 404. QUESTION NO : 38 Example 1: Input: 5 -> N (size of the array) 10 11 13 5 3 -> Array ‘Arr’ (Elements of the array will be space separated Output: 0 Explanation: The given array is already a zero Array since 10 & 11 & 13 & 5 & 3 = 0. So,minimum number of moves required are 0.
  • 405. #include <stdio.h> int main() { int N; scanf("%d", &N); // Read the size of the array int Arr[N]; for (int i = 0; i < N; i++) { scanf("%d", &Arr[i]); // Read the elements of the array } int minMoves = 0; int bitwiseAnd = Arr[0]; // Initialize the bitwise AND with the first element // Calculate the bitwise AND of all elements in the array for (int i = 1; i < N; i++) { bitwiseAnd &= Arr[i]; } // Count the number of set bits in the bitwise AND while (bitwiseAnd != 0) { if (bitwiseAnd & 1) { 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 406. minMoves++; } bitwiseAnd >>= 1; } printf("%dn", minMoves); // Print the minimum number of moves return 0; } 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
  • 407. #include <iostream> using namespace std; int main() { int N; cin >> N; // Read the size of the array int Arr[N]; for (int i = 0; i < N; i++) { cin >> Arr[i]; // Read the elements of the array } int minMoves = 0; int bitwiseAnd = Arr[0]; // Initialize the bitwise AND with the first element // Calculate the bitwise AND of all elements in the array for (int i = 1; i < N; i++) { bitwiseAnd &= Arr[i]; } // Count the number of set bits in the bitwise AND while (bitwiseAnd != 0) { if (bitwiseAnd & 1) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 408. { minMoves++; } bitwiseAnd >>= 1; } cout << minMoves; // Print the minimum number of moves return 0; } 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
  • 409. import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int N = scanner.nextInt(); // Read the size of the array int[] Arr = new int[N]; for (int i = 0; i < N; i++) { Arr[i] = scanner.nextInt(); // Read the elements of the array } int minMoves = 0; int bitwiseAnd = Arr[0]; // Calculate the bitwise AND of all elements in the array for (int i = 1; i < N; i++) { bitwiseAnd &= Arr[i]; } // Count the number of set bits in the bitwise AND while (bitwiseAnd != 0) { 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 410. if ((bitwiseAnd & 1) == 1) { minMoves++; } bitwiseAnd >>= 1; } System.out.println(minMoves); // Print the minimum number of moves } } 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
  • 411. N = int(input()) # Read the size of the array Arr = list(map(int, input().split())) # Read the elements of the array minMoves = 0 bitwiseAnd = Arr[0] # Initialize the bitwise AND with the first element # Calculate the bitwise AND of all elements in the array for i in range(1, N): bitwiseAnd &= Arr[i] # Count the number of set bits in the bitwise AND while bitwiseAnd != 0: if bitwiseAnd & 1 == 1: minMoves += 1 bitwiseAnd >>= 1 print(minMoves) # Print the minimum number of moves 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 412. QUESTION NO : 39 An English teacher wants the overall development of the students. She plans a surprise quiz to test the analytical skills of the students. She gives two words (str1,str2), the task for the students here is: Observe both the words carefully. Change the word1 to word2. The student who can change the words with a minimum number of steps is the winner. Note: Only of the operations – insert, delete or replace can be performed in one step. All the operators should be performed only on word1. The string cannot have any special characters, space or number. Constraints: Str1={a-z) Str1 != (A-Z0-9,special characters) No spaces between characters Size of Str1 and Str2<50
  • 413. QUESTION NO : 39 Input format for testing The candidate has to write the code to accept 2 input(s). First Input - Accept value str1 which is a string. Second Input -Accept value str1 which is a string. Output format for testing The output should be a single integer value or a message if given in the problem statement (Check the output in Example 1. Example 2) Additional messages in output will cause the failure of test cases. Example 1 Input: Capture -> value of str 1 Capsule -> value of str 2 Output: 2-> number of steps required to convert str 1 to str 2
  • 414. QUESTION NO : 39 Explanation: To convert capture to capsule in Step 1: 't' is replaced with ‘s’(capsure) Step 2: 'r' is replaced with ‘l' (capsule) Hence, the output is 2. Example 2 Input: Computer -> value of str 1 Compute -> value of str 2 Output: 1 -> number of steps required to convert computer to compute, Explanation: To convert from computer to compute, in Step 1: ‘r’ is removed (computer) Hence, the output is 1.
  • 415. #include <stdio.h> #include <string.h> int min(int a, int b, int c) { if (a <= b && a <= c) return a; else if (b <= a && b <= c) return b; else return c; } int findMinSteps(char *str1, char *str2) { int m = strlen(str1); int n = strlen(str2); // Create a 2D table to store subproblem results int dp[m+1][n+1]; // Fill the table bottom-up for (int i = 0; i <= m; i++) { for (int j = 0; j <= n; j++) { 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 416. // If str1 is empty, then we need to insert all characters from str2 if (i == 0) dp[i][j] = j; // If str2 is empty, then we need to delete all characters from str1 else if (j == 0) dp[i][j] = i; // If the last characters are the same, no operation needed else if (str1[i-1] == str2[j-1]) dp[i][j] = dp[i-1][j-1]; // If the last characters are different, consider all possibilities else dp[i][j] = 1 + min(dp[i][j-1], dp[i-1][j], dp[i-1][j-1]); } } return dp[m][n]; } int main() { char str1[50], str2[50]; scanf("%s", str1); scanf("%s", str2); int minSteps = findMinSteps(str1, str2); printf("%d",minSteps); return 0; } 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
  • 417. #include <iostream> #include <cstring> using namespace std; int min(int a, int b, int c) { if (a <= b && a <= c) return a; else if (b <= a && b <= c) return b; else return c; } int findMinSteps(const char* str1, const char* str2) { int m = strlen(str1); int n = strlen(str2); // Create a 2D table to store subproblem results int dp[m + 1][n + 1]; // Fill the table bottom-up for (int i = 0; i <= m; i++) { for (int j = 0; j <= n; j++) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 418. { // If str1 is empty, then we need to insert all characters from str2 if (i == 0) dp[i][j] = j; // If str2 is empty, then we need to delete all characters from str1 else if (j == 0) dp[i][j] = i; // If the last characters are the same, no operation needed else if (str1[i - 1] == str2[j - 1]) dp[i][j] = dp[i - 1][j - 1]; // If the last characters are different, consider all possibilities else dp[i][j] = 1 + min(dp[i][j - 1], dp[i - 1][j], dp[i - 1][j - 1]); } } return dp[m][n]; } int main() { char str1[50], str2[50]; cin >> str1 >> str2; int minSteps = findMinSteps(str1, str2); 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
  • 419. cout << minSteps; return 0; } 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
  • 420. import java.util.Scanner; public class Main { public static int min(int a, int b, int c) { if (a <= b && a <= c) return a; else if (b <= a && b <= c) return b; else return c; } public static int findMinSteps(String str1, String str2) { int m = str1.length(); int n = str2.length(); // Create a 2D table to store subproblem results int[][] dp = new int[m + 1][n + 1]; // Fill the table bottom-up for (int i = 0; i <= m; i++) { for (int j = 0; j <= n; j++) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 421. { // If str1 is empty, then we need to insert all characters from str2 if (i == 0) dp[i][j] = j; // If str2 is empty, then we need to delete all characters from str1 else if (j == 0) dp[i][j] = i; // If the last characters are the same, no operation needed else if (str1.charAt(i - 1) == str2.charAt(j - 1)) dp[i][j] = dp[i - 1][j - 1]; // If the last characters are different, consider all possibilities else dp[i][j] = 1 + min(dp[i][j - 1], dp[i - 1][j], dp[i - 1][j - 1]); } } return dp[m][n]; } public static void main(String[] args) 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
  • 422. int minSteps = findMinSteps(str1, str2); System.out.println(minSteps); } } 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
  • 423. def min(a, b, c): if a <= b and a <= c: return a elif b <= a and b <= c: return b else: return c def findMinSteps(str1, str2): m = len(str1) n = len(str2) # Create a 2D table to store subproblem results dp = [[0] * (n + 1) for _ in range(m + 1)] # Fill the table bottom-up for i in range(m + 1): for j in range(n + 1): # If str1 is empty, then we need to insert all characters from str2 if i == 0: dp[i][j] = j # If str2 is empty, then we need to delete all characters from str1 elif j == 0: dp[i][j] = i # If the last characters are the same, no operation needed 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 424. elif str1[i - 1] == str2[j - 1]: dp[i][j] = dp[i - 1][j - 1] # If the last characters are different, consider all possibilities else: dp[i][j] = 1 + min(dp[i][j - 1], dp[i - 1][j], dp[i - 1][j - 1]) return dp[m][n] str1 = input() str2 = input() minSteps = findMinSteps(str1, str2) print(minSteps) 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
  • 425. QUESTION NO : 40 A single currency note(N) and a coin(R) are given. The task is to fight in how many ways can make the value that is equal to the currency note using the coin.The coin can be used in the following ways: The value of the coin represents the maximum range values(1,R) that can be used to make the sum equal to N. Each integer value up to the range C can be used multiple times to make the sum. Constraints: 1< =N<=100 1<=R <=100 The Input format for testing •The candidate has to write the code to accept 2 input(s) •First Input - Accept value for input string. •First Input - Accept value for input key.
  • 426. QUESTION NO : 40 The Output format for testing •The output should be a sorted string based on the input key given by the user as mentioned in the above criteria. (Check the output in Example 1, Example 2) •Additional messages in output will cause the failure of test cases. Example 1: Input: 8 -> Value of N 2 -> Value of R Output: 5 Maximum combinations using values up to R to get the sum equal to N →
  • 427. QUESTION NO : 40 Explanation: The various combinations the currency note N=8 can be formed using the values upto range 2 are: 1+1+1+1+1+1+1+1=8 2+1+1+1+1+1+1=8 2+2+1+1+1+1=8 2+2+2+1+1=8 2+2+2+2=8 Hence there are 5 ways the coin with range up to 2 can be used to get the value of currency note i.e 8
  • 428. QUESTION NO : 40 Example 2: Input: 2 -> Value of N 2-> Value of R Output: 2 Maximum combinations using values up to R to get the sum equal to N → Explanation: The various combinations the currency note N=2 can be formed using the values upto range 2 are: R={1,2} 1+1=2 Hence there are 2 ways the coin with range up to 2 can be used to get the value of currency note i.e 2
  • 429. #include <stdio.h> int findCombinations(int N, int R) { int dp[101] = {0}; // Dynamic programming array dp[0] = 1; // Base case for (int i = 1; i <= R; i++) { for (int j = i; j <= N; j++) { dp[j] += dp[j - i]; a } } return dp[N]; } int main() { int N, R; scanf("%d", &N); scanf("%d", &R); int combinations = findCombinations(N, R); printf("%d", combinations); return 0; } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 430. #include <iostream> using namespace std; int findCombinations(int N, int R) { int dp[101] = {0}; // Dynamic programming array dp[0] = 1; // Base case for (int i = 1; i <= R; i++) { for (int j = i; j <= N; j++) { dp[j] += dp[j -i]; } } return dp[N]; } int main() { int N, R; cin >> N >> R; int combinations = findCombinations(N, R); cout << combinations; return 0; } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 431. import java.util.Scanner; public class Main { public static int findCombinations(int N, int R) { int[] dp = new int[101]; // Dynamic programming array dp[0] = 1; // Base case for (int i = 1; i <= R; i++) { for (int j = i; j <= N; j++) { dp[j] += dp[j - i]; } } return dp[N]; } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int N = scanner.nextInt(); int R = scanner.nextInt(); int combinations = findCombinations(N, R); System.out.println(combinations); }} 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 432. def findCombinations(N, R): dp = [0] * (N + 1) # Dynamic programming array dp[0] = 1 # Base case for i in range(1, R + 1): for j in range(i, N + 1): dp[j] += dp[j - i] # Calculate combinations using values up to range R return dp[N] N = int(input()) R = int(input()) combinations = findCombinations(N, R) print(combinations) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 434. QUESTION NO : 41 Given N stones, each stone has some weight assigned to it. A box with C capacity is also given. The task is to find out, the minimum number po/boxes which are e require the box. Note: C>Arr[0] to Arr[N], where Arr[i] represents the weight of ith stone. Example 1: Input: 5 -> Value of N 10 20 30 40 50 -> Element of Arr[] 60 -> Value of C Output: 3 ->Minimum 3 boxes required. Explanation: Arr[]={10,20,30,40,50} and C-60 1st box={10,20,30} 2nd box=(40)
  • 435. QUESTION NO : 41 Constraints: 1<N<=100 1<=Arr[i]<=100 Arr[i]<C<=200 Example 2: Input: 4 -> Value of N 10 20 30 30 -> Element of Arr[] 80 -> Value of C Output: 2 -> Minimum 2 boxes required.
  • 436. #include <iostream> using namespace std; int minBoxesRequired(int n, int arr[], int c) { int boxes = 0; int currentCapacity = c; for (int i = 0; i < n; i++) { if (arr[i] <= currentCapacity) { currentCapacity -= arr[i]; } else { boxes++; currentCapacity = c - arr[i]; } } if (currentCapacity < c) boxes++; return boxes; } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 437. int main() { int n; cin >> n; int arr[n]; for (int i = 0; i < n; i++) { cin >> arr[i]; } int c; cin >> c; int minBoxes = minBoxesRequired(n, arr, c); cout << minBoxes; return 0; } 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
  • 438. #include<stdio.h> int minBoxesRequired(int n, int arr[], int c) { int boxes = 0; int currentCapacity = c; for (int i = 0; i < n; i++) { if (arr[i] <= currentCapacity) { currentCapacity -= arr[i]; } else { boxes++; currentCapacity = c - arr[i]; } } if (currentCapacity < c) boxes++; return boxes; } int main() 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 439. { int n; scanf("%d", &n); int arr[n]; for (int i = 0; i < n; i++) { scanf("%d", &arr[i]); } int c; scanf("%d", &c); int minBoxes = minBoxesRequired(n, arr, c); printf("%d", minBoxes); return 0; } 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
  • 440. import java.util.Scanner; public class Main { public static int minBoxesRequired(int n, int[] arr, int c) { int boxes = 0; int currentCapacity = c; for (int i = 0; i < n; i++) { if (arr[i] <= currentCapacity) { currentCapacity -= arr[i]; } else { boxes++; currentCapacity = c - arr[i]; } } if (currentCapacity < c) boxes++; return boxes; 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 441. } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); int[] arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = scanner.nextInt(); } int c = scanner.nextInt(); int minBoxes = minBoxesRequired(n, arr, c); System.out.println(minBoxes); scanner.close(); } } 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
  • 442. def min_boxes_required(n, arr, c): boxes = 0 current_capacity = c for i in range(n): if arr[i] <= current_capacity: current_capacity -= arr[i] else: boxes += 1 current_capacity = c - arr[i] if current_capacity < c: boxes += 1 return boxes n = int(input()) arr = list(map(int, input().split())) c = int(input()) min_boxes = min_boxes_required(n, arr, c) print(min_boxes) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 443. QUESTION NO : 42 Given a string Str, which contains numbers (0 to 9)and also letters of the English and to 'Z'). The task is to reverse string the string in such a way that the positiors of numbers in the string are left unaltered. Example 1: Input: a1b2igh3 -> Value of Str Output: h1g2iba3 Explanation: Without changing the positions of 1, 2 and 3, only the positions of characters 'h', 'g, "i', 'b' and 'a' have been reversed.
  • 444. QUESTION NO : 42 Example 2: Input: Ab5c7de96 -> Value of Str Output: ed5c7bA96
  • 445. #include <stdio.h> #include <ctype.h> void reverseString(char str[]) { int len = 0; while (str[len] != '0') { len++; } int start = 0; int end = len - 1; while (start < end) { // Skip numbers in the string while (isdigit(str[start])) { start++; } while (isdigit(str[end])) { end--; } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 446. // Swap characters char temp = str[start]; str[start] = str[end]; str[end] = temp; start++; end--; } } int main() { char str[100]; scanf("%s", str); reverseString(str); printf("%s", str); return 0; } 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
  • 447. #include <iostream> #include <cctype> using namespace std; void reverseString(char str[]) { int len = 0; while (str[len] != '0') { len++; } int start = 0; int end = len - 1; while (start < end) { // Skip numbers in the string while (isdigit(str[start])) { start++; } while (isdigit(str[end])) { end--; 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 448. } // Swap characters char temp = str[start]; str[start] = str[end]; str[end] = temp; start++; end--; } } int main() { char str[100]; cin >> str; reverseString(str); cout << str; return 0; } 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
  • 449. import java.util.Scanner; public class Main { public static void reverseString(char[] str) { int len = str.length; int start = 0; int end = len - 1; while (start < end) { // Skip numbers in the string while (Character.isDigit(str[start])) { start++; } while (Character.isDigit(str[end])) { end--; } // Swap characters char temp = str[start]; str[start] = str[end]; 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 450. str[end] = temp; start++; end--; } } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); String input = scanner.nextLine(); char[] str = input.toCharArray(); reverseString(str); System.out.println(str); scanner.close(); } } 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
  • 451. def reverseString(str): start = 0 end = len(str) - 1 while start < end: # Skip numbers in the string while str[start].isdigit(): start += 1 while str[end].isdigit(): end -= 1 # Swap characters str[start], str[end] = str[end], str[start] start += 1 end -= 1 # Main function input_str = input() str_list = list(input_str) reverseString(str_list) print("".join(str_list)) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 452. QUESTION NO : 43 A thief pretending to be a customer entered a jewellery store. On the same night, he planned a burglary. There is 'N' number of items with their (a[]) on display boards. The thief scans through the prices of all the items. The task here is to find the most valuable (costliest) items of jewellery to steal. Example 1: Input: 8 Value of N → 102 101 5 7 99 1 2 3 a[], Elements a[0]to a[N- 1], where input each element is → seperated by a new line Output: 111 Number of elements whose adjacent elements are greater →
  • 453. QUESTION NO : 43 Explanation: Starting from the first element we create subarrays of elements which are in ascending order. a[0]>a[1] Subarray 1: {102} a[1]>a[2] Subarray 2: {101} a[2]<a[3] In this case,we will continue to compare with next element until we find a greater number. a[3]<a[4],continue a[4]>a[5],stop and create sub array Subarray 3: {5,7,99} a[5]>a[6],continue a[6]>a[7],end of array
  • 454. QUESTION NO : 43 Subarray 4:{1,2,3} Summing up prices of each subarray: above,we can deduce the sub array 3 has the most valuable items. Hence the output is 111. Example 2: Input: 5 Value of N → 10 20 30 40 50 a[], Elements a[0]to a[N- 1], where input each element is → seperated by a new line Output: 150 Number of elements whose adjacent elements are greater →
  • 455. #include <stdio.h> int countValuableItems(int a[], int N) { int count = 0; int maxSum = 0; int currentSum = 0; for (int i = 0; i < N - 1; i++) { if (a[i] < a[i + 1]) { currentSum += a[i]; count++; } else { currentSum += a[i]; if (currentSum > maxSum) { maxSum = currentSum; } currentSum = 0; } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 456. } // Check if the last element is part of a valuable item if (a[N - 2] < a[N - 1]) { currentSum += a[N - 1]; count++; } if (currentSum > maxSum) { maxSum = currentSum; } return maxSum; } int main() { int N; scanf("%d", &N); int a[N]; for (int i = 0; i < N; i++) { scanf("%d", &a[i]); } 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
  • 457. int result = countValuableItems(a, N); printf("%dn", result); return 0; } 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
  • 458. #include <iostream> using namespace std; int countValuableItems(int a[], int N) { int count = 0; int maxSum = 0; int currentSum = 0; for (int i = 0; i < N - 1; i++) { if (a[i] < a[i + 1]) { currentSum += a[i]; count++; } else { currentSum += a[i]; maxSum = max(maxSum, currentSum); currentSum = 0; } } // Check if the last element is part of a valuable item 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 459. if (a[N - 2] < a[N - 1]) { currentSum += a[N - 1]; count++; } maxSum = max(maxSum, currentSum); return maxSum; } int main() { int N; cin >> N; int a[N]; for (int i = 0; i < N; i++) { cin >> a[i]; } int result = countValuableItems(a, N); cout <<result << endl; return 0; } 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
  • 460. import java.util.Scanner; public class Main { public static int countValuableItems(int[] a, int N) { int count = 0; int maxSum = 0; int currentSum = 0; for (int i = 0; i < N - 1; i++) { if (a[i] < a[i + 1]) { currentSum += a[i]; count++; } else { currentSum += a[i]; if (currentSum > maxSum) { maxSum = currentSum; } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 461. currentSum = 0; } } // Check if the last element is part of a valuable item if (a[N - 2] < a[N - 1]) { currentSum += a[N - 1]; count++; } if (currentSum > maxSum) { maxSum = currentSum; } return maxSum; } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int N = scanner.nextInt(); int[] a = new int[N]; for (int i = 0; i < N; i++) { 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
  • 462. a[i] = scanner.nextInt(); } int result = countValuableItems(a, N); System.out.println(result); } } 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
  • 463. def countValuableItems(a, N): count = 0 maxSum = 0 currentSum = 0 for i in range(N - 1): if a[i] < a[i + 1]: currentSum += a[i] count += 1 else: currentSum += a[i] if currentSum > maxSum: maxSum = currentSum currentSum = 0 # Check if the last element is part of a valuable item if a[N - 2] < a[N - 1]: currentSum += a[N - 1] count += 1 if currentSum > maxSum: maxSum = currentSum return maxSum N = int(input()) a = list(map(int, input().split())) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 464. result = countValuableItems(a, N) print(result) 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
  • 465. QUESTION NO : 44 An automation company is about to launch its beta version of automatic doors for the home. Before using voice assistant or Smartphone control, they build a remote control to operate the doors. Due to technical wirework issues, the automation process isn't operating correctly. Assume, there are an N number of doors in a home. It so happens that if one door is opened/closed using a remote control, all the doors in the following indexes will also change their state. i.e. if the initial state of a door(a[0]) is open(1), on pressing the open button on the remote control, all the doors(a[1],a[2],a[3]........) change their state. Initially, the state of each whether doors open close (0) is given as array elements. The task hereis to find the LEAST number of times the button (On/Off) on the remote control has to be used such that all the doors are opened. Note: The On/Off button for each door can be pressed multiple times.
  • 466. QUESTION NO : 44 Example 1: Input: 5 -> value of N (1,0,1,1,1] a[], Element of a[0]to a[N-1],While → Input each element is separated by new line Output: 2 Least count of button press → Explanation: a0=[1,0,1,1,1] Press button 1: [1,1,0,0,0] Press button 2: [1,1,1,1,1] Hence, Least 2 button press required to open the all doors
  • 467. #include <stdio.h> int findLeastButtonPress(int doors[], int n) { int count = 0; int i, j; // Iterate over the doors for (i = 0; i < n; i++) { // If the current door is closed (0), press the button if (doors[i] == 0) { count++; // Change the state of all following doors for (j = i; j < n; j++) { doors[j] = 1 - doors[j]; } } } return count; } int main() 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 468. { int N; scanf("%d", &N); int doors[N]; int i; for (i = 0; i < N; i++) { scanf("%d", &doors[i]); } int result = findLeastButtonPress(doors, N); printf("%dn", result); return 0; } 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
  • 469. #include <iostream> #include <vector> using namespace std; int findLeastButtonPress(vector<int>& doors) { int n = doors.size(); int count = 0; // Iterate over the doors for (int i = 0; i < n; i++) { // If the current door is closed (0), press the button if (doors[i] == 0) { count++; // Change the state of all following doors for (int j = i; j < n; j++) { doors[j] = 1 - doors[j]; } } } return count; 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 470. } int main() { int N; cin >> N; vector<int> doors(N); for (int i = 0; i < N; i++) { cin >> doors[i]; } int result = findLeastButtonPress(doors); cout << result << endl; return 0; } 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
  • 471. import java.util.Scanner; public class Main { public static int findLeastButtonPress(int[] doors, int n) { int count = 0; // Iterate over the doors for (int i = 0; i < n; i++) { // If the current door is closed (0), press the button if (doors[i] == 0) { count++; // Change the state of all following doors for (int j = i; j < n; j++) { doors[j] = 1 - doors[j]; } } } return count; } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 472. public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int N = scanner.nextInt(); int[] doors = new int[N]; for (int i = 0; i < N; i++) { doors[i] = scanner.nextInt(); } int result = findLeastButtonPress(doors, N); System.out.println(result); } } 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
  • 473. def findLeastButtonPress(doors, n): count = 0 # Iterate over the doors for i in range(n): # If the current door is closed (0), press the button if doors[i] == 0: count += 1 # Change the state of all following doors for j in range(i, n): doors[j] = 1 - doors[j] return count # Main function N = int(input()) doors = list(map(int, input().split())) result = findLeastButtonPress(doors, N) print(result) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 474. QUESTION NO : 45 A safety and security services agency communicates to its employees only in secret messages in case of emergency. The employee sends the message with a secret code(key). Here, the code will be same combination of characters in both the messages(strings) sent. The task is to find the combination of letters(key) that is present both the strings. Input format for testing: The candidate has to write the code to accept 2 inputs. First Input- Accept a string value consisting of only literal characters. Second Input-Accept a string value consisting of only characters. Output format for testing: The output should be string of characters which is same in both the input strings (check the output in Example 1 and 2) The output should be generated in alphabetic order sequence. Additional message in output cause the failure of test cases.
  • 475. QUESTION NO : 45 Constraints: Str 1= {a-z} Str 2= {a-z} 0<size of str 1 <20 0< size of str 2 <20 Example1: Input: beads -> value for str1 leaps value for str2 → Output: aes -> the key ‘aes’ is present in both strings
  • 476. QUESTION NO : 45 Example2: Input: abcdefgh -> value for str1 abcdxyz value for str2 → Output: abcd –> key ‘abcd’ is present in both the strings
  • 477. #include <stdio.h> #include <string.h> char* findCommonKey(const char* str1, const char* str2) { static char commonKey[20]; int count1[26] = {0}; int count2[26] = {0}; int len1 = strlen(str1); int len2 = strlen(str2); for (int i = 0; i < len1; i++) { count1[str1[i] - 'a']++; } for (int i = 0; i < len2; i++) { count2[str2[i] - 'a']++; } int index = 0; for (int i = 0; i < 26; i++) { int minCount = (count1[i] < count2[i]) ? count1[i] : count2[i]; for (int j = 0; j < minCount; j++) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 478. { commonKey[index++] = 'a' + i; } } commonKey[index] = '0'; return commonKey; } int main() { char str1[20], str2[20]; scanf("%s %s", str1, str2); char* commonKey = findCommonKey(str1, str2); printf("%sn", commonKey); return 0; } 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
  • 479. #include <iostream> #include <string> using namespace std; string findCommonKey(const string& str1, const string& str2) { string commonKey; int count1[26] = {0}; int count2[26] = {0}; for (char ch : str1) { count1[ch - 'a']++; } for (char ch : str2) { count2[ch - 'a']++; } for (int i = 0; i < 26; i++) { int minCount = min(count1[i], count2[i]); for (int j = 0; j < minCount; j++) { commonKey += 'a' + i; 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 480. } } return commonKey; } int main() { string str1, str2; cin >> str1 >> str2; string commonKey = findCommonKey(str1, str2); cout << commonKey << endl; return 0; } 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
  • 481. import java.util.Scanner; public class Main { public static String findCommonKey(String str1, String str2) { StringBuilder commonKey = new StringBuilder(); int[] count1 = new int[26]; int[] count2 = new int[26]; for (char ch : str1.toCharArray()) { count1[ch - 'a']++; } for (char ch : str2.toCharArray()) { count2[ch - 'a']++; } for (int i = 0; i < 26; i++) { int minCount = Math.min(count1[i], count2[i]); for (int j = 0; j < minCount; j++) { commonKey.append((char)('a' + i)); 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 482. } } return commonKey.toString(); } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); String str1 = scanner.nextLine(); String str2 = scanner.nextLine(); String commonKey = findCommonKey(str1, str2); System.out.println(commonKey); } } 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
  • 483. def find_common_key(str1, str2): common_key = "" count1 = [0] * 26 count2 = [0] * 26 for ch in str1: count1[ord(ch) - ord('a')] += 1 for ch in str2: count2[ord(ch) - ord('a')] += 1 for i in range(26): min_count = min(count1[i], count2[i]) common_key += chr(ord('a') + i) * min_count return common_key str1 = input() str2 = input() common_key = find_common_key(str1, str2) print(common_key) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 484. QUESTION NO : 46 An upmarket housing society has N number of row houtes The electrical boards of all the houses are connected through common wiring. Due to the faulty wiring system a major fire broke out and all the houses are in the grave danger. The fire brigade has arrived and they have started evacuating people from their houses.The number of people in each house depicts the elements of array(a[]).the task here is to find the number of steps that the fire fighters Will require to evacuate members the houses in the following manner – 1.evacuate the house with the largest number of members(L) 2.Next,clear all the houses to the right of the house 1 3.Repeat step 1 and step 2. 4.The task is complete when all the members are evacuated.
  • 485. QUESTION NO : 46 Example 1: Input: 5 -> value of N 10 5 15 6 25-> a[],Elements a[0] to a[N-1] ,where input of each element is seperated by a new line. Output: 3 -> value of S
  • 486. #include <stdio.h> int findEvacuationSteps(int* houses, int N) { int steps = 0; int maxMembers = houses[0]; for (int i = 1; i < N; i++) { if (houses[i] > maxMembers) { maxMembers = houses[i]; } } while (maxMembers > 0) { steps++; int maxIndex = 0; for (int i = 0; i < N; i++) { if (houses[i] == maxMembers) { maxIndex = i; break; 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 487. } } for (int i = maxIndex; i < N; i++) { houses[i] = 0; } maxMembers = 0; for (int i = 0; i < N; i++) { if (houses[i] > maxMembers) { maxMembers = houses[i]; } } } return steps; } int main() { int N; scanf("%d", &N); int houses[N]; 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
  • 488. for (int i = 0; i < N; i++) { scanf("%d", &houses[i]); } int evacuationSteps = findEvacuationSteps(houses, N); printf("%dn", evacuationSteps); return 0; } 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
  • 489. #include <iostream> #include <algorithm> using namespace std; int findEvacuationSteps(int* houses, int N) { int steps = 0; int maxMembers = *max_element(houses, houses + N); while (maxMembers > 0) { steps++; int maxIndex = distance(houses, find(houses, houses + N, maxMembers)); for (int i = maxIndex; i < N; i++) { houses[i] = 0; } maxMembers = *max_element(houses, houses + N); } return steps; } int main() { int N; 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 490. cin >> N; int houses[N]; for (int i = 0; i < N; i++) { cin >> houses[i]; } int evacuationSteps = findEvacuationSteps(houses, N); cout << evacuationSteps << endl; return 0; } 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
  • 491. import java.util.Scanner; public class Main { public static int findEvacuationSteps(int[] houses, int N) { int steps = 0; int maxMembers = houses[0]; for (int i = 1; i < N; i++) { if (houses[i] > maxMembers) { maxMembers = houses[i]; } } while (maxMembers > 0) { steps++; int maxIndex = 0; for (int i = 0; i < N; i++) { if (houses[i] == maxMembers) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 492. { maxIndex = i; break; } } for (int i = maxIndex; i < N; i++) { houses[i] = 0; } maxMembers = 0; for (int i = 0; i < N; i++) { if (houses[i] > maxMembers) { maxMembers = houses[i]; } } } return steps; } public static void main(String[] args) { 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
  • 493. Scanner scanner = new Scanner(System.in); int N = scanner.nextInt(); int[] houses = new int[N]; for (int i = 0; i < N; i++) { houses[i] = scanner.nextInt(); } int evacuationSteps = findEvacuationSteps(houses, N); System.out.println(evacuationSteps); } } 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
  • 494. def find_evacuation_steps(houses, N): steps = 0 max_members = max(houses) while max_members > 0: steps += 1 max_index = houses.index(max_members) for i in range(max_index, N): houses[i] = 0 max_members = max(houses) return steps N = int(input()) houses = list(map(int, input().split())) evacuation_steps = find_evacuation_steps(houses, N) print(evacuation_steps) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 495. QUESTION NO : 47 Our Friend Monk has finally found the Temple of Programming secrets. However, the door of the temple is firmly locked. Now, as per the rules of the temple, Monk needs to enter a Secret Password in a special language to unlock the door. This language, unlike English consists of K alphabets. The properties of this secret password are: 1.It has a length of N characters. 2.It is composed only of the K characters belonging to the Special language. 3.Each character belonging to the special language has been used at max once in the secret code. Now, Monk has no idea about what the ideal password may be and needs you help. You need to help Monk find the total number of distinct candidate Strings for it Modulo 109+7.
  • 496. QUESTION NO : 47 Input Format: The first line contains a single integer T denoting the number of test cases. Each of the next T lines contain two integers N and K denoting the length of the Secret Password and the number of characters of the Special language to be used respectively. Output Format: For each test case, output the number of possible distinct secret passwords Modulo 109+7. Constraints: 1 T 10 ≤ ≤ 1 N K 105 ≤ ≤ ≤
  • 497. QUESTION NO : 47 Note: You need to print the value of each element and not their weight. Sample Input: 1 3 3 Output: 6
  • 498. QUESTION NO : 47 Explanation: Let's number the characters of the special language to be 1 , 2 and 3 respectively. So, all possible candidate Strings are: 123 132 213 231 312 321 So, here we have 6 possible passwords. So, the answer = 6%(109+7)=6
  • 499. #include <stdio.h> #define ll long long int ll MOD = 1000000007; int main() { ll T, n, res, k, i; scanf("%lld", &T); while (T--) { scanf("%lld %lld", &n, &k); res = 1; for (i = k - n + 1; i <= k; i++) res = (res * i) % MOD; printf("%lldn", res); } return 0; } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 500. #include<bits/stdc++.h> using namespace std; #define ll long long int ll MOD = 1000000007; int main() { ll T,n,res,k,i; cin>>T; while(T--) { cin>>n>>k; res = 1; for(i=k-n+1;i<=k;i++) res = (res*i)%MOD; cout<<res<<"n"; } return 0; } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 501. import java.util.Scanner; public class Main { static long MOD = 1000000007; public static void main(String[] args) { Scanner scanner = new Scanner(System.in); long T = scanner.nextLong(); while (T-- > 0) { long n = scanner.nextLong(); long k = scanner.nextLong(); long res = 1; for (long i = k - n + 1; i <= k; i++) { res = (res * i) % MOD; } System.out.println(res); } scanner.close(); } } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 502. MOD = 1000000007 T = int(input()) for _ in range(T): n, k = map(int, input().split()) res = 1 for i in range(k - n + 1, k + 1): res = (res * i) % MOD print(res) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 503. QUESTION NO : 48 Alice did a survey of students training for competitive programming, where the ith student gave the response - "I practiced for xi hours". Alice recorded the observations as the number of minutes each student practiced (60 * xi). She could also have written the number with leading zeroes. For example if a student said "I studied for 2 hours", Alice could have stored the data as 00120 instead of 120. Now Bob took Alice's notebook and for each number, he did one of the following operations : 1.Rearranged its digits 2.Wrote a Random number instead of it. Thus Bob generated number y1, y2, ... yn. Your task is to tell for each number yi, can it be a permutation of numbers divisible by 60(possibly with leading zeroes)
  • 504. QUESTION NO : 48 Input The first line of input contains a single integer N - the number of people surveyed. (1 <= N <= 500) The next N lines contains a single number of 2 to 100 digits. Output For each number print YES, if yi can be a permutation of numbers divisible by 60, else NO.
  • 505. QUESTION NO : 48 Example 1 Input 5 603 006 205 228 1053 Output YES YES NO NO NO
  • 506. QUESTION NO : 48 Example 2 Input 1 0000000000000000000000000000000000000000000000 Output YES
  • 507. #include <stdio.h> #include <stdbool.h> #include <string.h> bool isDivisibleBy3(const char* s) { int sum = 0, ct_0 = 0, even = 0; int len = strlen(s); for (int i = 0; i < len; i++) { sum += s[i] - '0'; ct_0 += s[i] == '0'; even += (s[i] - '0') % 2 == 0; } return (sum % 3 == 0 && ct_0 > 0 && even > 1); } int main() { int n; scanf("%d", &n); for (int t = 0; t < n; t++) { char s[100]; 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 508. scanf("%s", s); if (isDivisibleBy3(s)) { printf("YESn"); } else { printf("NOn"); } } return 0; } 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
  • 509. #include <bits/stdc++.h> using namespace std; int main() { int n; cin >> n; for(int t = 0; t < n; t++) { string s; cin >> s; int sum = 0, ct_0 = 0, even = 0; for(int i = 0; i < (int)s.size(); i++) { sum += s[i] - '0'; ct_0 += s[i] == '0'; even += (s[i] - '0') % 2 == 0; } sum % 3 == 0 and ct_0 > 0 and even > 1 ? cout << "YESn" : cout << "NOn"; } return 0; } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 510. import java.util.Scanner; public class Main { public static boolean isDivisibleBy3(String s) { int sum = 0, ct_0 = 0, even = 0; int len = s.length(); for (int i = 0; i < len; i++) { sum += s.charAt(i) - '0'; ct_0 += s.charAt(i) == '0' ? 1 : 0; even += (s.charAt(i) - '0') % 2 == 0 ? 1 : 0; } return (sum % 3 == 0 && ct_0 > 0 && even > 1); } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); scanner.nextLine(); for (int t = 0; t < n; t++) { 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 511. String s = scanner.nextLine(); if (isDivisibleBy3(s)) { System.out.println("YES"); } else { System.out.println("NO"); } } scanner.close(); } } 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
  • 512. def is_divisible_by_3(s): _sum = 0 ct_0 = 0 even = 0 for i in range(len(s)): _sum += int(s[i]) ct_0 += 1 if s[i] == '0' else 0 even += 1 if int(s[i]) % 2 == 0 else 0 return _sum % 3 == 0 and ct_0 > 0 and even > 1 n = int(input()) for _ in range(n): s = input() if is_divisible_by_3(s): print("YES") else: print("NO") 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 513. QUESTION NO : 49 Nick went to a carnival where he saw one of the booths having a strange game. The game was simple. There will be an integer number A displayed on the Screen, and you will be gwen another number B from the booth. Now, you can convert the same number.B into binary,right-adjust the binary digits any number of times, and then give back the decimal conversion C of it.You have to return a number such that, if your number C and the number displayed on the screen A goes through an Exclusive-OR operation it should output the maximum result.Your task is to find out the minimum right binary operation which has to be performed to achieve the maximum results. Below is an idea of right-adjust operation: Suppose there is a binary number represented as D1,D2,D3,D4, where D1, D2, D3 and D4 are the different digits.
  • 514. QUESTION NO : 49 1. Right-Shift operation will make the number as D3D1D2D3 The next Right-Shift operation will make the number as D3D4D1D2 Given A and B, find the number of operations requir28231160 achieve the maximum result of A (EX-OR) B, and also output the result of it. **Note: while performing an Exclusive-OR operation, the number of binary digits should be the same. Let us try to understand it with an example. consider the input A= 4 and B=5 The respective binary of: A = 100 B=101 Default: A(EX-OR) B= 100 (EX-OR) 101=001 = 1 Right-Shift-#1: B become 110 A (EX-OR) B = 100 (EX-OR)110=010=2
  • 515. QUESTION NO : 49 Right-Shift-#2: B become 011 A (EX-OR) B = 100 (EX-OR)011=111=7 For a 3 digit binary,this is the highest value that can be acheived.Hence after 2 operations,the result was 7.So the answer is 2 7(separated by space) Input format First Input -Accept value of Integer, A. Second Input -Accept value of Integer, B (Next Line) Output format The output are 2 integer values (Separated by Space) as per above logic. (Check the output in Example 1. Example 2) Additional messages in output will cause the failure of test cases. Constraints: 1<=A, B<=1000000 Only positive Integer values
  • 516. QUESTION NO : 49 Example 1: Input: 1 -> Input integer ,A 3 ->Input integer , B Output: 0 2 ->Output Explanation: In this scenario, the respective binary ofA=01 B=110Default: A (EX-OR) B=01 (EX- OR) 11=10=2 Right-Shift-1: become 11 (EX-OR)=01 (EX-OR) 11=10=2 There will not be any change the value of B after performing any number of Right-Shift operations Hence the output is going to be the same always. So the output will be 0 2.
  • 517. #include <stdio.h> int countRightShifts(int num) { int count = 0; while (num % 2 == 0) { num >>= 1; count++; } return count; } int main() { int A, B; scanf("%d %d", &A, &B); int shifts = countRightShifts(B); int result = A ^ (B >> shifts); printf("%d %dn", shifts, result); return 0; } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 518. #include <iostream> using namespace std; int countRightShifts(int num) { int count = 0; while (num % 2 == 0) { num >>= 1; count++; } return count; } int main() { int A, B; cin >> A >> B; int shifts = countRightShifts(B); int result = A ^ (B >> shifts); cout << shifts << " " << result << endl; return 0; } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 519. import java.util.Scanner; public class Main { public static int countRightShifts(int num) { int count = 0; while (num % 2 == 0) { num >>= 1; count++; } return count; } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int A = scanner.nextInt(); int B = scanner.nextInt(); int shifts = countRightShifts(B); int result = A ^ (B >> shifts); System.out.println(shifts + " " + result); } } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 520. #include <stdio.h> int main() { char s[100]; scanf("%s", s); int sum = 0; for (int i = 0; s[i] != '0'; i++) { if (s[i] >= 'a' && s[i] <= 'z') sum += (s[i] - 'a' + 1); else if (s[i] >= 'A' && s[i] <= 'Z') sum += (s[i] - 'A' + 1); } if (sum % 9 == 0) printf("9n"); else printf("%dn", sum % 9); return 0; } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 521. def count_right_shifts(num): count = 0 while num % 2 == 0: num >>= 1 count += 1 return count A = int(input()) B = int(input()) shifts = count_right_shifts(B) result = A ^ (B >> shifts) print(shifts, result) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 522. QUESTION NO : 50 You are given a string that contains a name hidden in it. Find the hidden name and try to find the Lucky number for it. Input Format The input contains a single string with a maximum of 32 characters in it. Output Format: The output contains a single integer representing the lucky number for the name decoded from the input. Explanation : Find the alpha characters and find the sum of alphabetical values. The lucky number is the digital sum reduced up to a single digit. Constraints: TC: O(n) ASC: O(1)
  • 523. QUESTION NO : 50 Sample Input 1: D@h*o1n&i% Sample Output 1: 5 Explanation: The hidden name is Dhoni. So the sum will be 4+8+15+14+9 = 50 Digital sum reduced up to single-digit will be 50 => 5+0 = 5. Sample Input 2: !K#o$h*l@i Sample Output 2: 1 Explanation: The hidden name isKohli. So the sum will be 11+15+8+12+9 = 55 Digital sum reduced upto single digit will be 55 => 5+5 = 10 => 1+0 = 1
  • 524. #include <stdio.h> int main() { char s[100]; scanf("%s", s); int sum = 0; for (int i = 0; s[i] != '0'; i++) { if (s[i] >= 'a' && s[i] <= 'z') sum += (s[i] - 'a' + 1); else if (s[i] >= 'A' && s[i] <= 'Z') sum += (s[i] - 'A' + 1); } if (sum % 9 == 0) printf("9n"); else printf("%dn", sum % 9); return 0; } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 525. #include <bits/stdc++.h> using namespace std; int main() { string s ; cin >> s ; int sum = 0 ; for(int i = 0 ; s[i] ; i++) { if(s[i]>='a'&&s[i]<='z') sum += (s[i]-'a'+1) ; else if(s[i]>='A'&&s[i]<='Z') sum += (s[i]-'A'+1) ; } if(sum%9==0) cout << 9 ; else cout << sum%9 ; return 0 ; } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 526. import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); String s = scanner.next(); int sum = 0; for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); if (Character.isLowerCase(c)) sum += (c - 'a' + 1); else if (Character.isUpperCase(c)) sum += (c - 'A' + 1); } if (sum % 9 == 0) System.out.println("9"); else System.out.println(sum % 9); } } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 527. s = input() sum = 0 for c in s: if c.islower(): sum += ord(c) - ord('a') + 1 elif c.isupper(): sum += ord(c) - ord('A') + 1 if sum % 9 == 0: print("9") else: print(sum % 9) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 528. s = input() sum = 0 for c in s: if c.islower(): sum += ord(c) - ord('a') + 1 elif c.isupper(): sum += ord(c) - ord('A') + 1 if sum % 9 == 0: print("9") else: print(sum % 9) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 529. QUESTION NO : 51 Given a string S and a character C, write a program to count the number of sub-strings of S that contains only the character C. Input: First line contains the string S Second line contains the character C. Output: Single Integer denoting the no.of sub-string containing only the given character C. Examples: Input: 0110111 1 Output: 9
  • 530. QUESTION NO : 51 Explanation: The sub-strings containing only ‘1’ are: “1” — 5 times “11” — 3 times “111” — 1 time Hence, the count is 9.
  • 531. #include <stdio.h> void countSubString(char *S, char C) { int count = 0; int conCount = 0; for (int i = 0; S[i] != '0'; i++) { char ch = S[i]; if (ch == C) conCount++; else { count += (conCount * (conCount + 1)) / 2; conCount = 0; } } count += (conCount * (conCount + 1)) / 2; printf("%d", count); } int main() { char S[100]; 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 532. char C; fgets(S, sizeof(S), stdin); scanf("%c", &C); countSubString(S, C); return 0; } 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
  • 533. #include <bits/stdc++.h> using namespace std; void countSubString(string S, char C) { int count = 0; int conCount = 0; for (int i =0;S[i]!='0';i++) { char ch = S[i]; if (ch == C) conCount++; else { count += (conCount * (conCount + 1))/ 2; conCount = 0; } } count += (conCount* (conCount + 1))/ 2; cout << count; } int main() { 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 534. string S; char C; getline(cin,S); cin>>C; countSubString(S, C); return 0; } 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
  • 535. import java.util.Scanner; class Main { public static void countSubString(String S, char C) { int count = 0; int conCount = 0; for (int i = 0; i < S.length(); i++) { char ch = S.charAt(i); if (ch == C) conCount++; else { count += (conCount * (conCount + 1)) / 2; conCount = 0; } } count += (conCount * (conCount + 1)) / 2; System.out.print(count); } public static void main(String[] args) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 536. { Scanner scanner = new Scanner(System.in); String S = scanner.nextLine(); char C = scanner.next().charAt(0); countSubString(S, C); } } 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
  • 537. import sys def countSubString(S, C): count = 0 conCount = 0 for i in range(len(S)): ch = S[i] if ch == C: conCount += 1 else: count += (conCount * (conCount + 1)) // 2 conCount = 0 count += (conCount * (conCount + 1)) // 2 sys.stdout.write(str(count)) S = input() C = input()[0] countSubString(S, C) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 538. QUESTION NO : 52 Rahul is working with his friend Jitu on a sequence (1 based index). The intention is to simplify the sequence, but they were not very sure about the rules with which they are going to reduce it. But then Jitu came up with a rule. He said the sequence has to be simplified in the following manner: •Select a particular index ‘i’ within 1 to N range. •Chose an integer divisor D of A[i] such that D<= K •Divide A[i] by D •Replace A[i] with the quotient of A[i]/D You can perform the above operation any number of times. You must simplify the sequence such that there is no such integer value greater than 1 which can divide every element of the sequence A. Alternatively we can say that the GCD of all the elements of the sequence
  • 539. QUESTION NO : 52 You can perform the above operation any number of times. You must simplify the sequence such that there is no such integer value greater than 1 which can divide every element of the sequence A. Alternatively we can say that the GCD of all the elements of the sequence A is 1. Return “Yes” if it is possible to bring simplify the sequence with the above conditions such that the GCD of each element of A is 1. Otherwise, print “No”. Consider number of element N=3 and K=6. And each element of A= [10,15,30] Lets choose the •Element A[1] = 10, we need to choose a divisor less than or equal to k=6. Let us choose 5. Then A[1] becomes 10/5=2
  • 540. QUESTION NO : 52 •Element A[2] = 15, we need to choose a divisor less than or equal to k=6. Let us choose 5. Then A[2] becomes 15/5=3 •Element A[3]=30, we need to choose a divisor less than or equal to k=6. Let us choose 5. Then A[3] becomes 30/5=6. •Again , if we choose element A[3] = 6, we need to choose a divisor less than or equal k=6. Let us choose 6. Then A[3] becomes6/6 = 1. Now, the updated sequence is as [2 3 1]. And the GCD of the elements of the sequence would be 1. Hence the answer is 1.
  • 541. QUESTION NO : 52 Example 1: Input: 3 4_> Input integer, N, K 5 10 20 -> Input integer, A[] Output: No-> Output Example 2: Input: 3 5 -> Input integer, N, K 10 15 20 -> Input integer, A[] Output: Yes-> Output
  • 542. #include <stdio.h> #include <stdbool.h> bool simplifySequence(int N, int K, int A[]) { for (int i = 0; i < N; i++) { int num = A[i]; while (num > 1) { bool foundDivisor = false; for (int j = 2; j <= K; j++) { if (num % j == 0 && A[i] % j == 0) { num /= j; foundDivisor = true; break; } } if (!foundDivisor) { return false; 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 543. } } } return true; } int main() { int N, K; scanf("%d", &N); scanf("%d", &K); int A[N]; for (int i = 0; i < N; i++) { scanf("%d", &A[i]); } if (simplifySequence(N, K, A)) { printf("Yesn"); } else { printf("Non"); } return 0; } 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
  • 544. #include <vector> using namespace std; bool simplifySequence(int N, int K, vector<int>& A) { for (int i = 0; i < N; i++) { int num = A[i]; while (num > 1) { bool foundDivisor = false; for (int j = 2; j <= K; j++) { if (num % j == 0 && A[i] % j == 0) { num /= j; foundDivisor = true; break; } } if (!foundDivisor) { 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 545. return false; } }} return true; } int main() { int N, K; cin >> N; cin >> K; vector<int> A(N); for (int i = 0; i < N; i++) { cin >> A[i]; } if (simplifySequence(N, K, A)) { cout << "Yes" << endl; } else { cout << "No" << endl; } return 0; } 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
  • 546. import java.util.Scanner; public class Main { public static boolean simplifySequence(int N, int K, int[] A) { for (int i = 0; i < N; i++) { int num = A[i]; while (num > 1) { boolean foundDivisor = false; for (int j = 2; j <= K; j++) { if (num % j == 0 && A[i] % j == 0) { num /= j; foundDivisor = true; break; } } if (!foundDivisor) { 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 547. return false; } }} return true; } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int N = scanner.nextInt(); int K = scanner.nextInt(); int[] A = new int[N]; for (int i = 0; i < N; i++) { A[i] = scanner.nextInt(); } if (simplifySequence(N, K, A)) { System.out.println("Yes"); } else { System.out.println("No"); } } } 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
  • 548. def simplify_sequence(N, K, A): for i in range(N): num = A[i] while num > 1: found_divisor = False for j in range(2, K + 1): if num % j == 0 and A[i] % j == 0: num //= j found_divisor = True break if not found_divisor: return False return True N, K = map(int, input().split()) A = list(map(int, input().split())) if simplify_sequence(N, K, A): print("Yes") else: print("No") 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 549. QUESTION NO : 53 Jack has given a word to its student to check whether it is palindrome. But there is catch, if the word is not palindrome, they will get 1 chance to swap 2 alphabets to make it palindrome. After 1 swap, if the word becomes palindrome, then the student wins, otherwise they lose. Create a program that return True, if just 1 swap makes the word palindrome, otherwise False.
  • 550. QUESTION NO : 53 Example 1 Input : abab Output: True Explanation: The input word is abab. If the first and second alphabet swap each other, then it makes the word as baab, which ultimately makes it palindrome. So the result is True.
  • 551. QUESTION NO : 53 Example 2 Input : abcabc Output: True Explanation: The input word is abcabc. If the first and third alphabet swap each other, then it makes the word as cbaabc, which ultimately makes it palindrome. So the result is True.
  • 552. #include <stdio.h> #include <stdbool.h> #include <string.h> bool isPalindromePossible(char* input) { int length = strlen(input); int diffCount = 0; int i = 0; char diff[2][2] = {'0'}; while (i < length / 2) { if (input[i] != input[length - i - 1]) { if (diffCount == 2) { return false; } diff[diffCount][0] = input[i]; diff[diffCount][1] = input[length - i - 1]; diffCount++; } i++; 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 553. } if (diffCount == 0) { return true; } else if (diffCount == 1) { char midChar = input[i]; if (length % 2 != 0 && (diff[0][0] == midChar || diff[0][1] == midChar)) { return true; } } else if (diffCount == 2) { if ((diff[0][0] == diff[1][0] && diff[0][1] == diff[1][1]) || (diff[0][0] == diff[1][1] && diff[0][1] == diff[1][0])) { return true; } } 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
  • 554. return false; } int main() { char input[100]; scanf("%s", input); if (isPalindromePossible(input)) { printf("Truen"); } else { printf("Falsen"); } return 0; } 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
  • 555. #include <iostream> #include <cstring> using namespace std; bool isPalindromePossible(const char* input) { int length = strlen(input); int diffCount = 0; int i = 0; char diff[2][2] = {'0'}; while (i < length / 2) { if (input[i] != input[length - i - 1]) { if (diffCount == 2) { return false; } diff[diffCount][0] = input[i]; diff[diffCount][1] = input[length - i - 1]; diffCount++; } i++; 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 556. } if (diffCount == 0) { return true; } else if (diffCount == 1) { char midChar = input[i]; if (length % 2 != 0 && (diff[0][0] == midChar || diff[0][1] == midChar)) { return true; } } else if (diffCount == 2) { if ((diff[0][0] == diff[1][0] && diff[0][1] == diff[1][1]) || (diff[0][0] == diff[1][1] && diff[0][1] == diff[1][0])) { return true; } } return false; 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
  • 557. } int main() { char input[100]; cin >> input; if (isPalindromePossible(input)) { cout << "True" ; } else { cout << "False" ; } return 0; } 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
  • 558. import java.util.Scanner; public class Main { public static boolean isPalindromePossible(String input) { int length = input.length(); int diffCount = 0; int i = 0; char[][] diff = new char[2][2]; while (i < length / 2) { if (input.charAt(i) != input.charAt(length - i - 1)) { if (diffCount == 2) { return false; } diff[diffCount][0] = input.charAt(i); diff[diffCount][1] = input.charAt(length - i - 1); diffCount++; } i++; 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 559. } if (diffCount == 0) { return true; } else if (diffCount == 1) { char midChar = input.charAt(i); if (length % 2 != 0 && (diff[0][0] == midChar || diff[0][1] == midChar)) { return true; } } else if (diffCount == 2) { if ((diff[0][0] == diff[1][0] && diff[0][1] == diff[1][1]) || (diff[0][0] == diff[1][1] && diff[0][1] == diff[1][0])) { return true; } } 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
  • 560. return false; } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); String input = scanner.next(); if (isPalindromePossible(input)) { System.out.println("True"); } else { System.out.println("False"); } } } 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
  • 561. def isPalindromePossible(input: str) -> bool: length = len(input) diffCount = 0 i = 0 diff = [['0'] * 2] * 2 while i < length // 2: if input[i] != input[length - i - 1]: if diffCount == 2: return False diff[diffCount][0] = input[i] diff[diffCount][1] = input[length - i - 1] diffCount += 1 i += 1 if diffCount == 0: return True elif diffCount == 1: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 562. midChar = input[i] if length % 2 != 0 and (diff[0][0] == midChar or diff[0][1] == midChar): return True elif diffCount == 2: if (diff[0][0] == diff[1][0] and diff[0][1] == diff[1][1]) or ( diff[0][0] == diff[1][1] and diff[0][1] == diff[1][0]): return True return False str = input() print(isPalindromePossible(str)) 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
  • 563. QUESTION NO : 54 Given a positive integer number N. the task is to find the number of ways in which the given number can be represented as the product of two distinct numbers. Example 1 Input: 14 Output: 2 Explanation: 14 can be represented as 1 * 14 and 2 * 7
  • 564. QUESTION NO : 54 Example 2 Input : 16 Output : 2 Explanation : 16 can be represented as 1*16 and 2 * 8 Note 4*4 is not valid way because both the numbers are same.
  • 565. #include <stdio.h> int main() { int n; scanf("%d", &n); int count = 0; for (int i = 1; i*i <=n ; i++) { if (n % i == 0 && n / i != i) { count++; } } printf("%dn", count); return 0; } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 566. #include <iostream> using namespace std; int main() { int n; cin >> n; int count = 0; for (int i = 1; i * i <= n; i++) { if (n % i == 0 && n / i != i) { count++; } } cout << count; return 0; } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 567. import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); int count = 0; for (int i = 1; i * i <= n; i++) { if (n % i == 0 && n / i != i) { count++; } } System.out.println(count); } } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 568. import math n = int(input()) count = 0 for i in range (1, int(math.sqrt(n))): if n % i == 0 and n//i != i: count = count + 1 print(count) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 569. QUESTION NO : 55 Consider the series below: {2, 1, 3, 4, 7, 11, 18, so on} In the above series first two elements are 2 and 1 respectively and other elements are the sum of its two immediately previous elements. The task is to find the minimum number of elements that need to be changed in the given array Arr to make a series as per the above statement. For example: Arr[] = {2, 1, 3, 4, 9, 11, 18} In the given array 5th element (9) needs to replace with 7 to make the correct series. This means there is only one element that needs to replace in the given array. Hence the output = 1;
  • 570. QUESTION NO : 55 Example 1 Input : 7 2 1 3 4 9 11 18 Output : 1 Explanation : In the given array 5th element (9) needs to replace with 7 to make the correct series. This means there is only one element that needs to replace in the given array. Hence the output = 1;
  • 571. #include <stdio.h> int main() { int n; scanf("%d", &n); int arr[n]; for (int i = 0; i < n; i++) { scanf("%d", &arr[i]); } int a = 2; int b = 1; int count = 0; if (arr[0] != a) { count++; } if (arr[1] != b) { count++; } for (int i = 2; i < n; i++) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 572. { int c = a + b; a = b; b = c; if (arr[i] != c) { count++; } } printf("%dn", count); return 0; } 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
  • 573. #include <iostream> #include <vector> using namespace std; int main() { int n; cin >> n; vector<int> arr(n); for (int i = 0; i < n; i++) { cin >> arr[i]; } int a = 2; int b = 1; int count = 0; if (arr[0] != a) { count++; } if (arr[1] != b) { count++; 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 574. } for (int i = 2; i < n; i++) { int c = a + b; a = b; b = c; if (arr[i] != c) { count++; } } cout << count; return 0; } 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
  • 575. import java.util.Scanner; import java.util.ArrayList; import java.util.List; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); List<Integer> arr = new ArrayList<>(); for (int i = 0; i < n; i++) { arr.add(scanner.nextInt()); } int a = 2; int b = 1; int count = 0; if (arr.get(0) != a) { count++; } if (arr.get(1) != b) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 576. { count++; } for (int i = 2; i < n; i++) { int c = a + b; a = b; b = c; if (arr.get(i) != c) { count++; } } System.out.println(count); } } 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
  • 577. n = int(input()) arr = list(map(int, input().strip().split())) a = 2 b = 1 count = 0 if arr[0] != a: count = count + 1 if arr[1] != b: count = count + 1 for i in range(2, n): c = a + b a = b b = c if arr[i] != c: count = count + 1 print(count) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 578. QUESTION NO : 56 A group of friends are playing cards. Only numeric cards are being used, along with the joker card (equivalent to 0) and the symbols in the cards are not taken into account. Each player will receive a set of cards. The rule of the game is to rearrange the set of cards to the possible lowest number sequence. The player with the set of cards forming the smallest number wins the game. The number sequence of the cards should not start with a joker card. The task is to write a program for developing the logic of the game considering the set of cards as a number. The output will be the lowest possible number that can be formed, not beginning with 0.
  • 579. QUESTION NO : 56 Example 1 Input : 34201 Output : 10234 Explanation : The lowest number formation by rearranging the digits of the number 34201 and not starting with a 0 will be 10234. Hence the output is 10234
  • 580. #include <stdio.h> #include <stdlib.h> #include <string.h> char* smallest(char* lst, int length) { int i; char tmp; for (i = 0; i < length; i++) { if (lst[i] != '0') { tmp = lst[i]; break; } } memmove(&lst[i], &lst[i + 1], (length - i) * sizeof(char)); lst[length - 1] = '0'; char* result = (char*)malloc((length + 1) * sizeof(char)); sprintf(result, "%c%s", tmp, lst); return result; } int main() 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 581. { int n; scanf("%d", &n); char lst[12]; sprintf(lst, "%d", n); int length = strlen(lst); qsort(lst, length, sizeof(char), strcmp); char* result = smallest(lst, length); printf("%sn", result); free(result); return 0; } 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
  • 582. #include <iostream> #include <cstring> #include <algorithm> using namespace std; string smallest(string lst) { char tmp; int length = lst.length(); for (int i = 0; i < length; i++) { if (lst[i] != '0') { tmp = lst[i]; lst.erase(i, 1); break; } } string result = tmp + lst; return result; } int main() { 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 583. int n; cin >> n; string lst = to_string(n); int length = lst.length(); sort(lst.begin(), lst.end()); string result = smallest(lst); cout << result << endl; return 0; } 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
  • 584. import java.util.Scanner; import java.util.Arrays; public class Main { public static String smallest(String lst) { char tmp = ' '; int length = lst.length(); for (int i = 0; i < length; i++) { if (lst.charAt(i) != '0') { tmp = lst.charAt(i); lst = lst.substring(0, i) + lst.substring(i + 1); break; } } String result = tmp + lst; return result; } public static void main(String[] args) { 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 585. Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); String lst = String.valueOf(n); int length = lst.length(); char[] lstChars = lst.toCharArray(); Arrays.sort(lstChars); lst = new String(lstChars); String result = smallest(lst); System.out.println(result); } } 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
  • 586. def smallest(lst): for i, n in enumerate(lst): if n != '0': tmp = lst.pop(i) break return str(tmp) + ''.join(lst) if __name__ == '__main__': n = int(input()) lst = list(str(n)) lst.sort() print(smallest(lst)) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 587. QUESTION NO : 57 Mr. Rao is relocating from place A to B. the moving truck has a maximum capacity C. there are N items in the house where each item has a corresponding value (vi) and weight (Wi). Mr. Rao has to carry only the most valuable items whose total weight does not exceed the capacity of the truck. The task here is to find those items (single or combination of items) whose total value (v) will be the maximum and their corresponding weight (w) will not exceed truck capacity ( C ) here N = no. of items C – maximum capacity of the truck, an integer value W[0 to N-1] – An array consisting weight of each item V[0 to N-1] – An array consisting value of each item.
  • 588. QUESTION NO : 57 Example 1 Input: 4 -> Value of N 80 -> Value of C 10 45 60 90 -> Elements of array V[] 15 20 30 40 -> Elements of array W[] Output: 150
  • 589. #include <stdio.h> int max(int a, int b) { return (a > b) ? a : b; } int knapSack(int W, int wt[], int val[], int n) { if (n == 0 || W == 0) { return 0; } if (wt[n - 1] > W) { return knapSack(W, wt, val, n - 1); } else { return max(val[n - 1] + knapSack(W - wt[n - 1], wt, val, n - 1), knapSack(W, wt, val, n - 1)); } } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 590. int main() { int N, C; scanf("%d", &N); scanf("%d", &C); int val[N]; int wt[N]; for (int i = 0; i < N; i++) { scanf("%d", &val[i]); } for (int i = 0; i < N; i++) { scanf("%d", &wt[i]); } int result = knapSack(C, wt, val, N); printf("%dn", result); return 0; } 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
  • 591. #include <iostream> using namespace std; int max(int a, int b) { return (a > b) ? a : b; } int knapSack(int W, int wt[], int val[], int n) { if (n == 0 || W == 0) { return 0; } if (wt[n - 1] > W) { return knapSack(W, wt, val, n - 1); } else { return max(val[n - 1] + knapSack(W - wt[n - 1], wt, val, n - 1), knapSack(W, wt, val, n - 1)); } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 592. } int main() { int N, C; cin >> N >> C; int val[N]; int wt[N]; for (int i = 0; i < N; i++) { cin >> val[i]; } for (int i = 0; i < N; i++) { cin >> wt[i]; } int result = knapSack(C, wt, val, N); cout << result << endl; return 0; } 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
  • 593. import java.util.Scanner; public class Main { public static int max(int a, int b) { return (a > b) ? a : b; } public static int knapSack(int W, int[] wt, int[] val, int n) { if (n == 0 || W == 0) { return 0; } if (wt[n - 1] > W) { return knapSack(W, wt, val, n - 1); } else { return max(val[n - 1] + knapSack(W - wt[n - 1], wt, val, n - 1), knapSack(W, wt, val, n - 1)); 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 594. } } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int N = scanner.nextInt(); int C = scanner.nextInt(); int[] val = new int[N]; int[] wt = new int[N]; for (int i = 0; i < N; i++) { val[i] = scanner.nextInt(); } for (int i = 0; i < N; i++) { wt[i] = scanner.nextInt(); } int result = knapSack(C, wt, val, N); System.out.println(result); } } 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
  • 595. def knapSack(W, wt, val, n): if n == 0 or W == 0: return 0 if (wt[n-1] > W): return knapSack(W, wt, val, n-1) else: return max( val[n-1] + knapSack( W-wt[n-1], wt, val, n-1), knapSack(W, wt, val, n-1)) N = int(input()) C = int(input()) val = list(map(int, input().strip().split())) Wt = list(map(int, input().strip().split())) print (knapSack(C, Wt, val, N)) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 596. QUESTION NO : 58 Given two non-negative integers n1 and n2, where n1 < n2. The task is to find the total number of integers in the range interval [n1, n2] (both inclusive) which have no repeated digits. For example: Suppose n1 = 11 and n2 = 15 There is the number 11, which has repeated digits, but 12, 13, 14 and 15 have no repeated digits. So, the output is 4.
  • 597. QUESTION NO : 58 Example 1 Input : 11 15 Output : 4 Example 2 Input : 101 200 Output : 72
  • 598. #include <stdio.h> int repeated_digit(int n) { int a[10] = {0}; while (n != 0) { int d = n % 10; if (a[d] == 1) { return 0; } a[d] = 1; n = n / 10; } return 1; } int calculate(int L, int R) { int answer = 0; for (int i = L; i <= R; i++) { answer = answer + repeated_digit(i); 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 599. } return answer; } int main() { int L, R; scanf("%d", &L); scanf("%d", &R); int result = calculate(L, R); printf("%dn", result); return 0; } 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
  • 600. #include <iostream> using namespace std; int repeated_digit(int n) { int a[10] = {0}; while (n != 0) { int d = n % 10; if (a[d] == 1) { return 0; } a[d] = 1; n = n / 10; } return 1; } int calculate(int L, int R) { int answer = 0; for (int i = L; i <= R; i++) { 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 601. answer = answer + repeated_digit(i); } return answer; } int main() { int L, R; cin >> L >> R; int result = calculate(L, R); cout << result << endl; return 0; } 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
  • 602. import java.util.Scanner; public class Main { public static int repeated_digit(int n) { int[] a = new int[10]; while (n != 0) { int d = n % 10; if (a[d] == 1) { return 0; } a[d] = 1; n = n / 10; } return 1; } public static int calculate(int L, int R) { int answer = 0; 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 603. for (int i = L; i <= R; i++) { answer = answer + repeated_digit(i); } return answer; } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int L = scanner.nextInt(); int R = scanner.nextInt(); int result = calculate(L, R); System.out.println(result); } } 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
  • 604. def repeated_digit(n): a = [] while n != 0: d = n % 10 if d in a: return 0 a.append(d) n = n // 10 return 1 def calculate(L, R): answer = 0 for i in range(L, R + 1): answer = answer + repeated_digit(i) return answer L = int(input()) R = int(input()) print(calculate(L, R)) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 605. QUESTION NO : 59 Given a sentence str. The task is to find whether the given sentence contains all letters of the English alphabet (a to z or A to Z). If it does not, then print all missing letters of the alphabet, otherwise print 0. Note All characters in the given sentence should be treated as case insensitive, which means that ‘A’ and ‘a’ are to be treated as the same. The output should be in alphabetic order The output should contain only lowercase alphabets If none of the letters are missing, print 0 as output
  • 606. QUESTION NO : 59 Example 1 Input : The four boxing wizard starts over the quickly. Output : jmp Explanation : “The four boxing wizard starts over the quickly” does not contain all the letters from ‘a’ to ‘z’ or ‘A’ to ‘Z’ as ‘j’, ‘m’ and ‘p’ are missing.
  • 607. #include <stdio.h> #include <ctype.h> #include <stdbool.h> int main() { char str[100]; fgets(str, sizeof(str), stdin); // Convert the string to lowercase for (int i = 0; str[i]; i++) { str[i] = tolower(str[i]); } bool present[26] = {false}; // Array to track the presence of letters // Mark the presence of each letter in the string for (int i = 0; str[i]; i++) { if (isalpha(str[i])) { int index = str[i] - 'a'; 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 608. present[index] = true; } } // Print the missing letters for (int i = 0; i < 26; i++) { if (!present[i]) { char missingLetter = i + 'a'; printf("%c", missingLetter); } } return 0; } 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
  • 609. #include <iostream> #include <cctype> #include <vector> using namespace std; int main() { string str; getline(cin, str); // Convert the string to lowercase for (char& c : str) { c = tolower(c); } vector<bool> present(26, false); // Vector to track the presence of letters // Mark the presence of each letter in the string for (char c : str) { if (isalpha(c)) { int index = c - 'a'; present[index] = true; 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 610. } } // Print the missing letters for (int i = 0; i < 26; i++) { if (!present[i]) { char missingLetter = i + 'a'; cout << missingLetter; } } return 0; } 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
  • 611. import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); String str = scanner.nextLine(); // Convert the string to lowercase str = str.toLowerCase(); boolean[] present = new boolean[26]; // Array to track the presence of letters // Mark the presence of each letter in the string for (char c : str.toCharArray()) { if (Character.isLetter(c)) { int index = c - 'a'; present[index] = true; } } // Print the missing letters for (int i = 0; i < 26; i++) { 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 612. if (!present[i]) { char missingLetter = (char) (i + 'a'); System.out.print(missingLetter); } } } } 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
  • 613. str = input() str = str.lower() for i in range (0, 26): t = chr(97+i) if t not in str: print (t, end='') 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 614. QUESTION NO : 60 An accountant in a firm has a serious issue with numbers. He types the numbers in a reverse manner. Suppose he has to enter 123, he enters the number 321. He has the habit of reading numbers from right to left. The boss became aware of this only after he found out at the end of the billing month when he had to file the tax. He has to correct al the numbers by reentering each number from right to left. This gives the corrected number. Given a number N, help the boss find out the corrected numbers. Display the corrected numbers as output. Also ignore any 0’s at the end of the number. Note The corrected numbers should be only 16-bit signed integers. If the output (the corrected number is outside the range display “Wrong value”.
  • 615. QUESTION NO : 60 Example 1 Input : -4512 Output : -2154 Explanation : From the inputs given below N = -4512 The correct number would be from right to left which is 2154 and the sign is retained. Hence the outpt is -2154
  • 616. QUESTION NO : 60 Example 2 Input : 500 Output : 5 Explanation : From the inputs given above: N = 500 The correct number would be from right to left which is 005 which can be displayed as 5. Hence the output is 5.
  • 617. #include <stdio.h> #include <stdbool.h> int main() { int n; scanf("%d", &n); int temp = n; if (n >= -32786 && n <= 32767) { if (n < 0) { n = n * -1; } int rev = 0; while (n != 0) { int rem = n % 10; rev = rev * 10 + rem; n = n / 10; } if (temp < 0) { 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 618. printf("%dn", rev * -1); } else { printf("%dn", rev); } } else { printf("Wrong valuen"); } return 0; } 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
  • 619. #include <iostream> using namespace std; int main() { int n; cin >> n; int temp = n; if (n >= -32786 && n <= 32767) { if (n < 0) { n = n * -1; } int rev = 0; while (n != 0) { int rem = n % 10; rev = rev * 10 + rem; n = n / 10; } if (temp < 0) { 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 620. cout << rev * -1 << std::endl; } else { cout << rev << std::endl; } } else { cout << "Wrong value" << std::endl; } return 0; } 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
  • 621. import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); int temp = n; if (n >= -32786 && n <= 32767) { if (n < 0) { n = n * -1; } int rev = 0; while (n != 0) { int rem = n % 10; rev = rev * 10 + rem; n = n / 10; } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  • 622. if (temp < 0) { System.out.println(rev * -1); } else { System.out.println(rev); } } else { System.out.println("Wrong value"); } } } 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
  • 623. n = int(input()) temp = n if (n >= -32786 and n <= 32767): if(n < 0): n = n * -1 rev = 0 while(n != 0): rem = n % 10 rev = rev * 10 + rem n = n // 10 if(temp < 0): print(rev * -1 ) else: print(rev) else: print("Wrong value") 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22

Editor's Notes

  • #1: 1st slide (Mandatory)
  • #2: Cover Page Font: Nunito Sans Primary colors: Black, White and Red (#F05136) General Instruction: Don’t edit this PPT (keep it for future reference) Copy paste the required slide into your PPT. Format it there. Write less, talk/present more Use the font Nunito Sans Regular. You can download it from google fonts (https://fonts.google.com/specimen/Nunito+Sans). Don’t change the size and/or positions of headings, texts, unless absolutely necessary. (minimum size: 20) The size of the image must be adjusted according to the text. (try to make it look visually attractive) 1 image per slide. No more than 4 points per slide.
  • #3: Cover Page Font: Nunito Sans Primary colors: Black, White and Red (#F05136) General Instruction: Don’t edit this PPT (keep it for future reference) Copy paste the required slide into your PPT. Format it there. Write less, talk/present more Use the font Nunito Sans Regular. You can download it from google fonts (https://fonts.google.com/specimen/Nunito+Sans). Don’t change the size and/or positions of headings, texts, unless absolutely necessary. (minimum size: 20) The size of the image must be adjusted according to the text. (try to make it look visually attractive) 1 image per slide. No more than 4 points per slide.
  • #4: Question+ Input + Output (Programming)
  • #5: Question+ Input + Output (Programming)
  • #6: Question+ Input + Output (Programming)
  • #7: Question+ Input + Output (Programming)
  • #8: Question+ Input + Output (Programming)
  • #9: Question+ Input + Output (Programming)
  • #10: Question+ Input + Output (Programming)
  • #11: Question+ Input + Output (Programming)
  • #32: Question+ Input + Output (Programming)
  • #33: Question+ Input + Output (Programming)
  • #34: Question+ Input + Output (Programming)
  • #35: Question+ Input + Output (Programming)
  • #36: Question+ Input + Output (Programming)
  • #45: Question+ Input + Output (Programming)
  • #46: Question+ Input + Output (Programming)
  • #61: Question+ Input + Output (Programming)
  • #62: Question+ Input + Output (Programming)
  • #63: Question+ Input + Output (Programming)
  • #71: Question+ Input + Output (Programming)
  • #72: Question+ Input + Output (Programming)
  • #77: Question+ Input + Output (Programming)
  • #82: Question+ Input + Output (Programming)
  • #83: Question+ Input + Output (Programming)
  • #84: Question+ Input + Output (Programming)
  • #89: Question+ Input + Output (Programming)
  • #90: Question+ Input + Output (Programming)
  • #91: Question+ Input + Output (Programming)
  • #96: Question+ Input + Output (Programming)
  • #97: Question+ Input + Output (Programming)
  • #111: Question+ Input + Output (Programming)
  • #119: Question+ Input + Output (Programming)
  • #126: Question+ Input + Output (Programming)
  • #127: Question+ Input + Output (Programming)
  • #128: Question+ Input + Output (Programming)
  • #129: Question+ Input + Output (Programming)
  • #130: Question+ Input + Output (Programming)
  • #135: Question+ Input + Output (Programming)
  • #136: Question+ Input + Output (Programming)
  • #142: Question+ Input + Output (Programming)
  • #143: Question+ Input + Output (Programming)
  • #144: Question+ Input + Output (Programming)
  • #145: Question+ Input + Output (Programming)
  • #146: Question+ Input + Output (Programming)
  • #154: Question+ Input + Output (Programming)
  • #155: Question+ Input + Output (Programming)
  • #156: Question+ Input + Output (Programming)
  • #157: Question+ Input + Output (Programming)
  • #166: Question+ Input + Output (Programming)
  • #167: Question+ Input + Output (Programming)
  • #168: Question+ Input + Output (Programming)
  • #169: Question+ Input + Output (Programming)
  • #170: Question+ Input + Output (Programming)
  • #171: Question+ Input + Output (Programming)
  • #179: Question+ Input + Output (Programming)
  • #180: Question+ Input + Output (Programming)
  • #181: Question+ Input + Output (Programming)
  • #182: Question+ Input + Output (Programming)
  • #190: Question+ Input + Output (Programming)
  • #191: Question+ Input + Output (Programming)
  • #192: Question+ Input + Output (Programming)
  • #198: Question+ Input + Output (Programming)
  • #199: Question+ Input + Output (Programming)
  • #200: Question+ Input + Output (Programming)
  • #201: Question+ Input + Output (Programming)
  • #210: Question+ Input + Output (Programming)
  • #211: Question+ Input + Output (Programming)
  • #216: Question+ Input + Output (Programming)
  • #217: Question+ Input + Output (Programming)
  • #218: Question+ Input + Output (Programming)
  • #230: Question+ Input + Output (Programming)
  • #231: Question+ Input + Output (Programming)
  • #232: Question+ Input + Output (Programming)
  • #233: Question+ Input + Output (Programming)
  • #234: Question+ Input + Output (Programming)
  • #235: Question+ Input + Output (Programming)
  • #236: Question+ Input + Output (Programming)
  • #237: Question+ Input + Output (Programming)
  • #252: Question+ Input + Output (Programming)
  • #253: Question+ Input + Output (Programming)
  • #254: Question+ Input + Output (Programming)
  • #255: Question+ Input + Output (Programming)
  • #256: Question+ Input + Output (Programming)
  • #264: Question+ Input + Output (Programming)
  • #265: Question+ Input + Output (Programming)
  • #266: Question+ Input + Output (Programming)
  • #267: Question+ Input + Output (Programming)
  • #268: Question+ Input + Output (Programming)
  • #279: Question+ Input + Output (Programming)
  • #280: Question+ Input + Output (Programming)
  • #281: Question+ Input + Output (Programming)
  • #282: Question+ Input + Output (Programming)
  • #290: Question+ Input + Output (Programming)
  • #291: Question+ Input + Output (Programming)
  • #296: Question+ Input + Output (Programming)
  • #297: Question+ Input + Output (Programming)
  • #298: Question+ Input + Output (Programming)
  • #306: Question+ Input + Output (Programming)
  • #307: Question+ Input + Output (Programming)
  • #312: Question+ Input + Output (Programming)
  • #313: Question+ Input + Output (Programming)
  • #318: Cover Page Font: Nunito Sans Primary colors: Black, White and Red (#F05136) General Instruction: Don’t edit this PPT (keep it for future reference) Copy paste the required slide into your PPT. Format it there. Write less, talk/present more Use the font Nunito Sans Regular. You can download it from google fonts (https://fonts.google.com/specimen/Nunito+Sans). Don’t change the size and/or positions of headings, texts, unless absolutely necessary. (minimum size: 20) The size of the image must be adjusted according to the text. (try to make it look visually attractive) 1 image per slide. No more than 4 points per slide.
  • #319: Question+ Input + Output (Programming)
  • #320: Question+ Input + Output (Programming)
  • #328: Question+ Input + Output (Programming)
  • #329: Question+ Input + Output (Programming)
  • #330: Question+ Input + Output (Programming)
  • #331: Question+ Input + Output (Programming)
  • #332: Question+ Input + Output (Programming)
  • #333: Question+ Input + Output (Programming)
  • #334: Question+ Input + Output (Programming)
  • #342: Question+ Input + Output (Programming)
  • #343: Question+ Input + Output (Programming)
  • #344: Question+ Input + Output (Programming)
  • #345: Question+ Input + Output (Programming)
  • #353: Question+ Input + Output (Programming)
  • #354: Question+ Input + Output (Programming)
  • #355: Question+ Input + Output (Programming)
  • #356: Question+ Input + Output (Programming)
  • #368: Question+ Input + Output (Programming)
  • #369: Question+ Input + Output (Programming)
  • #370: Question+ Input + Output (Programming)
  • #371: Question+ Input + Output (Programming)
  • #379: Question+ Input + Output (Programming)
  • #380: Question+ Input + Output (Programming)
  • #381: Question+ Input + Output (Programming)
  • #382: Question+ Input + Output (Programming)
  • #383: Question+ Input + Output (Programming)
  • #392: Question+ Input + Output (Programming)
  • #393: Question+ Input + Output (Programming)
  • #394: Question+ Input + Output (Programming)
  • #402: Question+ Input + Output (Programming)
  • #403: Question+ Input + Output (Programming)
  • #404: Question+ Input + Output (Programming)
  • #412: Question+ Input + Output (Programming)
  • #413: Question+ Input + Output (Programming)
  • #414: Question+ Input + Output (Programming)
  • #425: Question+ Input + Output (Programming)
  • #426: Question+ Input + Output (Programming)
  • #427: Question+ Input + Output (Programming)
  • #428: Question+ Input + Output (Programming)
  • #433: Cover Page Font: Nunito Sans Primary colors: Black, White and Red (#F05136) General Instruction: Don’t edit this PPT (keep it for future reference) Copy paste the required slide into your PPT. Format it there. Write less, talk/present more Use the font Nunito Sans Regular. You can download it from google fonts (https://fonts.google.com/specimen/Nunito+Sans). Don’t change the size and/or positions of headings, texts, unless absolutely necessary. (minimum size: 20) The size of the image must be adjusted according to the text. (try to make it look visually attractive) 1 image per slide. No more than 4 points per slide.
  • #434: Question+ Input + Output (Programming)
  • #435: Question+ Input + Output (Programming)
  • #443: Question+ Input + Output (Programming)
  • #444: Question+ Input + Output (Programming)
  • #452: Question+ Input + Output (Programming)
  • #453: Question+ Input + Output (Programming)
  • #454: Question+ Input + Output (Programming)
  • #465: Question+ Input + Output (Programming)
  • #466: Question+ Input + Output (Programming)
  • #474: Question+ Input + Output (Programming)
  • #475: Question+ Input + Output (Programming)
  • #476: Question+ Input + Output (Programming)
  • #484: Question+ Input + Output (Programming)
  • #485: Question+ Input + Output (Programming)
  • #495: Question+ Input + Output (Programming)
  • #496: Question+ Input + Output (Programming)
  • #497: Question+ Input + Output (Programming)
  • #498: Question+ Input + Output (Programming)
  • #503: Question+ Input + Output (Programming)
  • #504: Question+ Input + Output (Programming)
  • #505: Question+ Input + Output (Programming)
  • #506: Question+ Input + Output (Programming)
  • #513: Question+ Input + Output (Programming)
  • #514: Question+ Input + Output (Programming)
  • #515: Question+ Input + Output (Programming)
  • #516: Question+ Input + Output (Programming)
  • #522: Question+ Input + Output (Programming)
  • #523: Question+ Input + Output (Programming)
  • #529: Question+ Input + Output (Programming)
  • #530: Question+ Input + Output (Programming)
  • #538: Question+ Input + Output (Programming)
  • #539: Question+ Input + Output (Programming)
  • #540: Question+ Input + Output (Programming)
  • #541: Question+ Input + Output (Programming)
  • #549: Question+ Input + Output (Programming)
  • #550: Question+ Input + Output (Programming)
  • #551: Question+ Input + Output (Programming)
  • #563: Question+ Input + Output (Programming)
  • #564: Question+ Input + Output (Programming)
  • #569: Question+ Input + Output (Programming)
  • #570: Question+ Input + Output (Programming)
  • #578: Question+ Input + Output (Programming)
  • #579: Question+ Input + Output (Programming)
  • #587: Question+ Input + Output (Programming)
  • #588: Question+ Input + Output (Programming)
  • #596: Question+ Input + Output (Programming)
  • #597: Question+ Input + Output (Programming)
  • #605: Question+ Input + Output (Programming)
  • #606: Question+ Input + Output (Programming)
  • #614: Question+ Input + Output (Programming)
  • #615: Question+ Input + Output (Programming)
  • #616: Question+ Input + Output (Programming)
  • #624: Thank you slide