Documente Academic
Documente Profesional
Documente Cultură
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
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.
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:
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:
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)