0% found this document useful (0 votes)
20 views

Coding Questions

Uploaded by

21ve1a6799
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views

Coding Questions

Uploaded by

21ve1a6799
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 166

1.

Problem Statement –

An automobile company manufactures both a two-wheeler (TW) and a


four wheeler (FW). A company manager wants to make the production of
both types of vehicle according to the given data below:

● 1st data, Total number of vehicle (two-wheeler + four-wheeler)=v


● 2nd data, Total number of wheels = W

The task is to find how many two-wheelers as well as four-wheelers


need to manufacture as per the given data.
Example :

Input :
200 -> Value of V
540 -> Value of W Output : TW =130 FW=70

Explanation:
130+70 = 200 vehicles
(70*4)+(130*2)= 540 wheels

Constraints :

● 2<=W
● W%2=0
● V<W

Print “INVALID INPUT” , if inputs did not meet the constraints.


The input format for testing
The candidate has to write the code to accept two positive numbers
separated by a new line.

● First Input line – Accept value of V.


● Second Input line- Accept value for W.

The output format for testing

● Written program code should generate two outputs, each


separated by a single space character(see the example)
● Additional messages in the output will result in the failure of test
case

Code:
import java.util.*;
public class Main
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
int v=sc.nextInt();
int w=sc.nextInt();
float res=((4*v)-w)/2;
if(w>=2 && (w%2==0) && v<w)
System.out.println("TW= "+(int)(res)+" FW= "+(int)(v-res));
else
System.out.println("INVALID INPUT");
}
}

0
2. Problem Statement –

Given a string S(input consisting) of ‘*’ and ‘#’. The length of the string is
variable. The task is to find the minimum number of ‘*’ or ‘#’ to make it a
valid string. The string is considered valid if the number of ‘*’ and ‘#’ are
equal. The ‘*’ and ‘#’ can be at any position in the string.
Note : The output will be a positive or negative integer based on number
of ‘*’ and ‘#’ in the input string.

● (*>#): positive integer


● (#>*): negative integer
● (#=*): 0

Example 1:
Input 1:

● ###*** -> Value of S

Output :

● 0 → number of * and # are equal

Code:
import java.util.*;
public class Main
{
public static void main(String[] args)
{

String str="Hello";
int count1=0,count2=0;
for(int i=0;i< str.length();i++)
{
if(str.charAt(i)=='*')
count1++;##
else if(str.charAt(i)=='#')
count2++;
}
System.out.println(count1-count2);
}
}

3. Problem Statement:
Given an integer array Arr of size N the task is to find the count of
elements whose value is greater than all of its prior elements.

Note : 1st element of the array should be considered in the count of the
result.

For example,
Arr[]={7,4,8,2,9}
As 7 is the first element, it will consider in the result.
8 and 9 are also the elements that are greater than all of its previous
elements.
Since total of 3 elements is present in the array that meets the
condition.
Hence the output = 3.
Example 1:
Input
5 -> Value of N, represents size of Arr
7-> Value of Arr[0]
4 -> Value of Arr[1]
8-> Value of Arr[2]
2-> Value of Arr[3]
9-> Value of Arr[4]

Output :
3

Example 2:
5 -> Value of N, represents size of Arr
3 -> Value of Arr[0]
4 -> Value of Arr[1]
5 -> Value of Arr[2]
8 -> Value of Arr[3]
9 -> Value of Arr[4]

Output :
5

Constraints

● 1<=N<=20
● 1<=Arr[i]<=10000

Code:
import java.util.*;
class Main
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int arr[]=new int[n];
for(int i=0;imax)
{
max=arr[i];
count++;
}
}
System.out.println(count);
}
}

4. Problem Statement:
A parking lot in a mall has RxC number of parking spaces. Each parking
space will either be empty(0) or full(1). The status (0/1) of a parking
space is represented as the element of the matrix. The task is to find
index of the prpeinzta row(R) in the parking lot that has the most of the
parking spaces full(1).

Note :
RxC- Size of the matrix
Elements of the matrix M should be only 0 or 1.

Example 1:
Input :
3 -> Value of R(row)
3 -> value of C(column)
[0 1 0 1 1 0 1 1 1] -> Elements of the array M[R][C] where each element
is separated by new line.
Output :
3 -> Row 3 has maximum number of 1’s

Example 2:
input :
4 -> Value of R(row)
3 -> Value of C(column)
[0 1 0 1 1 0 1 0 1 1 1 1] -> Elements of the array M[R][C]
Output :
4 -> Row 4 has maximum number of 1’s

Code:
import java.util.*;
class Main
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
int row=sc.nextInt();
int col=sc.nextInt();
int arr[][]=new int[row][col];
for(int i=0;i< row;i++)
for(int j=0;j< col;j++)
arr[i][j]=sc.nextInt();

int max=0,count=0,index=0;
for(int i=0;i< row;i++)
{
count=0;
for(int j=0;j< col;j++)
{
if(arr[i][j]==1)
count++;
}
if(count>max)
{
max=count;
index=i+1;
}
}
System.out.println(index);
}
}
5. Problem Statement:
A party has been organised on cruise. The party is organised for a
limited time(T). The number of guests entering (E[i]) and leaving (L[i]) the
party at every hour is represented as elements of the array. The task is
to find the maximum number of guests present on the cruise at any
given instance within T hours.

Example 1:
Input :

● 5 -> Value of T
● [7,0,5,1,3] -> E[], Element of E[0] to E[N-1], where input each
element is separated by new line
● [1,2,1,3,4] -> L[], Element of L[0] to L[N-1], while input each
element is separate by new line.

Output :
8 -> Maximum number of guests on cruise at an instance.

Explanation:

1st hour:
Entry : 7 Exit: 1
No. of guests on ship : 6
2nd hour :
Entry : 0 Exit : 2
No. of guests on ship : 6-2=4

Hour 3:
Entry: 5 Exit: 1
No. of guests on ship : 4+5-1=8

Hour 4:
Entry : 1 Exit : 3
No. of guests on ship : 8+1-3=6

Hour 5:
Entry : 3 Exit: 4
No. of guests on ship: 6+3-4=5
Hence, the maximum number of guests within 5 hours is 8.

Example 2:
Input:
4 -> Value of T
[3,5,2,0] -> E[], Element of E[0] to E[N-1], where input each element is
separated by new line.
[0,2,4,4] -> L[], Element of L[0] to L[N-1], while input each element in
separated by new line
Output:
6
Cruise at an instance

Explanation:
Hour 1:
Entry: 3 Exit: 0
No. of guests on ship: 3

Hour 2:
Entry : 5 Exit : 2
No. of guest on ship: 3+5-2=6

Hour 3:
Entry : 2 Exit: 4
No. of guests on ship: 6+2-4= 4

Hour 4:
Entry: 0 Exit : 4
No. of guests on ship : 4+0-4=0

Hence, the maximum number of guests within 5 hours is 6.


The input format for testing
The candidate has to write the code to accept 3 input.
First input- Accept value for number of T(Positive integer number)
Second input- Accept T number of values, where each value is
separated by a new line.
Third input- Accept T number of values, where each value is separated
by a new line.
The output format for testing
The output should be a positive integer number or a message as given
in the problem statement(Check the output in Example 1 and Example 2)

Constraints:

● 1<=T<=25
● 0<= E[i] <=500
● 0<= L[i] <=500

Code:
import java.util.*;
class Main
{
public static void main (String[]args)
{
Scanner sc = new Scanner (System.in);
int t = sc.nextInt ();
int e[] = new int[t];
int l[] = new int[t];
for (int i = 0; i < t; i++)
e[i] = sc.nextInt ();

for (int i = 0; i < t; i++)


l[i] = sc.nextInt ();

int max = 0, sum = 0;


for (int i = 0; i < t; i++)
{
sum += e[i] - l[i];
max = Math.max (sum, max);
}
System.out.println (max);
}
}

6. Problem Statement:
At a fun fair, a street vendor is selling different colours of balloons. He
sells N number of different colours of balloons (B[]). The task is to find
the colour (odd) of the balloon which is present odd number of times in
the bunch of balloons.

Note: If there is more than one colour which is odd in number, then the
first colour in the array which is present odd number of times is
displayed. The colours of the balloons can all be either upper case or
lower case in the array. If all the inputs are even in number, display the
message “All are even”.

Example 1:

● 7 -> Value of N
● [r,g,b,b,g,y,y] -> B[] Elements B[0] to B[N-1], where each input
element is sepārated by ṉew line.

Output :

● r -> [r,g,b,b,g,y,y] -> “r” colour balloon is present odd number of


times in the bunch.
Explanation:
From the input array above:

● r: 1 balloon
● g: 2 balloons
● b: 2 balloons
● y : 2 balloons
Hence , r is only the balloon which is odd in number.

Example 2:
Input:

● 10 -> Value of N
● [a,b,b,b,c,c,c,a,f,c] -> B[], elements B[0] to B[N-1] where input each
element is separated by new line.

Output :
b-> ‘b’ colour balloon is present odd number of times in the bunch.

Explanation:
From the input array above:

● a: 2 balloons
● b: 3 balloons
● c: 4 balloons
● f: 1 balloons

Here, both ‘b’ and ‘f’ have odd number of balloons. But ‘b’ colour balloon
occurs first.
Hence , b is the output.

Input Format for testing


The candidate has to write the code to accept: 2 input
● First input: Accept value for number of N(Positive integer number).
● Second Input : Accept N number of character values (B[]), where
each value is separated by a new line.

Output format for testing


The output should be a single literal (Check the output in example 1 and
example 2)

Constraints:

● 3<=N<=50
● B[i]={{a-z} or {A-Z}}

import java.util.HashMap;
import java.util.Map;

public class BalloonOddCount {


public static void main(String[] args) {
// Example input
int N = 7;
String[] balloons = {"r", "g", "b", "b", "g", "y", "y"};

// Find the first balloon with an odd count


String result = findOddBalloon(balloons, N);
System.out.println(result);
}

public static String findOddBalloon(String[] balloons, int N) {


// Step 1: Create a HashMap to store frequency of each
balloon color
Map<String, Integer> balloonMap = new HashMap<>();
// Step 2: Traverse the array and update the HashMap
for (String balloon : balloons) {
// Update the count in the HashMap
balloonMap.put(balloon,
balloonMap.getOrDefault(balloon, 0) + 1);

// Step 3: Check if the count is odd and return


immediately
if (balloonMap.get(balloon) % 2 != 0) {
return balloon; // Return the first balloon with an odd
count
}
}

// Step 4: If no balloon has an odd count, return "All are


even"
return "All are even";
}
}

Code:
import java.util.*;
class Main
{
public static void main (String[]args)
{
Scanner sc = new Scanner (System.in);
int n = sc.nextInt ();
char arr[] = new char[n];
for (int i = 0; i < n; i++)
arr[i] = sc.next ().charAt (0);
int lower[] = new int[26];
int upper[] = new int[26];
for (int i = 0; i < n; i++)
{
if ((arr[i] >= 'A') && (arr[i] <= 'Z'))
upper[arr[i] - 'A']++;
else if ((arr[i] >= 'a') && (arr[i] <= 'z'))
lower[arr[i] - 'a']++;
}
boolean flag = false;
char ch = '\0';
for (int i = 0; i < n; i++)
{
if ((arr[i] >= 'A') && (arr[i] <= 'Z'))
{
if (upper[arr[i] - 'A'] % 2 == 1)
{
ch = (char) (arr[i]);
flag = true;
break;
}
}
else if ((arr[i] >= 'a') && (arr[i] <= 'z'))
{
if (lower[arr[i] - 'a'] % 2 == 1)
{
ch = (char) (arr[i]);
flag = true;
break;
}

}
if (flag == true)
System.out.println (ch);
else
System.out.println ("All are even");
}
}

7. Problem Statement:
There is a JAR full of candies for sale at a mall counter. JAR has the
capacity N, that is JAR can contain maximum N candies when JAR is
full. At any point of time. JAR can have M number of Candies where
M<=N. Candies are served to the customers. JAR is never remain empty
as when last k candies are left. JAR if refilled with new candies in such a
way that JAR get full.
Write a code to implement above scenario. Display JAR at counter with
available number of candies. Input should be the number of candies one
customer can order at point of time. Update the JAR after each purchase
and display JAR at Counter.

Output should give number of Candies sold and updated number of


Candies in JAR.

If Input is more than candies in JAR, return: “INVALID INPUT”


Given,
N=10, where N is NUMBER OF CANDIES AVAILABLE
K =< 5, where k is number of minimum candies that must be inside JAR
ever.
Example 1:(N = 10, k =< 5)

Input Value
3
Output Value
NUMBER OF CANDIES SOLD : 3
NUMBER OF CANDIES AVAILABLE : 7

Example : (N=10, k<=5)

Input Value
0
Output Value
INVALID INPUT NUMBER OF
CANDIES LEFT : 10

Code:
import java.util.Scanner;
class Main{
public static void main(String[] args) {
int n = 10, k = 5;
int num;
Scanner sc = new Scanner(System.in);
num = sc.nextInt();
if(num >= 1 && num <= 5) {
System.out.println("NUMBER OF CANDIES SOLD : "
+ num);
System.out.print("NUMBER OF CANDIES LEFT : " +
(n - num));
} else {
System.out.println("INVALID INPUT");
System.out.print("NUMBER OF CANDIES LEFT : " +
n);
}
}
}

8. Problem Statement:
Selection of MPCS exams include a fitness test which is conducted on
ground. There will be a batch of 3 trainees, appearing for running test in
track for 3 rounds. You need to record their oxygen level after every
round. After trainee are finished with all rounds, calculate for each
trainee his average oxygen level over the 3 rounds and select one with
highest oxygen level as the most fit trainee. If more than one trainee
attains the same highest average level, they all need to be selected.

Display the most fit trainee (or trainees) and the highest average oxygen
level.

Note:

● The oxygen value entered should not be accepted if it is not in the


range between 1 and 100.
● If the calculated maximum average oxygen value of trainees is
below 70 then declare the trainees as unfit with meaningful
message as “All trainees are unfit.
● Average Oxygen Values should be rounded.

Example 1:
INPUT VALUES
95
92
95
92
90
92
90
92
90

OUTPUT VALUES
Trainee Number : 1
Trainee Number : 3

Note:
Input should be 9 integer values representing oxygen levels entered in
order as

Round 1

● Oxygen value of trainee 1


● Oxygen value of trainee 2
● Oxygen value of trainee 3

Round 2
● Oxygen value of trainee 1
● Oxygen value of trainee 2
● Oxygen value of trainee 3

Round 3

● Oxygen value of trainee 1


● Oxygen value of trainee 2
● Oxygen value of trainee 3

Output must be in given format as in above example. For any wrong


input final output should display “INVALID INPUT”

Code:

import java.util.Scanner;
class Main {
public static void main(String[] args) {
int[][] trainee = new int[3][3];
int[] average = new int[3];
int max = 0;
Scanner sc = new Scanner(System.in);
for(int i = 0; i < 3; i++) {
for(int j = 0; j < 3; j++) {
trainee[i][j] = sc.nextInt();
if(trainee[i][j] < 1 || trainee[i][j] > 100) {
trainee[i][j] = 0;
}
}
}
for(int i = 0; i < 3; i++) {
for(int j = 0; j < 3; j++) {
average[i] = average[i] + trainee[j][i];
}
average[i] = average[i] / 3;
}
for(int i = 0; i < 3; i++) { if(average[i] > max) {
max = average[i];
}
}
for(int i = 0; i < 3; i++) {
if(average[i] == max) {
System.out.println("Trainee Number : " + (i +
1));
}
if(average[i] <70) {
System.out.print("Trainee is Unfit");
}
}
}

9.
10. `Problem Statement:
A washing machine works on the principle of Fuzzy System, the weight
of clothes put inside it for washing is uncertain But based on weight
measured by sensors, it decides time and water level which can be
changed by menus given on the machine control area.
For low level water, the time estimate is 25 minutes, where
approximately weight is between 2000 grams or any nonzero positive
number below that.

For medium level water, the time estimate is 35 minutes, where


approximately weight is between 2001 grams and 4000 grams.

For high level water, the time estimate is 45 minutes, where


approximately weight is above 4000 grams.

Assume the capacity of machine is maximum 7000 grams

Where approximately weight is zero, time estimate is 0 minutes.

Write a function which takes a numeric weight in the range [0,7000] as


input and produces estimated time as output is: “OVERLOADED”, and
for all other inputs, the output statement is

“INVALID INPUT”.

Input should be in the form of integer value –

Output must have the following format –

Time Estimated: Minutes

Example:
Input value
2000
Output value
Time Estimated: 25 minutes

Code:
public class WashingMachine {

public static String estimateTime(int weight) {


if (weight < 0 || weight > 7000) {
return "INVALID INPUT";
} else if (weight == 0) {
return "Time Estimated: 0 minutes";
} else if (weight > 0 && weight <= 2000) {
return "Time Estimated: 25 minutes";
} else if (weight >= 2001 && weight <= 4000) {
return "Time Estimated: 35 minutes";
} else if (weight >= 4001 && weight <= 7000) {
return "Time Estimated: 45 minutes";
} else {
return "OVERLOADED";
}
}

public static void main(String[] args) {


// Example input
int inputWeight = 2000;
String result = estimateTime(inputWeight);
System.out.println(result);
}
}
11. Problem Statement:
The Caesar cipher is a type of substitution cipher in which each alphabet
in the plaintext or messages is shifted by a number of places down the
alphabet.
For example,with a shift of 1, P would be replaced by Q, Q would
become R, and so on.
To pass an encrypted message from one person to another, it is first
necessary that both parties have the ‘Key’ for the cipher, so that the
sender may encrypt and the receiver may decrypt it.
Key is the number of OFFSET to shift the cipher alphabet. Key can have
basic shifts from 1 to 25 positions as there are 26 total alphabets.
As we are designing custom Caesar Cipher, in addition to alphabets, we
are considering numeric digits from 0 to 9. Digits can also be shifted by
key places.
For Example, if a given plain text contains any digit with values 5 and
keyy =2, then 5 will be replaced by 7, “-”(minus sign) will remain as it is.
Key value less than 0 should result into “INVALID INPUT”

Example 1:
Enter your PlainText: All the best
Enter the Key: 1

The encrypted Text is: Bmm uif Cftu


Write a function CustomCaesarCipher(int key, String message) which
will accept plaintext and key as input parameters and returns its cipher
text as output.

Code:

public class CaesarCipher {

public static String CustomCaesarCipher(int key, String


message) {
// Check for invalid key value
if (key < 0) {
return "INVALID INPUT";
}

StringBuilder encryptedMessage = new StringBuilder();

for (char ch : message.toCharArray()) {


if (Character.isLetter(ch)) {
// Shift for alphabets
char base = Character.isUpperCase(ch) ? 'A' : 'a';
char encryptedChar = (char) ((ch - base + key) % 26 +
base);
encryptedMessage.append(encryptedChar);
} else if (Character.isDigit(ch)) {
// Shift for digits
char encryptedChar = (char) ((ch - '0' + key) % 10 +
'0');
encryptedMessage.append(encryptedChar);
} else {
// Keep other characters as they are (e.g., spaces,
punctuation)
encryptedMessage.append(ch);
}
}

return encryptedMessage.toString();
}

public static void main(String[] args) {


// Example input
String plainText = "All the best 123";
int key = 1;

String encryptedText = CustomCaesarCipher(key,


plainText);
System.out.println("The encrypted Text is: " +
encryptedText);
}
}

12. Problem Statement:


We want to estimate the cost of painting a property. Interior wall painting
cost is Rs.18 per sq.ft. and exterior wall painting cost is Rs.12 per sq.ft.

Take input as
1. Number of Interior walls
2. Number of Exterior walls
3. Surface Area of each Interior 4. Wall in units of square feet
Surface Area of each Exterior Wall in units of s

If a user enters zero as the number of walquare feet


ls then skip Surface area values as User may don’t want to paint that
wall.

Calculate and display the total cost of painting the property


Example 1:
6
3
12.3
15.2
12.3
15.2
12.3
15.2
10.10
10.10
10.00
Total estimated Cost : 1847.4 INR
Note: Follow in input and output format as given in above example

Code:
import java.util.Scanner;
class Main {
public static void main(String[] args) {
int ni, ne, i = 0;
Float cost = 0, temp;
Scanner sc = new Scanner(System.in);
ni = sc.nextInt();
ne = sc.nextInt();
if(ni < 0 || ne < 0) {
System.out.print("INVALID INPUT");
}
else {
for(i = 0; i < ni; i++) {
temp = sc.nextFloat();
cost +=18 * temp;
}
for(i = 0; i < ne; i++) {
temp = sc.nextFloat();
cost += 12 * temp;
}
System.out.printf("Total estimated Cost : %.1f", cost);
}
}
}

13. Problem Statement:


A City Bus is a Ring Route Bus which runs in circular fashion.That is,
Bus once starts at the Source Bus Stop, halts at each Bus Stop in its
Route and at the end it reaches the Source Bus Stop again.
If there are n number of Stops and if the bus starts at Bus Stop 1, then
after nth Bus Stop, the next stop in the Route will be Bus Stop number 1
always.
If there are n stops, there will be n paths.One path connects two stops.
Distances (in meters) for all paths in Ring Route is given in array Path[]
as given below:
Path = [800, 600, 750, 900, 1400, 1200, 1100, 1500]
Fare is determined based on the distance covered from source to
destination stop as Distance between Input Source and Destination
Stops can be measured by looking at values in array Path[] and fare can
be calculated as per following criteria:

● If d =1000 metres, then fare=5 INR


● (When calculating fare for others, the calculated fare containing
any fraction value should be ceiled. For example, for distance 900n
when fare initially calculated is 4.5 which must be ceiled to 5)

Path is circular in function. Value at each index indicates distance till


current stop from the previous one. And each index position can be
mapped with values at same index in BusStops [] array, which is a string
array holding abbreviation of names for all stops as-
“THANERAILWAYSTN” = ”TH”, “GAONDEVI” = “GA”, “ICEFACTROY” =
“IC”, “HARINIWASCIRCLE” = “HA”, “TEENHATHNAKA” = “TE”,
“LUISWADI” = “LU”, “NITINCOMPANYJUNCTION” = “NI”,
“CADBURRYJUNCTION” = “CA”

Given, n=8, where n is number of total BusStops.


BusStops = [ “TH”, ”GA”, ”IC”, ”HA”, ”TE”, ”LU”, ”NI”,”CA” ]

Path = [800, 600, 750, 900, 1400, 1200, 1100, 1500]


Write a code with function getFare(String Source, String Destination)
which take Input as source and destination stops(in the format
containing first two characters of the Name of the Bus Stop) and
calculate and return travel fare.

Example 1:
Input Values
ca
Ca
Output Values
INVALID OUTPUT

Example 2:
Input Values
NI
HA
Output Values :23.0 INR
Note: Input and Output should be in format given in example.
Input should not be case sensitive and output should be in the format
INR

Code:
import java.util.HashMap;
import java.util.Map;

public class RingRouteBusFare {


private static final int[] Path = {800, 600, 750, 900, 1400, 1200,
1100, 1500};
private static final String[] BusStops = {"TH", "GA", "IC", "HA",
"TE", "LU", "NI", "CA"};
private static final Map<String, Integer> stopIndexMap = new
HashMap<>();

static {
for (int i = 0; i < BusStops.length; i++) {
stopIndexMap.put(BusStops[i].toUpperCase(), i);
}
}

public static String getFare(String Source, String Destination) {


Source = Source.toUpperCase();
Destination = Destination.toUpperCase();

if (!stopIndexMap.containsKey(Source) || !
stopIndexMap.containsKey(Destination)) {
return "INVALID OUTPUT";
}

int sourceIndex = stopIndexMap.get(Source);


int destinationIndex = stopIndexMap.get(Destination);

int forwardDistance = 0;
int backwardDistance = 0;

// Calculate forward distance


for (int i = sourceIndex; i != destinationIndex; i = (i + 1) %
Path.length) {
forwardDistance += Path[i];
}

// Calculate backward distance


for (int i = sourceIndex; i != destinationIndex; i = (i - 1 +
Path.length) % Path.length) {
backwardDistance += Path[(i - 1 + Path.length) %
Path.length];
}

// Minimum of forward and backward distances


int distance = Math.min(forwardDistance,
backwardDistance);

// Calculate fare
double fare = Math.ceil(distance / 1000.0) * 5;

return fare + " INR";


}

public static void main(String[] args) {


// Example inputs
System.out.println(getFare("NI", "HA")); // Output: 23.0 INR
System.out.println(getFare("ca", "Ca")); // Output: INVALID
OUTPUT
}
}
14. Problem Statement:
There are total n number of Monkeys sitting on the branches of a huge
Tree. As travelers offer Bananas and Peanuts, the Monkeys jump down
the Tree. If every Monkey can eat k Bananas and j Peanuts. If total m
number of Bananas and p number of Peanuts are offered by travelers,
calculate how many Monkeys remain on the Tree after some of them
jumped down to eat.
At a time one Monkeys gets down and finishes eating and go to the
other side of the road. The Monkey who climbed down does not climb up
again after eating until the other Monkeys finish eating.
Monkey can either eat k Bananas or j Peanuts. If for last Monkey there
are less than k Bananas left on the ground or less than j Peanuts left on
the ground, only that Monkey can eat Bananas(<k) along with the
Peanuts(<j).
Write code to take inputs as n, m, p, k, j and return the number of
Monkeys left on the Tree.
Where, n= Total no of Monkeys
k= Number of eatable Bananas by Single Monkey (Monkey that
jumped down last may get less than k Bananas)
j = Number of eatable Peanuts by single Monkey(Monkey that
jumped down last may get less than j Peanuts)
m = Total number of Bananas
p = Total number of Peanuts
Remember that the Monkeys always eat Bananas and Peanuts, so there
is no possibility of k and j having a value zero

Example 1:
Input Values
20
2
3
12
12

Output Values
Number of Monkeys left on the tree:10
Note: Kindly follow the order of inputs as n,k,j,m,p as given in the above
example. And output must include the same format as in above
example(Number of Monkeys left on the Tree:)
For any wrong input display INVALID INPUT

Code:
import java.util.*;
class Monkeys
{
public static void main(String []args)
{
Scanner sc = new Scanner (System.in);
int n = sc.nextInt();
int k = sc.nextInt();
int j = sc.nextInt();
int m = sc.nextInt();
int p = sc.nextInt();
int atebanana=0 ,atepeanut=0;
if( n<0 && k<0 || j<0 || m<0 || p<0)
{
System.out.println("Invalid Input");
}
else
{
if(k>0)
{
atebanana =m/k;
m=m%k;
}
if(j>0)
{
atepeanut = p/j;
p=p%j;
}
n=n-atebanana-atepeanut;
if((m!=0) || (p!=0))
n=n-1;
System.out.println("Number of Monkeys left on the Tree:
"+n);
}
}
}
15. Problem Statement:
Chain Marketing Organization has has a scheme for income generation,
through which its members generate income for themselves. The
scheme is such that suppose A joins the scheme and makes R and V to
join this scheme then A is Parent Member of R and V who are child
Members. When any member joins the scheme then the parent gets
total commission of 10% from each of its child members.
Child members receive commission of 5% respectively. If a Parent
member does not have any member joined under him, then he gets
commission of 5%.
Take name of the members joining the scheme as input.
Display how many members joined the scheme including parent
member.Calculate the Total commission gained by each members in the
scheme. The fixed amount for joining the scheme is Rs.5000 on which
commission will be generated
SchemeAmount = 5000

Example 1: When there are more than one child members


Input : (Do not give input prompts.Accept values as follows. )
Amit //Enter parent Member as this
Y //Enter Y if Parent member has child members
otherwise enter N
Rajesh,Virat //Enter names of child members of Amit in comma
separated
Output:(Final Output must be in format given below.)
TOTAL MEMBERS:3
COMISSION DETAILS
Amit: 1000 INR
Rajesh :250 INR
Virat: 250 INR

Example 2: When there is only one child member in the hierarchy


Input :
Amit
Y
Rajesh
Output:
Total Members: 2
Comission Details
Amit: 500 INR
Rajesh: 250 INR

Code:
import java.util.*;

public class ChainMarketing {

private static final int SCHEME_AMOUNT = 5000;

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);
// Input for Parent Member
String parentMember = scanner.nextLine().trim();

// Input to check if parent has child members


String hasChildMembers =
scanner.nextLine().trim().toUpperCase();

// List to store all members


List<String> members = new ArrayList<>();
members.add(parentMember);

Map<String, Double> commissionMap = new


HashMap<>();
commissionMap.put(parentMember, 0.0);

// Handle child members


if (hasChildMembers.equals("Y")) {
String childMembersInput = scanner.nextLine().trim();
String[] childMembers = childMembersInput.split(",");

for (String child : childMembers) {


child = child.trim();
members.add(child);
commissionMap.put(child, SCHEME_AMOUNT *
0.05); // Each child gets 5% of the scheme amount
}

// Parent gets 10% from each child


commissionMap.put(parentMember,
childMembers.length * (SCHEME_AMOUNT * 0.1));

} else {
// Parent gets 5% if no child members
commissionMap.put(parentMember, SCHEME_AMOUNT
* 0.05);
}

// Output total members


System.out.println("TOTAL MEMBERS: " +
members.size());

// Output commission details


System.out.println("COMMISSION DETAILS");
for (String member : members) {
System.out.printf("%s: %.0f INR%n", member,
commissionMap.get(member));
}
}
}

16. Problem Statement:


FULLY AUTOMATIC VENDING MACHINE – dispenses your cuppa on
just press of button. A vending machine can serve range of products as
follows:

Coffee

1. Espresso Coffee
2. Plain Tea
3. Cappuccino Coffee
4. Latte Coffee
Tea

1. Assam Tea
2. Ginger Tea
3. Cardamom Tea
4. Masala Tea
5. Lemon Tea
6. Green Tea
7. Organic Darjeeling Tea

Soups

1. Hot and Sour Soup


2. Veg Corn Soup
3. Tomato Soup
4. Spicy Tomato Soup

Beverages

1. Hot Chocolate Drink


2. Badam Drink
3. Badam-Pista Drink

Write a program to take input for main menu & sub menu and display the
name of sub menu selected in the following format (enter the first letter
to select main menu):

Welcome to CCD
Enjoy your
Example 1:

Input:
c
1
Output
Welcome to CCD!
Enjoy your Espresso Coffee!

Example 2:
Input:
t
9
Output
INVALID OUTPUT!

Code:
import java.util.Scanner;

public class VendingMachine {

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

// Main menu options


System.out.println("Select your option: ");
char mainMenuOption =
scanner.next().toLowerCase().charAt(0);

// Sub-menu selection
int subMenuOption = scanner.nextInt();
String selectedDrink = getSelectedDrink(mainMenuOption,
subMenuOption);

if (selectedDrink.equals("INVALID")) {
System.out.println("INVALID OUTPUT!");
} else {
System.out.println("Welcome to CCD!");
System.out.println("Enjoy your " + selectedDrink + "!");
}
}

private static String getSelectedDrink(char mainMenuOption,


int subMenuOption) {
switch (mainMenuOption) {
case 'c': // Coffee
switch (subMenuOption) {
case 1: return "Espresso Coffee";
case 2: return "Cappuccino Coffee";
case 3: return "Latte Coffee";
default: return "INVALID";
}
case 't': // Tea
switch (subMenuOption) {
case 1: return "Plain Tea";
case 2: return "Assam Tea";
case 3: return "Ginger Tea";
case 4: return "Cardamom Tea";
case 5: return "Masala Tea";
case 6: return "Lemon Tea";
case 7: return "Green Tea";
case 8: return "Organic Darjeeling Tea";
default: return "INVALID";
}
case 's': // Soups
switch (subMenuOption) {
case 1: return "Hot and Sour Soup";
case 2: return "Veg Corn Soup";
case 3: return "Tomato Soup";
case 4: return "Spicy Tomato Soup";
default: return "INVALID";
}
case 'b': // Beverages
switch (subMenuOption) {
case 1: return "Hot Chocolate Drink";
case 2: return "Badam Drink";
case 3: return "Badam-Pista Drink";
default: return "INVALID";
}
default:
return "INVALID";
}
}
}

17. Problem Statement:


A doctor has a clinic where he serves his patients. The doctor’s
consultation fees are different for different groups of patients depending
on their age. If the patient’s age is below 17, fees are 200 INR. If the
patient’s age is between 17 and 40, the fee is 400 INR. If the patient's
age is above 40, fees is 300 INR. Write a code to calculate earnings in a
day for which one array/List of values representing the age of patients
visited on that day is passed as input.
Note:

● Age should not be zero or less than zero or above 120


● Doctor consults a maximum of 20 patients a day
● Enter age value (press Enter without a value to stop):

Example 1:
Input
20 30 40 50 2 3 14
Output
Total Income 2000 INR
Note: Input and Output Format should be same as given in the above
example.For any wrong input display INVALID INPUT
Output Format
Total Income 2100 INR

Code:
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class DoctorEarnings {

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);
List<Integer> ages = new ArrayList<>();
int totalIncome = 0;
System.out.println("Enter age value (press Enter without a
value to stop):");

// Reading input until Enter without a value is pressed


while (true) {
String input = scanner.nextLine().trim();
if (input.isEmpty()) {
break;
}
try {
int age = Integer.parseInt(input);
if (age <= 0 || age > 120) {
System.out.println("INVALID INPUT");
return;
}
if (ages.size() >= 20) {
System.out.println("INVALID INPUT");
return;
}
ages.add(age);
} catch (NumberFormatException e) {
System.out.println("INVALID INPUT");
return;
}
}

// Calculate total income based on age


for (int age : ages) {
if (age < 17) {
totalIncome += 200;
} else if (age <= 40) {
totalIncome += 400;
} else {
totalIncome += 300;
}
}

// Output the total income


System.out.println("Total Income " + totalIncome + " INR");
}
}

18. Problem Statement:


Checking if a given year is leap year or not

Explanation:
To check whether a year is leap or not
Step 1:

● We first divide the year by 4.


● If it is not divisible by 4 then it is not a leap year.
● If it is divisible by 4 leaving remainder 0

Step 2:

● We divide the year by 100


● If it is not divisible by 100 then it is a leap year.
● If it is divisible by 100 leaving remainder 0
Step 3:

● We divide the year by 400


● If it is not divisible by 400 then it is a leap year.
● If it is divisible by 400 leaving remainder 0

Then it is a leap year

Code:
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
//scanner class declaration
Scanner sc=new Scanner(System.in);
//input year from user
System.out.println("Enter a Year");
int year = sc.nextInt();
//condition for checking year entered by user is a leap year
or not
if((year % 4 == 0 && year % 100 != 0) || year % 400 == 0)
System.out.println(year + " is a leap year.");
else
System.out.println(year + " is not a leap year.");
}
}
19. Problem Statement:

Ques. Write a code to check whether no is prime or not.


Condition use function check() to find whether entered no is
positive or negative ,if negative then enter the no, And if yes pas
no as a parameter to prime() and check whether no is prime or
not?

Whether the number is positive or not, if it is negative then print


the message “please enter the positive number”
It is positive then call the function prime and check whether the
take positive number is prime or not.

Code:
import java.util.Scanner;
class Main
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
//input a number from user
System.out.println("Enter the number to be checked : ");
int n = sc.nextInt();
//create object of class CheckPrime
Main ob=new Main();
//calling function with value n, as parameter
ob.check(n);
}
//function for checking number is positive or negative
void check(int n)
{
if(n<0)
System.out.println("Please enter a positive integer");
else
prime(n);
}
//function for checking number is prime or not
void prime(int n)
{
int c=0;
for(int i=2;i<n;i++)
{
if(n%i==0)
++c;
}
if(c>=1)
System.out.println("Entered number is not a prime number");
else
System.out.println("Entered number is a prime number");
}
}

20. Problem Statement:

Find the 15th term of the series?


0,0,7,6,14,12,21,18, 28
Explanation :
In this series the odd term is increment of 7 {0, 7, 14, 21, 28, 35 – – – – –
–}
And even term is a increment of 6 {0, 6, 12, 18, 24, 30 – – – – – – }
Code:
class Main
{
public static void main(String[] args)
{
int a = 7, b = 0,c;
System.out.println("Series :");
for(int i = 1 ; i < 8 ; i++)
{
c = a * b;
System.out.print(c+" "+(c-b)+" ");
b++;
}
c = a * b;
System.out.println(c);
System.out.print("15th element of the series is =
"+c);
}
}

21. Problem Statement:


Consider the following series: 1, 1, 2, 3, 4, 9, 8, 27, 16, 81, 32,
243, 64, 729, 128, 2187 …

This series is a mixture of 2 series – all the odd terms in this


series form a geometric series and all the even terms form yet
another geometric series. Write a program to find the Nth term in
the series.
The value N in a positive integer that should be read from
STDIN. The Nth term that is calculated by the program should be
written to STDOUT. Other than value of n th term,no other
character / string or message should be written to STDOUT. For
example , if N=16, the 16th term in the series is 2187, so only
value 2187 should be printed to STDOUT.

You can assume that N will not exceed 30.

Code:
import java.util.Scanner;
class Main
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
//input value of n
System.out.print("Enter the value of n : ");

int n = sc.nextInt();
int a = 1, b = 1;
//statement for even value of n
if(n % 2 == 0)
{
for(int i = 1 ; i <= (n-2) ; i = i+2)
{
a = a * 2;
b = b * 3;
}
System.out.print(n+" element of the series is =
"+b);
}
//statement for odd value of n
else
{
for(int i = 1 ; i < (n-2) ; i = i+2)
{
a = a * 2;
b = b * 3;
}
a = a * 2;
System.out.print(n+" element of the series is =
"+a);
}
}
}
22. Problem Statement:
Consider the below series :

0, 0, 2, 1, 4, 2, 6, 3, 8, 4, 10, 5, 12, 6, 14, 7, 16, 8

This series is a mixture of 2 series all the odd terms in this series form
even numbers in ascending order and every even terms is derived from
the previous term using the formula (x/2)
Write a program to find the nth term in this series.
The value n in a positive integer that should be read from STDIN the nth
term that is calculated by the program should be written to STDOUT.
Other than the value of the nth term no other characters /strings or
message should be written to STDOUT.

For example if n=10,the 10 th term in the series is to be derived from the


9th term in the series. The 9th term is 8 so the 10th term is (8/2)=4. Only
the value 4 should be printed to STDOUT.

You can assume that the n will not exceed 20,000.

Code:
import java.util.Scanner;
class Main
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int a = 0, b = 0;
if(n % 2 == 0)
{
for(int i = 1 ; i <= (n-2) ; i = i+2)
{
a = a + 2;
b = a / 2;
}
System.out.print(b);
}
else
{
for(int i = 1 ; i < (n-2) ; i = i+2)
{
a = a + 2;
b = a / 2;
}
a = a + 2;
System.out.print(a);
}
}
}
23. Problem Statement:
The program will recieve 3 English words inputs from STDIN

1. These three words will be read one at a time, in three separate line
2. The first word should be changed like all vowels should be
replaced by %
3. The second word should be changed like all consonants should be
replaced by #
4. The third word should be changed like all char should be converted
to upper case
5. Then concatenate the three words and print them

Other than these concatenated word, no other characters/string should


or message should be written to STDOUT

For example if you print how are you then output should be h
%wa#eYOU.

You can assume that input of each word will not exceed more than 5
chars

Code:
import java.util.*;
public class Main
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter three words : ");

String s1 = sc.next();
String s2 = sc.next();
String s3 = sc.next();

int l1 = s1.length();
int l2 = s2.length();

String str1 = "";


String str2 = "";
String str3 = "";
char c;
for(int i = 0 ; i < l1 ; i++)
{
c = s1.charAt(i);
if(c == 'A' || c == 'a' || c == 'E' ||
c == 'e' || c == 'I' || c == 'i' || c == 'O' || c == 'o' || c ==
'U' || c == 'u')
str1 = str1 + "%";
else
str1 = str1 + c;
}
for(int i = 0 ; i < l2 ; i++)
{
c = s2.charAt(i);
if((c >= 'A' && c <= 'Z')||(c >= 'a' && c <= 'z'))
{
if(c == 'A' || c == 'a' || c == 'E' || c == 'e' ||
c == 'I' || c == 'i' || c == 'O' || c == 'o' || c == 'U' || c ==
'u')
str2 = str2 + c;
else
str2 = str2 + "#";
}
else
str2 = str2 + c;
}
str3 = s3.toUpperCase();
System.out.println(str1+str2+str3);
}
}

24. Problem Statement:


Using a method, pass two variables and find the sum of two numbers.
Test case:
Number 1 – 20
Number 2 – 20.38
Sum = 40.38

There were a total of 4 test cases. Once you compile 3 of them will be
shown to you and 1 will be a hidden one. You have to display error
message if numbers are not numeric.

Code:
import java.util.Scanner;
class Main
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.print("Number 1 : ");
int num1 = sc.nextInt();
System.out.print("Number 2 : ");
float num2 = sc.nextFloat();
float sum = num1 + num2;
System.out.println("Sum = "+sum);
}
}

25. Problem Statement:


Consider the below series :
0, 0, 2, 1, 4, 2, 6, 3, 8, 4, 10, 5, 12, 6, 14, 7, 16, 8
This series is a mixture of 2 series all the odd terms in this series form
even numbers in ascending order and every even terms is derived from
the previous term using the formula (x/2)
Write a program to find the nth term in this series.
The value n in a positive integer that should be read from STDIN the nth
term that is calculated by the program should be written to STDOUT.
Other than the value of the nth term no other characters /strings or
message should be written to STDOUT.
For example if n=10,the 10 th term in the series is to be derived from the
9th term in the series. The 9th term is 8 so the 10th term is (8/2)=4. Only
the value 4 should be printed to STDOUT.

You can assume that the n will not exceed 20,000.

Code:
26. Problem Statement:
Given a non-negative integer array Arr having size N. Each
element of the array will carry a different
value. This means no two elements can have the same
values.The candidate has to do this with minimal
changes in the original value of the elements, making every
element as least as much value as it originally
had.
Find the minimum sum of all elements that can be set the array
for:
Example 1:
Input
3 -> Value of N, represents size of Arr
2 -> Value of Arr[0]
2-> Value of Arr[1]
4-> Value of Arr[2]
Output
9
Explanation:
As two elements have the same value, max value for the one of
them needs to be incremented to 3.
He can set the array with 2+3+4=9
Example 2:
Input
2 -> Value of N, represents size of Arr
3 -> Value of Arr[0]
4-> Value of Arr[1]
5-> Value of Arr[2]
Output
Wrong Input
Explanation:
Here N=2, so we need to provide value of only two elements but
we are providing value of three elements
so result is “Wrong Input”
The Input format for the testing
First input line: Accept a single positive integer value for N
representing the size of Arr[]
Second input line: Accept N number of integer values separated
by a new line, representing the original
value assigned to each element.
Output Format for testing:
The output must be a non integer only (See the output format
example).

Violation of input criteria: System should display message as


“Wrong Input”.
Additional messages in the output will result in the failure of the
test cases.

Code:
import java.util.Arrays;
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;

public class MinArraySum {

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

// Read the value of N


int N = scanner.nextInt();
// Validate the input size
int[] Arr = new int[N];
for (int i = 0; i < N; i++) {
if (scanner.hasNextInt()) {
Arr[i] = scanner.nextInt();
} else {
System.out.println("Wrong Input");
return;
}
}

// Additional check if more numbers are provided


if (scanner.hasNextInt()) {
System.out.println("Wrong Input");
return;
}

// Sort the array to make handling duplicates easier


Arrays.sort(Arr);

// Set to keep track of the unique values


Set<Integer> uniqueValues = new HashSet<>();

int sum = 0;
for (int i = 0; i < N; i++) {
// Increment the value until it's unique
while (uniqueValues.contains(Arr[i])) {
Arr[i]++;
}
uniqueValues.add(Arr[i]);
sum += Arr[i];
}

// Output the minimum sum


System.out.println(sum);
}
}

27. Problem Statement:


Joseph is learning digital logic subject which will be for his next
semester. He usually tries to solve unit assignment problems
before the lecture. Today, he got one tricky question. The
problem statement is “A positive integer has been given as an
input. Convert decimal value to binary representation. Toggle all
bits
of it after the most significant bit including the most significant bit.
Print the positive integer value after
toggling all bits”.

Constraints
1 <=N <=100
Example 1
Input:
10 ---> Integer
Output:
5 → result - Integer
Explanation:
Binary representation of 10 is 1010. After toggling the bits
(1010), will get 0101, which represents “5”.
Hence the output will print “5”.
Example 2
Input:
101 ---> Integer
Output:
Wrong input → result - String
Explanation:
Given integer “101” is out of range. Hence the output will print
“Wrong input”.
The input format for testing
The candidate has to write the code to accept one input(s).
1. First Input - First line contains an integer
The output format for testing
1. Print integer value based on the number got after toggling all
the bits of given input.
2. Print “Wrong input if the string length is out of the range.
3. Additional messages in output will cause the failure of test
cases.
Instructions
1. The system doesn’t allow any kind of hard-coded input value.
2. Written program code by the candidate will be verified against
all the inputs which are supplied from
the system.

Code:
import java.util.Scanner;

public class ToggleBits {

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

// Read the input integer


int N = scanner.nextInt();
// Check if the input is within the valid range
if (N < 1 || N > 100) {
System.out.println("Wrong input");
return;
}

// Convert the integer to its binary representation as a string


String binaryString = Integer.toBinaryString(N);

// Toggle the bits


StringBuilder toggledBinary = new StringBuilder();
for (int i = 0; i < binaryString.length(); i++) {
// If the bit is '1', change it to '0', and vice versa
if (binaryString.charAt(i) == '1') {
toggledBinary.append('0');
} else {
toggledBinary.append('1');
}
}

// Convert the toggled binary string back to an integer


int result = Integer.parseInt(toggledBinary.toString(), 2);

// Print the result


System.out.println(result);
}
}
28. Problem Statement:
Airport security officials have confiscated several items of the
passenger at the security checkpoint. All
the items have been dumped into a huge box(array). Each item
possessed a certain amount of risk(0,1,2).
Here is the risk severity of the item representing an array[] of N
number of integer values. The risk here is to
sort the item based on their level of risk values range from 0 to 2.
Example 1:
Input:
7 ----- Value of N
[1,0,2,0,1,0,2] -> Element of arr[0] to arr[N-1], while input each
element is separated by new line
Output:
0 0 0 1 1 2 2 -> Element after sorting based on the risk severity.
Example 2:
Input:
10 ----- Value of N
[2,1,0,2,1,0,0,1,2,0] -> Element of arr[0] to arr[N-1], while input
each element is separated by new line
Output:
0 0 0 0 0 1 1 1 2 2 2 -> Element after sorting based on the risk
severity.
Constraints
0<N<=100
0<=arr[i]<=2

Code:
import java.util.Scanner;

public class AirportSecurity {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

// Read the value of N


int N = scanner.nextInt();

// Validate the input size


if (N <= 0 || N > 100) {
System.out.println("Wrong input");
return;
}

int[] arr = new int[N];

// Read the elements into the array


for (int i = 0; i < N; i++) {
arr[i] = scanner.nextInt();
// Validate each element to be within the range [0, 2]
if (arr[i] < 0 || arr[i] > 2) {
System.out.println("Wrong input");
return;
}
}

// Sort the array based on the risk severity


sortRiskSeverity(arr);

// Print the sorted array


for (int i = 0; i < N; i++) {
System.out.print(arr[i] + " ");
}
}
// Function to sort the array with 0s, 1s, and 2s
public static void sortRiskSeverity(int[] arr) {
int low = 0, mid = 0, high = arr.length - 1;

while (mid <= high) {


switch (arr[mid]) {
case 0:
// Swap arr[low] and arr[mid], increment low and mid
int temp0 = arr[low];
arr[low] = arr[mid];
arr[mid] = temp0;
low++;
mid++;
break;

case 1:
// Just increment mid
mid++;
break;

case 2:
// Swap arr[mid] and arr[high], decrement high
int temp2 = arr[mid];
arr[mid] = arr[high];
arr[high] = temp2;
high--;
break;
}
}
}
}
29. Problem Statement:
Given N gold wires, each wire has a length associated with it. At
a time, only two adjacent small wres
assembled at the end of a large wire and the cost of forming is
the sum of their length. Find the minimum
cost when all wires are assembled to form a single wire.
For Example:
Suppose, Arr[] = {7, 6, 8, 6, 1, 1}
{7, 6, 8, 6, 1, 1} - {7, 6, 8, 6, 2}, cost = 2
{7, 6, 8, 6, 2} - {7, 6, 8, 8}, cost = 8
{7, 6, 8, 8} - {13, 8, 8}, cost =13
{13, 8, 8} - {13, 16}, cost = 16
{13, 16} - {29}, cost = 29
2 + 8 + 13 + 16 + 29 = 68
Hence, the minimum cost to assemble all gold wires is : 68
Constraints:
1 <= N <= 30
1<= Arr[] <= 100
Example 1:
Input:
6 -> Value of N, represents size of Arr
7 -> Value of Arr[0], represents length of 1st wire
6 -> Value of Arr[1], represents length of 2nd wire
8 -> Value of Arr[2], represents length of 3rd wire
6 -> Value of Arr[3], represents length of 4th wire
-1 -> Value of Arr[4], represents length of 5th wire
1 -> Value of Arr[5], represents length of 6th wire
Output:
68
Example 2:
Input:
4 -> Value of N, represents size of Arr
12 -> Value of Arr[0], represents length of 1st wire
2 -> Value of Arr[1], represents length of 2nd wire
2 -> Value of Arr[2], represents length of 3rd wire
5 -> Value of Arr[3], represents length of 4th wire

Output:
34

Code:
import java.util.PriorityQueue;
import java.util.Scanner;

public class GoldWireAssembly {

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

// Read the value of N


int N = scanner.nextInt();

// Validate the input size


if (N < 1 || N > 30) {
System.out.println("Wrong input");
return;
}

PriorityQueue<Integer> pq = new PriorityQueue<>();


// Read the lengths of the wires into the priority queue
for (int i = 0; i < N; i++) {
int length = scanner.nextInt();
if (length < 1 || length > 100) {
System.out.println("Wrong input");
return;
}
pq.add(length);
}

int totalCost = 0;

// Combine the wires until we have one wire left


while (pq.size() > 1) {
int first = pq.poll();
int second = pq.poll();

int combined = first + second;


totalCost += combined;

pq.add(combined);
}

// Output the minimum cost


System.out.println(totalCost);
}
}
30. Problem Statement:
A carpet manufacturing industry has newly ventured into the
carpet installation business. All the carpets
manufactured are large squares in shape. To install, each carpet
has to be cut into shapes of squares or
rectangles. The number of slits to be made is given as N.
The task is to find the maximum number of equal squares or
rectangles that can be achieved using N slits.
Note:
The square carpet can be cut only using horizontal or vertical
slits.
Cuttings are done on a single carpet which should be rolled out
completely i.e. no folding or stacking is
allowed.
Squares or rectangles cut should be equal size.
Example 1:
Input:
4 → Value of N(No. of cuts)
Output:
9 → maximum number of equal squares or rectangles
Explanation:

Solution 2
Maximum number of squares/rectangles that can be obtained
with N=4 is 9(Solution 1)
Hence, output is 9
Example 2:
Input:
1 → Value of N(No. of teams)
Output:
2 → maximum number of equal squares or rectangles
Code:
import java.util.Scanner;

public class CarpetCutting {

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

// Read the value of N (number of slits)


int N = scanner.nextInt();

// Calculate maximum number of equal squares or


rectangles
int maxHorizontal = (N / 2) + 1;
int maxVertical = ((N + 1) / 2) + 1;
int maxPieces = maxHorizontal * maxVertical;

// Output the result


System.out.println(maxPieces);
}
}

31. Problem Statement:


A family is about to break their piggy bank to use the money for
different purposes. The piggy bank here
represents an array (arr[]) consisting of N coins. The family has
to split the coins of piggy bank into smaller
stack (sub-array) of coins such that the sum of the difference
between the maximum value and the minimum
value of the coins for all the stacks (sub-arrays) is maximum.
Note: Each value of the array can be used only once that is only
in one subarray.

Constraints:
1 <= N <= 500
1 <=arr[i] <= 100
Example 1:
Input:
5 → Value of N
{8,1,7,9,2} → arr[] elements from arr[0] to arr [N-1],
Where each element is separated by new line.
Output:
14
Explanation:

21

Let us break the array elements into following subarrays:


1. (8,1) → Max:8 Min:1
2. (7,9,2) → Max:9 Min:2
So, the difference between the maximum and minimum elements
in each subarrays is
1. 8-1=7
2.9-2=7
Now, the sum of the differences of subarray is:
7+7=14
Hence, output is 14.
Example 2:
Input:
5 → Value of N
{1,2,1,0,5} → arr[], elements from arr[0] to arr [N-1],
where each elements is separated by a new line.
Output:
6
Explanation:
Let us break the array elements into following subarrays:
1. (1,2,1) → max:2, min:1
2. (0,5) → max:5, min:0
So, the difference between the max and min elements in each
subarray is
1. 2-1 = 1
2. 5-0 = 5
Now, the sum of the differences of subarraya is:
1+5 = 6
Hence, output is 6.
The input format for testing
The candidate has to write the code to accept 2 inputs.
First input - Accept value for N(positive integer number)
Second input - Accept N number of values (arr[]), where each
value is separated by a new line.

Code:
import java.util.Arrays;
import java.util.Scanner;

public class PiggyBank {

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

// Read the value of N


int N = scanner.nextInt();

// Read the elements into the array


int[] arr = new int[N];
for (int i = 0; i < N; i++) {
arr[i] = scanner.nextInt();
}

// Sort the array


Arrays.sort(arr);

int maxDifferenceSum = 0;

// Calculate the differences by splitting


for (int i = 0; i < N / 2; i++) {
maxDifferenceSum += arr[N - 1 - i] - arr[i];
}

// If the number of elements is odd, add the middle


element's contribution
if (N % 2 == 1) {
maxDifferenceSum += arr[N / 2];
}

// Output the maximum sum of differences


System.out.println(maxDifferenceSum);
}
}

32. Problem Statement:


A supermarket maintains a pricing format for all its products. A
value N printed on each product. When
the scanner reads the value N on the item, the product of all the
digits in the value N is the price of the item.
The task is to design a software such that given the code of any
item N the product(multiplication) of all the
digits of value should be computed(price).
Example 1:
Input:
5244 -->Value of N
Output:
160 -->Price
Explanation:
From the input above:
Product of the digits: 5,1,4,4
5*2*4*4 = 160
Hence Output is 160

Code:
import java.util.Scanner;

public class ProductPriceCalculator {

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

// Read the value of N


int N = scanner.nextInt();
int price = 1;

// Calculate the product of the digits


while (N > 0) {
int digit = N % 10; // Get the last digit
price *= digit; // Multiply it to the product
N /= 10; // Remove the last digit from N
}

// Output the calculated price


System.out.println(price);
}
}

33. Problem Statement:


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, 56 and G, & should be deleted
The characters EF should be in the same format.
Example 1:
Input:
4523EF58G -> Value of STR1
Output:
452358 -> After removal of characters
‘EF’ and ‘G’
Example 2:
Input:
E12F35G58 -> Value of STR1
Output:
E12F3558 -> After removal of character ‘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 removal.
The Input format for testing
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.
The output format for testing
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

Code:
import java.util.Scanner;

public class TicketFilter {

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

// Read the input string


String str1 = scanner.nextLine();

// Remove "EF", "56", and "G" from the string


String result = str1.replaceAll("EF", "")
.replaceAll("56", "")
.replaceAll("G", "");
// Output the resulting string
System.out.println(result);
}
}

34. Problem Statement:


Given an array Arr[] of size T, contains binary digits.
Where
0 represents a biker running to the north.
1 represents a biker running to the south.
The task is to count crossing bikers in such a way that each pair
of crossing bikers (N, S), where 0<=N<S<T,
is passing when N is running to the north and S is running to the
south.

23

Constraints:
<=N<S<T
Example -1:
Input:
5. -> Number of elements i.e. T
0. -> Value of 1st element
1. -> Value of 2nd element
0. -> Value of 3rd element
1. -> Value of 4th element
1. -> Value of 5th element
Output:
5
Explanation:
The 5 pairs are (Arr[0], Arr[1]), (Arr[0], Arr[3]), (Arr[0], Arr[4]),
(Arr[2], Arr[3]) and (Arr[2], Arr[4]).
Note that in all pairs first element is 0, second element is 1 and
index of first element is smaller than index
of second element.
The Input format for testing:
First input line: Accept a single positive integer value for T
representing the size of Arr[].
Second input line:: Accept N number of integer values (0 or 1)
separated by a new line.
Output Format for Testing:
The output must be a non-negative integer number only (See the
output format in example).
Additional messages in the output will result in the failure of test
cases.

Code:
import java.util.Scanner;

public class BikerCrossing {

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

// Read the number of elements T


int T = scanner.nextInt();

int[] Arr = new int[T];


for (int i = 0; i < T; i++) {
Arr[i] = scanner.nextInt();
}
int count = 0;
int northBikers = 0;

// Loop through the array and count the crossings


for (int i = 0; i < T; i++) {
if (Arr[i] == 0) {
// Count the number of bikers running to the north
northBikers++;
} else if (Arr[i] == 1) {
// Every south-bound biker (1) can pair with all
previous north-bound bikers (0)
count += northBikers;
}
}

// Output the result


System.out.println(count);
}
}

35. Problem Statement:


Given an array of integers where every element appears even
number of times except one element which appears odd number
of times, write a program to find that odd occurring element in
O(log n) time. The equal elements must appear in pairs in the
array but there cannot be more than two consecutive
occurrences of an element.

For example :
3

232

It doesn't have equal elements appear in pairs

1122233

It contains three consecutive instances of an element.

22311

It is valid and the odd occurring element present in it is 3.

Enter only valid inputs.

Sample Input :

22311

Sample Output :

Code:
import java.util.*;

public class Main

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

int n = sc.nextInt();

int arr[] = new int[n];

for(int i=0 ; i<n ; i++){

arr[i] = sc.nextInt();

int left=0,right=n-1,mid,pre,nxt;

if(arr[0] != arr[1]){

System.out.print(arr[0]);

else if(arr[n-1] != arr[n-2]){

System.out.print(arr[n-1]);
}

else{

while(left <= right){

mid = ((right-left)/2)+left;

pre = mid-1;

nxt = mid+1;

if((arr[pre] != arr[mid]) && (arr[nxt] != arr[mid])){

System.out.print(arr[mid]);

break;

else if(mid%2==0){

if(arr[pre] == arr[mid])

right = mid - 1;

else

left = mid + 1;

}
else{

if(arr[pre] == arr[mid])

left = mid + 1;

else

right = mid - 1;

36. Problem Statement:


Given an array of integers and a sum, the task is to count all
subsets of given array with sum equal to given sum.
Input :

The first line of input contains an integer T denoting the number


of test cases. Then T test cases follow. Each test case contains
an integer n denoting the size of the array. The next line contains
n space separated integers forming the array. The last line
contains the sum.
Output :

Count all the subsets of given array with sum equal to given
sum.

NOTE: Since result can be very large, print the value modulo
109+7.

Constraints :

1<=T<=100

1<=n<=103

1<=a[i]<=103

1<=sum<=103

Example :

Input :

2 3 5 6 8 10

10

5
12345

10

Output :

Explanation :

Testcase 1: possible subsets : (2,3,5) , (2,8) and (10)

Testcase 2: possible subsets : (1,2,3,4) , (2,3,5) and (1,4,5)

Code:
import java.io.*;

import java.util.*;

class Main {

static void printBool(int n, int len)

while (n>0) {
if ((n & 1) == 1)

System.out.print(1);

else

System.out.print(0);

n >>= 1;

len--;

while (len>0) {

System.out.print(0);

len--;

System.out.println();

}
static void printSubsetsCount(int set[], int n, int val)

int sum;

int count = 0;

for (int i = 0; i < (1 << n); i++) {

sum = 0;

for (int j = 0; j < n; j++)

if ((i & (1 << j)) > 0) {

sum += set[j];

if (sum == val) {

count++;

}
if (count == 0) {

System.out.println("No subset is
found");

else {

System.out.println(count);

public static void main(String[] args)

Scanner sc = new Scanner(System.in);

int t = sc.nextInt();

int n,sum;

while(t>0)

{
n=sc.nextInt();

int set[] = new int[n];

for(int i=0;i<n;i++)

set[i] = sc.nextInt();

sum = sc.nextInt();

printSubsetsCount(set, n, sum);

t--;

37. Problem Statement:


You are given a string A and you have to find the number of
different sub-strings of the string A which are fake palindromes.

Note:

1. Palindrome: A string is called a palindrome if you reverse the


string yet the order of letters remains the same. For example,
MADAM.
2. Fake Palindrome: A string is called as a fake palindrome if any
of its permutations is a palindrome. For example, AAC is fake
palindrome, but ACD is not.

3. Sub-string: A sub-string is a contiguous sequence (non-empty)


of characters within a string.

4. Two sub-strings are considered same if their starting indices


and ending indices are equal.

Input Format:

First line contains a string S

Output Format:

Print a single integer (number of fake palindrome sub-strings).

Constraints:

1 <= |S| <= 2 * 105

The string will contain only Upper case 'A' to 'Z'

Sample Input 1:

ABAB

Sample Output 1:

7
Explanation:

The fake palindrome for the string ABAB are A, B, A, B, ABA,


BAB, ABAB.

Sample Input 2:

AAA

Sample output 2:

Explanation:

The fake palindrome for the string AAA are A, A, A, AA, AA, AAA

Code:
import java.util.*;

class Main{

static void countSubString(String s)

int res = 0;

for (int i = 0; i < s.length(); i++)

{
int x = 0;

for (int j = i; j < s.length(); j++)

int temp = 1 << s.charAt(j) - 'a';

x ^= temp;

if ((x & (x - 1)) == 0)

res++;

System.out.print(res);

public static void main(String[] args)

{
Scanner sc = new Scanner(System.in);

String str = sc.nextLine();

countSubString(str);

38. Problem Statement:


For enhancing the book reading, school distributed story books
to students as part of the Children’s day celebrations. To
increase the reading habit, the class teacher decided to
exchange the books every weeks so that everyone will have a
different book to read. She wants to know how many possible
exchanges are possible.
If they have 4 books and students, the possible exchanges are 9.
Bi is the book of i-th student and after the exchange, he should
get a different book, other than Bi.

B1 B2 B3 B4 – first state, before exchange of the books

B2 B1 B4 B3

B2 B3 B4 B1

B2 B4 B1 B3
B3 B1 B4 B2

B3 B4 B1 B2

B3 B4 B2 B1

B4 B1 B2 B3

B4 B3 B1 B2

B4 B3 B2 B1

Find the number of possible exchanges, if the books are


exchanged so that every student will receive a different book.

Constraints

1<= N <= 1000000

Input Format

Input contains one line with N, indicates the number of books


and number of students.

Output Format

Output the answer modulo 100000007.

Refer the sample output for formatting

Sample Input :
4

Sample Output :

Code:
import java.util.*;

public class Main

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

int mod = (int)1e8+7;

long n,a=0,b=1,c=2,d=0;

n = sc.nextLong();

if(n==1 || n==2)

System.out.println(n-1);

else{

for(int i=3 ; i<=n ; i++){


d = (c * (a + b)) % mod ;

a = b;

b = d;

c++;

System.out.println(d);

39. Problem Statement:


Before the outbreak of corona virus to the world, a meeting
happened in a room in Wuhan. A person who attended that
meeting had COVID-19 and no one in the room knew about it!
So everyone started shaking hands with everyone else in the
room as a gesture of respect and after meeting unfortunately
every one got infected! Given the fact that any two persons
shake hand exactly once, Can you tell the total count of
handshakes happened in that meeting?
Input Format :

The first line contains the number of test cases T, T lines follow.
Each line then contains an integer N, the total number of people
attended that meeting.

Output Format :

Print the number of handshakes for each test-case in a new line.

Constraints :

1 <= T <= 1000

0 < N < 106

Sample Input :

Output :

Explanation :

Case 1 : The lonely board member shakes no hands, hence 0.

Case 2 : There are 2 board members, 1 handshake takes place.


Code:

import java.util.*;

public class Main

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

int t,n;

long sum;

t = sc.nextInt();

while(t > 0){

n = sc.nextInt();

n--;

sum = (n*(n+1))/2;

System.out.println(sum);

t--;
}

40. Problem Statement:


Given a maximum of four digit to the base 17 (10 - A, 11
- B, 12 - C, 13 - D .... 16 - G} as input, output its decimal
value.
Case 1:
Input - 1A
Expected Output - 27

Explantion : The value A will be multiplied by 17^0 and


value 1 will be multiplied by 17^1.
=> ((1*17^1) + (A*17^0))
=> ((1*17^1) + (10*17^0)) //As A equals 10
=> 17 + 10 => 27
So the output will be 27
Code:
import java.util.Scanner;

public class Base17ToDecimal {

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);
// Read the input number in base 17
String base17Number = scanner.nextLine().toUpperCase();

int decimalValue = 0;
int length = base17Number.length();

// Iterate through each character of the string


for (int i = 0; i < length; i++) {
char digitChar = base17Number.charAt(i);
int digitValue;

// Convert the character to its corresponding value


if (digitChar >= '0' && digitChar <= '9') {
digitValue = digitChar - '0';
} else if (digitChar >= 'A' && digitChar <= 'G') {
digitValue = 10 + (digitChar - 'A');
} else {
throw new IllegalArgumentException("Invalid character
in input");
}

// Calculate the decimal value


decimalValue = decimalValue * 17 + digitValue;
}

// Output the decimal value


System.out.println(decimalValue);
}
}
41. Problem Statement:
Given a maximum of 100 digit numbers as input, find
the difference between the sum of odd and even
position digits.

Case 1:
Input: 4567
Expected Output: 2
Explantion : Odd positions are 4 and 6 as they are pos:
1 and pos: 3, both have sum 10. Similarly, 5 and 7 are at
even positions pos: 2 and pos: 4 with sum 12. Thus,
difference is 12 - 10 = 2

Code:
import java.util.Scanner;

public class OddEvenPositionDifference {

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

// Read the input number as a string to handle large


numbers
String number = scanner.nextLine();

int oddSum = 0;
int evenSum = 0;

// Iterate through the string to compute sums


for (int i = 0; i < number.length(); i++) {
int digit = Character.getNumericValue(number.charAt(i));

if ((i + 1) % 2 == 0) {
// Even position (1-based index)
evenSum += digit;
} else {
// Odd position (1-based index)
oddSum += digit;
}
}

// Calculate the difference


int difference = Math.abs(evenSum - oddSum);

// Output the result


System.out.println(difference);
}
}

42. Problem Statement:


Our hoary culture had several great persons since time
immemorial and king vikramaditya’s nava ratnas (nine gems)
belongs to this ilk.They are named in the following shloka:
Among these, Varahamihira was an astrologer of eminence and
his book Brihat Jataak is recokened as the ultimate authority in
astrology. He was once talking with Amarasimha,another gem
among the nava ratnas and the author of Sanskrit thesaurus,
Amarakosha. Amarasimha wanted to know the final position of a
person, who starts from the origin 0 0 and travels per following
scheme.

He first turns and travels 10 units of distance


His second turn is upward for 20 units
Third turn is to the left for 30 units
Fourth turn is the downward for 40 units
Fifth turn is to the right(again) for 50 units
… And thus he travels, every time increasing the travel distance
by 10 units.

Constraints:

2<=n<=1000

Input:

Code:
import java.util.*;
import java.lang.*;

class Main {
public static void main (String[] args) {
Scanner sc = new Scanner(System.in);
int n=sc.nextInt();
char c = 'R';
int x = 0, y = 0;
while(n>0){
switch(c){
case 'R':
x = Math.abs(x) + 10;
y = Math.abs(y);
c ='U';
break;
case 'U':
y = y + 20;
c = 'L';
break;
case 'L':
x = -(x + 10);
c = 'D';
break;
case 'D':
y = -(y);
c = 'R';
break;
}
n--;
}
System.out.println(x+" "+y);
}
}

43. Problem Statement:


One programming language has the following keywords that
cannot be used as identifiers:

break, case, continue, default, defer, else, for, func, goto, if, map,
range, return, struct, type, var

Write a program to find if the given word is a keyword or not

Input #1:
defer
Output:
defer is a keyword

Input #2:
While

Code:
import java.util.Scanner;
class Main
{
public static void main(String args[])
{

String str[]= {"break", "case", "continue", "default", "defer",


"else","for", "func", "goto",
"if", "map", "range", "return", "struct", "type", "var"};
int flag = 0;
Scanner sc = new Scanner(System.in);
String input=sc.nextLine();

for(int i = 0; i<16;i++){

if(str[i].equals(input)){
flag = 1;
break;
}
}

if(flag==1){
System.out.println(input+" is a keyword");
}
else{
System.out.println(input+" is not a keyword");
}

}
}

44. Problem Statement:


Given a pair of positive integers m and n (m < n; 0 < m < 999; 1
< n < = 999), write a program to smartly affix zeroes, while
printing the numbers from m to n.

Example-1
Input

5 10

Expected output

05 06 07 08 09 10

Example-2

Input

9 100

Expected output

009 010 011 012 013 014 015 016 017 018 019 020 021 022
023 024 025 026 027 028 029 030 031 032 033 034 035 036
037 038 039 040 041 042 043 044 045 046 047 048 049 050
051 052 053 054 055 056 057 058 059 060 061 062 063 064
065 067 068 069 070 071 072 073 074 075 076 077 078 079
080 081 082 083 084 085 086 087 088 089 090 091 092 093
094 095 096 097 098 099 100

Example-3

Input
19

Code:
import java.util.*;
class Main
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
int low=sc.nextInt();
int up=sc.nextInt();
for(int i=low;i<=up;i++)
{
if(up>=100)
System.out.printf("%03d ",i);
else if(up>=10)
System.out.printf("%02d ",i);
else
System.out.printf("%d ",i);
}
}
}

45. Problem Statement:


It was one of the places, where people need to get their
provisions only through fair price (“ration”) shops. As the elder
had domestic and official work to attend to, their wards were
asked to buy the items from these shops. Needless to say, there
was a long queue of boys and girls. To minimize the tedium of
standing in the serpentine queue, the kids were given mints. I
went to the last boy in the queue and asked him how many mints
he has. He said that the number of mints he has is one less than
the sum of all the mints of kids standing before him in the queue.
So I went to the penultimate kid to know how many mints she
has.

She said that if I add all the mints of kids before her and subtract
one from it, the result equals the mints she has. It seemed to be
a uniform response from everyone. So, I went to the boy at the
head of the queue consoling myself that he would not give the
same response as others. He said, “I have four mints”.

Given the number of first kid’s mints (n) and the length (len) of
the queue as input, write a program to display the total number
of mints with all the kids.

constraints:

2<n<10

1<len<20

Input#1:

42

Output:
7

Input#2:

14 4

Code:
import java.util.*;
class Main
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
int s = sc.nextInt();
int n = sc.nextInt();
int sum=s,prev;
for(int i=1;i<n;i++)
{
prev=sum-1;
sum+=prev;
}
System.out.println(sum);
}
}

46. Problem Statement:


Mike has arranged a small party for the inauguration of his new
startup. He has invited all of his fellow employees who are N in
number. These employees are indexed with an array starting
from 1 to N. In this startup, everyone knows each other’s salary.
We will represent salary by an integer value. Mike has to arrange
tables, where he will accommodate everyone. But he is a little
thrifty in that, he wants to adjust everyone in as few tables as he
can. Tables of various seating are available. Let’s say the cost of
renting each table is K. All the employees have to seat in the
order of the index. The only problem is that the employees with
the same salary can get into arguments which can ruin the party.
Mike came across the term inefficiency of arrangement, which
can be defined as the sum of the cost of tables + the total
number of people getting into arguments. Given the number of
employees, N, and their salaries in array a[ ], he wants to find the
optimal inefficiency, i.e., the smallest possible value for the
inefficiency of arranging the N employees.

Let’s understand it with an example.


Number of employees invited N = 5
A a = {5 1 3 3 3}
K=1

Now let’s check all the combinations and how in-efficient is all of
them.

When we make 1st, 2nd, and 3rd employee on table-1 and 4th
and 5th on table-2
Cost of 2 tables = 2*1
Number of people getting into arguments = 2 (two 3’s: 4th and
5th employee)
Total = 2 + 2 = 4
When we make 1st, 2nd, 3rd, and 4th employees on table-1 and
5th on table-2
Cost of 2 tables = 2*1
Number of people getting into arguments = 2 (two 3’s: 4th and
5th employee)
Total = 2 + 2 = 4

When we make all of them sit at 1 table, then inefficiency will be


Cost of 1 table = 1
Number of people getting into arguments = 3 (all 3’s: 3rd, 4th
and 5th employee)
Total = 1 + 3 = 4

When we make 1st, 2nd and 3rd employee on table-1 and 4th on
table-2 and 5th on table-3
Cost of 3 tables = 3*1
Number of people getting into arguments = 0 (all 3’s are. sitting
at different tables)
Total = 3 + 0 = 3

Hence the optimal in-efficiency is 3.


So, the output will be 3.

Example 1:

Input:
5 1 -> Input Integer, N and K
{5, 1, 3, 3, 3) Input Integer, array elements a[i].
Output:
3 -> Output
Explanation:
Below is the seating for each case:
Case 1:
Table 1: 1st, 2nd, and 3rd
Table 2: 4th and 5th
Number of people getting into arguments: 2
Total in-efficiency: 2*1 + 2 = 4

Case 2:
Table 1: 1st, 2nd, 3rd, and 4th
Table 2: 5th
Number of people getting into arguments: 2
Total in-efficiency: 2*1 + 2 = 4

Case 3:
Table 1: 1st, 2nd, 3rd, 4th, and 5th
Number of people getting into arguments: 3
Total in-efficiency: 1*1 + 3 = 4

Case 4:
Table 1: 1st, 2nd, and 3rd
Table 2: 4th
Table 3: 5th
Number of people getting into arguments: 0
Total in-efficiency: 3*1 + 0 = 3

Choosing the minimum which is 3.


So, the answer is 3.
Example 2:

Input:
5 14 -> Input Integer, N and K.
{1, 4, 2, 4, 4} -> Input Integer, array elements a[i].
Output:
17 -> Output
Explanation:
Below is the seating for each case:

Case 1:
Table 1: 1st, 2nd, and 3rd
Table 2: 4th and 5th
Number of people getting into arguments: 2
Total in-efficiency: 2*14 + 2 = 30

Case 2:
Table 1: 1st, 2nd, 3rd, and 4th
Table 2: 5th
Number of people getting into arguments: 2
Total in-efficiency: 2*14 + 2 = 30

Case 3:
Table 1: 1st, 2nd, 3rd, 4th, and 5th
Number of people getting into arguments: 3
Total in-efficiency: 1*14+3 = 17

Case 4:
Table 1: 1st, 2nd, and 3rd
Table 2: 4th
Table 3: 5th
Number of people getting into arguments: 3
Total in-efficiency: 3*14+ 0 = 42

Chose the minimum which is 17.


So, the answer is 17.
Code:
import java.util.*;

public class Main {


public static int calculateInefficiency(int[] salaries, int
numTables, int tableCost) {
int inefficiency = 0;
int argumentsCount = 0;

for (int i = 0; i < numTables; i++) {


int tableArguments = 0;
List tableEmployees = new ArrayList<>();

// Get the employees sitting at the current table


for (int j = i; j < salaries.length; j += numTables) {
tableEmployees.add(salaries[j]);
}

// Count the number of arguments at the current table


Collections.sort(tableEmployees);
for (int j = 1; j < tableEmployees.size(); j++) {
if (tableEmployees.get(j).equals(tableEmployees.get(j -
1))) {
tableArguments++;
}
}

inefficiency += tableCost + tableArguments;


argumentsCount = Math.max(argumentsCount,
tableArguments);
}
inefficiency -= argumentsCount;
return inefficiency;
}

public static int findOptimalInefficiency(int[] salaries, int


numTables, int tableCost) {
int minInefficiency = Integer.MAX_VALUE;

// Generate all possible combinations of tables


for (int i = 1; i <= numTables; i++) {
int inefficiency = calculateInefficiency(salaries, i,
tableCost);
minInefficiency = Math.min(minInefficiency, inefficiency);
}

return minInefficiency;
}

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

System.out.print("Enter the number of employees: ");


int N = scanner.nextInt();

int[] salaries = new int[N];


System.out.print("Enter the salaries of employees: ");
for (int i = 0; i < N; i++) {
salaries[i] = scanner.nextInt();
}

System.out.print("Enter the cost of renting each table: ");


int K = scanner.nextInt();
int optimalInefficiency = findOptimalInefficiency(salaries, N,
K);
System.out.println("The optimal inefficiency is: " +
optimalInefficiency);
}
}

47. Problem Statement:


Jack and Jill are playing a string game. Jack has given Jill two
strings A and B. Jill has to derive a string C from A, by deleting
elements from string A, such that string C does not contain any
element of string B. Jill needs help to do this task. She wants a
program to do this as she is lazy. Given strings A and B as input,
give string C as Output.

Example 1:

Input:
tiger -> input string A
ti -> input string B
Output:
ger -> Output string C
Explanation:
After removing “t” and “i” from “tiger”, we are left with “ger”.
So, the answer is “ger”.
Example 2:

Input:
processed -> input string A
esd -> input string B
Output:
proc -> Output string C
Explanation:
After removing “e” “s” and “d” from “processed”, we are left with
“proc”.
So, the answer is “proc”.
Example 3:

Input:
talent -> input string A
tens -> input string B
Output:
al -> Output string C
Explanation:
After removing “t” “e” and “n” from “talent”, we are left with “al”.
So, the answer is “al”.

Code:
import java.util.Scanner;

public class Main {


public static String deriveStringC(String A, String B) {
StringBuilder result = new StringBuilder();

for (int i = 0; i < A.length(); i++) {


char currentChar = A.charAt(i);

if (B.indexOf(currentChar) == -1) {
result.append(currentChar);
}
}
return result.toString();
}

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

System.out.print("Enter string A: ");


String A = scanner.nextLine();

System.out.print("Enter string B: ");


String B = scanner.nextLine();

String C = deriveStringC(A, B);

System.out.println("Output string C: " + C);


}
}

48. Problem Statement:


Mahesh and Suresh are playing a new game “Checkers“. This is
a very simple game but becomes challenging when more expert
players are playing. Below is the description of the game and
rules: The game is played by 2 players. This game consists of an
N*M matrix. Each of the cells is background lit by lights. And
these cells are either Green or Black. The green and black cells
are randomly lit and will be represented with 1’s and 0’s
respectively. Green cells are the cells that need to be captured.
Black cells cannot be captured. Everyone is in the race to
capture the maximum number of cells possible.
In a single chance, a player can capture all those adjacent cells
which share an edge. Once there is no adjacent edge the
chance breaks and the next player will play.
Mahesh always starts the game and Suresh is second.
Both players are playing optimally, find out how many cells
Suresh captures.

Input:
N and M, size of the matrix
A[i][j] for all 1<=i<=N and 1<=j<=M

Let us try to understand it with an example

Consider the matrix below


N=4
M=4
A = 1001
0110
0110
1001

If Mahesh plays first, he will try to capture most of the 1’s, he will
capture A[2][2], A[2][3], A[3][2], and A[3][3]. Now there are no
adjacent cells left. So, the chance will be given to Suresh. Now
Suresh’s turn. He can capture either A[1][1] or A[4][1] or A[4][7]
or A[4][4]. He will capture any one cell, and as there is no
adjacent deft, the chance will now be given to Mahesh. The
game proceeds and then again Suresh’s turn will come, and he
will again be able to choose only 1 cell finally Mahesh will end
the game by choosing the final cell.
Like this Mahesh has captured 6 cells and Suresh has captured
only 2 cells.
Hence 2 is the answer.

Example 1:

Input:
22 -> Input integer, N, M
11 -> Input integer, A[i]
11 -> Input integer, A[N]
Output:
0 -> Output
Explanation:
In the above scenario, it is very clear that if Mahesh plays first,
he will capture all the cells as all the cells are adjacent to each
other.
There will be nothing left for Suresh. Hence the cells captured by
Suresh will be 0.
Hence the answer is 0.
Example 2:

Input:
44 -> Input integer, N, M
1001 -> Input integer, A[i]
0110 -> Input integer, A[i+1]
0110 -> Input integer, A[i+2]
1001 -> Input integer, A[N]
Output:
2 -> Output
Explanation:
If Mahesh plays first, he will try to cover most of the 1’s, he will
cover A[2][2], A[2][3], A[3][2], and A[3][3]. Now there are no
adjacent cells left. So, the chance will be given to Suresh. Now
Suresh’s turn. He can capture either of A[1][1] or A[4][1] or A[4]
[1] or A[4][4]. He will capture any one cell, and as there is no
adjacent left, the chance will now be given to Mahesh. The game
proceeds and then again Suresh’s turn will come, and he will
again be able to choose only 1 cell, and finally, Mahesh will end
the game by choosing the final cell.
Like this Mahesh has captured 6 cells and Suresh has captured
only 2 cells.
Hence 2 is the answer.

Code:
import java.util.Scanner;

public class Main {


static int[][] directions = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};

public static void captureCells(int[][] A, boolean[][] visited, int


player, int row, int col, int[] sureshCaptured) {
int N = A.length;
int M = A[0].length;

if (row < 0 || row >= N || col < 0 || col >= M || visited[row]


[col]) {
return;
}

visited[row][col] = true;

if (player == 2) {
sureshCaptured[0]++;
}

for (int[] dir : directions) {


int newRow = row + dir[0];
int newCol = col + dir[1];
captureCells(A, visited, 3 - player, newRow, newCol,
sureshCaptured);
}
}

public static int countSureshCapturedCells(int[][] A) {


int N = A.length;
int M = A[0].length;
int[] sureshCaptured = {0};

boolean[][] visited = new boolean[N][M];

for (int i = 0; i < N; i++) {


for (int j = 0; j < M; j++) {
if (!visited[i][j]) {
captureCells(A, visited, 1, i, j, sureshCaptured);
}
}
}

return sureshCaptured[0];
}

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

System.out.print("Enter the size of the matrix (N M): ");


int N = scanner.nextInt();
int M = scanner.nextInt();
int[][] A = new int[N][M];
System.out.println("Enter the matrix elements:");
for (int i = 0; i < N; i++) {
for (int j = 0; j < M; j++) {
A[i][j] = scanner.nextInt();
}
}

int sureshCaptured = countSureshCapturedCells(A);


System.out.println("The number of cells captured by
Suresh: " + sureshCaptured);
}
}

49. Problem Statement:


Joe was reading an interesting novel when all of a sudden, his 5-
year-old son came to him and started asking a few questions
about functions. He tried making him understand various
functions, but his son didn’t get find it interesting. Then he
created his function Absent number function A(S) According to
this function, there is always the smallest positive integer number
in a sequence that is not available. In simple words, if you sort
the given sequence, then the smallest integer number (other
than 0) which is not present in the sequence is the Absent
number. Consider a sequence S= [1, 2, 3], then B(S)=4. The
minimum value greater than 0 which is not present here in the
sequence is 4. Now his son found it interesting, so Joe extended
this logic to sub-sequence. If there is a given sequence S, you
have to find the Absent Number for each sub-sequence and then
sum it up. If the answer is large, print the result modulo, 109 +7.
Let say there exist a sequence with N = 3, and sequence S = [1,
2, 1]
Below are the various sub-sequences of it,

It will be 2N:

[ ] : B([ ]) = 1
[1] : B([1]) = 2
[2] : B([2]) = 1
[1] : B([1]) = 2
[1, 2] : B([1, 2]) = 3
[2, 1] : B([2, 1]) = 3
[1, 1] : B([1, 1]) = 2
[1, 2, 1] : B([1, 2, 1]) = 3

Total sum of all B(S) = 1+2+1+2+3+3+2+3 = 17.


Hence the answer is 17.

Example 1:

Input:
2 -> input Integer, N
1 1 -> input Integer, S
Output:
7 -> Output
Explanation:
In the above scenario below are the various sub-sequence and
their respective functions of it:
[ ] : B(l) = 1
[1]: B([1])= 2
[1]: B([1]) = 2
[1,1]: B([1,1]) = 2
Total sum of all B(S) = 1+2+2+2 = 7 Hence the answer is 7.
Example 2:

Input:
3 -> Input integer, N
1 2 1 -> Input integer, S
Output:
17->Output
Explanation:
In the above scenario below are the various sub-sequences and
their respective functions of it.
[ ] : B([ ]) = 1
[1] : B([1]) = 2
[2] : B([2]) =1
[1] : B([1]) = 2
[1, 2] : B([1, 2]) = 3
[2, 1] : B([2, 1]) = 3
[1, 1] : B([1, 1]) = 2
[1, 2, 1] : B([1, 2, 1]) = 3
Total sum of all B(S) = 1 + 2 + 1 + 2 + 3 + 3 + 2 + 3 = 17.
Hence the answer is 17.

Code:
import java.util.Arrays;
import java.util.Scanner;

public class Main {


static final int MOD = (int) (1e9 + 7);

public static int absentNumber(int[] subsequence) {


Arrays.sort(subsequence);
int n = subsequence.length;
int missing = 1;
for (int i = 0; i < n; i++) {
if (subsequence[i] == missing) {
missing++;
}
}

return missing;
}

public static int sumOfAbsentNumbers(int[] sequence) {


int n = sequence.length;
int sum = 0;

for (int i = 0; i < (1 << n); i++) {


int subsequenceSize = Integer.bitCount(i);
int[] subsequence = new int[subsequenceSize];

int index = 0;
for (int j = 0; j < n; j++) {
if ((i & (1 << j)) != 0) {
subsequence[index++] = sequence[j];
}
}

sum = (sum + absentNumber(subsequence)) % MOD;


}

return sum;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

System.out.print("Enter the size of the sequence (N): ");


int N = scanner.nextInt();

int[] sequence = new int[N];


System.out.print("Enter the sequence elements: ");
for (int i = 0; i < N; i++) {
sequence[i] = scanner.nextInt();
}

int sum = sumOfAbsentNumbers(sequence);


System.out.println("The sum of all Absent Numbers: " +
sum);
}
}

50. Problem Statement:


ames has a sequence of N numbers. There is also an integer X
which is a random number from other sources. He is allowed to
perform a specific operation on this sequence X number of
times. Below is the operation:

Pick exactly one element from the sequence and multiply it with -
1.
Your task is to find out the number of different sequences which
can be formed by performing the above operation. If the answer
is large, print the result modulo 109 +7.

Let us try to understand it with an example,


N=3
X=2
S = [1, 2, 3]

There are 2 ways in which this operation can be performed.

Way 1: Either -1 should be multiplied to the same element 2


times, OR
Way 2: -1. Should be multiplied by two different elements once
each.
Way 1:
If we multiply -1, to each element 2 times. It will become +1 (-1 *-
1).
We will get the same sequence for each element:

Multiply -1, 2 times to S[1] : [1, 2, 3].


Multiply -1, 2 times to S[2] : [1, 2, 3].
Multiply -1, 2 times to S[3] : [1, 2, 3].
So, the unique sequence is just 1 which is [1, 2, 3].

Way 2:
If we multiply -1, by two different elements just 1 time each. We
get:

Multiply -1 to S[1] & S[2] : [-1, -2, 3].


Multiply -1 to S[2] & S[3] : [1, -2, -3].
Multiply -1 to S[1] & S[3] : [-1, 2, -3].
Hence, we get a total of 3 different sequences from Way 2.
Total 1 + 3 = 4 different sequences.

Hence the answer is 4.000


Example 1:

Input:
3 1 -> Input integer, N, X
{1, 2, 1} -> Input integer, S
Output:
3 -> Output
Explanation:
In the given scenario, we have X =1. Hence, we can have this
multiplication of -1 only once.
So, if we multiply -1, by different elements just 1 time. We get:
Multiply -1 to S[1] & S[2] : [-1, -2, 1].
Multiply -1 to S[2] & S[3] : [1, -2, -1].
Multiply -1 to S[1] & S[3] : [-1, 2, -1].
Hence, we get a total of 3 different sequences.
So, the answer is 3.

Example 2:

Input:
3 2 -> Input integer, N, X
{1, 2, 3} -> Input integer, S
Output:
4 -> Output
Explanation:
There are 2 ways in which this operation can be performed
Way 1: Either – 1 should be multiplied to the same element 2
times, OR
Way 2: -1 should be multiplied by different elements once.
As shown in the above Demo example, there will be a total of 4
different sequences which can be achieved from this.
Hence the answer is 4.

Code:
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;

public class Main {


static final int MOD = (int) (1e9 + 7);

public static int countDifferentSequences(int N, int X, int[]


sequence) {
Set distinctElements = new HashSet<>();
for (int num : sequence) {
distinctElements.add(num);
}

int distinctCount = Math.min(distinctElements.size(), X);


int result = powMod(2, distinctCount);

return result;
}

public static int powMod(int base, int exponent) {


int result = 1;

while (exponent > 0) {


if (exponent % 2 == 1) {
result = (result * base) % MOD;
}

base = (base * base) % MOD;


exponent /= 2;
}

return result;
}

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

System.out.print("Enter the size of the sequence (N): ");


int N = scanner.nextInt();

System.out.print("Enter the number of times the operation


can be performed (X): ");
int X = scanner.nextInt();

int[] sequence = new int[N];


System.out.print("Enter the sequence elements: ");
for (int i = 0; i < N; i++) {
sequence[i] = scanner.nextInt();
}

int count = countDifferentSequences(N, X, sequence);


System.out.println("The number of different sequences: " +
count);
}
}

51. Problem Statement:


Two parallel roads separated by a river are connected from cities
A and B to an outer ring road. Both roads have a high flow of
traffic throughout the day. People who want to travel from city A
to city B or vice versa have to pass through the ring road which
is a huge waste of time and money. To ease the traffic and also
to make it convenient for commuters to travel from city A to city B
and vice versa, the construction of a bridge over the river is
planned.

The surveillance team submitted a report stating the bridge


should be constructed in the following manner:

The ground or soil is stronger at certain points on the road


favorable for the construction of the bridge.
The strong ground positions are given from the starting point of
each road. Say, the road of city A has strong ground at 1,4
meaning there is a strong ground at a distance of 1 unit, another
strong ground point at a distance of 4 units from the starting
point of the road of city A.
Collate the strong ground positions of both roads. Sort them in
ascending order. Calculate the middle point or median of the
combined strong ground positions. The bridge should be
constructed from road A as per the middle point calculated.
Given the number of strong positions on roads A and B(N1 and
N2 respectively) and the strong ground positions on each road,
the task here is to calculate the midpoint of the combined strong
positions on both roads.

NOTE: When the strong positions are combined, the repeated


positions on the different roads are dropped.

Example 1:

Input:
3 -> Value of N1
3 -> Value of N2
{3,5,2} -> a[ ], Elements a[0]to a[N1-1], where each input
element is separated by new line
{1,2,3} -> b[ ], Elements b[0]to b[N2-1), where each input
element is separated by new line
Output: 2.5
Explanation:
From the inputs given above:
Number of strong ground positions on road A:3
Number of strong ground positions on road B:3
The positions of strong ground from the starting point of road A
are at a distance of 3,5,2
The positions of strong ground from the starting point of road B
are at a distance of 1,2,3
Combining the strong ground positions of both the roads and
sorting them in ascending order
1, 2, 3, 5
The Middle points are 2 and 3
2+3 = 5
5/2 = 2.5
So, the middle point from where the bridge should be
constructed is 2.5.
Hence, the output is 2.5
Example 2:

Input:
2 -> Value of N1
3 -> Value of N2
{2,3} -> all, Elements a[O]to a[N1-1), where each input element
is separated by new line
{5,6,4} -> b[ ], Elements b[O]to b[N2-1], where each input
element is separated by new line
Output: 4
Explanation:
From the inputs given above:
Number of strong ground positions on road A: 2
Number of strong ground positions on road B: 3
The positions of strong ground from the starting point of road A
are at a distance of 2, 3 The positions of strong ground from the
starting point of road B are at a distance of 5, 6, and 4
Combining the strong ground positions of both the roads and
sorting them in ascending order: 2, 3, 4, 5, 6 > Middle point is 4
So, the middle point from where the bridge should be
constructed is 4.
Hence, the output is 4.

Code:
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;

public class Main {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

int N1 = scanner.nextInt();
int N2 = scanner.nextInt();

List arr1 = new ArrayList<>();


List arr2 = new ArrayList<>();
for (int i = 0; i < N1; i++) {
arr1.add(scanner.nextInt());
}

for (int i = 0; i < N2; i++) {


arr2.add(scanner.nextInt());
}

List combined = new ArrayList<>();


combined.addAll(arr1);
combined.addAll(arr2);

Collections.sort(combined);

double midpoint;
int size = combined.size();

if (size % 2 == 0) {
midpoint = (combined.get(size/2 - 1) +
combined.get(size/2)) / 2.0;
} else {
midpoint = combined.get(size/2);
}

System.out.println(midpoint);

scanner.close();
}
}
52. Problem Statement:
A chocolate factory is packing chocolates into packets. The
chocolate packets here represent an array arrt of N number of
integer values. The task is to find the empty packets(0) of
chocolate and push it to the end of the conveyor belt(array).

For Example:

N=7 and arr = [4,5,0,1.9,0,5,0].


There are 3 empty packets in the given set. These 3 empty
packets represented as O should be pushed towards the end of
the array
Example 1:

Input:

7 – Value of N
[4,5,0,1,0,0,5] – Element of arr[O] to arr[N-1],While input each
element is separated by newline
Output:

4519500
Example 2:

Input:

6
— Value of N.
[6,0,1,8,0,2] – Element of arr[0] to arr[N-1], While input each
element is separated by newline
Output:
618200

Code:
import java.util.*;
class Solution
{
public static void main (String[]args)
{
Scanner sc = new Scanner (System.in);
int n = sc.nextInt ();
int arr[] = new int[n];
for(int i = 0; i < n; i++)
arr[i] = sc.nextInt ();

int count = 0;

for(int i = 0; i < n; i++)


if (arr[i] != 0)
arr[count++] = arr[i];
for(int i = count; i < n; i++)
arr[i] = 0;

for (int i = 0; i < n; i++)


System.out.print (arr[i] + " ");
}
}

53. Problem Statement:


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 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.

Example 1:

Input :

● 4 -> Value of N
● 80 -> Value of C
● [10,45,60,90] -> Elements of array v[], where each element is
separated by new line.
● [15,20,30,40] -> Elements of array w[], where each element is
separated by new line.

Output: 150

Explanation:

● Value=10 weight=15
● Value=45 weight = 20
● Value = 60 weight=30
● Value=90 weight=40

The subsets that can be formed from the array V[], their corresponding
weight W[] and comparison with c=80
Valid (total weight(<C)

Invalid (total
Total Weig Total
weight>C)
Value Value ht Weight

10+45 55 15+2 35 Valid


0

10+60 70 15+3 45 Valid


0

10+90 100 15+4 55 Valid


0

45+60 105 20+3 50 Valid


0

45+90 135 20+4 60 Valid


0

60+90 150 20+4 70 Valid


0

10+45+6 115 20+4 65 Valid


0 0
10+60+9 160 20+4 85 Invalid
0 0

10+45+9 145 20+4 75 Valid


0 0

From the above table, it is perceived that particularly for the valid items,
maximum value=150 and their corresponding weight is 70. So the output
should be 150.

The input format for testing

First Input – Accept value for N (positive integer number).

Second input : Accept value for C (Positive integer number),

Third input – Accept N number of positive integer number for array v[0…
N-1], where each value is separated by a new line.

Fourth input – Accept N positive integer numbers for array [0….N-1],


where each value is separated by a new line.

The output format for testing


The output should be a positive integer number (Check the output in
Example 1)

Constraints:

● 0<=N<=10
● 0 <= C<=500
● 1<=V[i]<=500

Code:
import java.util.*;
class Solution
{
public static int solve(int c,int w[],int val[],int n)
{
if(n==0 || c==0)
return 0;
if(c<w[n-1])
return solve(c,w,val,n-1);
else
return Math.max(solve(c,w,val,n-1),val[n-1]+solve(c-
w[n-1],w,val,n-1));
}
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int c=sc.nextInt();
int v[]=new int[n];
int w[]=new int[n];

for(int i=0;i<n;i++)
v[i]=sc.nextInt();
for(int i=0;i<n;i++)
w[i]=sc.nextInt();
System.out.println(solve(c,w,v,n));
}
}

54. Problem Statement:


Problem Description -: Given an array Arr[ ] of N integers and a
positive integer K. The task is to cyclically rotate the array
clockwise by K.

Note : Keep the first of the array unaltered.

Example 1:

5 —Value of N
{10, 20, 30, 40, 50} —Element of Arr[ ]
2 —–Value of K
Output :

40 50 10 20 30

Example 2:

4 —Value of N
{10, 20, 30, 40} —Element of Arr[]
1 —–Value of K
Output :
40 10 20 30

Code:
import java.util.*;
public class Main
{
static int[] rotate(int nums[], int n, int k) {

if (k > n)
k = k % n;

int[] ans = new int[n];

for (int i = 0; i < k; i++) {


ans[i] = nums[n - k + i];
}

int index = 0;
for (int i = k; i < n; i++) {
ans[i] = nums[index++];
}
return ans;
}
public static void main(String[] args) {
int Array[] = { 1, 2, 3, 4, 5 };
int N = 5;
int K = 2;

int[] ans = rotate(Array, N, K);


for (int i = 0; i < N; ++i) {
System.out.println(ans[i]);
}
}
}

55. Problem Statement:


Given two non-negative integers n1 and n2, where n1

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.

Example1:

Input:

11 — Vlaue of n1
15 — value of n2
Output:

4
Example 2:

Input:

101 — value of n1
200 — value of n2
Output:

72
Code:
import java.util.*;
public class Main
{
static int find(int n1, int n2) {
int count = 0;
for (int i = n1 ; i <= n2 ; i++) {
int num = i;

boolean[] visited = new boolean[10];

while (num > 0) {


if (visited[num % 10] == true)
break;
visited[num % 10] = true;
num /= 10;
}

if (num == 0)
count++;
}
return count;
}
public static void main(String[] args) {
int n1 = 101, n2 = 200;
System.out.println(find(n1, n2));
}
}
56. Problem Statement:
Identify the logic behind the series

6 28 66 120 190 276….

The numbers in the series should be used to create a Pyramid.


The base of the Pyramid will be the widest and will start
converging towards the top where there will only be one element.
Each successive layer will have one number less than that on
the layer below it. The width of the Pyramid is specified by an
input parameter N. In other words there will be N numbers on the
bottom layer of the pyramid.

The Pyramid construction rules are as follows

First number in the series should be at the top of the Pyramid


Last N number of the series should be on the bottom-most layer
of the Pyramid, with Nthnumber being the right-most number of
this layer.
Numbers less than 5-digits must be padded with zeroes to
maintain the sanctity of a Pyramid when printed. Have a look at
the examples below to get a pictorial understanding of what this
rule actually means.
Example

If input is 2, output will be

00006
00028 00066
If input is 3, output will be

00006
00028 00066
00120 00190 00276
Formal input and output specifications are stated below

Input Format:

First line of input will contain number N that corresponds to the


width of the bottom-most layer of the Pyramid
Output Format:

The Pyramid constructed out of numbers in the series as per


stated construction rules
Constraints:

0 < N <= 14

Code:
import java.util.Scanner;
public class LogicPyramid
{
public static void main (String[]args)
{
int n, a = 0, b = 3, i, re, j;
Scanner sc = new Scanner (System.in);
n = sc.nextInt ();
for (i = 1; i <= n; i++)
{
for (j = 1; j <= i; j++)
{
a = a + 2;
if (i == 1)
b = 3;
else
b = b + 4;
re = a * b;
System.out.println (re);
}
System.out.println ();
}
}
}

57. Problem Statement:


There are two banks – Bank A and Bank B. Their interest rates
vary. You have received offers from both banks in terms of the
annual rate of interest, tenure, and variations of the rate of
interest over the entire tenure.You have to choose the offer
which costs you least interest and reject the other. Do the
computation and make a wise choice.

The loan repayment happens at a monthly frequency and


Equated Monthly Installment (EMI) is calculated using the
formula given below :

EMI = loanAmount * monthlyInterestRate / ( 1 – 1 / (1 +


monthlyInterestRate)^(numberOfYears * 12))

Constraints:

1 <= P <= 1000000


1 <=T <= 50
1<= N1 <= 30
1<= N2 <= 30

Input Format:

First line: P principal (Loan Amount)


Second line: T Total Tenure (in years).
Third Line: N1 is the number of slabs of interest rates for a given
period by Bank A. First slab starts from the first year and the
second slab starts from the end of the first slab and so on.
Next N1 line will contain the period and their interest rate
respectively.
After N1 lines we will receive N2 viz. the number of slabs offered
by the second bank.
Next N2 lines are the number of slabs of interest rates for a
given period by Bank B. The first slab starts from the first year
and the second slab starts from the end of the first slab and so
on.
The period and rate will be delimited by single white space.

Output Format: Your decision either Bank A or Bank B.

Explanation:

Example 1
Input
10000
20
3
5 9.5
10 9.6
5 8.5
3
10 6.9
5 8.5
5 7.9
Output: Bank B
Example 2
Input
500000
26
3
13 9.5
3 6.9
10 5.6
3
14 8.5
6 7.4
6 9.6
Output: Bank A

Code:
import java.util.Scanner;
public class Main
{
public static void main (String[]args)
{
Scanner sc = new Scanner (System.in);
double p, s, mi, sum, emi, sq;
int y, n, k, yrs, l = 0;
double[] bank = new double[5];
System.out.println ("Enter the principal amount");
p = sc.nextDouble ();
System.out.println ("Enter tenature year");
y = sc.nextInt ();
for (k = 0; k < 2; k++)
{
System.out.println ("Enter the no of slabs");
n = sc.nextInt ();
sum = 0;
for (int i = 0; i < n; i++)
{
System.out.println ("Enter the period :");
yrs = sc.nextInt ();
System.out.println ("Enter the intrest :");
s = sc.nextDouble ();
mi = 0;
sq = Math.pow ((1 + s), yrs * 12);
emi = (p * (s)) / (1 - 1 / sq);
sum = sum + emi;
}
bank[l++] = sum;
}
if (bank[0] < bank[1])
System.out.println ("Bank A");
else
System.out.println ("Bank B");

}
58. Problem Statement:
In this 3 Palindrome, Given an input string word, split the string
into exactly 3 palindromic substrings. Working from left to right,
choose the smallest split for the first substring that still allows the
remaining word to be split into 2 palindromes.

Similarly, choose the smallest second palindromic substring that


leaves a third palindromic substring.

If there is no way to split the word into exactly three palindromic


substrings, print “Impossible” (without quotes). Every character
of the string needs to be consumed.

Cases not allowed –

After finding 3 palindromes using above instructions, if any


character of the original string remains unconsumed.
No character may be shared in forming 3 palindromes.
Constraints

1 <= the length of input sting <= 1000


Input

First line contains the input string consisting of characters


between [a-z].
Output

Print 3 substrings one on each line.


Time Limit

1
Examples

Example 1

Input

nayannamantenet

Output

nayan

naman

tenet

Explanation

The original string can be split into 3 palindromes as mentioned


in the output.
However, if the input was nayanamantenet, then the answer
would be “Impossible”.
Example 2

Input

aaaaa

Output

a
a

aaa

Explanation

The other ways to split the given string into 3 palindromes are as
follows –
[a, aaa, a], [aaa, a, a], [aa, aa, a], etc.
Since we want to minimize the length of the first palindromic
substring using left to right processing, the correct way to split is
[a, a, aaa].
Example 3

Input

aaaabaaaa

Output

aaabaaa

Explanation

The other ways to split the given string into 3 palindromes are as
follows –
[aaaa, b, aaaa], [aa, aabaa, aa], etc.
Since we want to minimize the length of the first palindromic
substring using left to right processing, the correct way to split is
[a, aaabaaa, a].

Code:
import java.util.*;

class Solution
{

public static boolean isPalindrome (String s)


{

if (s.length () == 1)
return true;
StringBuilder sb = new StringBuilder (s);
sb = sb.reverse ();
String rev = new String (sb);
return s.equals (rev);
}

public static void main (String[]args)


{
Scanner sc = new Scanner (System.in);
String str = sc.next ();

int len = str.length ();


String str1 = "", str2 = "", str3 = "";

boolean flag = false;

for (int i = 1; i < len - 1; i++)


{
str1 = str.substring (0, i);
if (isPalindrome (str1))
{
for (int j = 1; j < len - i; j++)
{
str2 = str.substring (i, i + j);
str3 = str.substring (i + j, len);
if (isPalindrome (str2) && isPalindrome (str3))
{
System.out.println (str1 + "\n" + str2 + "\n" + str3);
flag = true;
break;
}
}
if (flag)
break;
}
}
if (flag == false)
System.out.println ("Impossible");
}
}

59. Problem Statement:


Roco is an island near Africa which is very prone to forest fire.
Forest fire is such that it destroys the complete forest. Not a
single tree is left.This island has been cursed by God , and the
curse is that whenever a tree catches fire, it passes the fire to all
its adjacent tree in all 8 directions,North, South, East, West,
North-East, North-West, South-East, and South-West.And it is
given that the fire is spreading every minute in the given manner,
i.e every tree is passing fire to its adjacent tree.Suppose that the
forest layout is as follows where T denotes tree and W denotes
water.

Your task is that given the location of the first tree that catches
fire, determine how long would it take for the entire forest to be
on fire. You may assume that the lay out of the forest is such that
the whole forest will catch fire for sure and that there will be at
least one tree in the forest

Input Format:

First line contains two integers, M, N, space separated, giving


the size of the forest in terms of the number of rows and columns
respectively.
The next line contains two integers X,Y, space separated, giving
the coordinates of the first tree that catches the fire.
The next M lines, where ith line containing N characters each of
which is either T or W, giving the position of the Tree and Water
in the ith row of the forest.
Output Format:

Single integer indicating the number of minutes taken for the


entire forest to catch fire

Constrains:

3 ≤ M ≤ 20
3 ≤ N ≤ 20
Sample Input 1:

33
WTT
TWW
WTT
Sample Output 1:

Explanation:
In the second minute,tree at (1,2) catches fire,in the third
minute,the tree at (2,1) catches fire,fourth minute tree at (3,2)
catches fire and in the fifth minute the last tree at (3,3) catches
fire.
Sample Input 2:
66
16
WTTTTT
TWWWWW
WTTTTT
WWWWWT
TTTTTT
TWWWWW

Sample Output 2:

16

Code:
import java.util.HashMap;
import java.util.Scanner;

class Temp {
static void print(int [][] arr){
for(int i=0;i<arr.length;i++){
for (int j=0;j<arr[0].length;j++){
System.out.print(arr[i][j]+"\t");
}
System.out.println();
}
}
public static void main (String[] args) {
Scanner scanner = new Scanner(System.in);
int N = scanner.nextInt();
int [][] array = new int[N][N];
HashMap<Integer, Integer> map = new HashMap<>();

int powerpoints = 1 + (N*N)/11;

int counter = 1;
int row = 0, col = 0; // for the current row/col that we are end
int endRow = 0, endColumn = 0; // for the row/col where we
need to stop

map.put(0,0);

for(int i=0;i<N/2;i++){
row = col = i;
endColumn = N-i-1;

while (col < endColumn) {


array[row][col] = counter;

if (counter % 11==0)
map.put(row,col);
counter++;
col++;
}
endRow = N-i-1;
while (row<endRow){
array[row][col] = counter;
if (counter % 11==0)
map.put(row,col);
counter++;
row++;
}

endColumn = i;
while (col>endColumn){
array[row][col] = counter;
if (counter % 11==0)
map.put(row,col);
counter++;
col--;
}

endRow = i;
while (row>endRow){
array[row][col] = counter;
if (counter % 11==0)
map.put(row,col);
counter++;
row--;
}
}
if (N%2==1)
array[N/2][N/2] = N*N;

print(array);
System.out.println("Total Power Points: " + powerpoints);
for (Integer key: map.keySet()) {
System.out.println("("+key+ ","+map.get(key)+")");

You might also like