"Find number formed by K times alternatively reducing X and adding Y to 0 | Java program for the above approach ; Function to find the value obtained after alternatively reducing X and adding Y to 0 total K number of times ; Stores the final result after adding only Y to 0 ; Stores the final number after reducing only X from 0 ; Return the result obtained ; Driver Code"
How can the above be solved in Java?

import java . util . * ; class GFG { static int positionAfterKJumps ( int X , int Y , int K ) { int addY = Y * ( K / 2 ) ; int reduceX = - 1 * X * ( K / 2 + K % 2 ) ; return addY + reduceX ; } public static void main ( String [ ] args ) { int X = 2 , Y = 5 , K = 3 ; System . out . print ( positionAfterKJumps ( X , Y , K ) ) ; } }


"Find number from given list for which value of the function is closest to A | Java program to find number from given list for which value of the function is closest to A ; Function to find number from given list for which value of the function is closest to A ; Stores the final index ; Declaring a variable to store the minimum absolute difference ; Finding F ( n ) ; Updating the index of the answer if new absolute difference is less than tmp ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { static int leastValue ( int P , int A , int N , int a [ ] ) { int ans = - 1 ; float tmp = Float . MAX_VALUE ; for ( int i = 0 ; i < N ; i ++ ) { float t = ( float ) ( P - a [ i ] * 0.006 ) ; if ( Math . abs ( t - A ) < tmp ) { tmp = Math . abs ( t - A ) ; ans = i ; } } return a [ ans ] ; } public static void main ( String [ ] args ) { int N = 2 , P = 12 , A = 2005 ; int a [ ] = { 1000 , 2000 } ; System . out . println ( leastValue ( P , A , N , a ) ) ; } }


"Find number from its divisors | Java implementation of the approach ; Function that returns X ; Sort the given array ; Get the possible X ; Container to store divisors ; Find the divisors of x ; Check if divisor ; sort the vec because a is sorted and we have to compare all the elements ; if size of both vectors is not same then we are sure that both vectors can 't be equal ; Check if a and vec have same elements in them ; Driver code ; Function call"
How can the above be solved in Java?

import java . util . * ; class GFG { static int findX ( int a [ ] , int n ) { Arrays . sort ( a ) ; int x = a [ 0 ] * a [ n - 1 ] ; Vector < Integer > vec = new Vector < Integer > ( ) ; for ( int i = 2 ; i * i <= x ; i ++ ) { if ( x % i == 0 ) { vec . add ( i ) ; if ( ( x / i ) != i ) vec . add ( x / i ) ; } } Collections . sort ( vec ) ; if ( vec . size ( ) != n ) return - 1 ; else { int i = 0 ; for ( int it : vec ) { if ( a [ i ++ ] != it ) return - 1 ; } } return x ; } public static void main ( String [ ] args ) { int a [ ] = { 2 , 5 , 4 , 10 } ; int n = a . length ; System . out . print ( findX ( a , n ) ) ; } }


"Find number of days between two given dates | Java program two find number of days between two given dates ; A date has day ' d ' , month ' m ' and year ' y ' ; To store number of days in all months from January to Dec . ; This function counts number of leap years before the given date ; Check if the current year needs to be considered for the count of leap years or not ; An year is a leap year if it is a multiple of 4 , multiple of 400 and not a multiple of 100. ; This function returns number of days between two given dates ; initialize count using years and day ; Add days for months in given date ; Since every leap year is of 366 days , Add a day for every leap year ; SIMILARLY , COUNT TOTAL NUMBER OF DAYS BEFORE ' dt2' ; return difference between two counts ; Driver code ; Function call"
How can the above be solved in Java?

class GFG { static class Date { int d , m , y ; public Date ( int d , int m , int y ) { this . d = d ; this . m = m ; this . y = y ; } } ; static int monthDays [ ] = { 31 , 28 , 31 , 30 , 31 , 30 , 31 , 31 , 30 , 31 , 30 , 31 } ; static int countLeapYears ( Date d ) { int years = d . y ; if ( d . m <= 2 ) { years -- ; } return years / 4 - years / 100 + years / 400 ; } static int getDifference ( Date dt1 , Date dt2 ) { int n1 = dt1 . y * 365 + dt1 . d ; for ( int i = 0 ; i < dt1 . m - 1 ; i ++ ) { n1 += monthDays [ i ] ; } n1 += countLeapYears ( dt1 ) ; int n2 = dt2 . y * 365 + dt2 . d ; for ( int i = 0 ; i < dt2 . m - 1 ; i ++ ) { n2 += monthDays [ i ] ; } n2 += countLeapYears ( dt2 ) ; return ( n2 - n1 ) ; } public static void main ( String [ ] args ) { Date dt1 = new Date ( 1 , 2 , 2000 ) ; Date dt2 = new Date ( 1 , 2 , 2004 ) ; System . out . println ( " Difference ▁ between ▁ two ▁ dates ▁ is ▁ " + getDifference ( dt1 , dt2 ) ) ; } }


"Find number of edges that can be broken in a tree such that Bitwise OR of resulting two trees are equal | Java implementation of the approach ; Function to perform simple DFS ; Finding the number of times each bit is set in all the values of a subtree rooted at v ; Checking for each bit whether the numbers with that particular bit as set are either zero in both the resulting trees or greater than zero in both the resulting trees ; Driver code ; Number of nodes ; ArrayList to store the tree ; Array to store the value of nodes ; Array to store the number of times each bit is set in all the values of a subtree ; Array to store the number of times each bit is set in all the values in complete tree ; Finding the set bits in the value of node i ; Add edges"
How can the above be solved in Java?

import java . util . * ; public class GFG { static int m [ ] , a [ ] [ ] , x [ ] ; static ArrayList < Integer > g [ ] ; static int ans = 0 ; static void dfs ( int u , int p ) { for ( int v : g [ u ] ) { if ( v != p ) { dfs ( v , u ) ; for ( int i = 0 ; i < 22 ; i ++ ) a [ u ] [ i ] += a [ v ] [ i ] ; } } int pp = 0 ; for ( int i = 0 ; i < 22 ; i ++ ) { if ( ! ( ( a [ u ] [ i ] > 0 && x [ i ] - a [ u ] [ i ] > 0 ) || ( a [ u ] [ i ] == 0 && x [ i ] == 0 ) ) ) { pp = 1 ; break ; } } if ( pp == 0 ) ans ++ ; } public static void main ( String args [ ] ) { int n = 4 ; g = new ArrayList [ n + 1 ] ; m = new int [ n + 1 ] ; m [ 1 ] = 1 ; m [ 2 ] = 3 ; m [ 3 ] = 2 ; m [ 4 ] = 3 ; a = new int [ n + 1 ] [ 22 ] ; x = new int [ 22 ] ; for ( int i = 1 ; i <= n ; i ++ ) { g [ i ] = new ArrayList < > ( ) ; int y = m [ i ] ; int k = 0 ; while ( y != 0 ) { int p = y % 2 ; if ( p == 1 ) { x [ k ] ++ ; a [ i ] [ k ] ++ ; } y = y / 2 ; k ++ ; } } g [ 1 ] . add ( 2 ) ; g [ 2 ] . add ( 1 ) ; g [ 1 ] . add ( 3 ) ; g [ 3 ] . add ( 1 ) ; g [ 1 ] . add ( 4 ) ; g [ 4 ] . add ( 1 ) ; dfs ( 1 , 0 ) ; System . out . println ( ans ) ; } }


"Find number of endless points | Java program to find count of endless points ; Returns count of endless points ; Fills column matrix . For every column , start from every last row and fill every entry as blockage after a 0 is found . ; flag which will be zero once we get a '0' and it will be 1 otherwise ; encountered a '0' , set the isEndless variable to false ; Similarly , fill row matrix ; Calculate total count of endless points ; If there is NO blockage in row or column after this point , increment result . ; driver code"
How can the above be solved in Java?

class GFG { static final int MAX = 100 ; static int countEndless ( boolean input [ ] [ ] , int n ) { boolean row [ ] [ ] = new boolean [ n ] [ n ] ; boolean col [ ] [ ] = new boolean [ n ] [ n ] ; for ( int j = 0 ; j < n ; j ++ ) { boolean isEndless = true ; for ( int i = n - 1 ; i >= 0 ; i -- ) { if ( input [ i ] [ j ] == false ) isEndless = false ; col [ i ] [ j ] = isEndless ; } } for ( int i = 0 ; i < n ; i ++ ) { boolean isEndless = true ; for ( int j = n - 1 ; j >= 0 ; j -- ) { if ( input [ i ] [ j ] == false ) isEndless = false ; row [ i ] [ j ] = isEndless ; } } int ans = 0 ; for ( int i = 0 ; i < n ; i ++ ) for ( int j = 1 ; j < n ; j ++ ) if ( row [ i ] [ j ] && col [ i ] [ j ] ) ans ++ ; return ans ; } public static void main ( String arg [ ] ) { boolean input [ ] [ ] = { { true , false , true , true } , { false , true , true , true } , { true , true , true , true } , { false , true , true , false } } ; int n = 4 ; System . out . print ( countEndless ( input , n ) ) ; } }


"Find number of factors of N when location of its two factors whose product is N is given | Java program to implement the above problem ; Function to find the number of factors ; print the number of factors ; Driver code ; initialize the factors position"
How can the above be solved in Java?

class GFG { static void findFactors ( int a , int b ) { int c ; c = a + b - 1 ; System . out . print ( c ) ; } public static void main ( String [ ] args ) { int a , b ; a = 13 ; b = 36 ; findFactors ( a , b ) ; } }


"Find number of magical pairs of string of length L | Java implementation of the approach ; Iterative Function to calculate ( x ^ y ) % p in O ( log y ) ; Initialize result ; Update x if it is >= p ; If y is odd , multiply x with result ; Y must be even now y = y >> 1 ; y = y / 2 ; Driver Code"
How can the above be solved in Java?

class GFG { static int power ( int x , int y , int p ) { int res = 1 ; x = x % p ; while ( y > 0 ) { if ( y % 2 == 1 ) { res = ( res * x ) % p ; } x = ( x * x ) % p ; } return res ; } public static void main ( String [ ] args ) { int L = 2 ; int P = ( int ) Math . pow ( 10 , 9 ) ; int ans = power ( 325 , L , P ) ; System . out . println ( ans ) ; } }


"Find number of pairs ( x , y ) in an Array such that x ^ y > y ^ x | Set 2 | Java program to finds the number of pairs ( x , y ) from X [ ] and Y [ ] such that x ^ y > y ^ x ; Function to return the count of pairs ; Compute suffix sums till i = 3 ; Base Case : x = 0 ; No valid pairs ; Base Case : x = 1 ; Store the count of 0 's ; Base Case : x = 2 ; Store suffix sum upto 5 ; Base Case : x = 3 ; Store count of 2 and suffix sum upto 4 ; For all other values of x ; For all x >= 2 , every y = 0 and every y = 1 makes a valid pair ; Return the count of pairs ; Driver code"
How can the above be solved in Java?

class GFG { static int countPairs ( int X [ ] , int Y [ ] , int m , int n ) { int [ ] suffix = new int [ 1005 ] ; long total_pairs = 0 ; for ( int i = 0 ; i < n ; i ++ ) suffix [ Y [ i ] ] ++ ; for ( int i = ( int ) 1e3 ; i >= 3 ; i -- ) suffix [ i ] += suffix [ i + 1 ] ; for ( int i = 0 ; i < m ; i ++ ) { if ( X [ i ] == 0 ) continue ; else if ( X [ i ] == 1 ) { total_pairs += suffix [ 0 ] ; continue ; } else if ( X [ i ] == 2 ) total_pairs += suffix [ 5 ] ; else if ( X [ i ] == 3 ) total_pairs += suffix [ 2 ] + suffix [ 4 ] ; else total_pairs += suffix [ X [ i ] + 1 ] ; total_pairs += suffix [ 0 ] + suffix [ 1 ] ; } return ( int ) total_pairs ; } public static void main ( String [ ] args ) { int X [ ] = { 10 , 19 , 18 } ; int Y [ ] = { 11 , 15 , 9 } ; int m = X . length ; int n = Y . length ; System . out . print ( countPairs ( X , Y , m , n ) ) ; } }


"Find number of pairs ( x , y ) in an array such that x ^ y > y ^ x | Java program to finds number of pairs ( x , y ) in an array such that x ^ y > y ^ x ; Function to return count of pairs with x as one element of the pair . It mainly looks for all values in Y [ ] where x ^ Y [ i ] > Y [ i ] ^ x ; If x is 0 , then there cannot be any value in Y such that x ^ Y [ i ] > Y [ i ] ^ x ; If x is 1 , then the number of pais is equal to number of zeroes in Y [ ] ; Find number of elements in Y [ ] with values greater than x getting upperbound of x with binary search ; If we have reached here , then x must be greater than 1 , increase number of pairs for y = 0 and y = 1 ; Decrease number of pairs for x = 2 and ( y = 4 or y = 3 ) ; Increase number of pairs for x = 3 and y = 2 ; Function to returns count of pairs ( x , y ) such that x belongs to X [ ] , y belongs to Y [ ] and x ^ y > y ^ x ; To store counts of 0 , 1 , 2 , 3 and 4 in array Y ; Sort Y [ ] so that we can do binary search in it ; Initialize result ; Take every element of X and count pairs with it ; Driver method"
How can the above be solved in Java?

import java . util . Arrays ; class Test { static int count ( int x , int Y [ ] , int n , int NoOfY [ ] ) { if ( x == 0 ) return 0 ; if ( x == 1 ) return NoOfY [ 0 ] ; int idx = Arrays . binarySearch ( Y , x ) ; int ans ; if ( idx < 0 ) { idx = Math . abs ( idx + 1 ) ; ans = Y . length - idx ; } else { while ( idx < n && Y [ idx ] == x ) { idx ++ ; } ans = Y . length - idx ; } ans += ( NoOfY [ 0 ] + NoOfY [ 1 ] ) ; if ( x == 2 ) ans -= ( NoOfY [ 3 ] + NoOfY [ 4 ] ) ; if ( x == 3 ) ans += NoOfY [ 2 ] ; return ans ; } static long countPairs ( int X [ ] , int Y [ ] , int m , int n ) { int NoOfY [ ] = new int [ 5 ] ; for ( int i = 0 ; i < n ; i ++ ) if ( Y [ i ] < 5 ) NoOfY [ Y [ i ] ] ++ ; Arrays . sort ( Y ) ; long total_pairs = 0 ; for ( int i = 0 ; i < m ; i ++ ) total_pairs += count ( X [ i ] , Y , n , NoOfY ) ; return total_pairs ; } public static void main ( String args [ ] ) { int X [ ] = { 2 , 1 , 6 } ; int Y [ ] = { 1 , 5 } ; System . out . println ( " Total ▁ pairs ▁ = ▁ " + countPairs ( X , Y , X . length , Y . length ) ) ; } }


"Find number of pairs ( x , y ) in an array such that x ^ y > y ^ x |"
How can the above be solved in Java?

public static long countPairsBruteForce ( long X [ ] , long Y [ ] , int m , int n ) { long ans = 0 ; for ( int i = 0 ; i < m ; i ++ ) for ( int j = 0 ; j < n ; j ++ ) if ( Math . pow ( X [ i ] , Y [ j ] ) > Math . pow ( Y [ j ] , X [ i ] ) ) ans ++ ; return ans ; }


"Find number of solutions of a linear equation of n variables | A Dynamic programming based Java program to find number of non - negative solutions for a given linear equation ; Returns counr of solutions for given rhs and coefficients coeff [ 0. . n - 1 ] ; Create and initialize a table to store results of subproblems ; Fill table in bottom up manner ; Driver code"
How can the above be solved in Java?

import java . util . Arrays ; class GFG { static int countSol ( int coeff [ ] , int n , int rhs ) { int dp [ ] = new int [ rhs + 1 ] ; Arrays . fill ( dp , 0 ) ; dp [ 0 ] = 1 ; for ( int i = 0 ; i < n ; i ++ ) for ( int j = coeff [ i ] ; j <= rhs ; j ++ ) dp [ j ] += dp [ j - coeff [ i ] ] ; return dp [ rhs ] ; } public static void main ( String [ ] args ) { int coeff [ ] = { 2 , 2 , 5 } ; int rhs = 4 ; int n = coeff . length ; System . out . print ( countSol ( coeff , n , rhs ) ) ; } }


"Find number of solutions of a linear equation of n variables | A naive recursive Java program to find number of non - negative solutions for a given linear equation ; Recursive function that returns count of solutions for given rhs value and coefficients coeff [ start . . end ] ; Base case ; Initialize count of solutions ; One by subtract all smaller or equal coefficiants and recur ; Driver Code"
How can the above be solved in Java?

import java . io . * ; class GFG { static int countSol ( int coeff [ ] , int start , int end , int rhs ) { if ( rhs == 0 ) return 1 ; int result = 0 ; for ( int i = start ; i <= end ; i ++ ) if ( coeff [ i ] <= rhs ) result += countSol ( coeff , i , end , rhs - coeff [ i ] ) ; return result ; } public static void main ( String [ ] args ) { int coeff [ ] = { 2 , 2 , 5 } ; int rhs = 4 ; int n = coeff . length ; System . out . println ( countSol ( coeff , 0 , n - 1 , rhs ) ) ; } }


"Find number of square of area Z which can be built in a matrix having blocked regions | Java implementation of the approach ; Function to calculate the number of square areas of size K * K ; Row array and column array to store the lengths of differences between consecutive rows / columns ; Fill the conrow vector ; Fill the concol vector ; To store the required answer ; Every pair of row size and column size would result in an unblocked region ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { static int subgrids ( int N , int Z , int row [ ] , int col [ ] , int r , int d ) { Vector < Integer > conrow = new Vector < Integer > ( ) ; Vector < Integer > concol = new Vector < Integer > ( ) ; int K = ( int ) Math . sqrt ( Z ) ; conrow . add ( row [ 0 ] - 0 - 1 ) ; conrow . add ( N + 1 - row [ r - 1 ] - 1 ) ; for ( int i = 1 ; i < r ; i ++ ) { conrow . add ( row [ i ] - row [ i - 1 ] - 1 ) ; } concol . add ( col [ 0 ] - 0 - 1 ) ; concol . add ( N + 1 - col [ d - 1 ] - 1 ) ; for ( int i = 1 ; i < d ; i ++ ) { concol . add ( col [ i ] - col [ i - 1 ] - 1 ) ; } int row_size = conrow . size ( ) ; int col_size = concol . size ( ) ; int answer = 0 ; for ( int i = 0 ; i < row_size ; i ++ ) { for ( int j = 0 ; j < col_size ; j ++ ) { int total = ( concol . get ( j ) / K ) * ( conrow . get ( i ) / K ) ; answer += ( total ) ; } } return answer ; } public static void main ( String [ ] args ) { int N = 8 , Z = 4 ; int row [ ] = { 4 , 6 } ; int col [ ] = { 3 , 8 } ; int r = row . length ; int d = col . length ; System . out . print ( subgrids ( N , Z , row , col , r , d ) ) ; } }


"Find number of subarrays with XOR value a power of 2 | Java Program to count number of subarrays with Bitwise - XOR as power of 2 ; Function to find number of subarrays ; Hash Map to store prefix XOR values ; When no element is selected ; Check for all the powers of 2 , till a MAX value ; Insert Current prefixxor in Hash Map ; Driver Code"
How can the above be solved in Java?

import java . util . * ; class GFG { static int MAX = 10 ; static int findSubarray ( int array [ ] , int n ) { HashMap < Integer , Integer > mp = new HashMap < Integer , Integer > ( ) ; mp . put ( 0 , 1 ) ; int answer = 0 ; int preXor = 0 ; for ( int i = 0 ; i < n ; i ++ ) { int value = 1 ; preXor ^= array [ i ] ; for ( int j = 1 ; j <= MAX ; j ++ ) { int Y = value ^ preXor ; if ( mp . containsKey ( Y ) ) { answer += mp . get ( Y ) ; } value *= 2 ; } if ( mp . containsKey ( preXor ) ) { mp . put ( preXor , mp . get ( preXor ) + 1 ) ; } else { mp . put ( preXor , 1 ) ; } } return answer ; } public static void main ( String [ ] args ) { int array [ ] = { 2 , 6 , 7 , 5 , 8 } ; int n = array . length ; System . out . println ( findSubarray ( array , n ) ) ; } }


"Find number of subarrays with even sum | Java program to count number of sub - arrays whose sum is even using brute force Time Complexity - O ( N ^ 2 ) Space Complexity - O ( 1 ) ; Find sum of all subarrays and increment result if sum is even ; Driver code"
How can the above be solved in Java?

import java . io . * ; class GFG { static int countEvenSum ( int arr [ ] , int n ) { int result = 0 ; for ( int i = 0 ; i <= n - 1 ; i ++ ) { int sum = 0 ; for ( int j = i ; j <= n - 1 ; j ++ ) { sum = sum + arr [ j ] ; if ( sum % 2 == 0 ) result ++ ; } } return ( result ) ; } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 2 , 2 , 3 , 4 , 1 } ; int n = arr . length ; System . out . print ( " The ▁ Number ▁ of ▁ Subarrays " + " ▁ with ▁ even ▁ sum ▁ is ▁ " ) ; System . out . println ( countEvenSum ( arr , n ) ) ; } }


"Find number of subarrays with even sum | Java program to count number of sub - arrays with even sum using an efficient algorithm Time Complexity - O ( N ) Space Complexity - O ( 1 ) ; A temporary array of size 2. temp [ 0 ] is going to store count of even subarrays and temp [ 1 ] count of odd . temp [ 0 ] is initialized as 1 because there a single even element is also counted as a subarray ; Initialize count . sum is sum of elements under modulo 2 and ending with arr [ i ] . ; i ' th ▁ iteration ▁ computes ▁ sum ▁ ▁ of ▁ arr [ 0 . . i ] ▁ under ▁ modulo ▁ 2 ▁ ▁ and ▁ increments ▁ even / odd ▁ count ▁ ▁ according ▁ to ▁ sum ' s value ; 2 is added to handle negative numbers ; Increment even / odd count ; Use handshake lemma to count even subarrays ( Note that an even cam be formed by two even or two odd ) ; Driver code"
How can the above be solved in Java?

import java . io . * ; class GFG { static int countEvenSum ( int arr [ ] , int n ) { int temp [ ] = { 1 , 0 } ; int result = 0 , sum = 0 ; for ( int i = 0 ; i <= n - 1 ; i ++ ) { sum = ( ( sum + arr [ i ] ) % 2 + 2 ) % 2 ; temp [ sum ] ++ ; } result = result + ( temp [ 0 ] * ( temp [ 0 ] - 1 ) / 2 ) ; result = result + ( temp [ 1 ] * ( temp [ 1 ] - 1 ) / 2 ) ; return ( result ) ; } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 2 , 2 , 3 , 4 , 1 } ; int n = arr . length ; System . out . println ( " The ▁ Number ▁ of ▁ Subarrays " + " ▁ with ▁ even ▁ sum ▁ is ▁ " + countEvenSum ( arr , n ) ) ; } }


"Find number of subarrays with even sum | Java program to count number of sub - arrays with even sum using an efficient algorithm Time Complexity - O ( N ) Space Complexity - O ( 1 ) ; result may be large enough not to fit in int ; ; to keep track of subarrays with even sum starting from index i ; if a [ i ] is odd then all subarrays starting from index i + 1 which was odd becomeseven when a [ i ] gets added to it . ; if a [ i ] is even then all subarrays starting from index i + 1 which was even remainseven and one extra a [ i ] even subarray gets added to it . ; Driver Code"
How can the above be solved in Java?

import java . io . * ; class GFG { public static long countEvenSum ( int a [ ] , int n ) { long res = 0 ; int s = 0 ; for ( int i = n - 1 ; i >= 0 ; i -- ) { if ( a [ i ] % 2 == 1 ) { s = n - i - 1 - s ; } else { s = s + 1 ; } res = res + s ; } return res ; } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 2 , 2 , 3 , 4 , 1 } ; int n = arr . length ; System . out . println ( " The ▁ Number ▁ of ▁ Subarrays " + " ▁ with ▁ even ▁ sum ▁ is ▁ " + countEvenSum ( arr , n ) ) ; } }


"Find number of substrings of length k whose sum of ASCII value of characters is divisible by k | Java program to find number of substrings of length k whose sum of ASCII value of characters is divisible by k ; Finding length of string ; finding sum of ASCII value of first substring ; Using sliding window technique to find sum of ASCII value of rest of the substring ; checking if sum is divisible by k ; Driver code"
How can the above be solved in Java?

public class GFG { static int count ( String s , int k ) { int n = s . length ( ) ; int d = 0 , i ; int count = 0 ; for ( i = 0 ; i < n ; i ++ ) d += s . charAt ( i ) ; if ( d % k == 0 ) count += 1 ; for ( i = k ; i < n ; i ++ ) { int prev = s . charAt ( i - k ) ; d -= prev ; d += s . charAt ( i ) ; if ( d % k == 0 ) count += 1 ; } return count ; } public static void main ( String [ ] args ) { String s = " bcgabc " ; int k = 3 ; int ans = count ( s , k ) ; System . out . println ( ans ) ; } }


"Find number of times a string occurs as a subsequence in given string | A Dynamic Programming based Java program to find the number of times the second string occurs in the first string , whether continuous or discontinuous ; Iterative DP function to find the number of times the second string occurs in the first string , whether continuous or discontinuous ; Create a table to store results of sub - problems ; If first string is empty ; If second string is empty ; Fill lookup [ ] [ ] in bottom up manner ; If last characters are same , we have two options - 1. consider last characters of both strings in solution 2. ignore last character of first string ; If last character are different , ignore last character of first string ; Driver Code"
How can the above be solved in Java?

import java . io . * ; class GFG { static int count ( String a , String b ) { int m = a . length ( ) ; int n = b . length ( ) ; int lookup [ ] [ ] = new int [ m + 1 ] [ n + 1 ] ; for ( int i = 0 ; i <= n ; ++ i ) lookup [ 0 ] [ i ] = 0 ; for ( int i = 0 ; i <= m ; ++ i ) lookup [ i ] [ 0 ] = 1 ; for ( int i = 1 ; i <= m ; i ++ ) { for ( int j = 1 ; j <= n ; j ++ ) { if ( a . charAt ( i - 1 ) == b . charAt ( j - 1 ) ) lookup [ i ] [ j ] = lookup [ i - 1 ] [ j - 1 ] + lookup [ i - 1 ] [ j ] ; else lookup [ i ] [ j ] = lookup [ i - 1 ] [ j ] ; } } return lookup [ m ] [ n ] ; } public static void main ( String [ ] args ) { String a = " GeeksforGeeks " ; String b = " Gks " ; System . out . println ( count ( a , b ) ) ; } }


"Find number of times a string occurs as a subsequence in given string | A Naive recursive java program to find the number of times the second string occurs in the first string , whether continuous or discontinuous ; Recursive function to find the number of times the second string occurs in the first string , whether continuous or discontinuous ; If both first and second string is empty , or if second string is empty , return 1 ; If only first string is empty and second string is not empty , return 0 ; If last characters are same Recur for remaining strings by 1. considering last characters of both strings 2. ignoring last character of first string ; If last characters are different , ignore last char of first string and recur for remaining string ; Driver code"
How can the above be solved in Java?

import java . io . * ; class GFG { static int count ( String a , String b , int m , int n ) { if ( ( m == 0 && n == 0 ) n == 0 ) return 1 ; if ( m == 0 ) return 0 ; if ( a . charAt ( m - 1 ) == b . charAt ( n - 1 ) ) return count ( a , b , m - 1 , n - 1 ) + count ( a , b , m - 1 , n ) ; else return count ( a , b , m - 1 , n ) ; } public static void main ( String [ ] args ) { String a = " GeeksforGeeks " ; String b = " Gks " ; System . out . println ( count ( a , b , a . length ( ) , b . length ( ) ) ) ; } }


"Find number of transformation to make two Matrix Equal | Java program to find number of countOpsation to make two matrix equals ; Update matrix A [ ] [ ] so that only A [ ] [ ] has to be countOpsed ; Check necessary condition for condition for existence of full countOpsation ; If countOpsation is possible calculate total countOpsation ; Driver code"
How can the above be solved in Java?

import java . io . * ; class GFG { static int countOps ( int A [ ] [ ] , int B [ ] [ ] , int m , int n ) { for ( int i = 0 ; i < n ; i ++ ) for ( int j = 0 ; j < m ; j ++ ) A [ i ] [ j ] -= B [ i ] [ j ] ; for ( int i = 1 ; i < n ; i ++ ) for ( int j = 1 ; j < m ; j ++ ) if ( A [ i ] [ j ] - A [ i ] [ 0 ] - A [ 0 ] [ j ] + A [ 0 ] [ 0 ] != 0 ) return - 1 ; int result = 0 ; for ( int i = 0 ; i < n ; i ++ ) result += Math . abs ( A [ i ] [ 0 ] ) ; for ( int j = 0 ; j < m ; j ++ ) result += Math . abs ( A [ 0 ] [ j ] - A [ 0 ] [ 0 ] ) ; return ( result ) ; } public static void main ( String [ ] args ) { int A [ ] [ ] = { { 1 , 1 , 1 } , { 1 , 1 , 1 } , { 1 , 1 , 1 } } ; int B [ ] [ ] = { { 1 , 2 , 3 } , { 4 , 5 , 6 } , { 7 , 8 , 9 } } ; System . out . println ( countOps ( A , B , 3 , 3 ) ) ; } }


"Find numbers a and b that satisfy the given conditions | Java implementation of the above approach ; Function to print the required numbers ; Suppose b = n and we want a % b = 0 and also ( a / b ) < n so a = b * ( n - 1 ) ; Special case if n = 1 we get a = 0 so ( a * b ) < n ; If no pair satisfies the conditions ; Driver code"
How can the above be solved in Java?

public class GFG { static void find ( int n ) { int b = n ; int a = b * ( n - 1 ) ; if ( a * b > n && a / b < n ) { System . out . print ( " a ▁ = ▁ " + a + " , ▁ b ▁ = ▁ " + b ) ; } else System . out . println ( - 1 ) ; } public static void main ( String [ ] args ) { int n = 10 ; find ( n ) ; } }


"Find numbers in range [ L , R ] that are coprime with given Array elements | Java program for the above approach ; Function to find all the elements in the range [ L , R ] which are co prime with all array elements ; Store all the divisors of array element in S ; Find the divisors ; Stores all possible required number satisfying the given criteria ; Insert all element [ L , R ] ; Traverse the set ; Remove the multiples of ele ; Print the resultant numbers ; Driver Code"
How can the above be solved in Java?

import java . util . * ; class GFG { static void elementsCoprimeWithArr ( int A [ ] , int N , int L , int R ) { HashSet < Integer > S = new HashSet < Integer > ( ) ; for ( int i = 0 ; i < N ; i ++ ) { int curr_ele = A [ i ] ; for ( int j = 1 ; j <= Math . sqrt ( curr_ele ) + 1 ; j ++ ) { if ( curr_ele % j == 0 ) { S . add ( j ) ; S . add ( curr_ele / j ) ; } } } HashSet < Integer > store = new HashSet < Integer > ( ) ; for ( int i = L ; i <= R ; i ++ ) store . add ( i ) ; S . remove ( 1 ) ; for ( int it : S ) { int ele = it ; int index = 1 ; while ( index * ele <= R ) { store . remove ( index * ele ) ; index ++ ; } } for ( int i : store ) { System . out . print ( i + " ▁ " ) ; } } public static void main ( String [ ] args ) { int arr [ ] = { 3 , 5 } ; int L = 1 , R = 10 ; int N = arr . length ; elementsCoprimeWithArr ( arr , N , L , R ) ; } }


"Find numbers of balancing positions in string | Java program to find number of balancing points in string ; method to return number of balancing points ; hash array for storing hash of string initialized by 0 being global ; process string initially for rightVisited ; check for balancing points ; for every position inc left hash & dec rightVisited ; check whether both hash have same character or not ; Either both leftVisited [ j ] and rightVisited [ j ] should have none zero value or both should have zero value ; if both have same character increment count ; Driver Method"
How can the above be solved in Java?

class GFG { static final int MAX_CHAR = 256 ; static int countBalance ( String s ) { char [ ] str = s . toCharArray ( ) ; int [ ] rightVisited = new int [ MAX_CHAR ] ; int [ ] leftVisited = new int [ MAX_CHAR ] ; for ( int i = 0 ; i < n ; i ++ ) rightVisited [ str [ i ] ] ++ ; int res = 0 ; for ( int i = 0 ; i < n ; i ++ ) { leftVisited [ str [ i ] ] ++ ; rightVisited [ str [ i ] ] -- ; int j ; for ( j = 0 ; j < MAX_CHAR ; j ++ ) { if ( ( leftVisited [ j ] == 0 && rightVisited [ j ] != 0 ) || ( leftVisited [ j ] != 0 && rightVisited [ j ] == 0 ) ) break ; } if ( j == MAX_CHAR ) res ++ ; } return res ; } public static void main ( String [ ] args ) { String str = " abaababa " ; System . out . println ( countBalance ( str ) ) ; } }


"Find numbers that divide X and Y to produce the same remainder | Java program to find numbers that divide X and Y to produce the same remainder ; Function to find the required number as M ; Finding the maximum value among X and Y ; Loop to iterate through maximum value among X and Y . ; If the condition satisfies , then print the value of M ; Driver code"
How can the above be solved in Java?

class GFG { static void printModulus ( int X , int Y ) { int n = Math . max ( X , Y ) ; for ( int i = 1 ; i <= n ; i ++ ) { if ( X % i == Y % i ) System . out . print ( i + " ▁ " ) ; } } public static void main ( String [ ] args ) { int X , Y ; X = 10 ; Y = 20 ; printModulus ( X , Y ) ; } }


"Find numbers that divide X and Y to produce the same remainder | Java program to find numbers that divide X and Y to produce the same remainder ; Function to print all the possible values of M such that X % M = Y % M ; Finding the absolute difference of X and Y ; Iterating from 1 ; Loop to print all the factors of D ; If i is a factor of d , then print i ; If d / i is a factor of d , then print d / i ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { static void printModulus ( int X , int Y ) { int d = Math . abs ( X - Y ) ; int i = 1 ; while ( i * i <= d ) { if ( d % i == 0 ) { System . out . print ( i + " ▁ " ) ; if ( d / i != i ) System . out . print ( d / i + " ▁ " ) ; } i ++ ; } } public static void main ( String [ ] args ) { int X = 10 ; int Y = 26 ; printModulus ( X , Y ) ; } }


"Find numbers which are multiples of first array and factors of second array | Java implementation of the approach ; Function to return the LCM of two numbers ; Function to print the required numbers ; To store the lcm of array a [ ] elements and the gcd of array b [ ] elements ; Finding LCM of first array ; Finding GCD of second array ; No such element exists ; All the multiples of lcmA which are less than or equal to gcdB and evenly divide gcdB will satisfy the conditions ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { static int __gcd ( int a , int b ) { if ( b == 0 ) return a ; return __gcd ( b , a % b ) ; } static int lcm ( int x , int y ) { int temp = ( x * y ) / __gcd ( x , y ) ; return temp ; } static void findNumbers ( int a [ ] , int n , int b [ ] , int m ) { int lcmA = 1 , gcdB = 0 ; for ( int i = 0 ; i < n ; i ++ ) lcmA = lcm ( lcmA , a [ i ] ) ; for ( int i = 0 ; i < m ; i ++ ) gcdB = __gcd ( gcdB , b [ i ] ) ; if ( gcdB % lcmA != 0 ) { System . out . print ( " - 1" ) ; return ; } int num = lcmA ; while ( num <= gcdB ) { if ( gcdB % num == 0 ) System . out . print ( num + " ▁ " ) ; num += lcmA ; } } public static void main ( String [ ] args ) { int a [ ] = { 1 , 2 , 2 , 4 } ; int b [ ] = { 16 , 32 , 64 } ; int n = a . length ; int m = b . length ; findNumbers ( a , n , b , m ) ; } }


"Find numbers with K odd divisors in a given range | Java program to count numbers with k odd divisors in a range . ; Utility function to check if number is perfect square or not ; Utility Function to return count of divisors of a number ; Note that this loop runs till square root ; If divisors are equal , count it only once ; Otherwise print both ; Function to calculate all divisors having exactly k divisors between a and b ; Initialize result ; calculate only for perfect square numbers ; check if number is perfect square or not ; total divisors of number equals to k or not ; Driver program to run the case"
How can the above be solved in Java?

import java . io . * ; import java . math . * ; class GFG { static boolean isPerfect ( int n ) { int s = ( int ) ( Math . sqrt ( n ) ) ; return ( s * s == n ) ; } static int divisorsCount ( int n ) { int count = 0 ; for ( int i = 1 ; i <= Math . sqrt ( n ) + 1 ; i ++ ) { if ( n % i == 0 ) { if ( n / i == i ) count += 1 ; else count += 2 ; } } return count ; } static int kDivisors ( int a , int b , int k ) { int count = 0 ; for ( int i = a ; i <= b ; i ++ ) { if ( isPerfect ( i ) ) if ( divisorsCount ( i ) == k ) count ++ ; } return count ; } public static void main ( String args [ ] ) { int a = 21 , b = 149 , k = 333 ; System . out . println ( kDivisors ( a , b , k ) ) ; } }


"Find one extra character in a string | Java program to find extra character in one string ; Determine String with extra character . ; Add character codes of both the strings ; Add last character code of large String . ; Minus the character code of smaller string from the character code of large string . The result will be the extra character code . ; Driver code"
How can the above be solved in Java?

public class Test { private static char findExtraCharacter ( String s1 , String s2 ) { String smallStr ; String largeStr ; if ( s1 . length ( ) > s2 . length ( ) ) { smallStr = s2 ; largeStr = s1 ; } else { smallStr = s1 ; largeStr = s2 ; } int smallStrCodeTotal = 0 ; int largeStrCodeTotal = 0 ; int i = 0 ; for ( ; i < smallStr . length ( ) ; i ++ ) { smallStrCodeTotal += smallStr . charAt ( i ) ; largeStrCodeTotal += largeStr . charAt ( i ) ; } largeStrCodeTotal += largeStr . charAt ( i ) ; int intChar = largeStrCodeTotal - smallStrCodeTotal ; return ( char ) intChar ; } public static void main ( String [ ] args ) { String s1 = " abcd " ; String s2 = " cbdae " ; char extraChar = findExtraCharacter ( s1 , s2 ) ; System . out . println ( " Extra ▁ character : ▁ " + extraChar ) ; } }


"Find one extra character in a string | Java program to find extra character in one string ; result store the result ; traverse string A till end and xor with res ; xor with res ; traverse string B till end and xor with res ; xor with res ; print result at the end ; Driver code ; given string"
How can the above be solved in Java?

import java . io . * ; class GFG { static char findExtraCharcter ( String strA , String strB ) { int res = 0 , i ; for ( i = 0 ; i < strA . length ( ) ; i ++ ) { res ^= strA . charAt ( i ) ; } for ( i = 0 ; i < strB . length ( ) ; i ++ ) { res ^= strB . charAt ( i ) ; } return ( ( char ) ( res ) ) ; } public static void main ( String args [ ] ) { String strA = " abcd " ; String strB = " cbdad " ; System . out . println ( findExtraCharcter ( strA , strB ) ) ; } }


"Find one extra character in a string | Java program to find extra character in one string ; store string values in map ; store second string in map with frequency ; store first string in map with frequency ; if the frequency is 1 then this character is which is added extra ; Driver code ; given string ; find Extra Character"
How can the above be solved in Java?

class GFG { static char findExtraCharcter ( char [ ] strA , char [ ] strB ) { int [ ] m1 = new int [ 256 ] ; for ( int i = 0 ; i < strB . length ; i ++ ) m1 [ strB [ i ] ] ++ ; for ( int i = 0 ; i < strA . length ; i ++ ) m1 [ strA [ i ] ] -- ; for ( int i = 0 ; i < m1 . length ; i ++ ) { if ( m1 [ i ] == 1 ) return ( char ) i ; } return Character . MIN_VALUE ; } public static void main ( String [ ] args ) { String strA = " abcd " ; String strB = " cbdad " ; System . out . println ( findExtraCharcter ( strA . toCharArray ( ) , strB . toCharArray ( ) ) ) ; } }


"Find optimal weights which can be used to weigh all the weights in the range [ 1 , X ] | Java implementation of the approach ; Function to find the optimal weights ; Number of weights required ; Finding the value of required powers of 3 ; Optimal Weights are powers of 3 ; Driver code"
How can the above be solved in Java?

import java . util . * ; public class GFG { static void findWeights ( int X ) { int sum = 0 ; int power = 0 ; int number = 3 ; while ( sum < X ) { sum = number - 1 ; sum /= 2 ; power ++ ; number *= 3 ; } int ans = 1 ; for ( int i = 1 ; i <= power ; i ++ ) { System . out . print ( ans + " ▁ " ) ; ans = ans * 3 ; } } public static void main ( String [ ] args ) { int X = 2 ; findWeights ( X ) ; } }


"Find original numbers from gcd ( ) every pair | Java implementation of the approach ; Utility function to print the contents of an array ; Function to find the required numbers ; Sort array in decreasing order ; Count frequency of each element ; Size of the resultant array ; Store the highest element in the resultant array ; Decrement the frequency of that element ; Compute GCD ; Decrement GCD value by 2 ; reverse array ; Driver code"
How can the above be solved in Java?

import java . util . Arrays ; class GFG { static void printArr ( int arr [ ] , int n ) { for ( int i = 0 ; i < n ; i ++ ) { System . out . print ( arr [ i ] + " ▁ " ) ; } } static void findNumbers ( int arr [ ] , int n ) { Arrays . sort ( arr ) ; reverse ( arr ) ; int freq [ ] = new int [ arr [ 0 ] + 1 ] ; for ( int i = 0 ; i < n ; i ++ ) { freq [ arr [ i ] ] ++ ; } int size = ( int ) Math . sqrt ( n ) ; int brr [ ] = new int [ size ] , x , l = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( freq [ arr [ i ] ] > 0 && l < size ) { brr [ l ] = arr [ i ] ; freq [ brr [ l ] ] -- ; l ++ ; for ( int j = 0 ; j < l ; j ++ ) { if ( i != j ) { x = __gcd ( arr [ i ] , brr [ j ] ) ; freq [ x ] -= 2 ; } } } } printArr ( brr , size ) ; } public static void reverse ( int [ ] input ) { int last = input . length - 1 ; int middle = input . length / 2 ; for ( int i = 0 ; i <= middle ; i ++ ) { int temp = input [ i ] ; input [ i ] = input [ last - i ] ; input [ last - i ] = temp ; } } static int __gcd ( int a , int b ) { if ( b == 0 ) { return a ; } return __gcd ( b , a % b ) ; } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 5 , 5 , 5 , 7 , 10 , 12 , 2 , 2 } ; int n = arr . length ; findNumbers ( arr , n ) ; } }


"Find original sequence from Array containing the sequence merged many times in order | Java program for the above approach ; Function that returns the restored permutation ; Vector to store the result ; Map to mark the elements which are taken in result ; Check if the element is coming first time ; Push in result vector ; Mark it in the map ; Return the answer ; Function to print the result ; Driver Code ; Given Array ; Function Call"
How can the above be solved in Java?

import java . util . * ; class GFG { static Vector < Integer > restore ( int arr [ ] , int N ) { Vector < Integer > result = new Vector < > ( ) ; HashMap < Integer , Integer > mp = new HashMap < Integer , Integer > ( ) ; for ( int i = 0 ; i < N ; i ++ ) { if ( mp . containsKey ( arr [ i ] ) && mp . get ( arr [ i ] ) == 0 ) { result . add ( arr [ i ] ) ; if ( mp . containsKey ( arr [ i ] ) ) { mp . put ( arr [ i ] , mp . get ( arr [ i ] ) + 1 ) ; } else { mp . put ( arr [ i ] , 1 ) ; } } else mp . put ( arr [ i ] , 0 ) ; } return result ; } static void print_result ( Vector < Integer > result ) { for ( int i = 0 ; i < result . size ( ) ; i ++ ) System . out . print ( result . get ( i ) + " ▁ " ) ; } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 13 , 1 , 24 , 13 , 24 , 2 , 2 } ; int N = arr . length ; print_result ( restore ( arr , N ) ) ; } }


"Find original sequence from Array containing the sequence merged many times in order | Java program for the above approach ; Function that returns the restored permutation ; Vector to store the result ; Set to insert unique elements ; Check if the element is coming first time ; Push in result vector ; Function to print the result ; Driver Code ; Given Array ; Function call"
How can the above be solved in Java?

import java . util . * ; class GFG { static Vector < Integer > restore ( int arr [ ] , int N ) { Vector < Integer > result = new Vector < Integer > ( ) ; int count1 = 1 ; HashSet < Integer > s = new HashSet < Integer > ( ) ; for ( int i = 0 ; i < N ; i ++ ) { s . add ( arr [ i ] ) ; if ( s . size ( ) == count1 ) { result . add ( arr [ i ] ) ; count1 ++ ; } } return result ; } static void print_result ( Vector < Integer > result ) { for ( int i = 0 ; i < result . size ( ) ; i ++ ) System . out . print ( result . get ( i ) + " ▁ " ) ; } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 13 , 1 , 24 , 13 , 24 , 2 , 2 } ; int N = arr . length ; print_result ( restore ( arr , N ) ) ; } }


"Find other two sides and angles of a right angle triangle | Java program to print all sides and angles of right angle triangle given one side ; Function to find angle A Angle in front of side a ; applied cosine rule ; convert into degrees ; Function to find angle B Angle in front of side b ; applied cosine rule ; convert into degrees and return ; Function to print all angles of the right angled triangle ; for calculate angle A ; for calculate angle B ; Function to find other two sides of the right angled triangle ; if n is odd ; case of n = 1 handled separately ; case of n = 2 handled separately ; Print angles of the triangle ; Driver Program"
How can the above be solved in Java?

import java . io . * ; class GFG { static double PI = 3.1415926535 ; static double findAnglesA ( double a , double b , double c ) { double A = Math . acos ( ( b * b + c * c - a * a ) / ( 2 * b * c ) ) ; return A * 180 / PI ; } static double findAnglesB ( double a , double b , double c ) { double B = Math . acos ( ( a * a + c * c - b * b ) / ( 2 * a * c ) ) ; return B * 180 / PI ; } static void printAngles ( int a , int b , int c ) { double x = ( double ) a ; double y = ( double ) b ; double z = ( double ) c ; double A = findAnglesA ( x , y , z ) ; double B = findAnglesB ( x , y , z ) ; System . out . println ( " Angles ▁ are ▁ A ▁ = ▁ " + A + " , ▁ B ▁ = ▁ " + B + " , ▁ C ▁ = ▁ " + 90 ) ; } static void printOtherSides ( int n ) { int b = 0 , c = 0 ; if ( ( n & 1 ) > 0 ) { if ( n == 1 ) System . out . println ( - 1 ) ; else { b = ( n * n - 1 ) / 2 ; c = ( n * n + 1 ) / 2 ; System . out . println ( " Side ▁ b ▁ = ▁ " + b + " , ▁ Side ▁ c ▁ = ▁ " + c ) ; } } else { if ( n == 2 ) System . out . println ( - 1 ) ; else { b = n * n / 4 - 1 ; c = n * n / 4 + 1 ; System . out . println ( " Side ▁ b ▁ = ▁ " + b + " , ▁ Side ▁ c ▁ = ▁ " + c ) ; } } printAngles ( n , b , c ) ; } public static void main ( String [ ] args ) { int a = 12 ; printOtherSides ( a ) ; } }


"Find other two sides of a right angle triangle | Java program to print other two sides of right angle triangle given one side ; Finds two sides of a right angle triangle if it they exist . ; if n is odd ; case of n = 1 handled separately ; case of n = 2 handled separately ; Driver code"
How can the above be solved in Java?

class GFG { static void printOtherSides ( int n ) { if ( n % 2 != 0 ) { if ( n == 1 ) System . out . println ( " - 1" ) ; else { int b = ( n * n - 1 ) / 2 ; int c = ( n * n + 1 ) / 2 ; System . out . println ( " b ▁ = ▁ " + b + " , ▁ c ▁ = ▁ " + c ) ; } } else { if ( n == 2 ) System . out . println ( " - 1" ) ; else { int b = n * n / 4 - 1 ; int c = n * n / 4 + 1 ; System . out . println ( " b ▁ = ▁ " + b + " , ▁ c ▁ = ▁ " + c ) ; } } } public static void main ( String [ ] args ) { int a = 3 ; printOtherSides ( a ) ; } }


"Find out the correct position of the ball after shuffling | Java implementation of the above approach ; Function to generate the index of the glass containing the ball ; Change the index ; Change the index ; Print the index ; Driver Code ; Storing all the shuffle operation"
How can the above be solved in Java?

import java . io . * ; class GFG { static int M = 3 ; static int N = 2 ; static void getIndex ( int n , int shuffle [ ] [ ] ) { for ( int i = 0 ; i < 3 ; i ++ ) { if ( shuffle [ i ] [ 0 ] == n ) n = shuffle [ i ] [ 1 ] ; else if ( shuffle [ i ] [ 1 ] == n ) n = shuffle [ i ] [ 0 ] ; } System . out . println ( n ) ; } public static void main ( String [ ] args ) { int n = 3 ; int shuffle [ ] [ ] = { { 3 , 1 } , { 2 , 1 } , { 1 , 2 } } ; getIndex ( n , shuffle ) ; } }


"Find out the prime numbers in the form of A + nB or B + nA | Java implementation of the approach ; Utility function to check whether two numbers is co - prime or not ; Utility function to check whether a number is prime or not ; Corner case ; Check from 2 to sqrt ( n ) ; finding the Prime numbers ; Checking whether given numbers are co - prime or not ; To store the N primes ; If ' possible ' is true ; Printing n numbers of prime ; checking the form of a + nb ; Checking the form of b + na ; If ' possible ' is false return - 1 ; Driver Code"
How can the above be solved in Java?

import java . util . * ; class GFG { static int __gcd ( int a , int b ) { if ( b == 0 ) return a ; return __gcd ( b , a % b ) ; } static boolean coprime ( int a , int b ) { if ( __gcd ( a , b ) == 1 ) return true ; else return false ; } static boolean isPrime ( int n ) { if ( n <= 1 ) return false ; if ( n == 2 n == 3 ) return true ; for ( int i = 2 ; i * i <= n ; i ++ ) if ( n % i == 0 ) return false ; return true ; } static void findNumbers ( int a , int b , int n ) { boolean possible = true ; if ( ! coprime ( a , b ) ) possible = false ; int c1 = 1 ; int c2 = 1 ; int num1 , num2 ; HashSet < Integer > st = new HashSet < Integer > ( ) ; if ( possible ) { while ( ( int ) st . size ( ) != n ) { num1 = a + ( c1 * b ) ; if ( isPrime ( num1 ) ) { st . add ( num1 ) ; } c1 ++ ; num2 = b + ( c2 * a ) ; if ( isPrime ( num2 ) ) { st . add ( num2 ) ; } c2 ++ ; } for ( int i : st ) System . out . print ( i + " ▁ " ) ; } else System . out . print ( " - 1" ) ; } public static void main ( String [ ] args ) { int a = 3 ; int b = 5 ; int n = 4 ; findNumbers ( a , b , n ) ; } }


"Find pair with greatest product in array | Java program to find a pair with product in given array . ; Function to find greatest number that us ; Driver code"
How can the above be solved in Java?

import java . io . * ; class GFG { static int findGreatest ( int [ ] arr , int n ) { int result = - 1 ; for ( int i = 0 ; i < n ; i ++ ) for ( int j = 0 ; j < n - 1 ; j ++ ) for ( int k = j + 1 ; k < n ; k ++ ) if ( arr [ j ] * arr [ k ] == arr [ i ] ) result = Math . max ( result , arr [ i ] ) ; return result ; } static public void main ( String [ ] args ) { int [ ] arr = { 30 , 10 , 9 , 3 , 35 } ; int n = arr . length ; System . out . println ( findGreatest ( arr , n ) ) ; } }


"Find pair with greatest product in array | Java program to find the largest product number ; Function to find greatest number ; Store occurrences of all elements in hash array ; m [ arr [ i ] ] ++ ; Sort the array and traverse all elements from end . ; For every element , check if there is another element which divides it . ; Check if the result value exists in array or not if yes the return arr [ i ] ; To handle the case like arr [ i ] = 4 and arr [ j ] = 2 ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { static int findGreatest ( int arr [ ] , int n ) { Map < Integer , Integer > m = new HashMap < > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( m . containsKey ( arr [ i ] ) ) { m . put ( arr [ i ] , m . get ( arr [ i ] ) + 1 ) ; } else { m . put ( arr [ i ] , m . get ( arr [ i ] ) ) ; } } Arrays . sort ( arr ) ; for ( int i = n - 1 ; i > 1 ; i -- ) { for ( int j = 0 ; j < i && arr [ j ] <= Math . sqrt ( arr [ i ] ) ; j ++ ) { if ( arr [ i ] % arr [ j ] == 0 ) { int result = arr [ i ] / arr [ j ] ; if ( result != arr [ j ] && m . get ( result ) == null || m . get ( result ) > 0 ) { return arr [ i ] ; } else if ( result == arr [ j ] && m . get ( result ) > 1 ) { return arr [ i ] ; } } } } return - 1 ; } public static void main ( String [ ] args ) { int arr [ ] = { 17 , 2 , 1 , 15 , 30 } ; int n = arr . length ; System . out . println ( findGreatest ( arr , n ) ) ; } }


"Find pair with maximum GCD for integers in range 2 to N | Java program to find a pair of integers less than or equal to N such that their GCD is maximum ; Function to find the required pair whose GCD is maximum ; If N is even ; If N is odd ; Driver Code"
How can the above be solved in Java?

 class GFG { static void solve ( int N ) { if ( N % 2 == 0 ) { System . out . print ( N / 2 + " ▁ " + N + "
"); } else { System . out . print ( ( N - 1 ) / 2 + " ▁ " + ( N - 1 ) + "
"); } } public static void main ( String [ ] args ) { int N = 10 ; solve ( N ) ; } }


"Find pair with maximum GCD in an array | JAVA Code for Find pair with maximum GCD in an array ; function to find GCD of pair with max GCD in the array ; Computing highest element ; Array to store the count of divisors i . e . Potential GCDs ; Iterating over every element ; Calculating all the divisors ; Divisor found ; Incrementing count for divisor ; Element / divisor is also a divisor Checking if both divisors are not same ; Checking the highest potential GCD ; If this divisor can divide at least 2 numbers , it is a GCD of at least 1 pair ; Driver program to test above function ; Array in which pair with max GCD is to be found ; Size of array"
How can the above be solved in Java?

class GFG { public static int findMaxGCD ( int arr [ ] , int n ) { int high = 0 ; for ( int i = 0 ; i < n ; i ++ ) high = Math . max ( high , arr [ i ] ) ; int divisors [ ] = new int [ high + 1 ] ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = 1 ; j <= Math . sqrt ( arr [ i ] ) ; j ++ ) { if ( arr [ i ] % j == 0 ) { divisors [ j ] ++ ; if ( j != arr [ i ] / j ) divisors [ arr [ i ] / j ] ++ ; } } } for ( int i = high ; i >= 1 ; i -- ) if ( divisors [ i ] > 1 ) return i ; return 1 ; } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 2 , 4 , 8 , 8 , 12 } ; int n = arr . length ; System . out . println ( findMaxGCD ( arr , n ) ) ; } }


"Find pair with maximum GCD in an array | Java Code to Find pair with maximum GCD in an array ; function to find GCD of pair with max GCD in the array ; Calculating MAX in array ; Maintaining count array ; Variable to store the multiples of a number ; Iterating from MAX to 1 GCD is always between MAX and 1 The first GCD found will be the highest as we are decrementing the potential GCD ; Iterating from current potential GCD till it is less than MAX ; A multiple found ; Incrementing potential GCD by itself To check i , 2 i , 3 i ... . ; 2 multiples found , max GCD found ; Driver program to test above function ; Array in which pair with max GCD is to be found ; Size of array"
How can the above be solved in Java?

class GFG { public static int findMaxGCD ( int arr [ ] , int n ) { int high = 0 ; for ( int i = 0 ; i < n ; i ++ ) high = Math . max ( high , arr [ i ] ) ; int count [ ] = new int [ high + 1 ] ; for ( int i = 0 ; i < n ; i ++ ) count [ arr [ i ] ] ++ ; int counter = 0 ; for ( int i = high ; i >= 1 ; i -- ) { int j = i ; while ( j <= high ) { if ( count [ j ] > 0 ) counter += count [ j ] ; j += i ; if ( counter == 2 ) return i ; } counter = 0 ; } return 1 ; } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 2 , 4 , 8 , 8 , 12 } ; int n = arr . length ; System . out . println ( findMaxGCD ( arr , n ) ) ; } }


"Find pair with maximum difference in any column of a Matrix | Java program to find column with max difference of any pair of elements ; Function to find the column with max difference ; Traverse matrix column wise ; Insert elements of column to vector ; calculating difference between maximum and minimum ; Driver Code"
How can the above be solved in Java?

public class GOC1 { static int colMaxDiff ( int mat [ ] [ ] ) { int max_diff = Integer . MIN_VALUE ; for ( int i = 0 ; i < N ; i ++ ) { int max_val = mat [ 0 ] [ i ] , min_val = mat [ 0 ] [ i ] ; for ( int j = 1 ; j < N ; j ++ ) { max_val = Math . max ( max_val , mat [ j ] [ i ] ) ; min_val = Math . min ( min_val , mat [ j ] [ i ] ) ; } max_diff = Math . max ( max_diff , max_val - min_val ) ; } return max_diff ; } public static void main ( String args [ ] ) { int mat [ ] [ ] = { { 1 , 2 , 3 , 4 , 5 } , { 5 , 3 , 5 , 4 , 0 } , { 5 , 6 , 7 , 8 , 9 } , { 0 , 6 , 3 , 4 , 12 } , { 9 , 7 , 12 , 4 , 3 } , } ; System . out . println ( " Max ▁ difference ▁ : ▁ " + colMaxDiff ( mat ) ) ; } }


"Find pair with maximum ratio in an Array | Java implementation to find the maximum pair in the array ; Function to find the maximum pair possible for the array ; Loop to iterate over every possible pair in the array ; Check pair ( x , y ) as well as ( y , x ) for maximum value ; Update the answer ; Driver code"
How can the above be solved in Java?

import java . io . * ; import java . util . * ; class GFG { static float computeMaxValue ( float arr [ ] , int n ) { float ans = 0 ; for ( int i = 0 ; i < n - 1 ; i ++ ) { for ( int j = i + 1 ; j < n ; j ++ ) { float val = Math . max ( arr [ i ] / arr [ j ] , arr [ j ] / arr [ i ] ) ; ans = Math . max ( ans , val ) ; } } return ans ; } public static void main ( String [ ] args ) { float arr [ ] = { 15 , 10 , 3 , 2 } ; int N = arr . length ; System . out . println ( computeMaxValue ( arr , N ) ) ; } }


"Find pairs in array whose sum does not exist in Array | Java program to implement the above approach ; Function to print all pairs with sum not present in the array ; Corner Case ; Stores the distinct array elements ; Generate all possible pairs ; Calculate sum of current pair ; Check if the sum exists in the HashSet or not ; Driver Code"
How can the above be solved in Java?

import java . util . * ; class GFG { public static void findPair ( int [ ] arr , int n ) { int i , j ; if ( n < 2 ) { System . out . println ( " - 1" ) ; } HashSet < Integer > hashMap = new HashSet < Integer > ( ) ; for ( Integer k : arr ) { hashMap . add ( k ) ; } for ( i = 0 ; i < n - 1 ; i ++ ) { for ( j = i + 1 ; j < n ; j ++ ) { int sum = arr [ i ] + arr [ j ] ; if ( ! hashMap . contains ( sum ) ) { System . out . println ( " ( " + arr [ i ] + " , ▁ " + arr [ j ] + " ) " ) ; } } } } public static void main ( String [ ] args ) { int [ ] arr = { 2 , 4 , 2 , 6 } ; int n = arr . length ; findPair ( arr , n ) ; } }


"Find pairs in array whose sums already exist in array | A simple Java program to find pair whose sum already exists in array ; Function to find pair whose sum exists in arr [ ] ; Driver code"
How can the above be solved in Java?

import java . io . * ; public class GFG { static void findPair ( int [ ] arr , int n ) { boolean found = false ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = i + 1 ; j < n ; j ++ ) { for ( int k = 0 ; k < n ; k ++ ) { if ( arr [ i ] + arr [ j ] == arr [ k ] ) { System . out . println ( arr [ i ] + " ▁ " + arr [ j ] ) ; found = true ; } } } } if ( found == false ) System . out . println ( " Not ▁ exist " ) ; } static public void main ( String [ ] args ) { int [ ] arr = { 10 , 4 , 8 , 13 , 5 } ; int n = arr . length ; findPair ( arr , n ) ; } }


"Find pairs with given sum in doubly linked list | Java program to find a pair with given sum x . ; structure of node of doubly linked list ; Function to find pair whose sum equal to given value x . ; Set two pointers , first to the beginning of DLL and second to the end of DLL . ; To track if we find a pair or not ; The loop terminates when they cross each other ( second . next == first ) , or they become same ( first == second ) ; pair found ; move first in forward direction ; move second in backward direction ; if pair is not present ; A utility function to insert a new node at the beginning of doubly linked list ; Driver Code"
How can the above be solved in Java?

class GFG { static class Node { int data ; Node next , prev ; } ; static void pairSum ( Node head , int x ) { Node first = head ; Node second = head ; while ( second . next != null ) second = second . next ; boolean found = false ; while ( first != second && second . next != first ) { if ( ( first . data + second . data ) == x ) { found = true ; System . out . println ( " ( " + first . data + " , ▁ " + second . data + " ) " ) ; first = first . next ; second = second . prev ; } else { if ( ( first . data + second . data ) < x ) first = first . next ; else second = second . prev ; } } if ( found == false ) System . out . println ( " No ▁ pair ▁ found " ) ; } static Node insert ( Node head , int data ) { Node temp = new Node ( ) ; temp . data = data ; temp . next = temp . prev = null ; if ( head == null ) ( head ) = temp ; else { temp . next = head ; ( head ) . prev = temp ; ( head ) = temp ; } return temp ; } public static void main ( String args [ ] ) { Node head = null ; head = insert ( head , 9 ) ; head = insert ( head , 8 ) ; head = insert ( head , 6 ) ; head = insert ( head , 5 ) ; head = insert ( head , 4 ) ; head = insert ( head , 2 ) ; head = insert ( head , 1 ) ; int x = 7 ; pairSum ( head , x ) ; } }


"Find pairs with given sum such that pair elements lie in different BSTs | Java program to find pairs with given sum such that one element of pair exists in one BST and other in other BST . ; A binary Tree node ; A utility function to create a new BST node with key as given num ; A utility function to insert a given key to BST ; store storeInorder traversal in auxiliary array ; Function to find pair for given sum in different bst vect1 . get ( ) - . stores storeInorder traversal of first bst vect2 . get ( ) - . stores storeInorder traversal of second bst ; Initialize two indexes to two different corners of two Vectors . ; find pair by moving two corners . ; If we found a pair ; If sum is more , move to higher value in first Vector . ; If sum is less , move to lower value in second Vector . ; Prints all pairs with given " sum " such that one element of pair is in tree with root1 and other node is in tree with root2 . ; Store inorder traversals of two BSTs in two Vectors . ; Now the problem reduces to finding a pair with given sum such that one element is in vect1 and other is in vect2 . ; Driver program to run the case ; first BST ; second BST"
How can the above be solved in Java?

import java . util . * ; class solution { static class Node { int data ; Node left , right ; } ; static Node newNode ( int num ) { Node temp = new Node ( ) ; temp . data = num ; temp . left = temp . right = null ; return temp ; } static Node insert ( Node root , int key ) { if ( root == null ) return newNode ( key ) ; if ( root . data > key ) root . left = insert ( root . left , key ) ; else root . right = insert ( root . right , key ) ; return root ; } static void storeInorder ( Node ptr , Vector < Integer > vect ) { if ( ptr == null ) return ; storeInorder ( ptr . left , vect ) ; vect . add ( ptr . data ) ; storeInorder ( ptr . right , vect ) ; } static void pairSumUtil ( Vector < Integer > vect1 , Vector < Integer > vect2 , int sum ) { int left = 0 ; int right = vect2 . size ( ) - 1 ; while ( left < vect1 . size ( ) && right >= 0 ) { if ( vect1 . get ( left ) + vect2 . get ( right ) == sum ) { System . out . print ( " ( " + vect1 . get ( left ) + " , ▁ " + vect2 . get ( right ) + " ) , ▁ " ) ; left ++ ; right -- ; } else if ( vect1 . get ( left ) + vect2 . get ( right ) < sum ) left ++ ; else right -- ; } } static void pairSum ( Node root1 , Node root2 , int sum ) { Vector < Integer > vect1 = new Vector < Integer > ( ) , vect2 = new Vector < Integer > ( ) ; storeInorder ( root1 , vect1 ) ; storeInorder ( root2 , vect2 ) ; pairSumUtil ( vect1 , vect2 , sum ) ; } public static void main ( String args [ ] ) { Node root1 = null ; root1 = insert ( root1 , 8 ) ; root1 = insert ( root1 , 10 ) ; root1 = insert ( root1 , 3 ) ; root1 = insert ( root1 , 6 ) ; root1 = insert ( root1 , 1 ) ; root1 = insert ( root1 , 5 ) ; root1 = insert ( root1 , 7 ) ; root1 = insert ( root1 , 14 ) ; root1 = insert ( root1 , 13 ) ; Node root2 = null ; root2 = insert ( root2 , 5 ) ; root2 = insert ( root2 , 18 ) ; root2 = insert ( root2 , 2 ) ; root2 = insert ( root2 , 1 ) ; root2 = insert ( root2 , 3 ) ; root2 = insert ( root2 , 4 ) ; int sum = 10 ; pairSum ( root1 , root2 , sum ) ; } }


"Find parent of given node in a Binary Tree with given postorder traversal | Java implementation to find the parent of the given node K in a binary tree whose post - order traversal is N natural numbers ; Function to find the parent of the given node ; Condition to check whether the given node is a root node . if it is then return - 1 because root node has no parent ; Loop till we found the given node ; Finding the middle node of the tree because at every level tree parent is divided into two halves ; if the node is found return the parent always the child nodes of every node is node 2 or ( node - 1 ) ; if the node to be found is greater than the mid search for left subtree else search in right subtree ; Driver Code"
How can the above be solved in Java?

import java . util . * ; class GFG { static int findParent ( int height , int node ) { int start = 1 ; int end = ( int ) Math . pow ( 2 , height ) - 1 ; if ( end == node ) return - 1 ; while ( node >= 1 ) { end = end - 1 ; int mid = start + ( end - start ) / 2 ; if ( mid == node end == node ) { return ( end + 1 ) ; } else if ( node < mid ) { end = mid ; } else { start = mid ; } } return - 1 ; } public static void main ( String [ ] args ) { int height = 4 ; int node = 6 ; int k = findParent ( height , node ) ; System . out . print ( k ) ; } }


"Find perimeter of shapes formed with 1 s in binary matrix | Java program to find perimeter of area coverede by 1 in 2D matrix consisits of 0 ' s ▁ and ▁ 1' s ; Find the number of covered side for mat [ i ] [ j ] . ; UP ; LEFT ; DOWN ; RIGHT ; Returns sum of perimeter of shapes formed with 1 s ; Traversing the matrix and finding ones to calculate their contribution . ; Driver code"
How can the above be solved in Java?

class GFG { static final int R = 3 ; static final int C = 5 ; static int numofneighbour ( int mat [ ] [ ] , int i , int j ) { int count = 0 ; if ( i > 0 && mat [ i - 1 ] [ j ] == 1 ) count ++ ; if ( j > 0 && mat [ i ] [ j - 1 ] == 1 ) count ++ ; if ( i < R - 1 && mat [ i + 1 ] [ j ] == 1 ) count ++ ; if ( j < C - 1 && mat [ i ] [ j + 1 ] == 1 ) count ++ ; return count ; } static int findperimeter ( int mat [ ] [ ] ) { int perimeter = 0 ; for ( int i = 0 ; i < R ; i ++ ) for ( int j = 0 ; j < C ; j ++ ) if ( mat [ i ] [ j ] == 1 ) perimeter += ( 4 - numofneighbour ( mat , i , j ) ) ; return perimeter ; } public static void main ( String [ ] args ) { int mat [ ] [ ] = { { 0 , 1 , 0 , 0 , 0 } , { 1 , 1 , 1 , 0 , 0 } , { 1 , 0 , 0 , 0 , 0 } } ; System . out . println ( findperimeter ( mat ) ) ; } }


"Find permutation of [ 1 , N ] such that ( arr [ i ] != i + 1 ) and sum of absolute difference between arr [ i ] and ( i + 1 ) is minimum | Function to generate the permutation of the first N natural numbers having sum of absolute difference between element and indices as minimum ; Initialize array arr [ ] from 1 to N ; Swap alternate positions ; Check N is greater than 1 and N is odd ; Swapping last two positions ; Print the permutation ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { static void findPermutation ( int N ) { int [ ] arr = new int [ N ] ; int temp ; for ( int i = 0 ; i < N ; i ++ ) { arr [ i ] = i + 1 ; } for ( int i = 1 ; i < N ; i += 2 ) { temp = arr [ i ] ; arr [ i ] = arr [ i - 1 ] ; arr [ i - 1 ] = temp ; } if ( N % 2 == 1 && N > 1 ) { temp = arr [ N - 1 ] ; arr [ N - 1 ] = arr [ N - 2 ] ; arr [ N - 2 ] = temp ; } for ( int i = 0 ; i < N ; i ++ ) { System . out . print ( arr [ i ] + " ▁ " ) ; } } public static void main ( String [ ] args ) { int N = 7 ; findPermutation ( N ) ; } }


"Find permutation of first N natural numbers that satisfies the given condition | Java implementation of the approach ; Function to find permutation ( p ) of first N natural numbers such that there are exactly K elements of permutation such that GCD ( p [ i ] , i ) > 1 ; First place all the numbers in their respective places ; Modify for first n - k integers ; In first index place n - k ; Print the permutation ; Driver code"
How can the above be solved in Java?

class GFG { static void Permutation ( int n , int k ) { int [ ] p = new int [ n + 1 ] ; for ( int i = 1 ; i <= n ; i ++ ) p [ i ] = i ; for ( int i = 1 ; i < n - k ; i ++ ) p [ i + 1 ] = i ; p [ 1 ] = n - k ; for ( int i = 1 ; i <= n ; i ++ ) System . out . print ( p [ i ] + " ▁ " ) ; } public static void main ( String [ ] args ) { int n = 5 , k = 2 ; Permutation ( n , k ) ; } }


"Find permutation of n which is divisible by 3 but not divisible by 6 | Java program to find permutation of n which is divisible by 3 but not divisible by 6 ; Function to find the permutation ; length of integer ; if integer is even ; return odd integer ; rotate integer ; return - 1 in case no required permutation exists ; Driver Code"
How can the above be solved in Java?

import java . lang . * ; import java . util . * ; class GFG { static int findPermutation ( int n ) { int len = ( int ) Math . ceil ( Math . log10 ( n ) ) ; for ( int i = 0 ; i < len ; i ++ ) { if ( n % 2 != 0 ) { return n ; } else { n = ( n / 10 ) + ( n % 10 ) * ( int ) Math . pow ( 10 , len - i - 1 ) ; continue ; } } return - 1 ; } public static void main ( String args [ ] ) { int n = 132 ; System . out . println ( findPermutation ( n ) ) ; } }


"Find permutation of numbers upto N with a specific sum in a specific range | Java program for the above approach ; Function to check if sum is possible with remaining numbers ; Stores the minimum sum possible with x numbers ; Stores the maximum sum possible with x numbers ; If S lies in the range [ minSum , maxSum ] ; Function to find the resultant permutation ; Stores the count of numbers in the given segment ; If the sum is not possible with numbers in the segment ; Output - 1 ; Stores the numbers present within the given segment ; Iterate over the numbers from 1 to N ; If ( S - i ) is a positive non - zero sum and if it is possible to obtain ( S - i ) remaining numbers ; Update sum S ; Update required numbers in the segement ; Push i in vector v ; If sum has been obtained ; Break from the loop ; If sum is not obtained ; Output - 1 ; Stores the numbers which are not present in given segment ; Loop to check the numbers not present in the segment ; Pointer to check if i is present in vector v or not ; If i is not present in v ; Push i in vector v1 ; Point to the first elements of v1 and v respectively ; Print the required permutation ; Driver Code"
How can the above be solved in Java?

import java . util . ArrayList ; class GFG { public static boolean possible ( int x , int S , int N ) { int minSum = ( x * ( x + 1 ) ) / 2 ; int maxSum = ( x * ( ( 2 * N ) - x + 1 ) ) / 2 ; if ( S < minSum S > maxSum ) { return false ; } return true ; } public static void findPermutation ( int N , int L , int R , int S ) { int x = R - L + 1 ; if ( ! possible ( x , S , N ) ) { System . out . print ( - 1 ) ; return ; } else { ArrayList < Integer > v = new ArrayList < > ( ) ; for ( int i = N ; i >= 1 ; -- i ) { if ( ( S - i ) >= 0 && possible ( x - 1 , S - i , i - 1 ) ) { S = S - i ; x -- ; v . add ( i ) ; } if ( S == 0 ) { break ; } } if ( S != 0 ) { System . out . print ( - 1 ) ; return ; } ArrayList < Integer > v1 = new ArrayList < Integer > ( ) ; for ( int i = 1 ; i <= N ; ++ i ) { boolean it = v . contains ( i ) ; if ( ! it ) { v1 . add ( i ) ; } } int j = 0 , f = 0 ; for ( int i = 1 ; i < L ; ++ i ) { System . out . print ( v1 . get ( j ) + " ▁ " ) ; j ++ ; } for ( int i = L ; i <= R ; ++ i ) { System . out . print ( v . get ( f ) + " ▁ " ) ; f ++ ; } for ( int i = R + 1 ; i <= N ; ++ i ) { System . out . print ( v1 . get ( j ) + " ▁ " ) ; j ++ ; } } return ; } public static void main ( String args [ ] ) { int N + C3 : AC3 = 6 , L = 3 , R = 5 , S = 8 ; findPermutation ( N , L , R , S ) ; } }


"Find permutation with maximum remainder Sum | Java implementation of the approach ; Function to find the permutation ; Put n at the first index 1 ; Put all the numbers from 2 to n sequentially ; Driver code ; Display the permutation"
How can the above be solved in Java?

import java . util . * ; class GFG { static int [ ] Findpermutation ( int n ) { int [ ] a = new int [ n + 1 ] ; a [ 1 ] = n ; for ( int i = 2 ; i <= n ; i ++ ) a [ i ] = i - 1 ; return a ; } public static void main ( String [ ] args ) { int n = 8 ; int [ ] v = Findpermutation ( n ) ; for ( int i = 1 ; i <= n ; i ++ ) System . out . print ( v [ i ] + " ▁ " ) ; } }


"Find points at a given distance on a line of given slope | Java program to find the points on a line of slope M at distance L ; Class to represent a co - ordinate point ; Function to print pair of points at distance ' l ' and having a slope ' m ' from the source ; m is the slope of line , and the required Point lies distance l away from the source Point ; Slope is 0 ; If slope is infinite ; Print the first Point ; Print the second Point ; Driver code"
How can the above be solved in Java?

class GFG { static class Point { float x , y ; Point ( ) { x = y = 0 ; } Point ( float a , float b ) { x = a ; y = b ; } } ; static void printPoints ( Point source , float l , int m ) { Point a = new Point ( ) ; Point b = new Point ( ) ; if ( m == 0 ) { a . x = source . x + l ; a . y = source . y ; b . x = source . x - l ; b . y = source . y ; } else if ( Double . isInfinite ( m ) ) { a . x = source . x ; a . y = source . y + l ; b . x = source . x ; b . y = source . y - l ; } else { float dx = ( float ) ( l / Math . sqrt ( 1 + ( m * m ) ) ) ; float dy = m * dx ; a . x = source . x + dx ; a . y = source . y + dy ; b . x = source . x - dx ; b . y = source . y - dy ; } System . out . println ( a . x + " , ▁ " + a . y ) ; System . out . println ( b . x + " , ▁ " + b . y ) ; } public static void main ( String [ ] args ) { Point p = new Point ( 2 , 1 ) , q = new Point ( 1 , 0 ) ; printPoints ( p , ( float ) Math . sqrt ( 2 ) , 1 ) ; System . out . println ( ) ; printPoints ( q , 5 , 0 ) ; } }


"Find position i to split Array such that prefix sum till i | Java program for the above approach ; Function to check if there is an element forming G . P . series having common ratio k ; If size of array is less than three then return - 1 ; Initialize the variables ; Calculate total sum of array ; Calculate Middle element of G . P . series ; Iterate over the range ; Store the first element of G . P . series in the variable temp ; Return position of middle element of the G . P . series if the first element is in G . P . of common ratio k ; Else return 0 ; if middle element is not found in arr [ ] ; Driver Code ; Given array"
How can the above be solved in Java?

import java . io . * ; class GFG { static int checkArray ( int arr [ ] , int N , int k ) { if ( N < 3 ) return - 1 ; int i , Sum = 0 , temp = 0 ; for ( i = 0 ; i < N ; i ++ ) Sum += arr [ i ] ; int R = ( k * k + k + 1 ) ; if ( Sum % R != 0 ) return 0 ; int Mid = k * ( Sum / R ) ; for ( i = 1 ; i < N - 1 ; i ++ ) { temp += arr [ i - 1 ] ; if ( arr [ i ] == Mid ) { if ( temp == Mid / k ) return i + 1 ; else return 0 ; } } return 0 ; } public static void main ( String [ ] args ) { int arr [ ] = { 5 , 1 , 4 , 20 , 6 , 15 , 9 , 10 } ; int N = arr . length ; int K = 2 ; System . out . println ( checkArray ( arr , N , K ) ) ; } }


"Find position of an element in a sorted array of infinite numbers | Java program to demonstrate working of an algorithm that finds an element in an array of infinite size ; Simple binary search algorithm ; Method takes an infinite size array and a key to be searched and returns its position if found else - 1. We don 't know size of arr[] and we can assume size to be  infinite in this function.  NOTE THAT THIS FUNCTION ASSUMES arr[] TO BE OF INFINITE SIZE  THEREFORE, THERE IS NO INDEX OUT OF BOUND CHECKING ; Find h to do binary search ; store previous high ; check that 2 * h doesn 't exceeds array  length to prevent ArrayOutOfBoundException ; update new val ; at this point we have updated low and high indices , thus use binary search between them ; Driver method to test the above function"
How can the above be solved in Java?

class Test { static int binarySearch ( int arr [ ] , int l , int r , int x ) { if ( r >= l ) { int mid = l + ( r - l ) / 2 ; if ( arr [ mid ] == x ) return mid ; if ( arr [ mid ] > x ) return binarySearch ( arr , l , mid - 1 , x ) ; return binarySearch ( arr , mid + 1 , r , x ) ; } return - 1 ; } static int findPos ( int arr [ ] , int key ) { int l = 0 , h = 1 ; int val = arr [ 0 ] ; while ( val < key ) { l = h ; if ( 2 * h < arr . length - 1 ) h = 2 * h ; else h = arr . length - 1 ; val = arr [ h ] ; } return binarySearch ( arr , l , h , key ) ; } public static void main ( String [ ] args ) { int arr [ ] = new int [ ] { 3 , 5 , 7 , 9 , 10 , 90 , 100 , 130 , 140 , 160 , 170 } ; int ans = findPos ( arr , 10 ) ; if ( ans == - 1 ) System . out . println ( " Element ▁ not ▁ found " ) ; else System . out . println ( " Element ▁ found ▁ at ▁ index ▁ " + ans ) ; } }


"Find position of given term in a series formed with only digits 4 and 7 allowed | Java program for the above approach ; Function to find the position of the number N ; To store the position of N ; Iterate through all digit of N ; If current digit is 7 ; If current digit is 4 ; Print the final position ; Driver Code ; Given number of the series ; Function Call"
How can the above be solved in Java?

import java . util . * ; class GFG { static void findPosition ( int n ) { int i = 0 ; int pos = 0 ; while ( n > 0 ) { if ( n % 10 == 7 ) { pos = pos + ( int ) Math . pow ( 2 , i + 1 ) ; } else { pos = pos + ( int ) Math . pow ( 2 , i ) ; } i ++ ; n = n / 10 ; } System . out . print ( pos ) ; } public static void main ( String [ ] args ) { int N = 777 ; findPosition ( N ) ; } }


"Find position of left most dis | Java program to find the leftmost position of first dis - similar bit ; Function to find first dis - similar bit ; return zero for equal number ; count bit length of n1 and n2 ; find bit difference and maxBit ; Driver Code"
How can the above be solved in Java?

import java . io . * ; class GFG { static int bitPos ( int n1 , int n2 ) { if ( n1 == n2 ) return 0 ; int bitCount1 = ( int ) Math . floor ( Math . log ( n1 ) / Math . log ( 2 ) ) + 1 ; int bitCount2 = ( int ) Math . floor ( Math . log ( n2 ) / Math . log ( 2 ) ) + 1 ; int bitDiff = Math . abs ( bitCount1 - bitCount2 ) ; int maxBitCount = Math . max ( bitCount1 , bitCount2 ) ; if ( bitCount1 > bitCount2 ) { n2 = n2 * ( int ) Math . pow ( 2 , bitDiff ) ; } else { n1 = n1 * ( int ) Math . pow ( 2 , bitDiff ) ; } int xorValue = n1 ^ n2 ; int bitCountXorValue = ( int ) Math . floor ( Math . log ( xorValue ) / Math . log ( 2 ) ) + 1 ; int disSimilarBitPosition = maxBitCount - bitCountXorValue + 1 ; return disSimilarBitPosition ; } public static void main ( String [ ] args ) { int n1 = 53 , n2 = 55 ; System . out . println ( bitPos ( n1 , n2 ) ) ; } }


"Find position of non | Java implementation to find count of placing non - attacking rooks on the N x N chessboard ; Function to find the count of placing non - attacking rooks on the N x N chessboard ; Count of the Non - attacking rooks ; Printing lexographically smallest configuration ; Driver Code ; Function Call"
How can the above be solved in Java?

import java . util . Scanner ; public class P2Placerooks { static void findCountRooks ( int row [ ] , int col [ ] , int n , int k ) { int res = n - k ; System . out . println ( res + " ▁ " ) ; int ri = 0 , ci = 0 ; while ( res -- > 0 ) { while ( ri < k && row [ ri ] == 1 ) { ri ++ ; } while ( ci < k && col [ ci ] == 1 ) { ci ++ ; } System . out . println ( ( ri + 1 ) + " ▁ " + ( ci + 1 ) + " ▁ " ) ; ri ++ ; ci ++ ; } } public static void main ( String [ ] args ) { int n = 4 ; int k = 2 ; int row [ ] = { 1 , 2 } ; int col [ ] = { 4 , 2 } ; findCountRooks ( row , col , n , k ) ; } }


"Find position of the only set bit | Java program to find position of only set bit in a given number ; A utility function to check whether n is a power of 2 or not . goo . gl / 17 Arj See http : ; Returns position of the only set bit in ' n ' ; Iterate through bits of n till we find a set bit i & n will be non - zero only when ' i ' and ' n ' have a set bit at same position ; Unset current bit and set the next bit in ' i ' ; increment position ; Driver code"
How can the above be solved in Java?

class GFG { static boolean isPowerOfTwo ( int n ) { return ( n > 0 && ( ( n & ( n - 1 ) ) == 0 ) ) ? true : false ; } static int findPosition ( int n ) { if ( ! isPowerOfTwo ( n ) ) return - 1 ; int i = 1 , pos = 1 ; while ( ( i & n ) == 0 ) { i = i << 1 ; ++ pos ; } return pos ; } public static void main ( String [ ] args ) { int n = 16 ; int pos = findPosition ( n ) ; if ( pos == - 1 ) System . out . println ( " n ▁ = ▁ " + n + " , ▁ Invalid ▁ number " ) ; else System . out . println ( " n ▁ = ▁ " + n + " , ▁ Position ▁ " + pos ) ; n = 12 ; pos = findPosition ( n ) ; if ( pos == - 1 ) System . out . println ( " n ▁ = ▁ " + n + " , ▁ Invalid ▁ number " ) ; else System . out . println ( " n ▁ = ▁ " + n + " , ▁ Position ▁ " + pos ) ; n = 128 ; pos = findPosition ( n ) ; if ( pos == - 1 ) System . out . println ( " n ▁ = ▁ " + n + " , ▁ Invalid ▁ number " ) ; else System . out . println ( " n ▁ = ▁ " + n + " , ▁ Position ▁ " + pos ) ; } }


"Find position of the only set bit | Java program to find position of only set bit in a given number ; A utility function to check whether n is power of 2 or not ; Returns position of the only set bit in ' n ' ; One by one move the only set bit to right till it reaches end ; increment count of shifts ; Driver code"
How can the above be solved in Java?

class GFG { static boolean isPowerOfTwo ( int n ) { return n > 0 && ( ( n & ( n - 1 ) ) == 0 ) ; } static int findPosition ( int n ) { if ( ! isPowerOfTwo ( n ) ) return - 1 ; int count = 0 ; while ( n > 0 ) { n = n >> 1 ; ++ count ; } return count ; } public static void main ( String [ ] args ) { int n = 0 ; int pos = findPosition ( n ) ; if ( pos == - 1 ) System . out . println ( " n ▁ = ▁ " + n + " , ▁ Invalid ▁ number " ) ; else System . out . println ( " n ▁ = ▁ " + n + " , ▁ Position ▁ " + pos ) ; n = 12 ; pos = findPosition ( n ) ; if ( pos == - 1 ) System . out . println ( " n ▁ = ▁ " + n + " , ▁ Invalid ▁ number " ) ; else System . out . println ( " n ▁ = ▁ " + n + " , ▁ Position ▁ " + pos ) ; n = 128 ; pos = findPosition ( n ) ; if ( pos == - 1 ) System . out . println ( " n ▁ = ▁ " + n + " , ▁ Invalid ▁ number " ) ; else System . out . println ( " n ▁ = ▁ " + n + " , ▁ Position ▁ " + pos ) ; } }


"Find postorder traversal of BST from preorder traversal | Java program for finding postorder traversal of BST from preorder traversal ; Function to find postorder traversal from preorder traversal . ; If entire preorder array is traversed then return as no more element is left to be added to post order array . ; If array element does not lie in range specified , then it is not part of current subtree . ; Store current value , to be printed later , after printing left and right subtrees . Increment preIndex to find left and right subtrees , and pass this updated value to recursive calls . ; All elements with value between minval and val lie in left subtree . ; All elements with value between val and maxval lie in right subtree . ; Function to find postorder traversal . ; To store index of element to be traversed next in preorder array . This is passed by reference to utility function . ; Driver code ; Calling function"
How can the above be solved in Java?

import java . util . * ; class Solution { static class INT { int data ; INT ( int d ) { data = d ; } } static void findPostOrderUtil ( int pre [ ] , int n , int minval , int maxval , INT preIndex ) { if ( preIndex . data == n ) return ; if ( pre [ preIndex . data ] < minval pre [ preIndex . data ] > maxval ) { return ; } int val = pre [ preIndex . data ] ; preIndex . data ++ ; findPostOrderUtil ( pre , n , minval , val , preIndex ) ; findPostOrderUtil ( pre , n , val , maxval , preIndex ) ; System . out . print ( val + " ▁ " ) ; } static void findPostOrder ( int pre [ ] , int n ) { INT preIndex = new INT ( 0 ) ; findPostOrderUtil ( pre , n , Integer . MIN_VALUE , Integer . MAX_VALUE , preIndex ) ; } public static void main ( String args [ ] ) { int pre [ ] = { 40 , 30 , 35 , 80 , 100 } ; int n = pre . length ; findPostOrder ( pre , n ) ; } }


"Find postorder traversal of BST from preorder traversal | run loop from 1 to length of pre ; print from pivot length - 1 to zero ; print from end to pivot length ; Driver Code"
How can the above be solved in Java?

import java . io . * ; class GFG { public void getPostOrderBST ( int pre [ ] ) { int pivotPoint = 0 ; for ( int i = 1 ; i < pre . length ; i ++ ) { if ( pre [ 0 ] <= pre [ i ] ) { pivotPoint = i ; break ; } } for ( int i = pivotPoint - 1 ; i > 0 ; i -- ) { System . out . print ( pre [ i ] + " ▁ " ) ; } for ( int i = pre . length - 1 ; i >= pivotPoint ; i -- ) { System . out . print ( pre [ i ] + " ▁ " ) ; } System . out . print ( pre [ 0 ] ) ; }


"Find prime factors of Array elements whose sum of exponents is divisible by K | Java program for the above approach ; To store the smallest prime factor till 10 ^ 5 ; Function to compute smallest prime factor array ; Initialize the spf array first element ; Marking smallest prime factor for every number to be itself ; Separately marking smallest prime factor for every even number as 2 ; Checking if i is prime ; Marking SPF for all numbers divisible by i ; Marking spf [ j ] if it is not previously marked ; Function that finds minimum operation ; Create a spf [ ] array ; Map created to store the unique prime numbers ; To store the result ; To store minimum operations ; To store every unique prime number ; Erase 1 as a key because it is not a prime number ; First prime number ; Frequency is divisible by K then insert primeNum in the result [ ] ; Print the elements if it exists ; Driver code ; Given array arr [ ] ; Given K ; Function call"
How can the above be solved in Java?

import java . util . * ; class GFG { static int [ ] spf = new int [ 10001 ] ; static void spf_array ( int spf [ ] ) { spf [ 1 ] = 1 ; for ( int i = 2 ; i < 1000 ; i ++ ) spf [ i ] = i ; for ( int i = 4 ; i < 1000 ; i += 2 ) spf [ i ] = 2 ; for ( int i = 3 ; i * i < 1000 ; i ++ ) { if ( spf [ i ] == i ) { for ( int j = i * i ; j < 1000 ; j += i ) if ( spf [ j ] == j ) spf [ j ] = i ; } } } static void frequent_prime ( int arr [ ] , int N , int K ) { spf_array ( spf ) ; Map < Integer , Integer > Hmap = new TreeMap < > ( ) ; ArrayList < Integer > result = new ArrayList < > ( ) ; int i = 0 ; int c = 0 ; for ( i = 0 ; i < N ; i ++ ) { int x = arr [ i ] ; while ( x != 1 ) { Hmap . put ( spf [ x ] , Hmap . getOrDefault ( spf [ x ] , 0 ) + 1 ) ; x = x / spf [ x ] ; } } Hmap . remove ( 1 ) ; for ( Map . Entry < Integer , Integer > x : Hmap . entrySet ( ) ) { int primeNum = x . getKey ( ) ; int frequency = x . getValue ( ) ; if ( frequency % K == 0 ) { result . add ( primeNum ) ; } } if ( result . size ( ) > 0 ) { for ( Integer it : result ) { System . out . print ( it + " ▁ " ) ; } } else { System . out . print ( " { } " ) ; } } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 4 , 6 } ; int K = 1 ; int N = arr . length ; frequent_prime ( arr , N , K ) ; } }


"Find prime factors of Z such that Z is product of all even numbers till N that are product of two distinct prime numbers | Java implementation of the above approach ; Function to print the prime factorization of the product of all numbers <= N that are even and can be expressed as a product of two distinct prime numbers ; Sieve of Eratosthenese ; Store prime numbers in the range [ 3 , N / 2 ] ; Print the coefficient of 2 in the prime factorization ; Print the coefficients of other primes ; Driver Code ; Input ; Function calling"
How can the above be solved in Java?

import java . util . * ; import java . util . HashMap ; class GFG { static void primeFactorization ( int N ) { int [ ] sieve = new int [ N / 2 + 1 ] ; for ( int i = 0 ; i <= N / 2 ; i ++ ) { sieve [ i ] = 0 ; } for ( int i = 2 ; i <= N / 2 ; i ++ ) { if ( sieve [ i ] == 0 ) { for ( int j = i * i ; j <= N / 2 ; j += i ) { sieve [ j ] = 1 ; } } } ArrayList < Integer > prime = new ArrayList < Integer > ( ) ; for ( int i = 3 ; i <= N / 2 ; i ++ ) if ( sieve [ i ] == 0 ) prime . add ( i ) ; int x = prime . size ( ) ; System . out . println ( "2 - > " + x ) ; for ( int i : prime ) System . out . println ( i + " - > 1" ) ; } public static void main ( String args [ ] ) { int N = 18 ; primeFactorization ( N ) ; } }


"Find prime number K in an array such that ( A [ i ] % K ) is maximum | Java implementation of the approach ; Function to return the required prime number from the array ; Find maximum value in the array ; USE SIEVE TO FIND ALL PRIME NUMBERS LESS THAN OR EQUAL TO max_val Create a boolean array " prime [ 0 . . n ] " . A value in prime [ i ] will finally be false if i is Not a prime , else true . ; Remaining part of SIEVE ; If prime [ p ] is not changed , then it is a prime ; Update all multiples of p ; To store the maximum prime number ; If current element is prime then update the maximum prime ; Return the maximum prime number from the array ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { static int getPrime ( int arr [ ] , int n ) { int max_val = Arrays . stream ( arr ) . max ( ) . getAsInt ( ) ; Vector < Boolean > prime = new Vector < > ( max_val + 1 ) ; for ( int i = 0 ; i < max_val + 1 ; i ++ ) prime . add ( i , Boolean . TRUE ) ; prime . add ( 1 , Boolean . FALSE ) ; prime . add ( 2 , Boolean . FALSE ) ; for ( int p = 2 ; p * p <= max_val ; p ++ ) { if ( prime . get ( p ) == true ) { for ( int i = p * 2 ; i <= max_val ; i += p ) prime . add ( i , Boolean . FALSE ) ; } } int maximum = - 1 ; for ( int i = 0 ; i < n ; i ++ ) { if ( prime . get ( arr [ i ] ) ) { maximum = Math . max ( maximum , arr [ i ] ) ; } } return maximum ; } public static void main ( String [ ] args ) { int arr [ ] = { 2 , 10 , 15 , 7 , 6 , 8 , 13 } ; int n = arr . length ; System . out . println ( getPrime ( arr , n ) ) ; } }


"Find prime numbers in the first half and second half of an array | Java program to print the prime numbers in the first half and second half of an array ; Function to check if a number is prime or not ; Function to find whether elements are prime or not ; Traverse in the given range ; Check if a number is prime or not ; Function to print the prime numbers in the first half and second half of an array ; Driver Code ; Function call"
How can the above be solved in Java?

import java . util . * ; class GFG { static boolean prime ( int n ) { for ( int i = 2 ; i * i <= n ; i ++ ) if ( n % i == 0 ) return false ; return true ; } static void prime_range ( int start , int end , int [ ] a ) { for ( int i = start ; i < end ; i ++ ) { if ( prime ( a [ i ] ) ) System . out . print ( a [ i ] + " ▁ " ) ; } } static void Print ( int arr [ ] , int n ) { System . out . print ( " Prime ▁ numbers ▁ in ▁ the ▁ first ▁ half ▁ are ▁ " ) ; prime_range ( 0 , n / 2 , arr ) ; System . out . println ( ) ; System . out . print ( " Prime ▁ numbers ▁ in ▁ the ▁ second ▁ half ▁ are ▁ " ) ; prime_range ( n / 2 , n , arr ) ; System . out . println ( ) ; } public static void main ( String [ ] args ) { int arr [ ] = { 2 , 5 , 10 , 15 , 17 , 21 , 23 } ; int n = arr . length ; Print ( arr , n ) ; } }


"Find probability of selecting element from kth column after N iterations | Java implementation of the above approach ; Function to calculate probability ; declare dp [ ] [ ] and sum [ ] ; precalculate the first row ; calculate the probability for each element and update dp table ; return result ; Driver code"
How can the above be solved in Java?

class GFG { final static int n = 4 ; final static int m = 4 ; static float calcProbability ( int M [ ] [ ] , int k ) { float dp [ ] [ ] = new float [ m ] [ n ] ; float sum [ ] = new float [ n ] ; for ( int j = 0 ; j < n ; j ++ ) { dp [ 0 ] [ j ] = M [ 0 ] [ j ] ; sum [ 0 ] = sum [ 0 ] + dp [ 0 ] [ j ] ; } for ( int i = 1 ; i < m ; i ++ ) { for ( int j = 0 ; j < n ; j ++ ) { dp [ i ] [ j ] += dp [ i - 1 ] [ j ] / sum [ i - 1 ] + M [ i ] [ j ] ; sum [ i ] += dp [ i ] [ j ] ; } } return dp [ n - 1 ] [ k - 1 ] / sum [ n - 1 ] ; } public static void main ( String [ ] args ) { int M [ ] [ ] = { { 1 , 1 , 0 , 3 } , { 2 , 3 , 2 , 3 } , { 9 , 3 , 0 , 2 } , { 2 , 3 , 2 , 2 } } ; int k = 3 ; System . out . println ( calcProbability ( M , k ) ) ; } }


"Find probability that a player wins when probabilities of hitting the target are given | Java implementation of the approach ; Function to return the probability of the winner ; Driver Code ; Will print 9 digits after the decimal point"
How can the above be solved in Java?

import java . util . * ; import java . text . DecimalFormat ; class solution { static double find_probability ( double p , double q , double r , double s ) { double t = ( 1 - p / q ) * ( 1 - r / s ) ; double ans = ( p / q ) / ( 1 - t ) ; return ans ; } public static void main ( String args [ ] ) { double p = 1 , q = 2 , r = 1 , s = 2 ; DecimalFormat dec = new DecimalFormat ( " # 0.000000000" ) ; System . out . println ( dec . format ( find_probability ( p , q , r , s ) ) ) ; } }


"Find product of all elements at indexes which are factors of M for all possible sorted subsequences of length M | Java program to find the product of all the combinations of M elements from an array whose index in the sorted order divides M completely ; Iterative Function to calculate ( x ^ y ) % p in O ( log y ) ; If y is odd , multiply x with result ; y must be even now ; Iterative Function to calculate ( nCr ) % p and save in f [ n ] [ r ] C ( n , r ) % p = [ C ( n - 1 , r - 1 ) % p + C ( n - 1 , r ) % p ] % p and C ( n , 0 ) = C ( n , n ) = 1 ; If j > i then C ( i , j ) = 0 ; If i is equal to j then C ( i , j ) = 1 ; C ( i , j ) = ( C ( i - 1 , j ) + C ( i - 1 , j - 1 ) ) % p ; Initialize the answer ; For every element arr [ i ] , x is count of occurrence of arr [ i ] in different set such that index of arr [ i ] in those sets divides m completely . ; Finding the count of arr [ i ] by placing it at the index which divides m completely ; Using fermat 's little theorem ; Multiplying with the count ; Driver code"
How can the above be solved in Java?

 import java . util . * ; class GFG { static int m = 4 ; static long power ( long x , long y , long p ) { long res = 1 ; x = x % p ; while ( y > 0 ) { if ( y % 2 == 1 ) res = ( res * x ) % p ; y = y >> 1 ; x = ( x * x ) % p ; } return res ; } static void nCr ( int n , long p , int f [ ] [ ] ) { for ( int i = 0 ; i <= n ; i ++ ) { for ( int j = 0 ; j <= m ; j ++ ) { if ( j > i ) f [ i ] [ j ] = 0 ; else if ( j == 0 j == i ) f [ i ] [ j ] = 1 ; else f [ i ] [ j ] = ( f [ i - 1 ] [ j ] + f [ i - 1 ] [ j - 1 ] ) % ( int ) p ; } } } static void operations ( int arr [ ] , int n , int f [ ] [ ] ) { long p = 1000000007 ; nCr ( n , p - 1 , f ) ; Arrays . sort ( arr ) ; long ans = 1 ; for ( int i = 0 ; i < n ; i ++ ) { long x = 0 ; for ( int j = 1 ; j <= m ; j ++ ) { if ( m % j == 0 ) x = ( x + ( f [ n - i - 1 ] [ m - j ] * f [ i ] [ j - 1 ] ) % ( p - 1 ) ) % ( p - 1 ) ; } ans = ( ( ans * power ( arr [ i ] , x , p ) ) % p ) ; } System . out . print ( ans + "
"); } public static void main ( String [ ] args ) { int arr [ ] = { 4 , 5 , 7 , 9 , 3 } ; int n = arr . length ; int [ ] [ ] f = new int [ n + 1 ] [ m + 1 ] ; operations ( arr , n , f ) ; } }


"Find profession in a special family | Java program to find profession of a person at given level and position . ; Function to get no of set bits in binary representation of passed binary no . ; Returns ' e ' if profession of node at given level and position is engineer . Else doctor . The function assumes that given position and level have valid values . ; Count set bits in ' pos - 1' ; If set bit count is odd , then doctor , else engineer ; Driver code"
How can the above be solved in Java?

class GFG { static int countSetBits ( int n ) { int count = 0 ; while ( n != 0 ) { n &= ( n - 1 ) ; count ++ ; } return count ; } static char findProffesion ( int level , int pos ) { int c = countSetBits ( pos - 1 ) ; return ( c % 2 != 0 ) ? ' d ' : ' e ' ; } public static void main ( String [ ] args ) { int level = 3 , pos = 4 ; String prof = ( findProffesion ( level , pos ) == ' e ' ) ? " Engineer " : " Doctor " ; System . out . print ( prof ) ; } }


"Find profession in a special family | Java program to find profession of a person at given level and position ; Returns ' e ' if profession of node at given level and position is engineer . Else doctor . The function assumes that given position and level have valid values . ; Base case ; Recursively find parent 's  profession. If parent  is a Doctor, this node  will be a Doctor if it  is at odd position and an  engineer if at even position ; If parent is an engineer , then current node will be an engineer if at add position and doctor if even position . ; Driver code"
How can the above be solved in Java?

import java . io . * ; class GFG { static char findProffesion ( int level , int pos ) { if ( level == 1 ) return ' e ' ; if ( findProffesion ( level - 1 , ( pos + 1 ) / 2 ) == ' d ' ) return ( pos % 2 > 0 ) ? ' d ' : ' e ' ; return ( pos % 2 > 0 ) ? ' e ' : ' d ' ; } public static void main ( String [ ] args ) { int level = 4 , pos = 2 ; if ( findProffesion ( level , pos ) == ' e ' ) System . out . println ( " Engineer " ) ; else System . out . println ( " Doctor " ) ; } }


"Find range of values for S in given Array with values satisfying [ arr [ i ] = floor ( ( i * S ) / K ) ] | Java program for the above approach ; Function to find the range of values for S in a given array that satisfies the given condition ; Stores the left range value ; Stores the right range value ; Find the current left range value for S ; Find the current right range value for S ; Updating L value ; Updating R value ; Driver Code"
How can the above be solved in Java?

import java . util . * ; import java . lang . * ; class Codechef { static void findRange ( int arr [ ] , int N , int K ) { int L = Integer . MIN_VALUE ; int R = Integer . MAX_VALUE ; for ( int i = 0 ; i < N ; i ++ ) { int l = ( int ) Math . ceil ( 1.0 * arr [ i ] * K / ( i + 1 ) ) ; int r = ( int ) Math . ceil ( ( 1.0 + arr [ i ] ) * K / ( i + 1 ) ) - 1 ; L = Math . max ( L , l ) ; R = Math . min ( R , r ) ; } System . out . println ( L + " ▁ " + R ) ; } public static void main ( String [ ] args ) { int arr [ ] = { 2 , 4 , 6 , 9 , 11 } ; int K = 10 ; int N = arr . length ; findRange ( arr , N , K ) ; } }


"Find relative complement of two sorted arrays | Java program to find all those elements of arr1 [ ] that are not present in arr2 [ ] ; If current element in arr2 [ ] is greater , then arr1 [ i ] can 't be  present in arr2[j..m-1] ; Skipping smaller elements of arr2 [ ] ; Equal elements found ( skipping in both arrays ) ; Printing remaining elements of arr1 [ ] ; Driver code"
How can the above be solved in Java?

class GFG { static void relativeComplement ( int arr1 [ ] , int arr2 [ ] , int n , int m ) { int i = 0 , j = 0 ; while ( i < n && j < m ) { if ( arr1 [ i ] < arr2 [ j ] ) { System . out . print ( arr1 [ i ] + " ▁ " ) ; i ++ ; } else if ( arr1 [ i ] > arr2 [ j ] ) { j ++ ; } else if ( arr1 [ i ] == arr2 [ j ] ) { i ++ ; j ++ ; } } while ( i < n ) System . out . print ( arr1 [ i ] + " ▁ " ) ; } public static void main ( String [ ] args ) { int arr1 [ ] = { 3 , 6 , 10 , 12 , 15 } ; int arr2 [ ] = { 1 , 3 , 5 , 10 , 16 } ; int n = arr1 . length ; int m = arr2 . length ; relativeComplement ( arr1 , arr2 , n , m ) ; } }


"Find relative rank of each element in array | Java program to implement the above approach ; Function to find relative rank for each element in the array A [ ] ; Create Rank Array ; Stack to store numbers in non - decreasing order from right ; Push last element in stack ; Iterate from second last element to first element ; If current element is less than the top of stack and push A [ i ] in stack ; Rank is stack size - 1 for current element ; Pop elements from stack till current element is greater than the top ; Push current element in Stack ; Rank is stack size - 1 ; Print rank of all elements ; Driver Code ; Given array A [ ] ; Function call"
How can the above be solved in Java?

import java . io . * ; import java . util . * ; import java . lang . * ; class GFG { static void findRank ( int [ ] A , int N ) { int [ ] rank = new int [ N ] ; Stack < Integer > s = new Stack < Integer > ( ) ; s . add ( A [ N - 1 ] ) ; for ( int i = N - 2 ; i >= 0 ; i -- ) { if ( A [ i ] < s . peek ( ) ) { s . add ( A [ i ] ) ; rank [ i ] = s . size ( ) - 1 ; } else { while ( ! s . isEmpty ( ) && A [ i ] >= s . peek ( ) ) { s . pop ( ) ; } s . add ( A [ i ] ) ; rank [ i ] = s . size ( ) - 1 ; } } for ( int i = 0 ; i < N ; i ++ ) { System . out . print ( rank [ i ] + " ▁ " ) ; } } public static void main ( String [ ] args ) { int A [ ] = { 1 , 2 , 3 , 5 , 4 } ; int N = A . length ; findRank ( A , N ) ; } }


"Find remainder when a number A raised to N factorial is divided by P | Java program for the above approach ; Function to calculate factorial ; Calculating factorial ; Returning factorial ; Function to calculate resultant remainder ; Function call to calculate factorial of n ; Calculating remainder ; Returning resultant remainder ; Driver Code ; Given Input ; Function Call"
How can the above be solved in Java?

import java . lang . * ; import java . util . * ; class GFG { static int fact ( int n ) { int ans = 1 ; for ( int i = 2 ; i <= n ; i ++ ) ans *= i ; return ans ; } static int remainder ( int n , int a , int p ) { int len = fact ( n ) ; int ans = 1 ; for ( int i = 1 ; i <= len ; i ++ ) ans = ( ans * a ) % p ; return ans ; } public static void main ( String args [ ] ) { int A = 2 , N = 1 , P = 2 ; System . out . println ( remainder ( N , A , P ) ) ; } }