0% found this document useful (0 votes)
14 views49 pages

ET Practice Coding Questions

The document contains a series of programming tasks and solutions in Java, covering topics such as string compression, case toggling, multithreading for ticket booking, array operations, linked list manipulation, and stock span calculations. Each task includes input formats, constraints, and sample outputs to illustrate the expected results. The solutions provided demonstrate the implementation of algorithms and data structures relevant to each task.

Uploaded by

a.p.p.l.e.99.3.4
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)
14 views49 pages

ET Practice Coding Questions

The document contains a series of programming tasks and solutions in Java, covering topics such as string compression, case toggling, multithreading for ticket booking, array operations, linked list manipulation, and stock span calculations. Each task includes input formats, constraints, and sample outputs to illustrate the expected results. The solutions provided demonstrate the implementation of algorithms and data structures relevant to each task.

Uploaded by

a.p.p.l.e.99.3.4
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

Q1. Take as input S, a string. Write a function that does basic string compression. Print the value returned.

E.g. for input “aaabbccds” print out a3b2c2d1s1.


Input Format
A single String S
Constraints
1 < = length of String < = 1000
Output Format
The compressed String.
Sample Input

aaabbccd
Sample Output

a3b2c2d1s
Explanation
In the given sample test case 'a' is repeated 3 times consecutively, 'b' is repeated twice, 'c' is repeated twice
and 'd and 's' occurred only once.

SOLUTION:

import [Link].*;

public class Main {

static String compress(String s) {


if ([Link]() == 0) {
return "";
}

char ch = [Link](0);
int i = 1;
while (i < [Link]() && [Link](i) == ch) {
i++;
}

String ros = [Link](i);


ros = compress(ros);

String charCount = i + "";


return ch + charCount + ros;
}
s

public static void main(String[] args) {

Scanner sc = new Scanner([Link]);


String s = [Link]();

[Link](compress(s));
}
}

Q2. Take as input S, a string. Write a function that toggles the case of all characters in the string.
Print the value returned.
Input Format

String
Constraints
Length of string should be between 1 to 1000.
Output Format

String
Sample Input

abC
Sample Output

ABc
Explanation
Toggle Case means to change UpperCase character to LowerCase character and vice-versa.

SOLUTION:

public static String toggleCase(String str){

String ans = "";

for(int i = 0;i < [Link]();i++){

char ch = [Link](i);

if(ch >= 'a' && ch <= 'z'){


ans += (char)(ch - 32); //Lower to Upper
}else if(ch >= 'A' && ch <= 'Z'){
ans += (char)(ch + 32); //Upper to Lower
}
}

return ans;
}

Q3. John and Mike are both trying to book few tickets available for a movie show. Write a Program
using Multithreading to book tickets ensuring required tickets can only be booked if available
tickets are more for each of them. (Creating, Evaluating)

Shown below is the class having main method. Complete rest of the code.

Prewritten code:
import [Link];
public class TicketBooking {
public static void main(String[] args) {
Scanner tk = new Scanner([Link]);
int availTickets = [Link]();
int reqJohn = [Link]();
int reqMike = [Link]();
AvailableTicket avlTic = new AvailableTicket(availTickets,reqJohn,reqMike);
Thread t = new Thread(avlTic);
Thread tt = new Thread(avlTic);
[Link]("John");
[Link]("Mike");
[Link](10);
[Link]();
[Link]();
}
}

Input format:
First line of the input contains available tickets. Second line contains tickets required by John and
third line contains tickets required by Mike.

Output format:
Each line of the output contains currentThread name (either John or Mike) followed by either ticket
booked or not. If ticket is booked then after currentThread print “: tickets booked: ” and if
available tickets is less than required by either of them then print “: not booked.”. Print the exact
message considering the spaces.
Sample Input:
5
3
2

Sample Output:
John: tickets booked: 3
Mike: tickets booked: 2

Sample Input:
6
4
3

Sample Output:
John: tickets booked: 4
Mike: not booked

SOLUTION:

class AvailableTicket extends Thread {


int available;
int wantedMike;
int wantedJohn;
public AvailableTicket(int avail,int reqJohn,int reqMike) {
available=avail;
wantedJohn = reqJohn;
wantedMike= reqMike;
}
public void run() {
synchronized (this) {
int wanted;
String threadName= [Link]().getName();
if(threadName=="John")
wanted=wantedJohn;
else
wanted=wantedMike;
if (available >= wanted) {
[Link]([Link]().getName());
[Link](": tickets booked: " + wanted);
available = available - wanted;
} else {
[Link]([Link]().getName() + ": not booked " );
}
}
}
}

Q4. Write a program in Java to implement an integer array and perform following operations in
form of functions one after another in same sequence as mentioned:

(Applying, Evaluating)

1. Create an integer array having length of five (05) elements.


2. Input all five elements one after another.
3. Find maximum element from the input array.
4. Find minimum element from the input array.
5. Find Subtraction of all elements of the input array consecutively. Subtract first element from
second, second element from third and so on. Subtraction starts from index 0 to index 4.
a. Raise exception “Subtract is greater than equal to Zero”, if subtraction result is in
positive or zero.
b. Raise exception “Subtract is less than Zero”, if subtraction result is zero.

Input format:
Each line of the input contains array of five integers separated with a space.

Constraints:
Entered elements should be greater than 0 and lesser than 10
(1>= Arr[i] >= 9)

Output format:
Each line of the output contains the result
1. Maximum integer of input array,
2. Minimum integer of input array,
3. Subtract all integers in input array as discussed above,
a. If subtraction result is in zero or positive, then raise exception “Subtract is greater than
equal to Zero”, and
b. If subtraction result is in negative, then raise exception “Subtract is less than Zero”,

Sample Input:
12345
Sample Output:
5
1
-13
[Link]: Subtract is less than Zero

Explanation:
1. Code should able to identify maximum and minimum elements of input array as 5 and 1
shown in above example.
2. Code should able to find subtraction and also able to raise exception as discussed above. For
example: If array elements are 1 2 3 4 5 then
1-2=-1
-1 - 3 = - 4
-4 - 4 = - 8
-8 - 5 = - 13

Code:

//Prewritten Code
import [Link];
public class Main
{
public static final MyArray myarr = new MyArray();
public static void main(String[] args)
{
[Link]();
[Link]();
[Link]();
try
{
[Link]();
}
catch (Exception e)
{
[Link](e);
}

}
}

SOLUTION:

class MyArray
{
Scanner sc = new Scanner([Link]);
public static final int[] Arr = new int[5];

public void input()


{
for(int i=0; i<5; i++)
{
Arr[i]=[Link]();
}
}

public void max()


{
int max = 0;
for (int i =0 ;i<5;i++)
{
if (Arr[i] > max)
{
max = Arr[i];
}
}
[Link](max);
}
public void min()
{
int min = 10;
for (int i =0 ;i<5;i++)
{
if (Arr[i] < min)
{
min = Arr[i];
}
}
[Link](min);
}
public void subfn() throws Exception
{
int sub = Arr[0];
for (int i =1 ;i<5;i++)
{
sub = sub - Arr[i];
}
[Link](sub);
if (sub<0)
{
throw new Exception("Subtract is less than Zero");
}
else
{
throw new Exception("Subtract is greater than equal to Zero");
}
}
}

Q5. Take as input S, a string. Write a function that does basic string compression. Print the value returned.
E.g. for input “aaabbccds” print out a3b2c2d1s1.
Input Format
A single String S
Constraints
1 < = length of String < = 1000
Output Format
The compressed String.
Sample Input

aaabbccd
Sample Output

a3b2c2d1s
Explanation
In the given sample test case 'a' is repeated 3 times consecutively, 'b' is repeated twice, 'c' is repeated twice
and 'd and 's' occurred only once.

SOLUTION:

import [Link].*;

public class Main {

static String compress(String s) {


if ([Link]() == 0) {
return "";
}

char ch = [Link](0);
int i = 1;
s

while (i < [Link]() && [Link](i) == ch) {


i++;
}

String ros = [Link](i);


ros = compress(ros);

String charCount = i + "";


return ch + charCount + ros;
}

public static void main(String[] args) {

Scanner sc = new Scanner([Link]);


String s = [Link]();

[Link](compress(s));
}
}

Q6 Given a linked list with n nodes. Find the kth element from last without computing the length of the linked list.

Input Format
First line contains space separated integers representing the node values of the linked list. The list ends when the
input comes as '-1'. The next line contains a single integer k.
Constraints
n < 10^5
Output Format
Output a single line containing the node value at the kth element from last.
Sample Input

1 2 3 4 5 6 -1

Sample Output

Explanation
The linked list is 1 2 3 4 5 6. -1 is not included in the list. So the third element from the last is 4
4

Q7. Given an array of patterns containing only I’s and D’s. I for increasing and D for decreasing.
Devise an algorithm to print the minimum number following that pattern. Digits from 1-9 and digits
can’t repeat.
Input Format
The First Line contains an Integer N, size of the array. Next Line contains N Strings separated by
space.
Constraints
1 ≤ T ≤ 100 1 ≤ Length of String ≤ 8
Output Format
Print the minimum number for each String separated by a new Line.
Sample Input
4
D I DD II

Sample Output
21
12
321
12
Explanation
For the Given sample case, For a Pattern of 'D' print a decreasing sequence which is 2 1.

Q8. Deepak has a limited amount of money that he can spend on his girlfriend. So he decides to buy
two roses for her. Since roses are of varying sizes, their prices are different. Deepak wishes to
completely spend that fixed amount of money on buying roses for her.
As he wishes to spend all the money, he should choose a pair of roses whose prices when summed
up are equal to the money that he has.
Help Deepak choose such a pair of roses for his girlfriend.

NOTE: If there are multiple solutions print the solution that minimizes the difference between the
prices i and j. After each test case, you must print a blank line.

Input Format

The first line indicates the number of test cases T.


Then, in the next line, the number of available roses, N is given.
The next line will have N integers, representing the price of each rose, a rose that costs less than
1000001.
Then there is another line with an integer M, representing how much money Deepak has.
There is a blank line after each test case.

Constraints

1≤ T ≤100
2 ≤ N ≤ 10000
Price[i]<1000001

Output Format
3

For each test case, you must print the message: ‘Deepak should buy roses whose prices are i and j.’,
where i and j are the prices of the roses whose sum is equal do M and i ≤ j. You can consider that it
is always possible to find a solution. If there are multiple solutions print the solution that minimizes
the difference between the prices i and j.

Sample Input
2
2
40 40
80

5
10 2 6 8 4
10

Sample Output
Deepak should buy roses whose prices are 40 and 40.
Deepak should buy roses whose prices are 4 and 6
Explanation

Find two such kinds of price of roses which has sum up to equal to Deepak's Money.

SOLUTION:

public static void roses(int[] arr, int target){

[Link](arr); // sort the Array

int fl = 0; //To store the leftmost index


int fr = 0; //To store the rightmost index

int left = 0;
int right = [Link] - 1;

while (left < right) {

int sum = arr[left] + arr[right];

if (sum > target) {


right--;
} else if (sum < target) {
left++;
.

} else {
fl = left;
fr = right;

left++;
right--;
}

[Link]("Deepak should buy roses whose prices are " + fl


+ " and " + fr + ".");

Q9. The stock span problem is a financial problem where we have a series of N daily price quotes
for a stock and we need to calculate span of stock’s price for all N days. You are given an array of
length N, where ith element of array denotes the price of a stock on ith. Find the span of stock's price
on ith day, for every 1<=i<=N.
A span of a stock's price on a given day, i, is the maximum number of consecutive days before the
(i+1)th day, for which stock's price on these days is less than or equal to that on the ith day.
Input Format

First line contains integer N denoting size of the array.


Next line contains N space separated integers denoting the elements of the array.
Constraints
1 <= N <= 10^6
Output Format

Display the array containing stock span values.


Sample Input

5
30
35
40
38
3
Sample Output

1 2 3 1 1 EN
Explanation
For the given case
for day1 stock span =1
5

for day2 stock span =2 (as 35>30 so both days are included in it)
for day3 stock span =3 (as 40>35 so 2+1=3)
for day4 stock span =1 (as 38<40 so only that day is included)
for day5 stock span =1 (as 35<38 so only that day is included)
hence output is 1 2 3 1 1 END

SOLUTION:

public static int[] StockSpanUsingStacks(int[] prices, Stack<Integer> stack)


throws Exception {

// span array stores the value of stock span for each day
int[] span = new int[[Link]];

// pushing the index of first day


[Link](0);

// span for 1st day will always be 1


span[0] = 1;

// Iterating over the prices array


for (int i = 1; i < [Link]; i++) {

// poping days from stack when price of the i th day is greater


than the price of day which is on top of stack
while ([Link]() != 0 && prices[i] > prices[[Link]()]) {
[Link]();
}

if ([Link]() == 0) {

// then all the previous prices are smaller than the price on
the ith day
span[i] = i + 1;
} else {

// the previous highest price will be on the top of the stack


span[i] = i - [Link]();
}

// pushing the index of the price array which is the number of


day in stack
[Link](i);
}
return span;
Q10. Take as input S, a string. Write a function that does basic string compression. Print the value returned.
E.g. for input “aaabbccds” print out a3b2c2d1s1.
Input Format
A single String S
Constraints
1 < = length of String < = 1000
Output Format
The compressed String.
Sample Input

aaabbccd
Sample Output

a3b2c2d1s
Explanation
In the given sample test case 'a' is repeated 3 times consecutively, 'b' is repeated twice, 'c' is repeated twice
and 'd and 's' occurred only once.

SOLUTION:

import [Link].*;

public class Main {

static String compress(String s) {


if ([Link]() == 0) {
return "";
}

char ch = [Link](0);
int i = 1;
while (i < [Link]() && [Link](i) == ch) {
i++;
}

String ros = [Link](i);


}

ros = compress(ros);

String charCount = i + "";


return ch + charCount + ros;
}

public static void main(String[] args) {

Scanner sc = new Scanner([Link]);


String s = [Link]();

[Link](compress(s));
}
}

Take an input N, the size of array. Take N more inputs and store that in an array. Write a func on
which returns the maximum value in the array. Print the value returned.
[Link] reads a number N.
[Link] Another N numbers as input and store them in an Array.
[Link] the max value in the array and return that value.

Input Format
First line contains integer n as size of array. Next n lines contains a single integer as element of array.

Constraints
N cannot be Nega ve. Range of Numbers can be between -1000000000 to 1000000000

Output Format
Print the required output.

Sample Input
4
2
8
6
4
Sample Output
8
Explana on
Arrays= {2, 8, 6, 4} => Max value = 8 .

SOLUTION:

import java.u l.*;


public class Main {
public sta c void main(String args[]) {
Scanner sc=new Scanner([Link]);
int n=[Link]();
int arr[]=new int[n];
ti
ti
ti
ti
ti
for(int i=0;i<n;i++){
arr[i]=[Link]();
}
int max=Integer.MIN_VALUE;
for(int i:arr){
max=[Link](max,i);
}
[Link](max);
}
}

Q11. Write a program in Java to implement an integer array and perform following operations in
form of functions one after another in same sequence as mentioned:

(Applying, Evaluating)

1. Create an integer array having length of five (05) elements.


2. Input all five elements one after another.
3. Find maximum element from the input array.
4. Find minimum element from the input array.
5. Find Subtraction of all elements of the input array consecutively. Subtract first element from
second, second element from third and so on. Subtraction starts from index 0 to index 4.
a. Raise exception “Subtract is greater than equal to Zero”, if subtraction result is in
positive or zero.
b. Raise exception “Subtract is less than Zero”, if subtraction result is zero.

Input format:
Each line of the input contains array of five integers separated with a space.

Constraints:
Entered elements should be greater than 0 and lesser than 10
(1>= Arr[i] >= 9)

Output format:
Each line of the output contains the result
1. Maximum integer of input array,
2. Minimum integer of input array,
3. Subtract all integers in input array as discussed above,
a. If subtraction result is in zero or positive, then raise exception “Subtract is greater than
equal to Zero”, and
b. If subtraction result is in negative, then raise exception “Subtract is less than Zero”,

Sample Input:
12345

Sample Output:
5
1
-13
[Link]: Subtract is less than Zero

Explanation:
1. Code should able to identify maximum and minimum elements of input array as 5 and 1
shown in above example.
2. Code should able to find subtraction and also able to raise exception as discussed above. For
example: If array elements are 1 2 3 4 5 then
1-2=-1
-1 - 3 = - 4
-4 - 4 = - 8
-8 - 5 = - 13

Code:

// Prewritten Code
import [Link];
public class Main
{
public static final MyArray myarr = new MyArray();
public static void main(String[] args)
{
[Link]();
[Link]();
[Link]();
try
{
[Link]();
}
catch (Exception e)
{
[Link](e);
}

}
}

SOLUTION:

class MyArray
{
Scanner sc = new Scanner([Link]);
public static final int[] Arr = new int[5];

public void input()


{
for(int i=0; i<5; i++)
{
Arr[i]=[Link]();
}
}

public void max()


{
int max = 0;
for (int i =0 ;i<5;i++)
{
if (Arr[i] > max)
{
max = Arr[i];
}
}
[Link](max);
}
public void min()
{
int min = 10;
for (int i =0 ;i<5;i++)
{
if (Arr[i] < min)
{
min = Arr[i];
}
}
[Link](min);
}
public void subfn() throws Exception
{
int sub = Arr[0];
for (int i =1 ;i<5;i++)
{
sub = sub - Arr[i];
}
[Link](sub);
if (sub<0)
{
throw new Exception("Subtract is less than Zero");
}
else
{
throw new Exception("Subtract is greater than equal to Zero");
}
}
}

Q 12 The stock span problem is a financial problem where we have a series of N daily price quotes
for a stock and we need to calculate span of stock’s price for all N days. You are given an array of
length N, where ith element of array denotes the price of a stock on ith. Find the span of stock's price
on ith day, for every 1<=i<=N.
A span of a stock's price on a given day, i, is the maximum number of consecutive days before the
(i+1)th day, for which stock's price on these days is less than or equal to that on the ith day.
Input Forma
First line contains integer N denoting size of the array.
Next line contains N space separated integers denoting the elements of the array.
Constraint
1 <= N <= 10^
Output Forma
Display the array containing stock span values.
Sample Inpu
5
30
35
40
38
35

Sample Outpu
1 2 3 1 1 END

Explanatio
For the given case
for day1 stock span =1
for day2 stock span =2 (as 35>30 so both days are included in it)
for day3 stock span =3 (as 40>35 so 2+1=3)
for day4 stock span =1 (as 38<40 so only that day is included)
for day5 stock span =1 (as 35<38 so only that day is included)
hence output is 1 2 3 1 1 EN
SOLUTION:

import [Link].*;
public class Main {

public static void main(String args[]) throws Exception {


// Your Code Here
Scanner sc = new Scanner ([Link]);
int n=[Link]();
int [] arr = new int[n];
for(int i=0;i<n;i++) {
arr[i]=[Link]();
s

Stack<Integer> st = new Stack<>();


int[] ans = new int[[Link]];
for (int i = 0; i < [Link]; i++) {

while (![Link]() && arr[i] > arr[[Link]()]) {


[Link]();
}

if ([Link]()) {
ans[i] = i + 1;

} else {
ans[i] = i - [Link]();
}

[Link](i);
}
for(int i=0;i<[Link];i++) {
[Link](ans[i]+" ");
}
[Link]("END");
}

Q13. Take as input S, a string. Write a program that gives the count of substrings of
this string which are palindromes and Print the ans.
Input Format

Single line input containing a string

Constraints
Length of string is between 1 to 1000

Output Format
Integer output showing the number of palindromic substrings.

Sample Input
abc
.

Sample Output
3

Explanation
For the given sample case , the palindromic substrings of the string abc are "a","b" and "c".So,
the ans is 3.

SOLUTION:

import [Link].*;
public class Main {
public static void main(String args[]) {
Scanner sc = new Scanner([Link]);
String s = [Link]();
int count = 0;
for (int i = 0; i < [Link](); i++) {
for (int j = i; j <= [Link](); j++) {
String ans = [Link](i, j);
if (ispalindrom(ans))
count = count + 1;
}
}
[Link](count);
}

private static boolean ispalindrom(String ans) {


int lo = 0;
int hi = [Link]() - 1;
if ([Link]() == 0) {
return false;
} else {
while (lo <= hi) {
if ([Link](lo) != [Link](hi)) {
return false;
}
lo++;
hi--;
}
return true;
}
}

}
Q14. A Good String is a string which contains only vowels (a,e,i,o,u) . Given a string S, print a
single positive integer N where N is the length of the longest substring of S that is also a Good
String.
Note: The time limit for this problem is 1 second, so you need to be clever in how you compute the
substrings.
Input Forma
A string 'S'
Constraint
Length of string < 10^
Output Forma
A single positive integer N, where N is the length of the longest sub-string of S that is also a Good
String.
Sample Inpu
cbaeicde
Sample Outpu
3
Explanatio
Longest good substring is "aei
SOLUTION:

import [Link].*;
public class Main {
public static void main(String args[]) {
Scanner sc = new Scanner([Link]);
String str = [Link]();
int i = 0;
int count = 0;
int ans = 0;
while (i < [Link]()) {
char ch = [Link](i);
if (isVovel(ch)) {
count++;
} else {
ans = [Link](ans, count);
count = 0;
}
i++;
}
[Link]([Link](ans, count));

private static boolean isVovel(char ch) {


// TODO Auto-generated method stub
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u')
return true;
s

"

return false;
}

Q 15 You are given two integers n and k. Find the greatest integer x, such that, x^k <= n.
Input Format
First line contains number of test cases, T. Next T lines contains integers, n and k.
Constraints
1<=T<=10
1<=N<=10^15
1<=K<=10^4
Output Format
Output the integer x
Sample Input
2
10000 1
1000000000000000 10

Sample Output
10000
31

Explanation
For the first test case, for x=10000, 10000^1=10000=n

SOLUTION:

import [Link].*;
public class Main {
public static void main(String args[]) {
// Your Code Here
Scanner s = new Scanner([Link]);
int t = [Link]();
for (int i = 1; i <= t; i++) {
long n = [Link]();
int k = [Link]();
[Link](root(n, k));
}
}
public static int root(long n, int k) {
long ans = 0;
long lo = 0;
long hi = n;
while (lo <= hi) {
long mid = lo + (hi - lo) / 2;
long check = (long) [Link](mid, k);
if (check > n) {
hi = mid - 1;
} else if (check < n) {
ans = mid;
lo = mid + 1;
} else {
ans = mid;
return (int) ans;
}

}
return (int) ans;
}
}

Q 16 . Given an array Arr[], Treat each element of the array as the digit and whole array as the
number. Implement the next permutation, which rearranges numbers into the numerically next
greater permutation of numbers.

If such arrangement is not possible, it must be rearranged as the lowest possible order ie,
sorted in an ascending order.

Note: The replacement must be in-place, do not allocate extra memory.

Input Format
The First Line contains the Number of test cases T.
Next Line contains an Integer N, number of digits of the number.
Next Line contains N-space separated integers which are elements of the array 'Arr'.

Constraints
1 <= T <= 100
1 <= N <= 1000
0 <= Ai <= 9

Output Format
Print the Next Permutation for each number separated by a new Line.

Sample Input
3
123

Sample Output
132

Explanation
Possible permutations for {1,2,3} are {1,2,3} , {1,3,2} , {2,1,3} , {2,3,1}, {3,1,2} and
{3,2,1}. {1,3,2} is the immediate next permutation after {1,2,3}.
For the second testcase , {3,2,1} is the last configuration so we print the first permutation as
its next permutation.

SOLUTION:

import [Link].*;
public class Main {
public static void main(String args[]) {
// TODO Auto-generated method stub
Scanner sc = new Scanner([Link]);
int n = [Link]();
int[] arr = new int[n];
for (int i = 0; i < n; i++)
arr[i] = [Link]();
nextPermutation(arr);
for (int i = 0; i < [Link]; i++) {
[Link](arr[i] + " ");
}

}
public static void nextPermutation(int[] arr) {

int p = -1;
for (int i = [Link] - 2; i >= 0; i--) {
if (arr[i] < arr[i + 1]) {
p = i;
break;
}

}
if (p == -1) {
Reverse(arr, 0, [Link] - 1);
return;
}
int q = -1;
for (int i = [Link] - 1; i > p; i--) {
if (arr[i] > arr[p]) {
q = i;
break;
}
}
// swap
int t = arr[p];
arr[p] = arr[q];
arr[q] = t;
Reverse(arr, p + 1, [Link] - 1);

public static void Reverse(int[] arr, int i, int j) {

while (i < j) {

int t = arr[i];
arr[i] = arr[j];
arr[j] = t;
i++;
j--;
}
}
}

Q 17 .You are given two integers n and k. Find the greatest integer x, such that, x^k <= n.
Input Format
First line contains number of test cases, T. Next T lines contains integers, n and k.
Constraints
1<=T<=10
1<=N<=10^15
1<=K<=10^4
Output Format
Output the integer x
Sample Input
2
10000 1
1000000000000000 10

Sample Output
10000
31

Explanation
For the first test case, for x=10000, 10000^1=10000=n

SOLUTION:

import [Link].*;
public class Main {
public static void main(String args[]) {
// Your Code Here
Scanner s = new Scanner([Link]);
int t = [Link]();
for (int i = 1; i <= t; i++) {
long n = [Link]();
int k = [Link]();
[Link](root(n, k));
}
}
public static int root(long n, int k) {
long ans = 0;
long lo = 0;
long hi = n;
while (lo <= hi) {
long mid = lo + (hi - lo) / 2;
long check = (long) [Link](mid, k);
if (check > n) {
hi = mid - 1;
} else if (check < n) {
ans = mid;
lo = mid + 1;
} else {
ans = mid;
return (int) ans;
}

}
return (int) ans;
}
}

Q 18. Given an integer array nums find the squares of each number sorted in non-decreasing
order.
Input Format
First line of input contains an integer n representing the length of array n. Next line contains n array
elements.
Constraints
1 <= [Link] <= 10^4
-10^4 <= nums[i] <= 10^4
nums is sorted in non-decreasing order.
Output Format
A sorted array representing squares of elements of nums array.
Sample Input
5
-4 -1 0 3 10

Sample Output
0 1 9 16 100

Explanation
After squaring, the array becomes [16,1,0,9,100]. After sorting, it becomes [0,1,9,16,100]

SOLUTION:

import [Link].*;

public class Main {


public static void main(String args[]) {
Scanner sc = new Scanner([Link]);
int n = [Link]();
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = [Link]();
}
Square(arr);
[Link](arr);
for (int i = 0; i < [Link]; i++) {
[Link](arr[i] + " ");
}

public static void Square(int arr[]) {


int sum = 0;
for (int i = 0; i < [Link]; i++) {
sum = arr[i] * arr[i];
arr[i] = sum;
}
}

Q 19. Given an array, print the Next Greater Element (NGE) for every element. The Next Greater
Element for an element x is the first greater element on the right side of x in array. Elements for
which no greater element exist, consider next greater element as -1.
Input Forma
t

First line of the input contains a single integer T denoting the number of testcases. First line of each
testcase contains an integer N denoting the size of array. Second line of each testcase contains N
space seperated integers denoting the array.
Constraint
1 <= T <= 50 1 <= N <= 10^
Output Forma
For each index, print its array element and its next greater element seperated by a comma in a new
line.
Sample Inpu

4
11 13 21 3
Sample Outpu
13 21 -1 -

Explanatio
For the rst testcase , the next greater element for 11 is 13 , for 13 its 21 and 21 being the largest
element of the array does not have a next greater element. Hence we print -1 for 21. 3 is the last
element of the array and does not have any greater element on its right. Hence we print -1 for it as well
SOLUTION:

import [Link].*;

public class StockSpan {


public static void main(String[] args) {

Scanner sc = new Scanner([Link]);


int n = [Link]();
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = [Link]();
}
int ans[] = new int[[Link]];

Stack<Integer> st = new Stack<>();

for (int i = 0; i < [Link]; i++) {

while (![Link]() && arr[i] > arr[[Link]()]) {


ans[[Link]()] = arr[i];
[Link]();
}
[Link](i);
}

while (![Link]()) {
ans[[Link]()] = -1;
[Link]();
fi
s

for(int a :ans) {
[Link](a+" ");
}
}

Q 20. Take as input S, a string. Write a function that returns the character with maximum
frequency. Print the value returned.

Input Format
String

Constraints
A string of length between 1 to 1000.

Output Format
Character

Sample Input
aaabacb
Sample Output
a
Explanation
For the given input string, a appear 4 times. Hence, it is the most frequent character.

SOLUTION:

import [Link].*;
public class Main {
public static void main(String args[]) {
// Your Code Here
Scanner sc = new Scanner([Link]);
String s = [Link]();
int max = 0;
char ch = [Link](0);
for (int i = 0; i < [Link](); i++) {
int local_max = 0;
char local_ch = [Link](i);
for (int j = i; j < [Link](); j++) {
if ([Link](i) == [Link](j)) {
local_max++;
}
if (local_max > max) {
ch = local_ch;
max = local_max;
}

}
[Link](ch);
}

Q21. You are provided n numbers (both +ve and -ve). Numbers are arranged in a circular
form. You need to find the maximum sum of consecutive numbers.

Input format:
For each test case, it contains an integer n which is the size of array and next line contains n
space separated integers denoting the elements of the array.
Constraints:
1<=n<=1000
|Ai| <= 10000

Output format:
Print the maximum circular sum in a new line.

Sample Input:
7
8 -8 9 -9 10 -11 12

Sample Output:
22

Explanation:
Maximum Circular Sum = 22 (12 + 8 - 8 + 9 - 9 + 10)

Solution:

import [Link].*;

public class Main {


public static void main(String args[]) {
Scanner sc = new Scanner([Link]);
int n = [Link]();
int[] arr = new int[n];
for (int i = 0; i < [Link]; i++) {
arr[i] = [Link]();
}
[Link](maxSubarraySumCircular(arr));

public static int maxSubarraySumCircular(int[] arr) {


int kad = kadane(arr);
int sum = sumofarray(arr);
int revkad = kadane(arr);
int total = revkad + sum;
if (total == 0) {
return kad;
}
return [Link](kad, total);

public static int kadane(int[] arr) {


int currentsum = 0;
int maxsum = Integer.MIN_VALUE;
for (int i = 0; i < [Link]; i++) {
if (currentsum < 0)
currentsum = 0;
currentsum += arr[i];
maxsum = [Link](maxsum, currentsum);
}
return maxsum;

public static int sumofarray(int[] arr) {


int sum = 0;
for (int i = 0; i < [Link]; i++) {
sum += arr[i];
arr[i] = -arr[i];
}
return sum;
}

}
Q22. Take input n numbers, if their sum is more than 100 then throw an Exception that says “Sum
limit exceeded” Otherwise print their sum.

Input Format:
First line contain size of the array.
Next line is the n integers of the array.

Output: If their sum is less than equal to 100 then print their sum otherwise throw an exception.

Sample Input 1:

100 200 300

Sample Output 1:

[Link]: Sum limit exceeded

Sample Input 2:
2
10 20
Sample Output 2:
30

SOLUTION:

import [Link];

public class Main {

static void getSum(int[] arr) throws Exception


{
int sum=0;
for(int i=0;i<[Link];i++)
{
sum+=arr[i];
}

if(sum<=100)
[Link](sum);

else
throw new Exception("Sum limit exceeded");
}

public static void main(String[] args) {

int n;
Scanner sc=new Scanner([Link]);

n=[Link]();
int[]arr=new int[n];

for(int i=0;i<n;i++)
{
arr[i]=[Link]();
}

try {
getSum(arr);
} catch (Exception e) {
[Link](e);
}
}
}
[Link] an integer array print 1 if any value appears at least twice in the array, and print 0 if every
element is dis nct.

Input format:
First line contain size of the array.

Next line is the n integers of the array.

Output Format

Print 1 if any element occur at least twice and 0 if every element is distinct.

SOLUTION:

import [Link].*;
public class Main {

public static boolean containsDuplicate(int[] nums)


{
HashMap<Integer,Integer> map = new HashMap<>();
for (int i = 0; i < [Link]; i++) {
if ([Link](nums[i])) {
return true;
}
[Link](nums[i],1);
}
return false;
}

public static void main(String args[]) {


int n;
Scanner sc=new Scanner([Link]);
n=[Link]();

int [] arr=new int [n];

for(int i=0;i<n;i++)
arr[i]=[Link]();

if(containsDuplicate(arr))
ti
[Link]("1");

else
[Link]("0");

}
}

Q24. Given an array of N integers. Write a program to check whether an arithmetic progression can
be formed using all the given elements.
Sample Input 1:
4
0 12 4 8
Sample Output 1: YES
Explanation: Rearrange given array as {0, 4, 8, 12} which forms an arithmetic progression.

Sample Input 1:
4
12 40 11 20
Output: NO

SOLUTION:

import [Link].*;
public class Main {
static boolean checkIsAP(int arr[] ,int n)
{

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


int min=Integer.MAX_VALUE;
int smin=Integer.MAX_VALUE;
for(int i=0;i<n;i++)
{
[Link](arr[i]);

if(arr[i]<min)
{
smin=min;
min=arr[i];
}
else if(arr[i]<smin)
{
smin=arr[i];
}
}

int d=smin-min;
for(int i=1;i<=n;i++)
{
int term=min+(i-1)*d;
if(![Link](term))
return false;
}

return true;
}

public static void main(String args[]) {

Scanner sc=new Scanner([Link]);


int n=[Link]();

int []arr=new int[n];


for(int i=0;i<n;i++)
arr[i]=[Link]();
if(checkIsAP(arr,n))
[Link]("YES");
else
[Link]("NO");
}
}

Q25. Given two strings A and B. Find the characters that are not common in the two strings. If no
such character exists return "-1".

Input: A = characters B = alphabets


Output: bclpr
Explanation: The characters 'b','c','l','p','r' are either present in A or B, but not in both.

Input: A = bbbbb B =bb


Output: -1

Solution:
import [Link].*;
public class Main {

static String UncommonChars(String A, String B)


{
// code here
HashSet<Character> set1 = new HashSet<>();
HashSet<Character> set2 = new HashSet<>();
ArrayList<Character> list = new ArrayList<>();

String str = "";

for(int i = 0; i < [Link](); i++)


{
char ch = [Link](i);
[Link](ch);
}

for(int i = 0; i < [Link](); i++)


{
char ch = [Link](i);
[Link](ch);
}

for(int i = 0; i < [Link](); i++)


{
char ch = [Link](i);
if(![Link](ch))
{
if(![Link](ch))
[Link](ch);
}

for(int i = 0; i < [Link](); i++)


{
char ch = [Link](i);
if(![Link](ch))
{
if(![Link](ch))
[Link](ch);
}
}

if([Link]() == 0)
return "-1";
[Link](list);
for(char ch : list)
{
str += ch;
}

return str;
}

public static void main(String args[]) {


String str1,str2;
Scanner sc=new Scanner([Link]);
str1=[Link]();
str2=[Link]();

[Link](UncommonChars(str1,str2));
}
}

Q26. Given an array arr[] of n integers. Check whether it contains a triplet that sums up to zero.

Input Format

First line contain size of the array.

Next line is the n integers of the array.

Output Format
Print 1 if the triplet with 0 exists and 0 if it doesn’t exists.

Sample Input
5
0 -1 2 -3 1

Sample Output
1

Explanation
0, -1 and 1 forms a triplet with sum equal to 0.

SOLUTION:

import [Link].*;
public class Main
{
static public boolean findTriplets(int arr[] , int n)
{
//add code here.
boolean found=false;
for(int i=0;i<n-1;i++){
HashSet<Integer> hs=new HashSet<>();
for(int j=i+1;j<n;j++){
int x=-(arr[i]+arr[j]);
if([Link](x)){
return true;
}else{
[Link](arr[j]);
}
}
}
return false;
}

public static void main(String args[]) {


int n;
Scanner sc=new Scanner([Link]);
n=[Link]();

int [] arr=new int[n];

for(int i=0;i<n;i++)
arr[i]=[Link]();

if(findTriplets(arr,n))
[Link]("1");

else
[Link]("0");

}
}

[Link] an integer array print 1 if any value appears at least twice in the array, and print 0 if every
element is dis nct.

Input format:
First line contain size of the array.

Next line is the n integers of the array.

Output Format

Print 1 if any element occur at least twice and 0 if every element is distinct.

SOLUTION:

import [Link].*;
public class Main {
ti
public static boolean containsDuplicate(int[] nums)
{
HashMap<Integer,Integer> map = new HashMap<>();
for (int i = 0; i < [Link]; i++) {
if ([Link](nums[i])) {
return true;
}
[Link](nums[i],1);
}
return false;
}

public static void main(String args[]) {


int n;
Scanner sc=new Scanner([Link]);
n=[Link]();

int [] arr=new int [n];

for(int i=0;i<n;i++)
arr[i]=[Link]();

if(containsDuplicate(arr))
[Link]("1");

else
[Link]("0");

}
}

Q 28 Given two strings str1 and str2, print the index of the rst occurrence of str2 in str1, or -1 if str2 is
not part of str1.

Input Format:
First line contains str1 i.e. bigger string
Second Line contains str2 i.e. smaller string
Output Format:
Print the index of rst occurrence of str2 in str1 if not found then print -1
Sample Input 1:
fi
fi
sadbutsad
sad
Sample Output 1:
0
Explanation: "sad" occurs at index 0 and 6.
The rst occurrence is at index 0, so we return 0.

Sample Input 2:
Hello
Bye
Sample Output 2:
-1
Explanation: “Bye” is not contained in str1
import [Link];
public class Main {

static int func(String haystack, String needle) {


int haylength=[Link]();
int needlelength=[Link]();
if(haylength<needlelength)
return -1;
for(int i=0;i<=[Link]()-[Link]();i++){
int j=0;
while(j<[Link]() && [Link](i+j)==[Link](j))
j++;
if(j==[Link]()){
return i;
}
}
return -1;
}
fi
public static void main(String args[]) {
String str1,str2;
Scanner sc=new Scanner([Link]);
str1=[Link]();
str2=[Link]();

[Link](func(str1,str2));
}
}

Q29. Given two strings A and B. Find the characters that are not common in the two strings. If no
such character exists return "-1".

Input: A = characters B = alphabets


Output: bclpr
Explanation: The characters 'b','c','l','p','r' are either present in A or B, but not in both.

Input: A = bbbbb B =bb


Output: -1
Explanation: No uncommon char exists

Solution:
import [Link].*;
public class Main {

static String UncommonChars(String A, String B)


{
// code here
HashSet<Character> set1 = new HashSet<>();
HashSet<Character> set2 = new HashSet<>();
ArrayList<Character> list = new ArrayList<>();
String str = "";

for(int i = 0; i < [Link](); i++)


{
char ch = [Link](i);
[Link](ch);
}

for(int i = 0; i < [Link](); i++)


{
char ch = [Link](i);
[Link](ch);
}

for(int i = 0; i < [Link](); i++)


{
char ch = [Link](i);
if(![Link](ch))
{
if(![Link](ch))
[Link](ch);
}

for(int i = 0; i < [Link](); i++)


{
char ch = [Link](i);
if(![Link](ch))
{
if(![Link](ch))
[Link](ch);
}
}

if([Link]() == 0)
return "-1";

[Link](list);
for(char ch : list)
{
str += ch;
}

return str;
}

public static void main(String args[]) {


String str1,str2;
Scanner sc=new Scanner([Link]);
str1=[Link]();
str2=[Link]();

[Link](UncommonChars(str1,str2));
}
}

Q30 Given an input string s, Check whether it is balanced parenthesis or not.

Balanced parentheses are a grouping of parentheses in a string such that every opening parenthesis
has a matching closing parenthesis and vice versa. For example, the following strings have balanced
parentheses:
"()" - contains one pair of balanced parentheses
"(()())" - contains two pairs of balanced parentheses
"(())()" - contains two pairs of balanced parentheses
"(((())))" - contains one pair of balanced parentheses

If the given String is balanced parenthesis then print 1 otherwise print 0.


Input format:
Accept a string

Output format:
Print the string of the words in reverse order

Sample Input 1:
()()
Sample Output 1:
1

Sample Input 2:
()(
(Sample Output 2:
0

Code:
import [Link].*;
class Bal
{
static boolean isBalanced(String str)
{
Stack<Character>st=new Stack<Character>();

for(int i=0;i<[Link]();i++)
{
if([Link](i)=='(')
[Link]('(');
else if([Link](i)==')' && [Link]())
return false;

else
[Link]();

return [Link]();
}

public static void main(String[] args)


{

String str;

Scanner sc=new Scanner([Link]);


str=[Link]();

if(isBalanced(str))
[Link]("1");
else
[Link]("0");
}
}

You might also like