You are on page 1of 64

Coding: 5 Marks

Question 1:

Attempt to open Vault

A money heist is going on in a bank. There is one specific vault in which the leader is
interested but it is locked and can be opened by entering a specific word. He has 5 attempts to
unlock the vault, so he starts by guessing the password and writing it down in a paper. You
have to find out at which attempt the vault will open if you know what words he chose.
Return -1 if any of the attempts couldn't open the vault.

Note: The vault may also open if the last characters of previous guess and first few or all
characters match the vault password. For example if the word at which the vault will open is
“save” and the 2nd guess of thief is “hansa” and 3rd guess is “vein” then the vault will open
at 3rd guess because last two characters of “hansa” is “sa” and first two characters of “vein”
is “ve” so it will make “save” and the vault will open.

P.S. Use KMP Algorithm

Sample Input 1:

save

fried hansa veins rambo jumbo

Sample Output 1:

Sample Input 2:

coffee

round think morocco fees light

Sample Output 2:

-1

Input Explanation:

1st Line: password of the vault


2nd Line: 5 passwords the leader wrote down in paper

Output Explanation:

Return the attempt number at which vault will open.

Return -1 if it doesn’t open

Test cases:

Test Case 1 Test Case 2 Test Case 3 Test Case 4

Input coffee save save Rift

round think fried hans Jumbo fried Couch SiRif tea mind
moroccof veins rambo hans veins full
fees light jumbo avebo

Output 4 -1 5 3

Solution:

import java.util.*;
class AttemptToOpenVault{
Scanner sc=new Scanner(System.in);
String password,attempts=""; String[] attemptpassword;
int[] attemptNumber=new int[5];
AttemptToOpenVault(){
password=sc.nextLine();
attemptpassword=sc.nextLine().split(" ");
for(int i=0;i<5;i++)
{attempts+=attemptpassword[i];attemptNumber[i]=attempts.length();}
}
void lpsArray(int[] lps){
int j=0,i=1;
lps[0]=0;
while(i<password.length()){
if(password.charAt(i)==password.charAt(j)){
j++;
lps[i]=j;
i++;
}
else{
if(j!=0) j=lps[j-1];
else {lps[i]=0;i++;}
}
}

}
void kmpAlgo(){
int[] lps=new int[password.length()];
int i=0,j=0;
lpsArray(lps);

while(i<attempts.length()){
if(password.charAt(j)==attempts.charAt(i)){
i++;j++;
}
if(j==password.length()){
if(i<=attemptNumber[0])System.out.println(1);
if(i>attemptNumber[0] &&
i<=attemptNumber[1])System.out.println(2);
if(i>attemptNumber[1] &&
i<=attemptNumber[2])System.out.println(3);
if(i>attemptNumber[2] &&
i<=attemptNumber[3])System.out.println(4);
if(i>attemptNumber[3] &&
i<=attemptNumber[4])System.out.println(5);
j=lps[j-1];
return;
}
else if(i<attempts.length() && password.charAt(j)!=attempts.charAt(i)){
if(j!=0) j=lps[j-1];
else i++;
}
}
System.out.println(-1);
}

public class Main{


public static void main(String[] args){

AttemptToOpenVault ATOV=new AttemptToOpenVault();

ATOV.kmpAlgo();

}
Coding: 5 Marks

Question 2:

All about Palindromes

Mananjay is playing with his son as well as teaching him about the palindromes. So, he took
out some scrabble tiles and now has some alphabet tiles with different frequencies of each of
those letters. First he arranged all those alphabets in a random order giving him an arbitrary
word. Now he has started counting how many palindromes he can make using those
alphabets without disturbing the order in which he arranged them. Help him complete this fun
game.

Sample Input 1:

aabab

Sample Output 1:

Sample Input 2:

ababab

Sample Output 2:

Input Explanation:

Random word Mananjay made

Output Explanation:

Number of palindromes in that word that he can make

In Sample 1, 5 possible palindromes are “a”, “aa”, “aba”, “b”and “bab”

In Sample 2, 6 possible palindromes are “a”, “aba”, “ababa”, “b”, “bab” and “babab”
Test cases:

Test Case 1 Test Case 2 Test Case 3 Test Case 4

Input coffeee jumbo abracadabra alohamora

Output 7 5 7 6

Solution:
import java.util.*;
class AllAboutPalindromes{
Scanner sc=new Scanner(System.in);
String s;
AllAboutPalindromes(){
s=sc.next();
}
void palindromeSubStrs()
{
TreeMap<String , Integer> m = new TreeMap<>();
int n = s.length();

int[][] R = new int[2][n+1];

s = "@" + s + "#";

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


{
int rp = 0;
R[j][0] = 0;

int i = 1;
while (i <= n)
{
while (s.charAt(i - rp - 1) == s.charAt(i +
j+
rp))
rp++;
R[j][i] = rp;
int k = 1;
while ((R[j][i - k] != rp - k) && (k < rp))
{
R[j][i + k] = Math.min(R[j][i - k],
rp - k);
k++;
}
rp = Math.max(rp - k,0);
i += k;
}
}

s = s.substring(1, s.length()-1);

m.put(s.substring(0,1), 1);
for (int i = 1; i < n; i++)
{
for (int j = 0; j <= 1; j++)
for (int rp = R[j][i]; rp > 0; rp--)
m.put(s.substring(i - rp - 1, i - rp - 1
+ 2 * rp + j), 1);
m.put(s.substring(i, i + 1), 1);
}

System.out.println(m.size());
}
}
public class Main
{
public static void main(String args[])
{
AllAboutPalindromes AAP=new AllAboutPalindromes();
AAP.palindromeSubStrs();
}
}
Coding: 5 Marks

Question 3:

Newborn’s Name

A couple had a baby 3 days ago and they have been thinking over what to name their baby so
they came up with an idea that they should merge their first names and come with a name.
But, they are afraid that it will be a long name. Help them figure out how small they can
come up with a name if they merge their names such that they get both their names as
subsequences in the child’s name.

Sample Input 1:

nisha antil

Sample Output 1:

Sample Input 2:

maahi ahima

Sample Output 2:

Input Explanation:

Space separated first name of couple

Output Explanation:

Number of characters in baby’s name

In Sample 1, shortest name could be “antilsha” of length “8” which has “antil” and “nisha” as
subsequence.

In Sample 2, shortest name could be “maahima”of length “7” which has “mahi” and “ahima”
as subsequence..
Test cases:

Test Case 1 Test Case 2 Test Case 3 Test Case 4

Input Rahul Rakhi jumbo boumj Abs klp aloha mora

Output 7 8 6 7

Solution:

import java.util.*;
class BabyName{
Scanner sc=new Scanner(System.in);
private String str1,str2;
BabyName(){
this.str1=sc.next();this.str2=sc.next();
}
void shortestNameLength()
{
int[][]L=new int [str1.length()+1][str2.length()+1];
int i,j;
for (i = 0; i <= str1.length(); i++) {
for (j = 0; j <= str2.length(); j++) {
if (i == 0 || j == 0)
L[i][j] = 0;

else if (str1.charAt(i - 1) == str2.charAt(j - 1))


L[i][j] = L[i - 1][j - 1] + 1;

else
L[i][j] = Math.max(L[i - 1][j],
L[i][j - 1]);
}
}
int k=str1.length()+str2.length()-L[str1.length()][str2.length()];
System.out.println(k);

}
}
public class Main
{
public static void main(String args[])
{
BabyName BN=new BabyName();
BN.shortestNameLength();
}
}
Coding: 5 Marks

Question 4:

Repeated Name

Mahesh was reading a book and realised that some words are repeated too many times in the
book. Can you write a Java program using Z-algorithm to find how many times a word is
being repeated in a given string?

Note: Rahul and rAhul are the same words and not different.

Sample Input 1:

Rahulkllklfjohfohohfohoa

Rahul

Sample Output 1:

Sample Input 2:

maahiahimaahima

maahi

Sample Output 2:

Input Explanation:

1st Line: String in which word is to be searched for

2nd Line: Word to be searched

Output Explanation:

Number of times word comes in given text.


Test cases:

Test Case 1 Test Case 2 Test Case 3 Test Case 4

Input Rahulrahul jumbo Leftist left the aloha mora


bounce party to the
rahul Jumbo jumb left Aloha
o
left
jumbo

Output 2 2 3 1

Solution:

import java.util.*;
class RepeatedName
{
Scanner sc=new Scanner(System.in);
String toSearch,inSearch;
int[] Z;
RepeatedName(){
inSearch=sc.nextLine();
toSearch=sc.nextLine();
}
void zArray()
{
String temp=toSearch+"$"+inSearch;
Z=new int[temp.length()];
int left=0, right=0,count=0;
for(int i=0; i<temp.length();i++){
if(i<=right){
Z[i]=Math.min(right-i+1, Z[i-left]);
}
while(i+Z[i]<temp.length() &&
Character.toLowerCase(temp.charAt(Z[i])) == Character.toLowerCase(temp.charAt(i+Z[i])))
Z[i]++;

if(i-Z[i]-1>right){
left=i;
right=i+Z[i]-1;}}
for(int i=toSearch.length()+1;i<temp.length();i++){
if(Z[i]==toSearch.length()){
count++;
}
}
System.out.println(count);
}

}
public class Random3
{
public static void main(String args[])
{
RepeatedName RN=new RepeatedName();
RN.zArray();
}
}
Coding: 5 Marks

Question 5:

Decipher the Alphabetic Code

While digging in his backyard, Anil has found a treasure box and a bottle with a note inside
it. The first line in the note says,” Biggers will be rewarded and the Smalls will be
slaughtered” and the second line is some arbitrary space separated words which does not
make any sense. After searching about such a treasure and note online, he came to
understand that the note holds the password for the treasure box. The arbitrary space
separated words actually form a number which could be used to open the box.

The number of those arbitrary words in the note is the number of digits of the required
number to open the box. A word represents a digit which can not be less than 0 and greater
than 9. So if the word deciphered into a number comes greater than 9, it is taken as 9 and if it
comes less than 0, it is taken as 0. The word can be transformed into a number by using
following rules:

1) Sum of values of each alphabet in the word gives the desired digit
2) Alphabets written in Capital are to be added while small ones are to be subtracted.
Example:

If the word is ANil

Value of A and N is to be added and the value of i and l is to be subtracted. Thus


giving a number

3) Alphabets A-Z are assigned values in ascending order from 1 to 26. Example:

A-1, C-3…………Z-26

So word anIL will give 6.

Help Anil write a JAVA program to find the code to open the treasure box and see what is
inside it.
Sample Input 1:

ABc CDeF GHi akN

Sample Output 1:

0862

Sample Input 2:

AbCD CDeF

Sample Output 2:

68

Input Explanation:

Space separated words.

Output Explanation:

Returns the code number.

Test cases:

Test Case 1 Test Case 2 Test Case 3 Test Case 4

Input MahESh Is A NaViGate AaFfGgOo RETURNthevalue


Good Man AAbbCCCdE PpLlUu oFSomeTHInG
GhHg

Output 90100 78 000 27


Solution:

import java.util.*;

class DecipherTheCode{

Scanner sc=new Scanner(System.in);

private String str; private int[] code; private int count=1;

DecipherTheCode(){

str=sc.nextLine();

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

if((int) str.charAt(i)==32) count++;

code=new int[count];

void decipher(){

int i=0,j=0;

while(i<str.length()){

if((int)str.charAt(i)==32) {i++;j++;}

if((int)str.charAt(i)>90) code[j]-=(int)str.charAt(i)-96;

else code[j]+=(int)str.charAt(i)-64;

i++;

for(j=0;j<code.length;j++){

if(code[j]>9) code[j]=9;if(code[j]<0) code[j]=0;

System.out.print(code[j]);

}
}

public class Main{

public static void main(String[] args){

DecipherTheCode DTC= new DecipherTheCode();

DTC.decipher();

}
Coding: 5 Marks

Question 6:

Decipher the Numeric Code

Mananjay found an ancient scripture engraved in a stone. It has some space separated
numbers written on it. After thorough searching, he found how to decipher that numeric code
into text. Rules to convert the numbers into words is as follows:

1) Each space separated number can be converted to a word of length equal to the
number of digits in that number.
2) Vowels {a,e,i,o} are represented by the first four prime numbers respectively.
3) Remaining numbers in a digit are assigned to {c,d,l,m,u,v} in ascending order
respectively.

Help him write a Java program to decipher this numeric code.

Sample Input 1:

5 26 544

Sample Output 1:

i am ill

Sample Input 2:

17 453

Sample Output 2:

do lie

Input Explanation:

Space separated numbers.

Output Explanation:

Returns the alphabetic code.


Test cases:

Test Case 1 Test Case 2 Test Case 3 Test Case 4

Input 2654 7890 67435 786 8 4793 63 1357 246 890 5 4793 8

Output amil ouvc molei oum u love me deio alm uvc i love u

Solution:

import java.util.*;

class DecipherTheCode2

Scanner sc=new Scanner(System.in);

private String str; private String[] code; private int count=1;

private char[] defaultChar= {'c','d','a','e','l','i','m','o','u','v'};

DecipherTheCode2(){

str=sc.nextLine();

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

if((int) str.charAt(i)==32) count++;

code=new String[count]; Arrays.fill(code, "");

void decipher(){
int i=0,j=0,k=0;

while(i<str.length()){

if((int)str.charAt(i)==32) {i++;code[j]+=" ";j++;}

k=(int)(str.charAt(i))-48;

code[j]+=defaultChar[k]; i++;

for(j=0;j<code.length;j++) {

System.out.print(code[j]);

public class Main{

public static void main(String[] args){

DecipherTheCode2 DTC= new DecipherTheCode2();

DTC.decipher();

}
Coding: 5 Marks

Question 7:

Alien with familiar language

A UFO landed in Bengaluru, India and an alien came out of it. He did not know any Earth
language but wanted to say something and blabbered something. One person realised that
there is a pattern in what he is saying. He figured that he was speaking English but in reverse.
For example if he wanted to say,”I am Rajesh”, he would say “Rajesh am I”.

Write a Java program to understand what the alien is trying to say.

Sample Input 1:

Want you what is here

Sample Output 1:

here is what you Want

Sample Input 2:

me hurt not do Please

Sample Output 2:

Please do not hurt me

Input Explanation:

A STRING

Output Explanation:

Return the required string


Test cases:

Test Case 1 Test Case 2 Test Case 3 Test Case 4

Input Am I What is Good is life you? are Who


happening?

Output I Am happening? is life is Good Who are you?


What

Solution:

import java.util.*;
class AliensWithFamilierLanguage
{
Scanner sc= new Scanner(System.in);
String[] str; String result="";
AliensWithFamilierLanguage(){
str=sc.nextLine().split(" ");
}
void decode(){
for(int i=str.length-1;i>=0;i--) {
result+=str[i]+" ";
}
System.out.println(result.substring(0,result.length()-1));
}

public class Main{

public static void main(String[] args){

AliensWithFamilierLanguage AWFL=new AliensWithFamilierLanguage();

AWFL.decode();

}
Coding: 5 Marks

Question 8:

Guys with same name

In a class, some students have the same first name but may have the same or different last
name. Your task is to find the most common first name. There is a catch that their last name
and first name is not separated by space but the first name and last name starts with a capital
alphabet, for example, VirajSingh.

Note: If there are two or more most common names, then return the name which comes first
in alphabetical order.

Sample Input 1:

AnujSaxena AnujRawat MananjayKumar MananjaySingh AnujRaturi AmanSingh

Sample Output 1:

Anuj

Sample Input 2:

HarishRawat NaruModi DeepeshSingh HarishBadoni DeepeshMalhotra

Sample Output 2:

Deepesh

Input Explanation:

Space separated names of students

Output Explanation:

Most common first name


Test cases:

Test Case 1 Test Case 2 Test Case 3 Test Case 4

Input AmPa AmNa SuNa AnPo GoodLife YouWho WooHoo


PaPa PaRa SuPo AnPo GoodBoy YouMe WooMe
KoPi SuPi GoodName KooPee
BrideMaid

Output Am Su Good Woo

Solution:

import java.util.*;

class GuysWithSameName{

Scanner sc=new Scanner (System.in);

String[] names, firstname;

GuysWithSameName(){names=sc.nextLine().split(" ");}

void separateFirstName(){

Arrays.sort(names);

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

firstname= names[i].split("(?=\\p{Upper})");

names[i]=names[i].replace(names[i],firstname[0]);

}
void mostCommonName(){

HashMap<String, Integer> freq = new HashMap<>();

HashMap<String, Integer> occurrence= new HashMap<>();

int max = 0;

String result = "";

int k = 1;

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

if (occurrence.containsKey(names[i])) {

continue;

occurrence.put(names[i], k);

k++;

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

if (freq.containsKey(names[i])) {

freq.put(names[i], freq.get(names[i]) + 1);

else

freq.put(names[i], +1);

if (max < freq.get(names[i])) {

if (max < freq.get(names[i])) {

max = freq.get(names[i]);result = names[i];

else {

if (occurrence.get(result)< occurrence.get(names[i])) {
max = freq.get(names[i]);result = names[i];

System.out.println(result);

public class Main{

public static void main(String[] args){

GuysWithSameName GWSN=new GuysWithSameName();

GWSN.separateFirstName();

GWSN.mostCommonName();

}
Coding: 5 Marks

Question 9:

Palindrome Obsession

Naman is so obsessed with palindromes that everywhere he sees a line or word he starts
thinking how he could make that line or word a palindrome. Help him a write a Java program
which guides him how many characters he has to take off from the line/word so that it
becomes a palindrome.

Sample Input 1:

lifeefql

Sample Output 1:

Sample Input 2:

free to eearn

Sample Output 2:

Input Explanation:

A string

Output Explanation:

Number of characters to delete to make it a palindrome

Note: In sample 1, one can remove “i” and “q” to make it a palindrome.

In sample 2, one can remove “f”, “o”, “a” and “n” to make it a palindrome.
Test cases:

Test Case 1 Test Case 2 Test Case 3 Test Case 4

Input life is efi l have your good for good bad for bad
way

Output 2 8 6 6

Solution:

import java.util.*;

class PalindromeObsession

Scanner sc=new Scanner (System.in);

String str;

int n;

PalindromeObsession(){

str=sc.nextLine();

n=str.length();

void numOfChar()

int[][]lps=new int[n][n];
for(int i=0;i<n;i++) lps[i][i]=1;

for (int l = 2; l <= n; l++){

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

int j = i + l - 1;

if (str.charAt(i) ==

str.charAt(j) && l == 2)

lps[i][j] = 2;

else if (str.charAt(i) ==

str.charAt(j))

lps[i][j] = lps[i + 1][j - 1] + 2;

else

lps[i][j] = Integer.max(lps[i][j - 1],

lps[i + 1][j]);

int count=n-lps[0][n-1];

System.out.println(count);

public class Main{

public static void main(String[] args){

PalindromeObsession PO =new PalindromeObsession();

PO.numOfChar();

}
Coding: 5 Marks

Question 10:

Pangram Check

Sumit wanted to make pangrams as short as possible and came up with few sentences and
wanted to check if they really are pangrams. Write a Java program to check if the sentences
Sumit wrote are pangrams or not.

Note: Apangram is a sentence using every letter of a given alphabet atleast once.

Sample Input 1:

The five boxing wizards jump quickly

The five boxing wizards bump quickly

Sample Output 1:

Pangram

Not Pangram

Sample Input 2:

Pack my box with five dozen liquor jugs

Sample Output 2:

Pangram

Input Explanation:

1st Line: Number of Test Cases, N, followed by N subsequent lines of sentences.

Output Explanation:

N lines depicting if they are Pangram or Not Pangram.

Test cases:
Test Case 1 Test Case 2 Test Case Test Case 4
3

Input 4 3 2 2
Waltz, bad Waltz, bad Waltz, bad Waltz, bad nymph, for
nymph, for quick nymph, for nymph, for quick jigs vex
jigs quick jigs vex quick jigs
Glib jocks quiz nymph to
vex
Glib jocks quiz Glib jocks quiz vex
nymph to vex nymph to vex Glib jocks
dwarf. quiz
Waltz, bad
nymph to
Sphinx of black nymph, for
vex dwarf.
quartz, judge my quick jigs vex
vow]

How quickly daft


jumping zebras

Output Not Pangram Pangram Pangram Pangram

Pangram Not Pangram Pangram Not Pangram

Pangram Pangram

Not Pangram

Solution:

import java.util.*;

class PangramCheck

Scanner sc=new Scanner (System.in);

String[] str;

int n;

PangramCheck(){
n=sc.nextInt();

sc.nextLine();

void makeString(){

str=new String[n];

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

str[i]=sc.nextLine();

boolean checkPangram(int k){

boolean[] mark = new boolean[26];

int index = 0;

for (int i = 0; i < str[k].length(); i++) {

if ('A' <= str[k].charAt(i)

&& str[k].charAt(i) <= 'Z')

index = str[k].charAt(i) - 'A';

else if ('a' <= str[k].charAt(i)

&& str[k].charAt(i) <= 'z')

index = str[k].charAt(i) - 'a';

else

continue;

mark[index] = true;

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


if (mark[i] == false)

return (false);

return (true);

void isPangram()

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

if (checkPangram(i) == true)

System.out.println("Pangram");

else

System.out.println("Not Pangram");

public class Main{

public static void main(String[] args){

PangramCheck PC=new PangramCheck();

PC.makeString();

PC.isPangram();

}
Coding: 5 Marks

Question 11:

Roman to Integer

Write a program to convert given Roman Number to an Integer.

Note:Number is not greater than 3999.

Sample Input 1:

MMMDCXVI

Sample Output 1:

3616

Sample Input 2:

MMDCCXIV

Sample Output 2:

2714

Input Explanation:

Roman Number

Output Explanation:

Integer

Test cases:

Test Case 1 Test Case 2 Test Case 3 Test Case 4

Input CDXLV MMDCCLXX MCCLXI MMCXCVII


IX

Output 445 2779 1261 2199


Solution:

import java.util.*;

class RomanToInteger

Scanner sc=new Scanner(System.in);

String str;

RomanToInteger()

str=sc.next();

int value(char r)

if (r == 'I')

return 1;

if (r == 'V')

return 5;

if (r == 'X')

return 10;

if (r == 'L')

return 50;

if (r == 'C')

return 100;

if (r == 'D')

return 500;

if (r == 'M')
return 1000;

return -1;

void convert()

int res = 0;

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

// Getting value of symbol s[i]

int s1 = value(str.charAt(i));

// Getting value of symbol s[i+1]

if (i + 1 < str.length()) {

int s2 = value(str.charAt(i + 1));

// Comparing both values

if (s1 >= s2) {

// Value of current symbol

// is greater or equalto

// the next symbol

res = res + s1;

else {

// Value of current symbol is


// less than the next symbol

res = res + s2 - s1;

i++;

else {

res = res + s1;

System.out.println(res);

public class Main{

public static void main(String[] args){

RomanToInteger RI=new RomanToInteger();

RI.convert();

}
Coding: 5 Marks

Question 12:

Integer to Roman

Write a program to convert given Integer to Roman Number

Note:Number is not greater than 3999.

Sample Input 1:

3616

Sample Output 1:

MMMDCXVI

Sample Input 2:

2714

Sample Output 2:

MMDCCXIV

Input Explanation:

Roman Number

Output Explanation:

Integer

Test cases:
Test Case 1 Test Case 2 Test Case 3 Test Case 4

Input 445 2779 1261 2199

Output CDXLV MMDCCLXXIX MCCLXI MMCXCVII

Solution:

import java.util.*;

class IntegertoRoman

Scanner sc=new Scanner(System.in);

int num;

IntegertoRoman()

num=sc.nextInt();

void convert()

String m[] = { "", "M", "MM", "MMM" };

String c[] = { "", "C", "CC", "CCC", "CD",

"D", "DC", "DCC", "DCCC", "CM" };

String x[] = { "", "X", "XX", "XXX", "XL",

"L", "LX", "LXX", "LXXX", "XC" };

String i[] = { "", "I", "II", "III", "IV",


"V", "VI", "VII", "VIII", "IX" };

String thousands = m[num / 1000];

String hundreds = c[(num % 1000) / 100];

String tens = x[(num % 100) / 10];

String ones = i[num % 10];

String ans = thousands + hundreds + tens + ones;

System.out.println(ans);

public class Main{

public static void main(String[] args){

IntegertoRoman IR=new IntegertoRoman();

IR.convert();

}
Coding: 5 Marks

Question 13:

Magnetic Force

Arun has K(>1) very strong magnets with him. He had a container and divided it into smaller
spaces using cardboard so that no two magnets get attracted towards each other and combine
to get destroyed from the edges. He placed some wood chips in some of the divisions he
made in the container. Now he has only N places to store the magnets which is sufficiently
more or equal to K magnets. The position of places which are empty are stored in an array.
Now, you need to place the magnets, such that the minimum distance between the magnets is
as large as possible. Return the largest minimum distance.

Sample Input 1:

64

0 3 4 7 10 9

Sample Output 1:

Sample Input 2:

52

42136

Sample Output 2:

Input Explanation:

Line1:space separated number of places empty and number of magnets

Line2: space separated position of empty places.


Output Explanation:

Largest minimum distance between the magnets.

Test cases:

Test Case 1 Test Case 2 Test Case 3 Test Case 4

Input 63 32 53 22

0 4 3 7 10 9 123 12489 36

Output 4 2 3 3

Solution:

import java.util.*;
class MagneticForce {
static boolean isCompatible(int arr[], int dist, int magnets) {
int n = arr.length;
int k = arr[0];
magnets--;
for (int i = 1; i < n; i++) {
if (arr[i] - k >= dist) {
magnets--;
if (magnets == 0) {
return true;
}
k = arr[i];
}
}
return false;
}
public static void main(String args[]) {

Scanner sc=new Scanner(System.in);


int size=sc.nextInt();
int K=sc.nextInt();
int[] arr=new int[size];
for(int i=0;i<size;i++)
{
arr[i]=sc.nextInt();
}
Arrays.sort(arr);
int maxD = arr[size - 1] - arr[0];
int ans = Integer.MIN_VALUE;
for (int d = 1; d <= maxD; d++) {
boolean possible = isCompatible(arr, d, K);
if (possible) {
ans = Math.max(ans, d);
}
}
System.out.println(ans);
sc.close();
}
}
Coding: 5 Marks

Question 14:

MotoGP

Varun enjoys watching MotoGP. He invited his friend over the weekend at his farm house

and asked his friend to pick a racer and see who wins. They decide to choose the racer such

that the race is close . This can happen only if the racers are comparable in their skill, i.e. the

difference in their skills is less.

There are N racers participating in the race. The skill of the racer k is represented by an

integer T[k]. Varun and his friend need to pick 2 racers for the race such that the difference

in their skills is minimum. This way, it will be a very interesting race. Your task is to help

him do this and report the minimum difference that is possible between 2 racers in the race.

Sample Input 1:

5
4 9 1 32 13

Sample Output 1:

Sample Input 2:

21 1 9

Sample Output 2:

8
Input Explanation:

Line1:Number of racers

Line2: space separated skills of each racer.

Output Explanation:

Minimum difference that is possible between the skills of racers.

Test cases:

Test Case 1 Test Case 2 Test Case 3 Test Case 4

Input 4 3 5 2

0437 123 1 4 8 13 19 1 21

Output 1 1 3 20

Solution:

import java.util.*;

import java.lang.Math;

class MotoGP

static void minSkill(int [] arr)

Arrays.sort(arr);

int minSkillDifference=Math.abs(arr[1]-arr[0]);

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

minSkillDifference = Math.min(arr[i]-arr[i-1], minSkillDifference);


}

System.out.print(minSkillDifference);

public static void main(String[] args)

Scanner sc=new Scanner(System.in);

int size=sc.nextInt();

int[] arr=new int[size];

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

arr[i]=sc.nextInt();

minSkill(arr);

sc.close();

}
Coding: 5 Marks

Question 15:

Number of Sticks

Mananjay has N sticks of K length. K being different or the same for every stick. He just

wants to know how many sticks of particular length L can he make using only two or only a

single of the sticks he has in stock. Two sticks or Single stick used to make the stick of

particular length L can not be used twice.

Sample Input 1:

5 13
4 9 1 32 13

Sample Output 1:

Sample Input 2:

3 11

21 1 9

Sample Output 2:

Input Explanation:

Line1:space separated number of sticks in stock N and Length L of the required stick

Line2: space separated length of sticks in stock.


Output Explanation:

Return number of sticks Mananjay can form using the sticks in stock..

Test cases:

Test Case 1 Test Case 2 Test Case 3 Test Case 4

Input 44 33 5 17 25

0437 123 1 4 8 13 9 1 21

Output 1 2 2 0

Solution:

import java.util.*;

class NumberOfSticks

static void numSticks(int[] arr, int K,int N)

int count=0;

Arrays.sort(arr);

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

if(arr[i]>K)

++i;

if(i>=N)break;

}
if(arr[i]==K)

++count;

++i;

if(i>=N)break;

int length=arr[i];

if(length<K)

for(int j=i+1;j<N;j++)

length+=arr[j];

if(length>K)

length-=arr[j];

if(length==K)

++count;

arr[j]=0;

break;

if(length<K)

length-=arr[j];

}
}

System.out.print(count);

public static void main(String[] args)

Scanner sc=new Scanner(System.in);

int N=sc.nextInt();

int K=sc.nextInt();

int[] arr=new int[N];

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

arr[i]=sc.nextInt();

numSticks(arr,K,N);

sc.close();

}
Coding: 5 Marks

Question 16:

Swap Books

Akshay has been given a task to sort the books kept in the rack with respect to the volume

number of those books. Find out the minimum number of swaps required to sort the books in

strictly ascending order.

Sample Input 1:

5
4 7 11 9 8

Sample Output 1:

Sample Input 2:

21 1 9

Sample Output 2:

Input Explanation:

Line1:Number of books

Line2: space separated Volume number of books.

Output Explanation:

Minimum number of swaps required.


Test cases:

Test Case 1 Test Case 2 Test Case 3 Test Case 4

Input 4 3 5 5

1437 123 1 4 15 12 13 1 21 4 7 2

Output 1 0 2 1

Solution:

import java.util.*;

class SwapBooks
{
static int minSwaps(int[] arr)
{
int len = arr.length;
HashMap<Integer, Integer> map = new HashMap<>();
for(int i=0;i<len;i++)
map.put(arr[i], i);

Arrays.sort(arr);
boolean[] visited = new boolean[len];
Arrays.fill(visited, false);

int ans = 0;
for(int i=0;i<len;i++) {

if(visited[i] || map.get(arr[i]) == i)
continue;

int j = i, cycle_size = 0;
while(!visited[j]) {
visited[j] = true;

j = map.get(arr[j]);
cycle_size++;
}

if(cycle_size > 0) {
ans += (cycle_size - 1);
}
}
return ans;
}

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();
}
System.out.println(minSwaps(arr));
sc.close();
}
}
Coding: 5 Marks

Question 17:

Ceiling of a number in an array

Given an array of N integers, Harman needs to find out the smallest integer K(as well as the

index of that number) greater than or equal to the provided integer M. Help her write the

program in Java. If there is no such number in the array which matches her requirement,

return -1.

Sample Input 1:

5 12
4 7 11 9 8

Sample Output 1:

-1

Sample Input 2:

3 10

21 1 9

Sample Output 2:

21 0

Input Explanation:

Line1: space separated size of array N and integer M whose ceiling number is to be found
out.

Line2: space separated N integers


Output Explanation:

Space separated Ceiling number K and its index if present, else -1

Test cases:

Test Case 1 Test Case 2 Test Case 3 Test Case 4

Input 47 34 5 14 55

1437 123 1 4 15 12 13 1 21 4 7 2

Output 73 -1 15 2 73

Solution:

import java.util.*;

public class CeilingNum


{
static int ceiling=-1;
static void ceiling(int arr[],int target)
{
Map<Integer,Integer> map=new HashMap<Integer,Integer>();
for (int i = 0; i < arr.length; i++)
{
map.put(arr[i], i);
}

Arrays.sort(arr);

int start=0;
int end=arr.length-1;
while(start<=end)
{
int mid=(start+end)/2;
if(arr[mid]==target) {ceiling=arr[mid];System.out.print(ceiling+"
"+map.get(ceiling));return;}
if(arr[mid]<target) start=mid+1;
else end=mid-1;
}
if(start>arr.length-1) {System.out.print(-1);return;}
ceiling=arr[start];
System.out.print(ceiling+" "+map.get(ceiling));
}

public static void main(String[] args)


{
Scanner sc=new Scanner(System.in);
int N=sc.nextInt();
int K=sc.nextInt();
int[] arr=new int[N];
for(int i=0;i<N;i++)
{
arr[i]=sc.nextInt();
}
ceiling(arr,K);
sc.close();

}
Coding: 5 Marks

Question 18:

Aggressive Cows

Given an array of length ‘N’, where each element denotes the position of a
stall. Now you have ‘N’ stalls and an integer ‘K’ which denotes the
number of cows that are aggressive. To prevent the cows from hurting each
other, you need to assign the cows to the stalls, such that the minimum
distance between any two of them is as large as possible. Return the largest
minimum distance.

Sample Input 1:

64

0 3 4 7 10 9

Sample Output 1:

Sample Input 2:

52

42136

Sample Output 2:

Input Explanation:

Line1:space separated number of places empty and number of cows

Line2: space separated position of empty places.


Output Explanation:

Largest minimum distance between the cows.

Test cases:

Test Case 1 Test Case 2 Test Case 3 Test Case 4

Input 63 32 53 22

0 4 3 7 10 9 123 12489 36

Output 4 2 3 3

Solution:

import java.util.*;
class AggressiveCows {
static boolean isCompatible(int arr[], int dist, int cows) {
int n = arr.length;
int k = arr[0];
cows--;
for (int i = 1; i < n; i++) {
if (arr[i] - k >= dist) {
cows--;
if (cows == 0) {
return true;
}
k = arr[i];
}
}
return false;
}
public static void main(String args[]) {

Scanner sc=new Scanner(System.in);


int size=sc.nextInt();
int K=sc.nextInt();
int[] arr=new int[size];
for(int i=0;i<size;i++)
{
arr[i]=sc.nextInt();
}
Arrays.sort(arr);
int maxD = arr[size - 1] - arr[0];
int ans = Integer.MIN_VALUE;
for (int d = 1; d <= maxD; d++) {
boolean possible = isCompatible(arr, d, K);
if (possible) {
ans = Math.max(ans, d);
}
}
System.out.println(ans);
sc.close();
}
}
Coding: 5 Marks

Question 19:

Topper of the class

Few toppers of your class will get pizza as a treat from your trainer. Given the
marks scored by N students of your class and top K scores who will get pizza ,
how many students will get the pizza treat?

Sample Input 1:

62

562312

Sample Output 1:

Sample Input 2:

51

55231

Sample Output 2:

Input Explanation:

Line1:space separated B number of students and top K scores who will get pizza

Line2: space separated marks scored by students.

Output Explanation:

Number of students who will get treats.


Test cases:

Test Case 1 Test Case 2 Test Case 3 Test Case 4

Input 63 32 53 92

0 4 3 7 10 9 122 14489 336553688

Output 3 3 4 4

Solution:

import java.util.*;

public class TopperNew{

public static void main(String[] args){


Scanner sc=new Scanner(System.in);
int size=sc.nextInt();
int K=sc.nextInt();
int[] arr=new int[size];
for(int i=0;i<size;i++){
arr[i]=sc.nextInt();
}
Arrays.sort(arr);
int count=1;
for(int i=arr.length-2;i>=0;i--){
if(K==0)
{
System.out.print(0);
break;
}
if(arr[i]!=arr[i+1]) count++;
if(count>K) {System.out.print(arr.length-1-i);break;}
if(i==0)System.out.print(arr.length);
}
sc.close();
}

}
Coding: 5 Marks

Question 20:

Team Qualify or Not

Smackdown 2022 is coming! There are two rounds (round A and round B) after the
qualification round. From both of them, teams can qualify to the pre-elimination round.
According to the rules, in each of these two rounds, teams are sorted in descending order by
their score and each team with a score greater or equal to the score of the team at the K=1500-
th place advances to the pre-elimination round (this means it is possible to have more than K
qualified teams from each round in the case of one or more ties after the K-th place).

Today, the organizers ask you to count the number of teams which would qualify for the pre-
elimination round from round A for a given value of K (teams that can qualify). They provided
the scores of all teams to you; you should ensure that all teams scoring at least as many points
as the K-th team qualify.

Sample Input 1:

62

562312

Sample Output 1:

Sample Input 2:

51

55231

Sample Output 2:

2
Input Explanation:

1st Line: Space separated N and K where,

N is total number of teams, K- is total teams to qualify

2nd Line: space separated points scored by N teams

Output Explanation:

Total teams to qualify

Test cases:

Test Case 1 Test Case 2 Test Case 3 Test Case 4

Input 63 32 53 92

0 4 3 7 10 9 122 14489 336553688

Output 3 2 4 2

Solution:

import java.util.*;

class Qualify

static int lower(int array[], int key)

int lowerBound = 0;

while (lowerBound < array.length) {


if (key > array[lowerBound])

lowerBound++;

else

return lowerBound;

return lowerBound;

public static void main(String[] args)

Scanner sc=new Scanner(System.in);

int size=sc.nextInt();

int K=sc.nextInt();

int[] arr=new int[size];

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

arr[i]=sc.nextInt();

Arrays.sort(arr);

int L=arr[size-K];

System.out.println(size-lower(arr,L));

sc.close();

You might also like