Sunteți pe pagina 1din 24

ZOHO INTERVIEW QUESTIONS for(int i=2; i<=Math.ceil(Math.

sqrt(n)); i++){
1. Return two prime numbers if(n%i==0){
Given an even number (greater than 2), return two return 0;
prime numbers whose sum will be equal to given }
number? There are several combinations possible. }
Print only first such pair. return 1;
NOTE: A solution will always exist, read Goldbach’s }
conjecture. Also, solve the problem in linear time public static void main (String[] args) {
complexity, i.e., O (n). Scanner input=new Scanner(System.in);
Input: int tc=input.nextInt();
The first line contains T, the number of test cases. while(tc!=0){
The following T lines consist of a number each, for int flag=0;
which we'll find two prime numbers. int n=input.nextInt();
Note: The number would always be an even if(n<4){
number. System.out.println(-1);
Output: tc--;
For every test case print two prime numbers space continue;
separated, such that the smaller number appears }
first. Answer for each test case must be in a new for(int i=2; i<=n-2; i++){
line. int res=prime(i);
Constraints: int res1=prime(n-i);
1 ≤ T ≤ 70 if(res==1 && res1==1){
1 ≤ N ≤ 10000 System.out.print(i+" "+(n-i));
Example: flag=1;
Input: break;
5 }
74 }
1024 if(flag==0){
66 System.out.print(-1);
8 }
9990 System.out.println();
Output: tc--;
3 71 }
3 1021 }
5 61 }
35
17 9973 2. Number of paths

Solution: The problem is to count all the possible paths from


top left to bottom right of aMxN matrix with the
import java.util.*; constraints that from each cell you can either move
import java.lang.*; to right ordown.
import java.io.*;
Input:
The first line of input contains an
class GFG {
integer T, denoting the number of test cases. The
public static int prime(int n){
first line of each test case is M and N, M is number
if(n==2){
of rows and N is number of columns.
return 1;
}
Output: if (sr == dr && sc == dc) {
For each test case, print the number of paths. return 1;
Constraints: }
1 ≤ T ≤ 30 int ans = 0;
1 ≤ M,N ≤ 10 if (sr + 1 < arr.length) {
Example: int path1 = paths(arr, sr + 1, sc, dr, dc);
Input ans = ans + path1;
2 }
33 if (sc + 1 < arr[0].length) {
28 int path2 = paths(arr, sr, sc + 1, dr, dc);
Output ans = ans + path2;
6 }
8 return ans;
Explanation: }
Testcase 1: Let the given input 3*3 matrix is filled }
as such:
ABC 3. Frequencies of Limited Range Array Elements
DEF
GHI Given an array A[] of N positive integers which can
The possible paths which exists to reach 'I' from 'A' contain integers from 1 to N where elements can
following above conditions are as follows: be repeated or can be absent from the array. Your
ABCFI, ABEHI, ADGHI, ADEFI, ADEHI, ABEFI. task is to count frequency of all elements from 1 to
N.
Solution:
Note: Expected time complexity is O(n) with O(1)
import java.lang.*; extra space.
import java.io.*; Input:
class GFG First line of input contains an integer T denoting
{ the number of test cases. For each test case, first
public static void main (String[] args) line contains an integer N denoting the size of
array. The second line containsN space-separated
{
integers A1, A2, ..., AN denoting the elements of the
Scanner scn = new Scanner(System.in); array.
int t = scn.nextInt();
Output:
for (int z = 0; z < t; z++) {
For each test case, output N space-separated
int row=scn.nextInt(); integers denoting the frequency of each element
int col=scn.nextInt(); from 1 to N.
int[][] arr = new int[row][col];
Constraints:
System.out.println(paths(arr, 0, 0, arr.length - 1,
1 ≤ T ≤ 100
arr[0].length - 1)); 1 ≤ N ≤ 106
} 1 <= A[i] <= 106
}
Example:
Input:
private static int paths(int[][] arr, int sr, int 2
sc, int dr, int dc) { 5
23235 {
4 sb.append(hm.get(i)+" ");
3333 }
Output: }
02201 System.out.println(sb);
0040 }
Explanation: public static void main (String[] args)throws
Testcase 1: Counting frequencies of each array IOException {
elements, we have: //code
1 occurring 0 times. BufferedReader br=new
2 occurring 2 times.
BufferedReader(new
3 occurring 2 times.
4 occurring 0 times. InputStreamReader(System.in));
5 occurring 1 time. int t=Integer.parseInt(br.readLine());
while(t-- >0)
Solution
{
int
import java.util.*; n=Integer.parseInt(br.readLine());
import java.lang.*; int a[]=new int[n];
import java.io.*; String line=br.readLine();
String s[]=line.trim().split("\\s+");
class GFG { for(int i=0;i<n;i++)
static void freq(int a[],int n) {
{ a[i]=Integer.parseInt(s[i]);
HashMap<Integer,Integer> hm=new }
HashMap<Integer,Integer>(); freq(a,n);
for(int i=0;i<n;i++) }
{ }
if(!hm.containsKey(a[i])) }
{ 4. Reverse each word in a given string
hm.put(a[i],1);
Given a String of length N reverse each word in it.
} Words are separated by dots.
else
{ Input:
The first line contains T denoting the number of
hm.put(a[i],hm.get(a[i])+1);
testcases. Then follows description of
} testcases. Each case contains a string containing
} dots and characters.
StringBuffer sb=new StringBuffer();
for(int i=1;i<=n;i++) Output:
{ For each test case, output a String in single line
if(!hm.containsKey(i)) containing the reversed words of the given String.
sb.append(0+" ");
else
Constraints: 5. Rearrange Array Alternately
1<=T<=10
1<=Length of String<=2000 Given a sorted array of positive integers. Your task
is to rearrange the array elements alternatively i.e
first element should be max value, second should
Example:
be min value, third should be second max, fourth
Input:
should be second min and so on...
2
i.like.this.program.very.much Note: O(1) extra space is allowed. Also, try to
pqr.mno modify the input array as required.
Output: Input:
i.ekil.siht.margorp.yrev.hcum First line of input conatins number of test cases T.
rqp.onm First line of test case contain an integer
denoting the array size N and second line of test
Solutions
case contain N space separated integers denoting
the array elements.
import java.lang.*;
import java.io.*; Output:
class GFG Output the modified array with alternated
elements.
{
public static void main (String[] args) Constraints:
{ 1 <=T<= 100
Scanner sc = new Scanner(System.in); 1 <=N<= 107
1 <=arr[i]<= 107
int t = sc.nextInt();
while(t>0){ Example:
String inp = sc.next(); Input:
2
//System.out.println(inp);
6
String[] input = inp.split("\\."); 123456
//System.out.println(input.length); 111
for(int i=0;i<input.length;i++){ 10 20 30 40 50 60 70 80 90 100 110
//System.out.println(input[i]);
Output:
String[] temp= input[i].split(""); 615243
for(int j=temp.length-1;j>=0;j--){ 110 10 100 20 90 30 80 40 70 50 60
System.out.print(temp[j]);
Explanation:
} Testcase 1: Max element = 6, min = 1, second max
if(i!= input.length-1){ = 5, second min = 2, and so on... Modified array is :
System.out.print("."); 6 1 5 2 4 3.
}
Solution
}
t--; import java.util.*;
System.out.println(); import java.lang.*;
} import java.io.*;
//code
} class GFG {
} public static void main (String[] args) {
Scanner input=new Scanner(System.in); wannacry
int tc=input.nextInt(); rensamwora
while(tc!=0){
int n=input.nextInt(); Solution:
int arr[]=new int[n];
for(int i=0; i<n; i++){ import java.util.*;
arr[i]=input.nextInt(); import java.lang.*;
} import java.io.*;
int res[]=new int[n];
int low=0; class GFG {
int high=arr.length-1; private static String reverseVowel(String a) {
while(low<high){ char b[] = a.toCharArray();
System.out.print(arr[high]+" "+arr[low]+" "); int len = b.length;
high--; int i=0, j=len-1;
low++; char temp;
} while(i<j) {
if(low==high){ if(b[i] == 'a' || b[i] == 'e' || b[i] == 'i' || b[i] == 'o' ||
System.out.print(arr[low]); b[i] == 'u') {
} if(b[j] == 'a' || b[j] == 'e' || b[j] == 'i' || b[j]
System.out.println(); == 'o' || b[j] == 'u') {
tc--; temp = b[i];
} b[i] = b[j];
} b[j] = temp;
} i++;
6. Reversing the vowels j--;
Given a string, reverse only the vowels present in it }
and print the resulting string. else {
Input: First line of the input file contains an integer j--;
T denoting the number of test cases. Then T test }
cases follow. Each test case has a single line }
containing a string.
else {
Output: Corresponding to each test case, output i++;
the string with vowels reversed. }
Example: }
Input: StringBuilder st = new StringBuilder();
4 for(int k=0;k<len;k++) {
geeksforgeeks st.append(b[k]);
practice
}
wannacry
ransomware return st.toString();
}
Output:
geeksforgeeks
public static void main(String[] args) {
prectica
Scanner sc = new int a=sc.nextInt();
Scanner(System.in); int b=sc.nextInt();
int n = sc.nextInt(); int[][] inp=new int[a][b];
for(int i=0; i<n; i++) { for(int i=0;i<a;i++){
String a = sc.next(); for(int j=0;j<b;j++){
String b = reverseVowel(a); inp[i][j]=sc.nextInt();
System.out.println(b); }
} }
int sum=0;
} for(int i=0;i<a;i++){
} for(int j=0;j<b;j++){
7. Sum of elements in a matrix sum+=inp[i][j];
Given a non null integer matrix,calculate the sum }
of its elements. }
Input: First line contains T , the number of test System.out.println(sum);
cases.First line of each test contains 2 integers N,M }
and N lines follow which contain M spaced }
integers. }
8. Solve the Sudoku
Output:Single line for each test case containing the
sum
Given an incomplete Sudoku configuration in terms
of a 9 x 9 2-D square matrix (mat[][]). The task
Constraints: 1<= N,M<=10, -1000<=elements of
to print a solved Sudoku. For simplicity you may
matrix<=1000
assume that there will be only one unique solution.
Example:
Sample Sudoku for you to get the logic for its
Input:
solution:
1
23
100
8 -9 -1
Output
-1
Solution

import java.util.*;
import java.lang.*;
import java.io.*;

class GFG {
public static void main (String[] args) {
Input:
Scanner sc=new Scanner(System.in); The first line of input contains an integer T
int t=sc.nextInt(); denoting the no of test cases. Then T test cases
while(t-->0){ follow. Each test case contains 9*9 space separated
values of the matrix mat[][] representing an StringBuilder sb = new StringBuilder();
incomplete Sudoku state where a 0 represents BufferedReader reader = new
empty block. BufferedReader(new
Output: InputStreamReader(System.in));
For each test case, in a new line, print the space int T = Integer.parseInt(reader.readLine());
separated values of the solution of the the sudoku. for(int i =0 ; i<T; i++) {
Constraints: String[] s = reader.readLine().replaceAll("
1 <= T <= 10 +"," ").split(" ");
0 <= mat[] <= 9 int[][] arr = new int[9][9];
Example: int l = 0;
Input: for(int j=0; j<9; j++) {
1 for(int k=0; k<9; k++) {
306508400 arr[j][k] = Integer.parseInt(s[l++]);
520000000
}
087000031
}
003010080
900863005 solve(arr, 0, sb);
050090600 System.out.print(sb.toString());
130000250 sb.setLength(0);
000000074 }
005206300 }catch(Exception e) {
Output: e.printStackTrace();
316578492 }
529134768 }
487629531 public static boolean isSafe(int[][] arr, int i, int j,
263415987
int val) {
974863125
851792643 //check subMatrix
138947256 int k1;
692351874 for(k1=2; k1<9; k1+=3) {
745286319 if(j<=k1) {
Explanation: break;
Testcase 1: Not needed, I guess. Sp;ved sudoku is }
already given in output. }
Solution int k2;
for(k2=2; k2<9; k2+=3) {
if(i<=k2) {
import java.lang.*; break;
import java.io.*; }
}
class GFG { for(int l=k2-2; l<=k2 ;l++) {
public static void main (String[] args) { for (int m=k1-2; m<=k1; m++) {
//code if(arr[l][m] == val)
try { return false;
} return true;
} }
//check row boolean res = solve(arr, i+1, sb);
for(int l=j; l<arr.length; l++) { arr[k][l] = 0;
if(arr[i][l] == val) if(res) {
return false; return true;
} }
for(int l=j; l>=0; l--) }
if(arr[i][l] == val) }
return false; } if (arr[k][l] == 0) {
//check col return false;
for(int l=i; l<arr.length; l++) { }
if(arr[l][j] == val) if (i <=80)
return false; solve(arr, i+1, sb);
} if(k == arr.length-1 && l == arr.length-1 &&
for(int l=i; l>=0; l--) arr[k][l] !=0 ) {
if(arr[l][j] == val) for(int c=0; c<arr.length; c++) {
return false; for(int d=0; d<arr.length; d++) {
return true;
} sb.append(Integer.toString(arr[c][d])).append(" ");
}
public static boolean solve(int[][] arr, int i, }
StringBuilder sb) { sb.append("\n");
if (i > 80) return true;
return true; }
int k = i/9; return false;
int l = i%9; }
if (arr[k][l] == 0 && i <=80) {
for(int m=1; m<=9; m++) { }
if(isSafe(arr,k,l,m)){
arr[k][l]=m; 9. The Celebrity Problem
//System.out.format("Setting value %d
You are in a party of N people, where only one
%d %d\n",k,l, m);
person is known to everyone. Such a person may
if(k == arr.length-1 && l == arr.length-1 be present in the party, if yes, (s)he doesn’t know
&& arr[k][l] !=0 ) { anyone in the party. Your task is to find the
for(int c=0; c<arr.length; c++) { stranger (celebrity) in party.
for(int d=0; d<arr.length; d++) { You will be given a square matrix M[][] where if an
element of row i and column j is set to 1 it means
sb.append(Integer.toString(arr[c][d])).append(" "); ith person knows jth person. You need to complete
the function getId() which finds the id of the
}
celebrity if present else return -1. The
} function getId() takes two arguments, the
sb.append("\n"); square matrix M and its size N.
Note: Expected time complexity is O(N) with {
constant extra space. int d=0,i;
Input: for(i=1;i<n;i++)
The first line of input contains an element {
T denoting the number of test cases. Then T test if(M[d][i]==1)
cases follow. Each test case consist of 2 lines. The d=i;
first line of each test case contains a number }
denoting the size of the matrix M. Then in the next
for(i=0;i<n;i++)
line are space separated values of the matrix M.
{
Output: if(i!=d && (M[d][i]==1 || M[i][d]==0))
For each test case output will be the id of the
return -1;
celebrity if present (0 based index). Else -1will be
printed. }
return d;
User Task:
}
The task is to complete the function getId() which
}
returns the Id of celebrity if present, else -1.
Constraints:
1 <= T <= 50 10. Smallest greater elements in whole array
2 <= N <= 501
0 <= M[][] <= 1 Given an array A of N length. We need to calculate
the next greater element for each element in given
Example: array. If next greater element is not available in
Input (To be used only for expected output) : given array then we need to fill ‘_’ at that index
2 place.
3
010000010 Input:
2 The first line contains an integer T, the number of
0110 test cases. For each test case, the first line contains
an integer n, the size of the array. Next line
Output : contains n space separated integers denoting the
1 elements of the array.
-1
Output:
Explanation : For each test case, the output is an array that
For the above test case the matrix will look like displays next greater element to element at that
010 index.
000
010 Constraints:
Here, the celebrity is the person with index 1 ie id 1 <= T <= 100
1 1 <= N <= 100
-106 <= Ai <= 106
Example:
Solution Input
class GfG 2
9
{
6 3 9 8 10 2 1 15 7
// The task is to complete this function 4
int getId(int M[][], int n) 13 6 7 12
Output: System.out.println();
7 6 10 9 15 3 2 _ 8
_ 7 12 13 }
Explanation: }
Testcase 1: Here every element of the array has }
next greater element but at index 7, 15 is the
greatest element of given array and no other 11. Total count
element is greater from 15 so at the index of 15 we
fill with '_'. Given an array of positive integers and a
Testcase 2: Here, at index 0, 13 is the greatest number K where K is used as threshold value to
value in given array and no other array element is divide each element of the array into sum of
greater from 13 so at index 0 we fill '_'. different numbers. Find the sum of count of the
Solution numbers in which array elements are divided.
Input:
import java.util.*; The first line of input contains a
import java.lang.*; single integer T denoting the number of test cases.
import java.io.*; Then T test cases follow. Each test case consist of
two lines. The first line of each test case consists of
an integer N and K, where N is the size of array and
class GFG {
K is the threshold value. The second line of each
public static void main (String[] args) { test case contains N space separated integers
Scanner sc = new Scanner(System.in); denoting array elements.
int t = sc.nextInt();
Output:
while(t-->0){ Corresponding to each test case, print the total
int n = sc.nextInt(); count.
int[] a = new int[n];
Constraints:
for(int i=0;i<n;i++){
1 ≤ T ≤ 100
a[i] = sc.nextInt(); 1 ≤ N ≤ 107
} 0 ≤ Ai ≤ 107
for(int i=0;i<n;i++){ 1 ≤ K ≤ 107
int diff = Integer.MAX_VALUE; Example:
int closest = -1; Input:
for(int j=0;j<n;j++){ 1
if (a[i] < a[j] && 43
a[j] - a[i] < diff){ 5 8 10 13
diff = a[j] - a[i]; Output:
closest = j; 14
} Explanation:
} Testcase 1: Each number can be expressed as sum
if(closest == -1) of different numbers less than or equal to K as 5 (3
System.out.print( "_ " ); + 2), 8 (3 + 3 + 2), 10 (3 + 3 + 3 + 1), 13 (3 + 3 + 3 + 3
else + 1). So, the sum of count of each element is 14.
System.out.print(a[closest] + " ");
} Solution
Output:
For each test case print in a single line the distance
import java.util.*; between the two points.
import java.lang.*;
Constraints:
import java.io.*;
1 <= T <= 100
-1000000 <= |x1,x2,y1,y2| <= 1000000
class GFG {
public static void main (String[] args) throws Example:
Exception{ Input:
int n,t,c,i,k,j; 4
BufferedReader ob=new 0 0 2 -2
BufferedReader(new -20 23 -15 68
InputStreamReader(System.in)); 30 37 79 -51
t=Integer.parseInt(ob.readLine()); -69 63 57 11
Output:
StringBuilder ob1=new
3
StringBuilder();
45
for(j=0;j<t;j++)
101
{
136
c=0;
String a[]=ob.readLine().split(" "); Solution
n=Integer.parseInt(a[0]);
k=Integer.parseInt(a[1]);
String s[]=ob.readLine().split(" "); import java.util.*;
for(i=0;i<n;i++) import java.lang.*;
{
import java.io.*;
int x=Integer.parseInt(s[i]);
if(x%k!=0)
c=c+(x/k)+1; class GFG {
else public static void main (String[] args) {
c=c+(x/k); //code
} Scanner sc=new Scanner(System.in);
ob1.append(c+"\n"); int n=sc.nextInt();
}
int x1,x2,y2,y1,d,i;
System.out.println(ob1);
} for(i=0;i<n;i++)
} {
x1=sc.nextInt();
12. Distance between 2 points x2=sc.nextInt();
y1=sc.nextInt();
Given coordinates of 2 points on a cartesian plane,
y2=sc.nextInt();
output the distance between them rounded up to
nearest integer.
Input: System.out.println(Math.round(Math.sqrt(Math.po
The first line of the input contains the number of
w(x1-y1,2)+Math.pow(x2-y2,2))));
test cases T. For each test case there will be single
line containing 4 integers denoting the 2 co- }
ordinates (x1,y1) and (x2,y2).
} BufferedReader in = new
} BufferedReader(new
13. Kadane's Algorithm InputStreamReader(System.in));
int t =Integer.parseInt(in.readLine());
Given an array arr of N integers. Find the while(t-->0)
contiguous sub-array with maximum sum.
{
Input: int n =Integer.parseInt(in.readLine());
The first line of input contains an int ar[] = new int[n];
integer T denoting the number of test cases. The StringTokenizer st = new
description of T test cases follows. The first line of
StringTokenizer(in.readLine());
each test case contains a single integer N denoting
the size of array. The second line contains N space- for(int temp=0;temp<n;temp++)
separated integers A1, A2, ..., AN denoting the {
elements of the array.
Output: ar[temp]=Integer.parseInt(st.nextToken());
Print the maximum sum of the contiguous sub- }
array in a separate line for each test case. long ans=Integer.MIN_VALUE;
long cursum=0;
Constraints:
1 ≤ T ≤ 110 for(int temp=0;temp<n;temp++)
1 ≤ N ≤ 106 {
-107 ≤ A[i] <= 107 cursum+=ar[temp];
Example: ans=Math.max(ans,cursum);
Input if(cursum<0)
2 {
5 cursum=0;
1 2 3 -2 5 }
4 }
-1 -2 -3 -4
System.out.println(ans);
Output
9 }
-1 }
}
Explanation:
Testcase 1: Max subarray sum is 9 of elements (1,
2, 3, -2, 5) which is a contiguous subarray. 14. Sum of two numbers represented as arrays
Given two numbers represented by two different
Solution arrays A and B. The task is to find the sum array.
import java.lang.*; The sum array is an array representation of
addition of two input arrays.
import java.io.*;
class GFG Input:
{ The first line of input contains an integer T
denoting the number of test cases. The first line of
public static void main (String[] args) throws
each test case contains two
IOException integers N and M separated by a space denoting
{ the size of A and B respectively. The second line of
each test case contains N elements and next line
contains M elements.
Output: arr2[f]=sc.nextInt();
Output the sum array. /* if(n1>n2)
Constraints: int arr3[]=new int[n1];
1 ≤ T ≤ 100 else
1 ≤ N ≤ M ≤ 106 int arr3[]=new int[n2];*/
0 ≤ Ai, Bi≤ 9 // int q=n1>n2?n1:n2;
Example: // System.out.println(n1+"
Input: "+n2+" "+q);
2 // int arr3[]=new int[q+1];
33 // int k=arr3.length;
563
// k--;
842
64 int c=0;
227533 ArrayList<Integer> arr3=new
4338 ArrayList<Integer>();
// int j=n2-1;
Output:
1405 int i,j;
231871 for(i=n1-1,j=n2-1;i>=0&&j>=0;i--,j--)
{
Explanation:
Testcase 2: Sum of each elements of both arrays A
and B gives an array equals 2, 3, 1, 8, 7, 1. int sum=arr1[i]+arr2[j]+c;
if(sum>=10)
{
Solution
arr3.add(sum%10);
c=1;
import java.util.*; }
import java.lang.*; else
import java.io.*; {
arr3.add(sum);
class GFG { c=0;
public static void main (String[] args) { }
//code }
Scanner sc=new Scanner(System.in);
int t=sc.nextInt(); //System.out.println("i="+i+"j="+j);
while(t-->0) if(i==-1)
{ {
int n1=sc.nextInt(); while(j>=0)
int n2=sc.nextInt(); {
int arr1[]=new int[n1]; int sum=arr2[j]+c;
int arr2[]=new int[n2]; if(sum>=10)
for(int f=0;f<n1;f++) {
arr1[f]=sc.nextInt(); arr3.add(sum%10);
for(int f=0;f<n2;f++) c=1;
} Collections.reverse(arr3);
else{ for(int k=0;k<arr3.size();k++)
arr3.add(sum); System.out.print(arr3.get(k)+"
c=0; ");
} // for(int i1=0;i1<arr3.length;i1++)
} // System.out.print(arr3[i1]+" ");
// c=0; /*if(n1>n2)
{
j--; int arr[]=new int[n1+1];
} int dif=n1-n2;
for(int i=0;i<diff;i++)
if(j==-1)
{ }*/
//System.out.println("f"); System.out.println();
}
while(i>=0) }
{ }
//System.out.println("f"); 15. Middle Pattern
// arr3.add(arr1[i]+c);
// c=0; Given an odd length word your task is to complete
the function printPatternthat takes a string s as its
// k--;
argument and prints it from the middle of the word
int sum=arr1[i]+c; such that it follows the following pattern.
if(sum>=10)
{
arr3.add(sum%10); Input: PROGRAM Input: RAT
c=1; Output: Output:
}
G A
else{
arr3.add(sum); GR AT
c=0; GRA ATR
}
GRAM
i--;
} GRAMP
// i--; GRAMPR
}
GRAMPRO

if(c==1)
{ The above is proper shaped pattern for the test
arr3.add(1); case, but when
} printed in a single line it becomes as shown in the
//ArratList<Integer> output.
arr4=arr3.reverse();
Input: for(int i=0; i<len; i++){
The first line of input contains an integer T
denoting the number of test cases. Then T test for(int j=0; j<2*(len-(i+1)); j++)
cases follow. Each test case consists of a single line
System.out.print(" ");
containing an odd length string s.
Output: w.append(word[n-1]);
Corresponding to each test case in a new line print System.out.print(w);
the pattern in a single line where each row of the
n++;
pattern is separated by a "$" instead of a new line.
Constraints: if(n==len+1) n=1;
1 ≤ T ≤ 20
1<=size of string(s)<=20
System.out.print("$");
Example(To be used only for expected ouput): }
Input
}
2
}
PROGRAM
RAT 16. Sum of primes
Your task is to calculate sum of primes present as
Output digits of given number N.

G$ GR$ GRA$ GRAM$ GRAMP$ GRA Input:


MPR$GRAMPRO$ The first line of input contains an integer T
A$ AT$ATR$ denoting the number of test cases. Then T test
cases follow. The next T lines contains an integer N.

Solution Output:
Print sum of primes in the digit
/*Please note that it's Function problem i.e.
Constraints:
you need to write your solution in the form of 1 ≤ T ≤ 50
Function(s) only. 2 ≤ N ≤ 50000
Driver Code to call/invoke your function is
mentioned above.*/ Example:

class GfG Input:


{ 2
/*method prints the given pattern in a single line 333
*/ 686
void printPattern(String s) Output:
{ 9
int len = s.length(); 0
int n = len/2 + 1; Solution
char[] word = s.toCharArray();
StringBuilder w = new StringBuilder(); import java.util.*;
import java.lang.*;
import java.io.*; cases follow. Each test case contains a string S and
a number N as input.
class GFG { Output:
public static void main (String[] args)throws For each test case, print the count of characters in
IOException { new line.
//code Constraints:
int n,i,r,c,j,s,a; 1<=T<=100
BufferedReader ob= new BufferedReader(new 1<=|String length |<=104
InputStreamReader(System.in)); 1<=N<=103
n=Integer.parseInt(ob.readLine()); Example:
for(i=0;i<n;i++){ Input:
s=0;c=0; 2
a=Integer.parseInt(ob.readLine()); abc 1
geeksforgeeks 2
while(a!=0)
{ Output:
c=0; 3
r=a%10; 4
a=a/10; Solution
import java.util.*;
for(j=1;j<=r;j++) import java.lang.*;
import java.io.*;
{
class GFG {
if(r%j==0) public static void main (String[] args) {
c++; Scanner sc=new Scanner(System.in);
int t;
} t=sc.nextInt();
if(c==2)
s+=r; while(t>0)
} {
System.out.println(s);
String inp=sc.next();
} int n=sc.nextInt();
} // System.out.println(inp+"Hi"+n);
} int[] ar=new int[26];
17. Count the characters int count=0;
Given a string S. The task is to count the characters
char temp='!';
that have ‘N’ number of occurrences. If a character
appears consecutively it is counted as 1 for(int i=0;i<inp.length();i++)
occurrence. {
//System.out.println(97-(int)inp.charAt(i));
Input:
The first line of input contains an integer T
denoting the number of test cases. Then T test if(temp!=inp.charAt(i)&&(int)inp.charAt(i)-97>=0)
{ Output:
//System.out.println(97-(int)inp.charAt(i)); For each test case, print (X + Y) space separated
ar[(int)inp.charAt(i)-97]++; integer representing the merged array.
temp= inp.charAt(i); Constraints:
1 <= T <= 100
} 1 <= X, Y <= 5*104
0 <= Pi, Qi <= 109
} Example:
//System.out.println(ar.length); Input:
for(int i=0;i<ar.length;i++) 1
45
{
1357
02689
//System.out.print("*"+ar[i]+"*");
Output:
if(n==ar[i])
012356789
{
count++; Explanation:
Testcase 1: After merging two non-decreasing
arrays, we have, 0 1 2 3 5 6 7 8 9.
}
} Solution
System.out.println(count);
t--; import java.util.*;
} import java.lang.*;
} import java.io.*;
}
class GFG {
public static void main (String[] args) throws
18. Merge Two Sorted Arrays
IOException {
Given two sorted arrays P[] and Q[] in non- BufferedReader br=new
decreasing order with size X and Y. The task is to BufferedReader(new
merge the two sorted arrays into one sorted array
InputStreamReader(System.in));
(in non-decreasing order).
int T=Integer.parseInt(br.readLine());
Note: Expected time complexity is O((X+Y) for (int i=0;i<T;i++)
log(X+Y)). DO NOT use extra space. {
Input: String
First line contains an integer T, denoting the s1[]=br.readLine().split("\\s+");
number of test cases. First line of each test case int X=Integer.parseInt(s1[0]);
contains two space separated integers X and Y,
denoting the size of the two sorted arrays. Second
line of each test case contains X space separated int Y=Integer.parseInt(s1[1]);
integers, denoting the first sorted array P. Third
line of each test case contains Y space separated int P[]=new int[X];
integers, denoting the second array Q. int Q[]=new int[Y];
String System.out.println(sb);
s2[]=br.readLine().split("\\s+"); }
for (int j=0;j<X;j++) }
P[j]=Integer.parseInt(s2[j]);
19. Sum Palindrome
String Given a number, reverse it and add it to itself
unless it becomes a palindrome or number of
s3[]=br.readLine().split("\\s+");
iterations reach becom more than 5. If it becomes
for (int j=0;j<Y;j++) a palindrome then print that palindrome
Q[j]=Integer.parseInt(s3[j]); number, otherwise print -1.
MergeSorted(P,X,Q,Y);
Input: First line of the input contains an integer T
}
denoting the number of test cases. Each test case
} has a single line containing a number.
Output: Corresponding to each test case, print the
public static void MergeSorted(int a1[],int n1,int
palindrome number or -1 as stated above.
a2[],int n2)
{ Constraints:
1 <= T <= 200
int i=0,j=0,k=0;
1 <= N <= 1000
StringBuffer sb=new StringBuffer();
while (i<n1 && j< n2) Example:
{ Input:
2
if (a1[i]<=a2[j])
23
{ 30
sb.append(a1[i]+" "); Output:
i++; 55
} 33
else Solution
{
sb.append(a2[j]+" "); import java.util.*;
j++; import java.lang.*;
} import java.io.*;
}
class GFG {
while (i<n1) public int reverse(int n){
{ int sum =0;
sb.append(a1[i]+" "); while(n>0)
i++; {
} int r = n % 10;
while (j<n2) sum = sum * 10 + r;
{ n = n/10;
sb.append(a2[j]+" "); }
j++; return sum;
} }
public static void main (String[] args) { }
Scanner scan = new Scanner(System.in);
int t = scan.nextInt();
while(t>0) 20. Total Decoding Messages
{
A top secret message containing letters from A-Z is
int orgnum = scan.nextInt(); being encoded to numbers using the following
GFG obj = new GFG(); mapping:
int revnum = obj.reverse(orgnum);
if(orgnum == revnum) 'A' -> 1
{ 'B' -> 2
System.out.println(orgnum);
...
}
else 'Z' -> 26
{
int ressum = orgnum + revnum; You are an FBI agent. You have to determine the
total number of ways that message can be
int result = 0;
decoded.
for(int i =0;i<5;i++) Note: An empty digit sequence is considered to
{ have one decoding. It may be assumed that the
// int ressum = orgnum + revnum; input contains valid digits from 0 to 9 and If there
result = obj.reverse(ressum); are leading 0’s, extra trailing 0’s and two or more
if(result == ressum) consecutive 0’s then it is an invalid string.
{ Example :
//System.out.println(result); Given encoded message "123", it could be
break; decoded as "ABC" (1 2 3) or "LC" (12 3) or "AW"(1
} 23).
So total ways are 3.
else {
ressum = result + ressum; Input:
// result = this.reverse(ressum); First line contains the test cases T. 1<=T<=1000
Each test case have two lines
}
First is length of string N. 1<=N<=40
}
Second line is string S of digits from '0' to '9' of N
if(result == ressum) length.
{
Example:
System.out.println(result);
Input:
} 2
else 3
{ 123
System.out.println("-1"); 4
} 2563
} Output:
3
t--;
2
}
} Solution
import java.util.*; if(str.length()>1&&str.charAt(0)=='2')
import java.lang.*; {
import java.io.*;
if(str.charAt(1)>=48&&str.charAt(1)<=54)
class GFG { {
static int solve(String str) if(str.charAt(1)=='0')
{ {
if(str.length()==0)
{ count=count+solve(str.substring(2));
return 1; }
} else
if(str.charAt(0)=='0') {
{
return 0; count=count+solve(str.substring(1))+solve(s
} tr.substring(2));
if(str.length()==1) }
{ }
return 1; else
} {

int count=0; count=count+solve(str.substring(1));


if(str.charAt(0)>50) }
{ }
return count;
count=count+solve(str.substring(1)); }
} public static void main (String[] args) {
//code
if(str.length()>1&&str.charAt(0)=='1') Scanner s=new Scanner(System.in);
{ int t=s.nextInt();
if(str.charAt(1)=='0') while(t>0)
{ {
int n=s.nextInt();
count=count+solve(str.substring(2)); String str=s.next();
} int count=solve(str);
else if(count<0)
{ {
System.out.println(0);
count=count+solve(str.substring(1))+solve(s }
tr.substring(2)); else
} {
}
System.out.println(count);
} The above is the proper cross manner for the test
t--; case, but when printed in a single line it becomes
} as shown in the output.
} Solution
}
21. Cross character
import java.util.*;
Convert a given string to its cross string (i.e import java.lang.*;
Diagonal from left-right and from right-left). import java.io.*;
Input:
class GFG {
The first line of input contains a
single integer T denoting the number of test cases. public static void main (String[] args) {
Then T test cases follow. Each test case consist of Scanner sc=new Scanner(System.in);
two lines. The first line of each test case consists of int i,j,k,l,n;
a String in lower case. n=sc.nextInt();
Output: sc.nextLine();
for(i=0;i<n;i++)
Print given string(in lower case) in cross manner.
{
Constraints: StringBuilder op=new
1 ≤ T ≤ 100 StringBuilder();
1 ≤ length of string ≤ 50 String str=sc.nextLine();
int len=str.length();
Example: for(j=0;j<len/2;j++)
Input {
2 for(l=0;l<j;l++)
geeks op.append(" ");
geeksforgeeks
Output op.append(str.charAt(j));
g sek e ekg s
g se k e e k e s g f for(k=(j*2)+2;k<len;k++)
r o f op.append(" ");
r s g k e e e e kg s
Explanation: op.append(str.charAt((len-1)-j));

For the 1st test case where string is geeks


for(l=0;l<j;l++)
op.append(" ");
G S
EK }
E
EK if(len%2==1)
{
G S
for(k=0;k<len/2;k++)
op.append(" ");
x = "GEEKS"
op.append(str.charAt(len/2));

Output: pattern found at 0, 0


for(k=0;k<len/2;k++)
op.append(" "); pattern found at 0, 8
} pattern found at 1, 0
//System.out.println();
for(j=(len/2)-1;j>=0;j--)
{
for(l=0;l<j;l++) Input:
op.append(" "); The first line of input contains an integer T
denoting the no of test cases. Then T test cases
op.append(str.charAt(j)); follow. Each test case contains two space
separated integers N and M denoting the size of
the grid. Then in the next line are N * M space
for(k=len-1;k>=(j*2)+2;k--)
separated values of the grid. In the next line is the
op.append(" "); word x.

op.append(str.charAt((len-1)-j)); Output:
For each test case in a new line print the space
for(l=0;l<j;l++) separated sorted indexes of the matrix where after
op.append(" "); each index there is a ', ' . If there are no such
occurences print -1.
}
Constraints:
System.out.println(op); 1<=T<100
} 1<=N,M<=100
} 1<=G[]<=100
}
Example:
22.
Input:
Find the string in grid
2
Given a 2D grid (G[]) of characters and a word(x),
33
find all occurrences of given word in grid. A word
abcdefghi
can be matched in all 8 directions at any point.
abc
Word is said be found in a direction if all characters
43
match in this direction (not in zig-zag form).
abababebebeb
The 8 directions are, Horizontally Left, Horizontally abe
Right, Vertically Up, Vertically down and 4 Diagonal Output:
directions. 0 0,
0 0, 0 2, 1 1,
Example:

Input: G[][] = {"GEEKSFORGEEKS", Solution


"GEEKSQUIZGEEK",
import java.util.*;
"IDEQAPRACTICE"}; import java.lang.*;
import java.io.*; int flag=0;
for(int row=0;row<m;row++)
{
class GFG { for(int col=0;col<n;col++)
static int m,n; {
static int[] x={0,0,1,-1,1,1,-1,-1}; if(test(ch,row,col,s))
static int[] y={1,-1,0,0,1,-1,-1,1}; {
public static Boolean test(char[][]ch,int row,int flag=1;
col,String s) System.out.print(row+" "+col+","+" ");
{ }
int k=0; }
if(ch[row][col]!=s.charAt(0)) }
return false; if(flag!=1)
for(int val=0;val<8;val++) {
{ System.out.print(-1);
int r=row+x[val],c=col+y[val]; }
for(k=1;k<s.length();k++)
{
if(r<0||r>=m||c<0||c>=n)
{ }
break;
} public static void main (String[] args) {
if(ch[r][c]!=s.charAt(k)) int t,l;
{ Scanner sc=new Scanner(System.in);
break; String s1,s;
} t=sc.nextInt();
r+=x[val]; for(int i=0;i<t;i++)
c+=y[val]; {
} l=0;
if(k==s.length()) m=sc.nextInt();
{ n=sc.nextInt();
return true; sc.nextLine();
} s1=sc.nextLine();
s=sc.nextLine();
s1=s1.replaceAll(" ","");
s1=s1.trim();
} char[][] ch=new char[m][n];
return false; for(int j=0;j<m;j++)
{
} for(int k=0;k<n;k++)
public static void display(char[][] ch,String s) {
{ ch[j][k]=s1.charAt(l++);
} return true;
} if(n%2==0 || n%3==0)
display(ch,s); return false;
System.out.println(); for(int i=5; i*i<=(n); i=i+6)
} if(n%i==0 || n%(i+2)==0)
} return false;
} return true;
}

23. Primes sum public static void main (String[] args) throws
Exception
Given a number N. Find if it can be expressed as
sum of two prime numbers. {
BufferedReader br = new
Input: BufferedReader(new
The first line of input contains an integer T
InputStreamReader(System.in));
denoting the number of test cases. Then T test
cases follow. Each test case contains an integer N int T = Integer.parseInt(br.readLine());
as input. while(T-->0){

Output:
For each test case, In new line print "Yes" if it can int n =
be expressed, Otherwise print "No". Integer.parseInt(br.readLine().trim());
if((n&1)==0)
Constraints:
System.out.println((n>2)?"Yes":"No");
1<=T<=2000
1<=N<=106 else if(isPrime(n-2))
System.out.println("Yes");
Example:
else
Input:
2 System.out.println("No");
34
23 }
br.close();
Output:
Yes }
No }

Solution
import java.lang.*;
import java.io.*;

class GFG
{
static boolean isPrime(int n){
if(n<=1)
return false;
if(n<=3)

S-ar putea să vă placă și