0% found this document useful (0 votes)
21 views48 pages

CODES

Uploaded by

shreekeerthykk
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views48 pages

CODES

Uploaded by

shreekeerthykk
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 48

ODD AND EVEN SORTING

REVERSE EVEN NUMBERS AND PRINT EVEN AND ODD IN ALTERNATIVE

IP: 1 5

OP:4,1,2,3,5.

import java.util.*;

public class Main

public static void main(String args[])

Scanner sc=new Scanner(System.in);

int a=sc.nextInt();

int b=sc.nextInt();

ArrayList<Integer> arr=new ArrayList<>();

ArrayList<Integer> arr1=new ArrayList<>();

for(int i=a;i<=b;i++)

if(i%2==0)

arr.add(i);

else

arr1.add(i);

System.out.print(arr+" ");

Collections.reverse(arr1);

System.out.print(arr1+" ");

System.out.println();

int m=arr.size();

System.out.println(m);
int l=arr1.size();

System.out.println(l);

int n=m+l;

System.out.println(n);

int ar[]=new int[n];

int j=0;

int p=0;

int g=0;

while(p<n)

if(p%2==0 && j<arr.size())

ar[p]=arr.get(j);

j++;

else if(g<arr1.size())

ar[p]=arr1.get(g);

g++;

p++;

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

System.out.print(ar[k]+" ");

}
2.REVERSE OF AN ARRAY

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];

int temp[]=new int[n];

int j=0;

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

arr[i]=sc.nextInt();

for(int i=n-1;i>=0;i--)

temp[j]=arr[i];

j++;

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

arr[i]=temp[i];

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

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

}
}

INPUT &OUTPUT:

12345

54321

=== Code Execution Successful ===

3. Given a String S, reverse the string without reversing its individual words.
Words are separated by dots.

Example 1:

Input:
S = i.like.this.program.very.much
Output: much.very.program.this.like.i
Explanation: After reversing the whole
string(not individual words), the input
string becomes
much.very.program.this.like.i

CODE:
class Solution {
// Function to reverse words in a given string.
String reverseWords(String S) {
// Split the string by dot, using escape sequence for dot.
String[] parts = S.split("\\.");
StringBuilder s = new StringBuilder();

// Iterate over the parts in reverse order.


for (int i = parts.length - 1; i >= 0; i--) {
s.append(parts[i]);
if (i != 0) {
s.append(".");
}
}
return s.toString();
}
}

4. /*Given two sorted arrays, find their union and intersection.

Example:

Input: arr1[] = {1, 3, 4, 5, 7}

arr2[] = {2, 3, 5, 6}

Output: Union : {1, 2, 3, 4, 5, 6, 7}

Intersection : {3, 5}

Input: arr1[] = {2, 5, 6}

arr2[] = {4, 6, 8, 10}

Output: Union : {2, 4, 5, 6, 8, 10}

Intersection : {6}*/

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];

int arr2[]=new int[n];

int j=0;

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

{
arr[i]=sc.nextInt();

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

arr2[i]=sc.nextInt();

List<Integer> list1 = new ArrayList<>();

for (int num : arr) {

list1.add(num);

List<Integer> list2 = new ArrayList<>();

for (int num : arr2) {

list2.add(num);

// Creating a HashSet from list1 and adding all elements from list2

Set<Integer> set = new HashSet<>(list1);

set.addAll(list2);

// Finding common elements

List<Integer> commonElements = new ArrayList<>(list1);

commonElements.retainAll(list2);

// Creating an ArrayList from the set

ArrayList<Integer> list = new ArrayList<>(set);

// Printing elements of the set

System.out.print("Union of both arrays: ");

for (int i : set) {

System.out.print(i + " ");


}

System.out.println(); // Newline for better readability

// Printing common elements

System.out.print("Common elements in both arrays: ");

for (int i : commonElements) {

System.out.print(i + " ");

5. Take discount or Not


There are 𝑁N items in a shop. You know that the price of the 𝑖i-th item is 𝐴𝑖Ai. Chef wants to buy all
the 𝑁N items.
There is also a discount coupon that costs 𝑋X rupees and reduces the cost of every item by 𝑌Y rupees. If
the price of an item was initially ≤𝑌≤Y, it becomes free, i.e, costs 00.
Determine whether Chef should buy the discount coupon or not. Chef will buy the discount coupon if and
only if the total price he pays after buying the discount coupon is strictly less than the price he pays
without buying the discount coupon.

Input Format
 The first line of input will contain a single integer 𝑇T, denoting the number of test cases. The
description of the test cases follows.
 Each test case consists of two lines of input.
o The first line of the test case contains three space-separated integers — 𝑁N, 𝑋X, and 𝑌Y.
o The second line contains 𝑁N space-separated integers — 𝐴1,𝐴2,…,𝐴𝑁A1,A2,…,AN.

Output Format
 For each test case, output COUPON if Chef should buy the discount coupon, and NO COUPON otherwise.
Each letter of the output may be printed in either lowercase or uppercase. For example, the
strings coupon, CouPoN, and COUPON will all be treated as equivalent.

Constraints
 1≤𝑇≤10001≤T≤1000
 1≤𝑁≤1001≤N≤100
 1≤𝑋,𝑌≤1051≤X,Y≤105
 1≤𝐴𝑖≤1051≤Ai≤105

Sample 1:
Input
Output
5
4 30 10
15 8 22 6
4 40 10
15 8 22 6
4 34 10
15 8 22 6
2 10 100
60 80
3 30 5
50 60 50
COUPON
NO COUPON
NO COUPON
COUPON
NO COUPON

Explanation:
Test case 11: The original cost of the items is 15+8+22+6=5115+8+22+6=51. Buying the coupon
costs 3030, and after buying it the cost of buying all the items is 5+0+12+0=175+0+12+0=17. The
total cost of buying everything with the coupon is 30+17=4730+17=47, which is strictly less
than 5151. So, Chef will buy the coupon.
Test case 22: The original cost of the items is 15+8+22+6=5115+8+22+6=51. Buying the coupon
costs 4040, and after buying it the cost of buying all the items is 5+0+12+0=175+0+12+0=17. The
total cost of buying everything with the coupon is 40+17=5740+17=57, which is more than 5151. So,
Chef will not buy the coupon.
Test case 33: The original cost of the items is 5151. Buying the coupon costs 3434, and the cost of
buying all the items after using it is 1717, making the total cost 34+17=5134+17=51. Since this is not
strictly less than the original cost, Chef won't buy the coupon.
Test case 44: The original cost of the items is 140140, the coupon costs 1010, and the cost of buying
everything after using the coupon is 00. Since 10+0<14010+0<140, Chef will buy the coupon.

CODE:

import java.util.Scanner;

public class Main {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

int t = scanner.nextInt();

while (t-- > 0) {

int n = scanner.nextInt();

int x = scanner.nextInt();

int y = scanner.nextInt();

int[] a = new int[n];

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

a[i] = scanner.nextInt();

int sum=0;

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

sum+=a[i];

int avg=0;

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

a[i]-=y;

if(a[i]>0)

{
avg+=a[i];

if(avg+x<sum)

System.out.println("COUPON");

else

System.out.println("NO COUPON");

6. Cost of Groceries
Chef visited a grocery store for fresh supplies. There are 𝑁N items in the store where the 𝑖𝑡ℎith item has a
freshness value 𝐴𝑖Ai and cost 𝐵𝑖Bi.
Chef has decided to purchase all the items having a freshness value greater than equal to 𝑋X. Find the
total cost of the groceries Chef buys.

Input Format
 The first line of input will contain a single integer 𝑇T, denoting the number of test cases.
 Each test case consists of multiple lines of input.
o The first line of each test case contains two space-separated integers 𝑁N and 𝑋X — the number of
items and the minimum freshness value an item should have.
o The second line contains 𝑁N space-separated integers, the array 𝐴A, denoting the freshness value of
each item.
o The third line contains 𝑁N space-separated integers, the array 𝐵B, denoting the cost of each item.

Output Format
For each test case, output on a new line, the total cost of the groceries Chef buys.

Constraints
 1≤𝑇≤1001≤T≤100
 1≤𝑁,𝑋≤1001≤N,X≤100
 1≤𝐴𝑖,𝐵𝑖≤1001≤Ai,Bi≤100

Sample 1:
Input

4
2 20
15 67
10 90
3 1
1 2 3
1 2 3
3 100
10 90 50
30 7 93
4 50
12 78 50 40
40 30 20 10
Output:
90
6
0
50

CODE:

import java.util.Scanner;

public class Main {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

int t = scanner.nextInt();

while (t-- > 0) {

int n = scanner.nextInt();

int x = scanner.nextInt();

int[] a = new int[n];


int[] b = new int[n];

//freshness value

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

a[i] = scanner.nextInt();

//cost

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

b[j] = scanner.nextInt();

int cost=0;

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

if(a[i]>=x)

cost+=b[i];

System.out.println(cost);

7. MIN To MAX
You are given an array 𝐴A of size 𝑁N.
Let 𝑀M be the minimum value present in the array initially.
In one operation, you can choose an element 𝐴𝑖Ai (1≤𝑖≤𝑁)(1≤i≤N) and an
integer 𝑋X (1≤𝑋≤100)(1≤X≤100), and set 𝐴𝑖=𝑋Ai=X.
Determine the minimum number of operations required to make 𝑀M the maximum value in the
array 𝐴A.

Input Format
 The first line of input will contain a single integer 𝑇T, denoting the number of test cases.
 Each test case consists of multiple lines of input.
o The first line of each test case contains a single integer 𝑁N - the size of the array.
o The next line of each test case contains 𝑁N space-separated integers 𝐴1,𝐴2,…,𝐴𝑁A1,A2,…,AN -
the elements of the array.

Output Format
For each test case, output on a new line, the minimum number of operations required to
make 𝑀M the maximum value in the array 𝐴A.

Constraints
 1≤𝑇≤1001≤T≤100
 1≤𝑁≤1001≤N≤100
 1≤𝐴𝑖≤1001≤Ai≤100

Sample 1:
Input

3
2
1 2
4
2 2 3 4
1
1
Output:
1
2
0

CODE:

import java.util.Scanner;

import java.util.Arrays;

public class Main {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

int t = scanner.nextInt();
while (t-- > 0) {

int n = scanner.nextInt();

int[] a = new int[n];

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

a[i] = scanner.nextInt();

// Your code goes here

int count=0;

Arrays.sort(a);

int x=a[0];

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

if(a[i]>x)

count++;

System.out.println(count);

8. DNA Storage
For encoding an even-length binary string into a sequence of A, T, C, and G, we iterate from left to
right and replace the characters as follows:
 00 is replaced with A
 01 is replaced with T
 10 is replaced with C
 11 is replaced with G
Given a binary string 𝑆S of length 𝑁N (𝑁N is even), find the encoded sequence.

Input Format
 First line will contain 𝑇T, number of test cases. Then the test cases follow.
 Each test case contains two lines of input.
 First line contains a single integer 𝑁N, the length of the sequence.
 Second line contains binary string 𝑆S of length 𝑁N.

Output Format
For each test case, output in a single line the encoded sequence.
Note: Output is case-sensitive.

Constraints
 1≤𝑇≤1001≤T≤100
 2≤𝑁≤1032≤N≤103
 𝑁N is even.
 Sum of 𝑁N over all test cases is at most 103103.
 𝑆S contains only characters 0 and 1.

Sample 1:
Input
Output
4
2
00
4
0011
6
101010
4
1001
Output:
A
AG
CCC
CT

CODE:

import java.util.*;
public class Main {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

int t = scanner.nextInt();

while (t-- > 0) {

int n = scanner.nextInt();

String s = scanner.next();

StringBuffer sb=new StringBuffer();

for(int i=1;i<n;i+=2)

if(s.charAt(i)=='0')

if(s.charAt(i-1)=='0')

sb.append("A");

else

sb.append("C");

else if(s.charAt(i)=='1')

if(s.charAt(i-1)=='0')

sb.append("T");

else{

sb.append("G");

}
}

System.out.println(sb.toString());

9. Wordle
Chef invented a modified wordle.
There is a hidden word 𝑆S and a guess word 𝑇T, both of length 55.
Chef defines a string 𝑀M to determine the correctness of the guess word. For the 𝑖𝑡ℎith index:
 If the guess at the 𝑖𝑡ℎith index is correct, the 𝑖𝑡ℎith character of 𝑀M is GG.
 If the guess at the 𝑖𝑡ℎith index is wrong, the 𝑖𝑡ℎith character of 𝑀M is BB.
Given the hidden word 𝑆S and guess 𝑇T, determine string 𝑀M.

Input Format
 First line will contain 𝑇T, number of test cases. Then the test cases follow.
 Each test case contains of two lines of input.
 First line contains the string 𝑆S - the hidden word.
 Second line contains the string 𝑇T - the guess word.

Output Format
For each test case, print the value of string 𝑀M.
You may print each character of the string in uppercase or lowercase (for example, the
strings BgBgBBgBgB, BGBGBBGBGB, bgbGBbgbGB and bgbgbbgbgb will all be treated as
identical).

Constraints
 1≤𝑇≤10001≤T≤1000
 ∣𝑆∣=∣𝑇∣=5∣S∣=∣T∣=5
 𝑆,𝑇S,T contain uppercase english alphabets only.

Sample 1:
Input
Input
3
ABCDE
EDCBA
ROUND
RINGS
START
STUNT

Output:
BBGBB
GBBBB
GGBBG

CODE:
import java.util.*;

import java.lang.*;

import java.io.*;

class Codechef

public static void main (String[] args) throws java.lang.Exception

Scanner sc =new Scanner(System.in);

int t=sc.nextInt();

while(t-- >0)

String S=sc.next();

String T=sc.next();

StringBuffer sb=new StringBuffer();

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

if(S.charAt(i)==T.charAt(i))

sb.append("G");

else

{
sb.append("B");

System.out.println(sb.toString());

10. Different Consecutive Characters


Chef has a binary string 𝑆S of length 𝑁N. Chef can perform the following operation on 𝑆S:
 Insert any character (00 or 11) at any position in 𝑆S.
Find the minimum number of operations Chef needs to perform so that no two consecutive characters are
same in 𝑆S.

Input Format
 The first line contains a single integer 𝑇T — the number of test cases. Then the test cases follow.
 The first line of each test case contains an integer 𝑁N — the length of the binary string 𝑆S.
 The second line of each test case contains a binary string 𝑆S of length 𝑁N containing 00s and 11s
only.

Output Format
For each test case, output on a new line the minimum number of operations Chef needs to perform so that
no two consecutive characters are same in 𝑆S.

Constraints
 1≤𝑇≤1001≤T≤100
 1≤𝑁≤10001≤N≤1000

Sample 1:
Input
Output
3
2
11
4
0101
5
00100
Output:
1
0
2

CODE:

import java.util.*;

import java.lang.*;

import java.io.*;

class Codechef

public static void main (String[] args) throws java.lang.Exception

Scanner sc =new Scanner(System.in);

int t=sc.nextInt();

while(t-- >0)

int n=sc.nextInt();

String s=sc.next();

int count=0;

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

if(s.charAt(i)==s.charAt(i-1))

count++;

System.out.println(count);

}
}

11. Convert String to Title Case


Given a string S consisting of only lowercase and uppercase English letters and spaces, your task is to
convert it into title case. In title case, the first letter of each word is capitalized while the rest are in
lowercase, except for words that are entirely in uppercase (considered as acronyms), which should remain
unchanged.
Note:
 Words are defined as contiguous sequences of English letters separated by spaces.
 Acronyms are words that are entirely in uppercase and should remain unchanged.
 Assume the input does not contain leading, trailing, or multiple spaces between words.

Input Format
 The first line contains a single integer T, the number of test cases.
 Each of the next T lines contains a string S.

Output Format
For each test case, print a single line containing the string S converted into title case.

Constraints
 1≤𝑇≤1001≤T≤100
 1≤∣𝑆∣≤10001≤∣S∣≤1000, where ∣𝑆∣∣S∣ is the length of the string.

Sample 1:
Input
Output
5
hello world
this is a CODECHEF problem
WELCOME to the JUNGLE
the quick BROWN fOx
programming in PYTHON
Output:
Hello World
This Is A CODECHEF Problem
WELCOME To The JUNGLE
The Quick BROWN Fox
Programming In PYTHON
CODE:

import java.util.*;

import java.lang.*;

import java.io.*;

class Codechef

public static void main (String[] args) throws java.lang.Exception

Scanner sc =new Scanner(System.in);

int t=sc.nextInt();

sc.nextLine();

while(t>0)

String s=sc.nextLine();

StringBuffer sb = new StringBuffer();

String []p=s.split(" ");

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

String word=p[i];

char c=word.charAt(0);

if(Character.isLowerCase(c))

sb.append(Character.toUpperCase(c));

sb.append(word.substring(1).toLowerCase());

//sb.append(" ");

else if(Character.isUpperCase(c))

sb.append(word);

//sb.append(" ");
}

sb.append(" ");

System.out.println(sb.toString().trim());

t-=1;

12. World Chess Championship


The World Chess Championship 20222022 is about to start. 1414 Classical games will be played
between Chef and Carlsen in the championship, where each game has one of three outcomes — it can be
won by Carlsen, won by Chef, or it can be a draw. The winner of a game gets 22 points, and the loser
gets 00 points. If it’s a draw, both players get 11 point each.
The total prize pool of the championship is 100⋅𝑋100⋅X. At end of the 1414 Classical games, if one
player has strictly more points than the other, he is declared the champion and gets 60⋅𝑋60⋅X as his
prize money, and the loser gets 40⋅𝑋40⋅X.
If the total points are tied, then the defending champion Carlsen is declared the winner. However, if this
happens, the winner gets only 55⋅𝑋55⋅X, and the loser gets 45⋅𝑋45⋅X.
Given the results of all the 1414 games, output the prize money that Carlsen receives.
The results are given as a string of length 1414 consisting of the characters C, N, and D.
 C denotes a victory by Carlsen.
 N denotes a victory by Chef.
 D denotes a draw.

Input Format
 The first line of input contains an integer 𝑇T, denoting the number of test cases. The description
of 𝑇T test cases follows.
 The first line of each test case contains one integer 𝑋X, denoting that the total prize pool
is 100⋅𝑋100⋅X.
 The second line contains the results of the match, as a string of length 1414 containing only the
characters C, N, and D.
Output Format
For each test case, output in a single line the total prize money won by Carlsen.

Constraints
 1≤𝑇≤10001≤T≤1000
 1≤𝑋≤1061≤X≤106
 ∣𝑆∣=14∣S∣=14
 𝑆S contains only characters D, C, N.

Subtasks
Subtask #1 (100 points): Original constraints

Sample 1:
Input
Output
4
100
CCCCCCCCCCCCCC
400
CDCDCDCDCDCDCD
30
DDCCNNDDDCCNND
1
NNDNNDDDNNDNDN
Output:
6000
24000
1650
40

Explanation:
Test case 11: Since Carlsen won all the games, he will be crowned the champion and will
get 60⋅𝑋60⋅X as the prize money which is 60⋅100=600060⋅100=6000
Test case 22: Carlsen won 77 games and drew 77, so his score is 2⋅7+1⋅7=212⋅7+1⋅7=21. Chef
lost 77 games and drew 77, so his score is 0⋅7+1⋅7=70⋅7+1⋅7=7. Since Carlsen has more points, he
will be crowned the champion and will get 60⋅𝑋60⋅X as the prize money which
is 60⋅400=2400060⋅400=24000
Test case 33: Carlsen and Chef both end up with 1414 points. So, Carlsen is declared the winner, but
because the points were tied, he receives 55⋅𝑋=55⋅30=165055⋅X=55⋅30=1650 in prize money.
CODE:

import java.util.*;

import java.lang.*;

import java.io.*;

class Codechef

public static void main (String[] args) throws java.lang.Exception

Scanner sc=new Scanner(System.in);

int t=sc.nextInt();

while(t>0)

int x=sc.nextInt();

String s=sc.next();

int res=0;

int Dcount=0;

int Ccount=0;

int Ncount=0;

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

if(s.charAt(i)=='D')

Dcount++;

else if(s.charAt(i)=='C')

Ccount++;

else

{
Ncount++;

int carlsenPoints = Ccount * 2 + Dcount;

int chefPoints = Ncount * 2 + Dcount;

if(carlsenPoints > chefPoints)

res = 60 * x;

else if(chefPoints > carlsenPoints)

res = 40 * x;

else if(chefPoints==carlsenPoints)

res = 55 * x;

System.out.println(res);

t--;

13. Add One


You are given a large number 𝑁N. You need to print the number 𝑁+1N+1.
Note: The number is very large and it will not fit in standard integer data type. You have to take the input
as String and then manipulate the digits to convert it to 𝑁+1N+1.

Input Format
 The first line of the input contains a single integer 𝑇T - the number of test cases. The description
of 𝑇T test cases follows.
 The first line of each test case contains a single integer 𝑁N.

Output Format
 For each test case, print a single line containing one integer - the number 𝑁+1N+1.

Constraints
 1≤𝑇≤1001≤T≤100
 1≤𝑁≤10200000−11≤N≤10200000−1
 the sum of the number of digits of all 𝑁N in a single test file does not exceed 4⋅1054⋅105

Subtasks
Subtask #1 (30 points):
 each digit of the number 𝑁N is at most 88
Subtask #2 (70 points): original constraints

Sample 1:
Input
Output
6
99
17
1
599
10000000000000000000
549843954323494990404
Output:
100
18
2
600
10000000000000000001
549843954323494990405

CODE:

import java.util.*;

import java.lang.*;

import java.io.*;

import java.math.BigInteger;
class Codechef

public static void main (String[] args) throws java.lang.Exception

Scanner sc=new Scanner(System.in);

int t=sc.nextInt();

while(t>0)

String s=sc.next();

BigInteger bigInt = new BigInteger(s);

BigInteger n = bigInt.add(BigInteger.ONE);

System.out.println(n.toString());

t--;

14. Chef and Happy String


Chef has a string 𝑆S with him. Chef is happy if the string contains a contiguous substring of
length strictly greater than 22 in which all its characters are vowels.

Determine whether Chef is happy or not.

Note that, in english alphabet, vowels are a, e, i, o, and u.

Input Format
 First line will contain 𝑇T, number of test cases. Then the test cases follow.
 Each test case contains of a single line of input, a string 𝑆S.

Output Format
For each test case, if Chef is happy, print HAPPY else print SAD.
You may print each character of the string in uppercase or lowercase (for example, the
strings hAppY, Happy, haPpY, and HAPPY will all be treated as identical).

Constraints
 1≤𝑇≤10001≤T≤1000
 3≤∣𝑆∣≤10003≤∣S∣≤1000, where ∣𝑆∣∣S∣ is the length of 𝑆S.
 𝑆S will only contain lowercase English letters.

Sample 1:
Input
Output
4
aeiou
abxy
aebcdefghij
abcdeeafg
Output:
Happy
Sad
Sad
Happy

Explanation:
Test case 11: Since the string aeiou is a contiguous substring and consists of all vowels and has a
length >2>2, Chef is happy.
Test case 22: Since none of the contiguous substrings of the string consist of all vowels and have a
length >2>2, Chef is sad.
Test case 33: Since none of the contiguous substrings of the string consist of all vowels and have a
length >2>2, Chef is sad.
Test case 44: Since the string eea is a contiguous substring and consists of all vowels and has a
length >2>2, Chef is happy.

CODE:

import java.util.Scanner;

public class Main {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

int t = scanner.nextInt();
while (t-- > 0) {

String s = scanner.next();

boolean check=true;

// Your code goes here

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

if ((s.charAt(i) == 'a' || s.charAt(i) == 'e' || s.charAt(i) == 'i' || s.charAt(i) == 'o' || s.charAt(i)


== 'u') &&

(s.charAt(i-1) == 'a' || s.charAt(i-1) == 'e' || s.charAt(i-1) == 'i' || s.charAt(i-1) == 'o' || s.charAt(i-1)


== 'u')

&& (s.charAt(i+1) == 'a' || s.charAt(i+1) == 'e' || s.charAt(i+1) == 'i' || s.charAt(i+1) == 'o' ||


s.charAt(i+1) == 'u'))

//System.out.println("Happy");

check=true;

break;

else

check=false;

if(check)

System.out.println("Happy");

else

System.out.println("Sad");

}
}

15.IP:”loveleetcode”

OP:2

IP:”LLEE”

OP:-1

class HelloWorld {

public static void main(String[] args) {

String s="llloo";

int index=-1;

int count=0;

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

count=1;

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

if(s.charAt(i)==s.charAt(j))

count++;

for(int j=i-1;j>=0;j--)

if(s.charAt(i)==s.charAt(j))

count++;

}
if(count==1)

index=i;

break;

System.out.println(index);

16. Blobby Volley Scores


Alice and Bob are playing a game of Blobby Volley. In this game, in each turn, one player is the server
and the other player is the receiver. Initially, Alice is the server, and Bob is the receiver.

If the server wins the point in this turn, their score increases by 1, and they remain as the server for the
next turn.
But if the receiver wins the point in this turn, their score does not increase. But they become the server in
the next turn.
In other words, your score increases only when you win a point when you are the server.
Please see the Sample Inputs and Explanation for more detailed explanation.

They start with a score of 00 each, and play 𝑁N turns. The winner of each of those hands is given to you
as a string consisting of 'A's and 'B's. 'A' denoting that Alice won that point, and 'B' denoting that Bob won
that point. Your job is the find the score of both of them after the 𝑁N turns.

Input Format
 The first line of input will contain a single integer 𝑇T, denoting the number of test cases.
 Each test case consists of two lines of input.
o The first line of each test case contains one integer 𝑁N — the number of turns.
o The line contains a string 𝑆S of length 𝑁N.
 If the 𝑖𝑡ℎith character of this string is 'A', then Alice won that point.
 If the 𝑖𝑡ℎith character of this string is 'B', then Bob won that point.

Output Format
For each test case, output on a new line, two space-separated integers - Alice's final score, and Bob's final
score.

Constraints
 1≤𝑇≤10001≤T≤1000
 1≤𝑁≤10001≤N≤1000
 Length of ∣𝑆∣∣S∣ = 𝑁N
 𝑆S consists only of the characters 'A' and 'B'.

Sample 1:
Input
Output
4
3
AAA
4
BBBB
5
ABABB
5
BABAB
Output:
3 0
0 3
1 1
0 0

CODE:

import java.util.Scanner;

public class Main {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

int t = scanner.nextInt();

while (t-- > 0) {

int n = scanner.nextInt();

String s = scanner.next();

//char ch=s.charAt(0);

int flag1=1;

int flag2=0;
int counta=0;

int countb=0;

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

if(s.charAt(i)=='A' && flag1==1)

counta++;

if(s.charAt(i)=='B' && flag2==1)

countb++;

if(s.charAt(i)=='A')

flag1=1;

flag2=0;

if(s.charAt(i)=='B')

flag2=1;

flag1=0;

System.out.println(counta+" "+countb);

17. Difficulty Rating Order


Our Chef has some students in his coding class who are practicing problems. Given the difficulty of the
problems that the students have solved in order, help the Chef identify if they are solving them in non-
decreasing order of difficulty. Non-decreasing means that the values in an array is either increasing or
remaining the same, but not decreasing. That is, the students should not solve a problem with
difficulty 𝑑1d1, and then later a problem with difficulty 𝑑2d2, where 𝑑1>𝑑2d1>d2.

Output “Yes” if the problems are attempted in non-decreasing order of difficulty rating and “No” if not.

Input Format
 The first line of input will contain a single integer 𝑇T, denoting the number of test cases. The
description of the test cases follows.
 Each test case consists of 22 lines of input.
o The first line contains a single integer 𝑁N, the number of problems solved by the students
o The second line contains 𝑁N space-separate integers, the difficulty ratings of the problems attempted
by the students in order.

Output Format
 For each test case, output in a new line “Yes” if the problems are attempted in non-decreasing order of
difficulty rating and “No” if not. The output should be printed without the quotes.
Each letter of the output may be printed in either lowercase or uppercase. For example, the
strings yes, YeS, and YES will all be treated as equivalent.

Constraints
 1≤𝑇≤1001≤T≤100
 2≤𝑁≤1002≤N≤100
 1≤1≤ difficulty of each problem ≤5000≤5000

Sample 1:
Input
Output
4
3
1 2 3
3
1 1 2
5
100 200 300 400 350
5
1000 2000 5000 3000 1000
Yes
Yes
No
No

Explanation:
Test case 11: 1≤2≤31≤2≤3. The students have solved problems in increasing order, and so the answer is
"Yes".
Test case 22: 1≤1≤21≤1≤2. The students have solved problems in non-decreasing order, and so the
answer is "Yes".
Test case 33: 400>350400>350, but the students have solved a 400400-difficulty level problem
before solving a 350350-difficulty problem. The students have not solved problems in non-decreasing
order, and so the answer is "No".
Test case 44: 5000>30005000>3000, but the students have solved a 50005000-difficulty level
problem before solving a 30003000-difficulty problem. The students have not solved problems in non-
decreasing order, and so the answer is "No".

CODE:

import java.util.Scanner;

public class Main {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

int t = scanner.nextInt();

while (t-- > 0) {

int n = scanner.nextInt();

int[] d = new int[n];

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

d[i] = scanner.nextInt();

int len=d.length;

boolean flag=true;
for(int i=0;i<len-1;i++)

if(d[i]>d[i+1])

flag=false;

if(!flag)

System.out.println("No");

else

System.out.println("Yes");

18. Running Comparison


Alice and Bob recently got into running, and decided to compare how much they ran on different days.
They each ran for 𝑁N days — on the 𝑖𝑡ℎith day, Alice ran 𝐴𝑖Ai meters and Bob ran 𝐵𝑖Bi meters.

On each day,

 Alice is unhappy if Bob ran strictly more than twice her distance, and happy otherwise.
 Similarly, Bob is unhappy if Alice ran strictly more than twice his distance, and happy otherwise.

For example, on a given day

 If Alice ran 200200 meters and Bob ran 500500, Alice would be unhappy but Bob would be happy.
 If Alice ran 500500 meters and Bob ran 240240, Alice would be happy and Bob would be unhappy.
 If Alice ran 300300 meters and Bob ran 500500, both Alice and Bob would be happy.
On how many of the 𝑁N days were both Alice and Bob happy?
Input Format
 The first line of input will contain a single integer 𝑇T, denoting the number of test cases.
 Each test case consists of three lines of input.
o The first line of each test case contains a single integer 𝑁N — the number of days.
o The second line of each test case contains 𝑁N space-separated integers 𝐴1,𝐴2,…,𝐴𝑁A1,A2,…,AN
— the distances run by Alice on the 𝑁N days.
o The third line of each test case contains 𝑁N space-separated integers 𝐵1,𝐵2,…,𝐵𝑁B1,B2,…,BN
— the distances run by Bob on the 𝑁N days.

Output Format
For each test case, output on a new line the number of days when both Alice and Bob were happy.

Constraints
 1≤𝑇≤10001≤T≤1000
 1≤𝑁≤1001≤N≤100
 1≤𝐴𝑖,𝐵𝑖≤1051≤Ai,Bi≤105

Sample 1:
Input
Output
4
3
100 200 300
300 200 100
4
1000 1000 1000 1000
400 500 600 1200
4
800 399 1400 532
2053 2300 3400 23
5
800 850 900 950 1000
600 800 1000 1200 1400
Output:
1
3
0
5

CODE:

import java.util.Scanner;
public class Main {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

int t = scanner.nextInt();

while (t-- > 0) {

int n = scanner.nextInt();

int[] a = new int[n];

int[] b = new int[n];

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

a[i] = scanner.nextInt();

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

b[i] = scanner.nextInt();

int count=0;

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

int alice=2*a[i];

int bob=2*b[i];

if(alice>=b[i] && bob>=a[i])

count++;

System.out.println(count);

}
}

19. Largest and Second Largest


You are given an array 𝐴A of 𝑁N integers.
Find the maximum sum of two distinct integers in the array.
Note: It is guaranteed that there exist at least two distinct integers in the array.

Input Format
 The first line of input will contain a single integer 𝑇T, denoting the number of test cases.
 Each test case consists of multiple lines of input.
o The first line of each test case contains single integer 𝑁N — the size of the array.
o The next line contains 𝑁N space-separated integers, denoting the array 𝐴A.

Output Format
For each test case, output on a new line, the maximum sum of two distinct integers in the array.

Constraints
 1≤𝑇≤10001≤T≤1000
 2≤𝑁≤1052≤N≤105
 1≤𝐴𝑖≤10001≤Ai≤1000
 The sum of 𝑁N over all test cases does not exceed 2⋅1052⋅105.

Sample 1:
Input
Output
4
3
4 1 6
7
3 7 2 1 1 5 3
5
8 2 9 4 9
2
1 2
10
12
17
3

Explanation:
Test case 11: The maximum sum of two distinct elements is 4+6=104+6=10 .
Test case 22: The maximum sum of two distinct elements is 7+5=127+5=12.
Test case 33: The maximum sum of two distinct elements is 8+9=178+9=17.
Test case 44: The maximum sum of two distinct elements is 1+2=31+2=3.

CODE;

import java.util.Scanner;

import java.util.Arrays;

public class Main {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

int t = scanner.nextInt();

while (t-- > 0) {

int n = scanner.nextInt();

int[] a = new int[n];

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

a[i] = scanner.nextInt();

Arrays.sort(a);

int firstmax=a[n-1];

int secmax=0;

int i=n-2;

while(i<n-1)

if(a[i]==a[n-1])

i--;

else

{
secmax=a[i];

break;

System.out.println(firstmax+secmax);

// Your code goes here

20. string str is given to you your task is to find out the duplicate characters
(Character those are repeating more than once) in the given string.
To solve this problem complete function duplicateCharacters with following
parameters:
String str: A non empty string str
Function returns:
String: The function returns a string consisting of duplicate characters in the input
string. If all character in the input string are unique then return string "-1".

Note: Your solution should run in linear time i.e. O(str.length()).

Constraints to be followed:
1 <= str.length() <= 1000
All characters in the string can be numeric, alphanumeric or special characters, and
alphanumeric characters can be lowercase or upper case.
duplicate characters in the resultant string should appear according to their first
occurrence in the input string.

Sample test case 1 :


Input:
abca11c
Output:
ac1
Sample test case 2:
Input:
aaaaaa
Output:
a
Brief editorial: In test case 1 in input string"abca11c" the characters occurring more
than once are 'a', 'c' and '1'. So they are ordered and returned as per their first
occurrence in the input string

Instruction: To complete the required function please follow the function rules given
below, And to run your custom test cases on the terminal please strictly follow the
input and output layout mentioned in the visible sample test case.
Function Rules:

Fill the missing logic in function duplicateCharacters with return


type String and parameters as listed below:

 String str

CODE:

import java.util.LinkedHashSet;

import java.util.Set;

public class DuplicateCharacters {

public static String duplicateCharacters(String str) {

int n = str.length();

Set<Character> st = new LinkedHashSet<>();

StringBuffer sb = new StringBuffer();

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

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

if (str.charAt(i) == str.charAt(j)) {

st.add(str.charAt(i));

break; // No need to check further once a duplicate is found

for (char c : st) {

sb.append(c);

if (st.isEmpty()) {

sb.append("-1");
}

return sb.toString();

public static void main(String[] args) {

// Sample test cases

System.out.println(duplicateCharacters("abca11c")); // Output: ac1

System.out.println(duplicateCharacters("aaaaaa")); // Output: a

System.out.println(duplicateCharacters("abcdef")); // Output: -1

System.out.println(duplicateCharacters("a1b2c3a1b2c3")); // Output: a1b2c3

21.LONGEST CONSECUTIVE SEQUENCE:

LOGIC:

Arrays.sort(arr);

int longestStreak = 0;

int currentStreak = 1;

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

if (arr[i] != arr[i-1]) { // Skip duplicates

if (arr[i] == arr[i-1] + 1) {

currentStreak++;

} else {

longestStreak = Math.max(longestStreak, currentStreak);

currentStreak = 1;

longestStreak = Math.max(longestStreak, currentStreak);


System.out.println(longestStreak);

Problem statement
Send feedback
You are given an unsorted array/list 'ARR' of 'N' integers. Your task is to return the length of the
longest consecutive sequence.
The consecutive sequence is in the form ['NUM', 'NUM' + 1, 'NUM' + 2, ..., 'NUM' + L] where
'NUM' is the starting integer of the sequence and 'L' + 1 is the length of the sequence.
Note:
If there are any duplicates in the given array we will count only one
of them in the consecutive sequence.
For example-

For the given 'ARR' [9,5,4,9,10,10,6].

Output = 3
The longest consecutive sequence is [4,5,6].
NOTE:THOUGH 9 10 IS CONSECUTIVE THEY ARE NOT LONG

22.MAXIMUM SUBARRAY SUM

int maxSoFar = 0;

int maxEndingHere = 0;

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

maxEndingHere = maxEndingHere + arr[i];

if (maxEndingHere < 0)

{ maxEndingHere = 0;

if (maxSoFar < maxEndingHere)

maxSoFar = maxEndingHere;

return maxSoFar;

you are provided with 2 strings you can perform operation such as adding removing or swapping
letter. eac operatio has a specigfi cost value assosiated with it if a letter is removed from s1,the
cost is 0 if a pair of letters are swapped in s1,then the cost is 0 if a new letter is added to end of
the s1,the cost is 1. Your task is to find and return int value reopresenting cost required to
transfrom from s1 to s2 sample ip: s1="ABD" s2="AABCCAD" sample op:4

CODE:

public class StringTransformation {

public static int transformationCost(String s1, String s2) {

// Define the maximum number of characters in the English alphabet

final int ALPHABET_SIZE = 26;

// Create arrays to count occurrences of each character in s1 and s2

int[] countS1 = new int[ALPHABET_SIZE];

int[] countS2 = new int[ALPHABET_SIZE];

// Count characters in s1

for (char c : s1.toCharArray()) {

countS1[c - 'A']++;

// Count characters in s2

for (char c : s2.toCharArray()) {

countS2[c - 'A']++;

// Calculate the cost based on the character counts

int cost = 0;

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

if (countS2[i] > countS1[i]) {

cost += countS2[i] - countS1[i];

return cost;
}

public static void main(String[] args) {

String s1 = "AA";

String s2 = "AAC";

System.out.println("Cost to transform s1 to s2: " + transformationCost(s1, s2)); // Output: 1

CODE:

class HelloWorld {

public static void main(String[] args) {

String s="1100010001000111";

int count=0;

int max=0;

StringBuilder sb=new StringBuilder();

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

if(s.charAt(i)=='1')

count++;

else if(s.charAt(i)=='0' && count>0)

int val=64+count;

sb.append((char)(val));

count=0;

}
int c=0;

for(int i=s.length()-1;i>=0;i--)

if(s.charAt(i)=='1')

c++;

else if(s.charAt(i)=='0')

break;

sb.append((char)(64+c));

String s1=sb.toString();

System.out.println(s1);

You might also like