"Divide array into two arrays which does not contain any pair with sum K | Java program for the above approach ; Function to split the given array into two separate arrays satisfying given condition ; Stores resultant arrays ; Traverse the array ; If a [ i ] is smaller than or equal to k / 2 ; Print first array ; Print second array ; Driver Code ; Given K ; Given array ; Given size"
How can the above be solved in Java?

import java . util . * ; class GFG { static void splitArray ( int a [ ] , int n , int k ) { Vector < Integer > first = new Vector < > ( ) ; Vector < Integer > second = new Vector < > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( a [ i ] <= k / 2 ) first . add ( a [ i ] ) ; else second . add ( a [ i ] ) ; } for ( int i = 0 ; i < first . size ( ) ; i ++ ) { System . out . print ( first . get ( i ) + " ▁ " ) ; } System . out . println ( ) ; for ( int i = 0 ; i < second . size ( ) ; i ++ ) { System . out . print ( second . get ( i ) + " ▁ " ) ; } } public static void main ( String [ ] args ) { int k = 5 ; int a [ ] = { 0 , 1 , 3 , 2 , 4 , 5 , 6 , 7 , 8 , 9 , 10 } ; int n = a . length ; splitArray ( a , n , k ) ; } }


"Divide array into two parts with equal sum according to the given constraints | Java implementation of the approach ; Function that checks if the given conditions are satisfied ; To store the prefix sum of the array elements ; Sort the array ; Compute the prefix sum array ; Maximum element in the array ; Variable to check if there exists any number ; Stores the index of the largest number present in the array smaller than i ; Stores the index of the smallest number present in the array greater than i ; Find index of smallest number greater than i ; Find index of smallest number greater than i ; If there exists a number ; If no such number exists print no ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { static void IfExists ( int arr [ ] , int n ) { int sum [ ] = new int [ n ] ; Arrays . sort ( arr ) ; sum [ 0 ] = arr [ 0 ] ; for ( int i = 1 ; i < n ; i ++ ) sum [ i ] = sum [ i - 1 ] + arr [ i ] ; int max = arr [ n - 1 ] ; boolean flag = false ; for ( int i = 1 ; i <= max ; i ++ ) { int findex = 0 ; int lindex = 0 ; int l = 0 ; int r = n - 1 ; while ( l <= r ) { int m = ( l + r ) / 2 ; if ( arr [ m ] < i ) { findex = m ; l = m + 1 ; } else r = m - 1 ; } l = 1 ; r = n ; flag = false ; while ( l <= r ) { int m = ( r + l ) / 2 ; if ( arr [ m ] > i ) { lindex = m ; r = m - 1 ; } else l = m + 1 ; } if ( sum [ findex ] == sum [ n - 1 ] - sum [ lindex - 1 ] ) { flag = true ; break ; } } if ( flag ) System . out . println ( " Yes " ) ; else System . out . println ( " No " ) ; } public static void main ( String args [ ] ) { int arr [ ] = { 1 , 2 , 2 , 5 } ; int n = arr . length ; IfExists ( arr , n ) ; } }


"Divide chocolate bar into pieces , minimizing the area of invalid pieces | Java program for the above approach ; Store valid dimensions ; Stores memoization ; Utility function to calculate minimum invalid area for Chocolate piece having dimension ( l , r ) ; Check whether current piece is valid or not . If it is , then return zero for current dimension ; Making all possible horizontal cuts , one by one and calculating the sum of minimum invalid area for both the resulting pieces ; Making all possible vertical cuts , one by one and calculating the sum of minimum invalid area for both the resulting pieces ; Store the computed result ; Function to calculate minimum invalid area for Chocolate piece having dimension ( l , r ) ; Total number of valid dimensions ; Storing valid dimensions as for every ( x , y ) both ( x , y ) and ( y , x ) are valid ; Fill dp [ ] [ ] table with - 1 , indicating that results are not computed yet ; Stores minimum area ; Print minArea as the output ; Driver Code ; Given N & M ; Given valid dimensions ; Function Call"
How can the above be solved in Java?

import java . io . * ; import java . util . * ; class GFG { static final int sz = 1001 ; static boolean ok [ ] [ ] = new boolean [ sz ] [ sz ] ; static int dp [ ] [ ] = new int [ sz ] [ sz ] ; static class pair { int first , second ; public pair ( int first , int second ) { this . first = first ; this . second = second ; } } static int minInvalidAreaUtil ( int l , int b ) { if ( dp [ l ] [ b ] == - 1 ) { if ( ok [ l ] [ b ] ) { return dp [ l ] [ b ] = 0 ; } int ans = l * b ; for ( int i = 1 ; i < b ; i ++ ) { ans = Math . min ( ans , minInvalidAreaUtil ( l , i ) + minInvalidAreaUtil ( l , b - i ) ) ; } for ( int i = 1 ; i < l ; i ++ ) { ans = Math . min ( ans , minInvalidAreaUtil ( i , b ) + minInvalidAreaUtil ( l - i , b ) ) ; } dp [ l ] [ b ] = ans ; } return dp [ l ] [ b ] ; } static void minInvalidArea ( int N , int M , Vector < pair > dimensions ) { int K = dimensions . size ( ) ; for ( int i = 0 ; i < K ; i ++ ) { ok [ dimensions . elementAt ( i ) . first ] [ dimensions . elementAt ( i ) . second ] = true ; ok [ dimensions . elementAt ( i ) . second ] [ dimensions . elementAt ( i ) . first ] = true ; } for ( int i = 0 ; i < sz ; i ++ ) { for ( int j = 0 ; j < sz ; j ++ ) { dp [ i ] [ j ] = - 1 ; } } int minArea = minInvalidAreaUtil ( N , M ) ; System . out . println ( minArea ) ; } public static void main ( String [ ] args ) { int N = 10 , M = 10 ; Vector < pair > dimensions = new Vector < > ( ) ; dimensions . add ( new pair ( 3 , 5 ) ) ; minInvalidArea ( N , M , dimensions ) ; } }


"Divide every element of one array by other array elements | Java program to find quotient of array elements ; Function to calculate the quotient of every element of the array ; Calculate the product of all elements ; To calculate the quotient of every array element ; Driver code"
How can the above be solved in Java?

import java . io . * ; class GFG { static void calculate ( int a [ ] , int b [ ] , int n , int m ) { int mul = 1 ; for ( int i = 0 ; i < m ; i ++ ) if ( b [ i ] != 0 ) mul = mul * b [ i ] ; for ( int i = 0 ; i < n ; i ++ ) { int x = ( int ) Math . floor ( a [ i ] / mul ) ; System . out . print ( x + " ▁ " ) ; } } public static void main ( String [ ] args ) { int a [ ] = { 5 , 100 , 8 } ; int b [ ] = { 2 , 3 } ; int n = a . length ; int m = b . length ; calculate ( a , b , n , m ) ; } }


"Divide first N natural numbers into 3 equal sum subsets | Java implementation of the approach ; Function that returns true if the subsets are possible ; If n <= 3 then it is not possible to divide the elements in three subsets satisfying the given conditions ; Sum of all the elements in the range [ 1 , n ] ; If the sum is divisible by 3 then it is possible ; Driver code"
How can the above be solved in Java?

import java . math . * ; class GFG { public static boolean possible ( int n ) { if ( n > 3 ) { int sum = ( n * ( n + 1 ) ) / 2 ; if ( sum % 3 == 0 ) { return true ; } } return false ; } public static void main ( String [ ] args ) { int n = 5 ; if ( possible ( n ) ) System . out . println ( " Yes " ) ; else System . out . println ( " No " ) ; } }


"Divide given numeric string into at most two increasing subsequences which form an increasing string upon concatenation | Java program for the above approach ; Function to check for valid subsequences ; Stores which element belongs to which subsequence ; Check for each pos if a possible subsequence exist or not ; Last member of 1 subsequence ; Last Member of 2 nd subsequence ; Check if current element can go to 2 nd subsequence ; Check if the current elements belongs to first subsequence ; If the current element does not belong to any subsequence ; Check if last digit of first subsequence is greater than pos ; If a subsequence is found , find the subsequences ; Stores the resulting subsequences ; Print the subsequence ; If no subsequence found , print - 1 ; Driver Code"
How can the above be solved in Java?

 class GFG { static void findSubsequence ( String str ) { int n = str . length ( ) ; char [ ] res = new char [ n ] ; for ( int i = 0 ; i < n ; i ++ ) res [ i ] = 0 ; for ( int pos = 0 ; pos <= 9 ; pos ++ ) { char lst1 = '0' ; boolean flag = true ; char lst2 = ( char ) ( pos + '0' ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( lst2 <= str . charAt ( i ) ) { res [ i ] = '2' ; lst2 = str . charAt ( i ) ; } else if ( lst1 <= str . charAt ( i ) ) { res [ i ] = '1' ; lst1 = str . charAt ( i ) ; } else flag = false ; } if ( lst1 > pos + '0' ) flag = false ; if ( flag ) { String S1 = " " ; String S2 = " " ; for ( int i = 0 ; i < n ; i ++ ) { if ( res [ i ] == '1' ) { S1 += str . charAt ( i ) ; } else { S2 += str . charAt ( i ) ; } } System . out . print ( S1 + " ▁ " + S2 + "
"); return ; } } System . out . print ( " - 1" ) ; } public static void main ( String [ ] args ) { String S = "040425524644" ; findSubsequence ( S ) ; S = "123456789" ; findSubsequence ( S ) ; } }


"Divide number into two parts divisible by given numbers | Java program to break the number string into two divisible parts by given numbers ; method prints divisible parts if possible , otherwise prints ' Not ▁ possible ' ; creating arrays to store reminder ; looping over all suffix and storing reminder with f ; getting suffix reminder from previous suffix reminder ; looping over all prefix and storing reminder with s ; getting prefix reminder from next prefix reminder ; updating base value ; now looping over all reminders to check partition condition ; if both reminders are 0 and digit itself is not 0 , then print result and return ; if we reach here , then string can ' be  partitioned under constraints ; Driver program"
How can the above be solved in Java?

public class DivisibleParts { static void printTwoDivisibleParts ( String num , int f , int s ) { int N = num . length ( ) ; int [ ] prefixReminder = new int [ N + 1 ] ; int [ ] suffixReminder = new int [ N + 1 ] ; suffixReminder [ 0 ] = 0 ; for ( int i = 1 ; i < N ; i ++ ) suffixReminder [ i ] = ( suffixReminder [ i - 1 ] * 10 + ( num . charAt ( i - 1 ) - '0' ) ) % f ; prefixReminder [ N ] = 0 ; int base = 1 ; for ( int i = N - 1 ; i >= 0 ; i -- ) { prefixReminder [ i ] = ( prefixReminder [ i + 1 ] + ( num . charAt ( i ) - '0' ) * base ) % s ; base = ( base * 10 ) % s ; } for ( int i = 0 ; i < N ; i ++ ) { if ( prefixReminder [ i ] == 0 && suffixReminder [ i ] == 0 && num . charAt ( i ) != '0' ) { System . out . println ( num . substring ( 0 , i ) + " ▁ " + num . substring ( i ) ) ; return ; } } System . out . println ( " Not ▁ Possible " ) ; } public static void main ( String [ ] args ) { String num = "246904096" ; int f = 12345 ; int s = 1024 ; printTwoDivisibleParts ( num , f , s ) ; } }


"Divide the array in K segments such that the sum of minimums is maximized | Java program to find the sum of the minimum of all the segments ; Function to maximize the sum of the minimums ; If k segments have been divided ; If we are at the end ; If we donot reach the end then return a negative number that cannot be the sum ; If at the end but k segments are not formed ; If the state has not been visited yet ; If the state has not been visited ; Get the minimum element in the segment ; Iterate and try to break at every index and create a segment ; Find the minimum element in the segment ; Find the sum of all the segments trying all the possible combinations ; Return the answer by memoizing it ; Driver Code ; Initialize dp array with - 1"
How can the above be solved in Java?

class GFG { static int MAX = 10 ; public static int maximizeSum ( int [ ] a , int n , int ind , int k , int [ ] [ ] dp ) { if ( k == 0 ) { if ( ind == n ) return 0 ; else return - 1000000000 ; } else if ( ind == n ) return - 1000000000 ; else if ( dp [ ind ] [ k ] != - 1 ) return dp [ ind ] [ k ] ; else { int ans = 0 ; int mini = a [ ind ] ; for ( int i = ind ; i < n ; i ++ ) { mini = Math . min ( mini , a [ i ] ) ; ans = Math . max ( ans , maximizeSum ( a , n , i + 1 , k - 1 , dp ) + mini ) ; } return dp [ ind ] [ k ] = ans ; } } public static void main ( String [ ] args ) { int [ ] a = { 5 , 7 , 4 , 2 , 8 , 1 , 6 } ; int k = 3 ; int n = a . length ; int [ ] [ ] dp = new int [ MAX ] [ MAX ] ; for ( int i = 0 ; i < MAX ; i ++ ) { for ( int j = 0 ; j < MAX ; j ++ ) dp [ i ] [ j ] = - 1 ; } System . out . println ( maximizeSum ( a , n , 0 , k , dp ) ) ; } }


"Divide the two given numbers by their common divisors | Java implementation of above approach ; Function to calculate gcd of two numbers ; Function to calculate all common divisors of two given numbers a , b -- > input integer numbers ; find gcd of a , b ; Driver code"
How can the above be solved in Java?

class GFG { static int gcd ( int a , int b ) { if ( a == 0 ) return b ; return gcd ( b % a , a ) ; } static void commDiv ( int a , int b ) { int n = gcd ( a , b ) ; a = a / n ; b = b / n ; System . out . println ( " A ▁ = ▁ " + a + " , ▁ B ▁ = ▁ " + b ) ; } public static void main ( String [ ] args ) { int a = 10 , b = 15 ; commDiv ( a , b ) ; } }


"Divide the two given numbers by their common divisors | Java implementation of above approach ; print the numbers after dividing them by their common factors ; iterate from 1 to minimum of a and b ; if i is the common factor of both the numbers ; Driver code ; divide A and B by their common factors"
How can the above be solved in Java?

import java . util . * ; class solution { static void divide ( int a , int b ) { for ( int i = 2 ; i <= Math . min ( a , b ) ; i ++ ) { while ( a % i == 0 && b % i == 0 ) { a = a / i ; b = b / i ; } } System . out . println ( " A ▁ = ▁ " + a + " , ▁ B ▁ = ▁ " + b ) ; } public static void main ( String args [ ] ) { int A = 10 , B = 15 ; divide ( A , B ) ; } }


"Divide two integers without using multiplication , division and mod operator | Java implementation to Divide two integers without using multiplication , division and mod operator ; Function to divide a by b and return floor value it ; Calculate sign of divisor i . e . , sign will be negative only iff either one of them is negative otherwise it will be positive ; remove sign of operands ; Initialize the quotient ; test down from the highest bit and accumulate the tentative value for valid bit 1 << 31 behaves incorrectly and gives Integer Min Value which should not be the case , instead 1L << 31 works correctly . ; if the sign value computed earlier is - 1 then negate the value of quotient ; Driver code"
How can the above be solved in Java?

import java . io . * ; import java . util . * ; class GFG { public static long divide ( long dividend , long divisor ) { long sign = ( ( dividend < 0 ) ^ ( divisor < 0 ) ) ? - 1 : 1 ; dividend = Math . abs ( dividend ) ; divisor = Math . abs ( divisor ) ; long quotient = 0 , temp = 0 ; for ( int i = 31 ; i >= 0 ; -- i ) { if ( temp + ( divisor << i ) <= dividend ) { temp += divisor << i ; quotient |= 1L << i ; } } if ( sign == - 1 ) quotient = - quotient ; return quotient ; } public static void main ( String args [ ] ) { int a = 10 , b = 3 ; System . out . println ( divide ( a , b ) ) ; int a1 = 43 , b1 = - 8 ; System . out . println ( divide ( a1 , b1 ) ) ; } }


"Divide two integers without using multiplication , division and mod operator | Set2 | Java program for above approach ; Returns the quotient of dividend / divisor . ; Calculate sign of divisor i . e . , sign will be negative only if either one of them is negative otherwise it will be positive ; Remove signs of dividend and divisor ; Zero division Exception . ; Using Formula derived above . ; Driver code"
How can the above be solved in Java?

import java . io . * ; class GFG { static void Divide ( int a , int b ) { long dividend = ( long ) a ; long divisor = ( long ) b ; long sign = ( dividend < 0 ) ^ ( divisor < 0 ) ? - 1 : 1 ; dividend = Math . abs ( dividend ) ; divisor = Math . abs ( divisor ) ; if ( divisor == 0 ) { System . out . println ( " Cannot ▁ Divide ▁ by ▁ 0" ) ; return ; } if ( dividend == 0 ) { System . out . println ( a + " ▁ / ▁ " + b + " ▁ is ▁ equal ▁ to ▁ : ▁ " + 0 ) ; return ; } if ( divisor == 1 ) { System . out . println ( a + " ▁ / ▁ " + b + " ▁ is ▁ equal ▁ to ▁ : ▁ " + sign * dividend ) ; return ; } System . out . println ( a + " ▁ / ▁ " + b + " ▁ is ▁ equal ▁ to ▁ : ▁ " + Math . floor ( sign * ( Math . exp ( Math . log ( dividend ) - Math . log ( divisor ) ) ) ) ) ; } public static void main ( String [ ] args ) { int a = 10 , b = 5 ; Divide ( a , b ) ; a = 49 ; b = - 7 ; Divide ( a , b ) ; } }


"Divisibility by 12 for a large number | Java Program to check if number is divisible by 12 ; if number greater then 3 ; find last digit ; no is odd ; find second last digit ; find sum of all digits ; if number is less then or equal to 100 ; driver function"
How can the above be solved in Java?

import java . io . * ; class GFG { static boolean isDvisibleBy12 ( String num ) { if ( num . length ( ) >= 3 ) { int d1 = ( int ) num . charAt ( num . length ( ) - 1 ) ; if ( d1 % 2 != 0 ) return false ; int d2 = ( int ) num . charAt ( num . length ( ) - 2 ) ; int sum = 0 ; for ( int i = 0 ; i < num . length ( ) ; i ++ ) sum += num . charAt ( i ) ; return ( sum % 3 == 0 && ( d2 * 10 + d1 ) % 4 == 0 ) ; } else { int number = Integer . parseInt ( num ) ; return ( number % 12 == 0 ) ; } } public static void main ( String [ ] args ) { String num = "12244824607284961224" ; if ( isDvisibleBy12 ( num ) ) System . out . print ( " Yes " ) ; else System . out . print ( " No " ) ; } }


"Divisibility by 3 where each digit is the sum of all prefix digits modulo 10 | Java code to check divisibility by 3 ; Function to check the divisibility ; Cycle ; no of residual terms ; sum of residual terms ; if no of residue term = 0 ; if no of residue term = 1 ; if no of residue term = 2 ; if no of residue term = 3 ; sum of all digits ; divisibility check ; Code driven"
How can the above be solved in Java?


"Divisibility by 64 with removal of bits allowed | Java program to find if given binary string can become divisible by 64 after removing some bits ; function to check if it is possible to make it a multiple of 64. ; counter to count 0 's ; length of the string ; loop which traverses right to left and calculates the number of zeros before 1. ; Driver code"
How can the above be solved in Java?

import java . io . * ; class GFG { static boolean checking ( String s ) { int c = 0 ; int n = s . length ( ) ; for ( int i = n - 1 ; i >= 0 ; i -- ) { if ( s . charAt ( i ) == '0' ) c ++ ; if ( c >= 6 && s . charAt ( i ) == '1' ) return true ; } return false ; } public static void main ( String [ ] args ) { String s = "100010001" ; if ( checking ( s ) ) System . out . println ( " Possible " ) ; else System . out . println ( " Not ▁ possible " ) ; } }


"Division without using ' / ' operator | Java program to divide a number by other without using / operator ; Function to find division without using ' / ' operator ; Handling negative numbers ; if num1 is greater than equal to num2 subtract num2 from num1 and increase quotient by one . ; checking if neg equals to 1 then making quotient negative ; Driver program"
How can the above be solved in Java?

import java . io . * ; class GFG { static int division ( int num1 , int num2 ) { if ( num1 == 0 ) return 0 ; if ( num2 == 0 ) return Integer . MAX_VALUE ; boolean negResult = false ; if ( num1 < 0 ) { num1 = - num1 ; if ( num2 < 0 ) num2 = - num2 ; else negResult = true ; } else if ( num2 < 0 ) { num2 = - num2 ; negResult = true ; } int quotient = 0 ; while ( num1 >= num2 ) { num1 = num1 - num2 ; quotient ++ ; } if ( negResult ) quotient = - quotient ; return quotient ; } public static void main ( String [ ] args ) { int num1 = 13 , num2 = 2 ; System . out . println ( division ( num1 , num2 ) ) ; } }


"Divisors of n | Java program to count number of divisors of n ^ 2 which are not divisible by divisor of n ; Function to count divisors of n ^ 2 having no factors of ' n ' ; Increment count of i - th prime divisor ; Find next prime divisor ; Increment count if divisor still remains ; Initialize variable for counting the factors of n ^ 2 and n as ans1 and ans2 respectively ; Range based for - loop ; Use formula as discussed in above ; return the difference of answers ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { static int factors ( int n ) { HashMap < Integer , Integer > prime = new HashMap < Integer , Integer > ( ) ; for ( int i = 2 ; i <= Math . sqrt ( n ) ; ++ i ) { while ( n % i == 0 ) { if ( prime . containsKey ( i ) ) { prime . put ( i , prime . get ( i ) + 1 ) ; } else { prime . put ( i , 1 ) ; } n = n / i ; } } if ( n > 2 ) { if ( prime . containsKey ( n ) ) { prime . put ( n , prime . get ( n ) + 1 ) ; } else { prime . put ( n , 1 ) ; } } int ans1 = 1 , ans2 = 1 ; for ( Map . Entry < Integer , Integer > it : prime . entrySet ( ) ) { ans1 *= 2 * it . getValue ( ) + 1 ; ans2 *= it . getValue ( ) + 1 ; } return ans1 - ans2 ; } public static void main ( String [ ] args ) { int n = 5 ; System . out . println ( factors ( n ) ) ; n = 8 ; System . out . println ( factors ( n ) ) ; } }


"Dodecagonal number | Java program to find the nth Dodecagonal number ; function for Dodecagonal number ; formula for find Dodecagonal nth term ; Driver Code"
How can the above be solved in Java?

import java . util . * ; class GFG { static int Dodecagonal_number ( int n ) { return 5 * n * n - 4 * n ; } public static void main ( String [ ] args ) { int n = 7 ; System . out . println ( Dodecagonal_number ( n ) ) ; n = 12 ; System . out . println ( Dodecagonal_number ( n ) ) ; } }


"Dodecahedral number | Java program to find nth dodecahedral number ; Function to find dodecahedral number ; Formula to calculate nth dodecahedral number and return it into main function . ; Driver Code ; print result"
How can the above be solved in Java?

import java . io . * ; class GFG { static int dodecahedral_num ( int n ) { return n * ( 3 * n - 1 ) * ( 3 * n - 2 ) / 2 ; } public static void main ( String [ ] args ) { int n = 5 ; System . out . print ( n + " the ▁ Dodecahedral " + " ▁ number : " ) ; System . out . println ( dodecahedral_num ( n ) ) ; } }


"Domino and Tromino tiling problem | Java program for the above approach ; Function to find the total number of ways to tile a 2 * N board using the given types of tile ; If N is less than 3 ; Store all dp - states ; Base Case ; Traverse the range [ 2 , N ] ; Update the value of dp [ i ] [ 0 ] ; Update the value of dp [ i ] [ 1 ] ; Update the value of dp [ i ] [ 2 ] ; Return the number of ways as the value of dp [ N ] [ 0 ] ; Driver Code"
How can the above be solved in Java?

import java . util . Arrays ; class GFG { public static long MOD = 1000000007l ; public static long numTilings ( int N ) { if ( N < 3 ) { return N ; } long [ ] [ ] dp = new long [ N + 1 ] [ 3 ] ; for ( long [ ] row : dp ) { Arrays . fill ( row , 0 ) ; } dp [ 0 ] [ 0 ] = dp [ 1 ] [ 0 ] = 1 ; dp [ 1 ] [ 1 ] = dp [ 1 ] [ 2 ] = 1 ; for ( int i = 2 ; i <= N ; i ++ ) { dp [ i ] [ 0 ] = ( dp [ i - 1 ] [ 0 ] + dp [ i - 2 ] [ 0 ] + dp [ i - 2 ] [ 1 ] + dp [ i - 2 ] [ 2 ] ) % MOD ; dp [ i ] [ 1 ] = ( dp [ i - 1 ] [ 0 ] + dp [ i - 1 ] [ 2 ] ) % MOD ; dp [ i ] [ 2 ] = ( dp [ i - 1 ] [ 0 ] + dp [ i - 1 ] [ 1 ] ) % MOD ; } return dp [ N ] [ 0 ] ; } public static void main ( String args [ ] ) { int N = 3 ; System . out . println ( numTilings ( N ) ) ; } }


"Doolittle Algorithm : LU Decomposition | Java Program to decompose a matrix into lower and upper triangular matrix ; Decomposing matrix into Upper and Lower triangular matrix ; Upper Triangular ; Summation of L ( i , j ) * U ( j , k ) ; Evaluating U ( i , k ) ; Lower Triangular ; lower [ i ] [ i ] = 1 ; Diagonal as 1 ; Summation of L ( k , j ) * U ( j , i ) ; Evaluating L ( k , i ) ; setw is for displaying nicely ; Displaying the result : ; Lower ; Upper ; Driver code"
How can the above be solved in Java?

 class GFG { static int MAX = 100 ; static String s = " " ; static void luDecomposition ( int [ ] [ ] mat , int n ) { int [ ] [ ] lower = new int [ n ] [ n ] ; int [ ] [ ] upper = new int [ n ] [ n ] ; for ( int i = 0 ; i < n ; i ++ ) { for ( int k = i ; k < n ; k ++ ) { int sum = 0 ; for ( int j = 0 ; j < i ; j ++ ) sum += ( lower [ i ] [ j ] * upper [ j ] [ k ] ) ; upper [ i ] [ k ] = mat [ i ] [ k ] - sum ; } for ( int k = i ; k < n ; k ++ ) { if ( i == k ) else { int sum = 0 ; for ( int j = 0 ; j < i ; j ++ ) sum += ( lower [ k ] [ j ] * upper [ j ] [ i ] ) ; lower [ k ] [ i ] = ( mat [ k ] [ i ] - sum ) / upper [ i ] [ i ] ; } } } System . out . println ( setw ( 2 ) + " 	 Lower ▁ Triangular " + setw ( 10 ) + " Upper ▁ Triangular " ) ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = 0 ; j < n ; j ++ ) System . out . print ( setw ( 4 ) + lower [ i ] [ j ] + " 	 " ) ; System . out . print ( " 	 " ) ; for ( int j = 0 ; j < n ; j ++ ) System . out . print ( setw ( 4 ) + upper [ i ] [ j ] + " 	 " ) ; System . out . print ( "
"); } } static String setw ( int noOfSpace ) { s = " " ; for ( int i = 0 ; i < noOfSpace ; i ++ ) s += " ▁ " ; return s ; } public static void main ( String arr [ ] ) { int mat [ ] [ ] = { { 2 , - 1 , - 2 } , { - 4 , 6 , 3 } , { - 4 , - 2 , 8 } } ; luDecomposition ( mat , 3 ) ; } }


"Doubly Circular Linked List | Set 1 ( Introduction and Insertion ) | Function to insert at the end ; If the list is empty , create a single node circular and doubly list ; If list is not empty Find last node ; Create Node dynamically ; Start is going to be next of new_node ; Make new node previous of start ; Make last preivous of new node ; Make new node next of old last"
How can the above be solved in Java?

static void insertEnd ( int value ) { if ( start == null ) { Node new_node = new Node ( ) ; new_node . data = value ; new_node . next = new_node . prev = new_node ; start = new_node ; return ; } Node last = ( start ) . prev ; Node new_node = new Node ( ) ; new_node . data = value ; new_node . next = start ; ( start ) . prev = new_node ; new_node . prev = last ; last . next = new_node ; }


"Doubly Circular Linked List | Set 1 ( Introduction and Insertion ) | Java program to illustrate inserting a Node in a Cicular Doubly Linked list in begging , end and middle ; Structure of a Node ; Function to insert at the end ; If the list is empty , create a single node circular and doubly list ; Find last node ; Create Node dynamically ; Start is going to be next of new_node ; Make new node previous of start ; Make last preivous of new node ; Make new node next of old last ; Function to insert Node at the beginning of the List , ; Pointer points to last Node ; Inserting the data ; setting up previous and next of new node ; Update next and previous pointers of start and last . ; Update start pointer ; Function to insert node with value as value1 . The new node is inserted after the node with with value2 ; Inserting the data ; Find node having value2 and next node of it ; insert new_node between temp and next . ; Driver code ; Start with the empty list ; Insert 5. So linked list becomes 5. null ; Insert 4 at the beginning . So linked list becomes 4.5 ; Insert 7 at the end . So linked list becomes 4.5 . 7 ; Insert 8 at the end . So linked list becomes 4.5 . 7.8 ; Insert 6 , after 5. So linked list becomes 4.5 . 6.7 . 8"
How can the above be solved in Java?

import java . util . * ; class GFG { static Node start ; static class Node { int data ; Node next ; Node prev ; } ; static void insertEnd ( int value ) { if ( start == null ) { Node new_node = new Node ( ) ; new_node . data = value ; new_node . next = new_node . prev = new_node ; start = new_node ; return ; } Node last = ( start ) . prev ; Node new_node = new Node ( ) ; new_node . data = value ; new_node . next = start ; ( start ) . prev = new_node ; new_node . prev = last ; last . next = new_node ; } static void insertBegin ( int value ) { Node last = ( start ) . prev ; Node new_node = new Node ( ) ; new_node . data = value ; new_node . next = start ; new_node . prev = last ; last . next = ( start ) . prev = new_node ; start = new_node ; } static void insertAfter ( int value1 , int value2 ) { Node new_node = new Node ( ) ; new_node . data = value1 ; Node temp = start ; while ( temp . data != value2 ) temp = temp . next ; Node next = temp . next ; temp . next = new_node ; new_node . prev = temp ; new_node . next = next ; next . prev = new_node ; } static void display ( ) { Node temp = start ; System . out . printf ( " Traversal in forward direction "); while ( temp . next != start ) { System . out . printf ( " % d ▁ " , temp . data ) ; temp = temp . next ; } System . out . printf ( " % d ▁ " , temp . data ) ; System . out . printf ( " Traversal in reverse direction "); Node last = start . prev ; temp = last ; while ( temp . prev != last ) { System . out . printf ( " % d ▁ " , temp . data ) ; temp = temp . prev ; } System . out . printf ( " % d ▁ " , temp . data ) ; } public static void main ( String [ ] args ) { Node start = null ; insertEnd ( 5 ) ; insertBegin ( 4 ) ; insertEnd ( 7 ) ; insertEnd ( 8 ) ; insertAfter ( 6 , 5 ) ; System . out . printf ( " Created ▁ circular ▁ doubly ▁ linked ▁ list ▁ is : ▁ " ) ; display ( ) ; } }


"Doubly Linked List | Set 1 ( Introduction and Insertion ) | Add a node at the end of the list ; 1. allocate node * 2. put in the data ; 3. This new node is going to be the last node , so * make next of it as NULL ; 4. If the Linked List is empty , then make the new * node as head ; 5. Else traverse till the last node ; 6. Change the next of last node ; 7. Make last node as previous of new node"
How can the above be solved in Java?

void append ( int new_data ) { Node new_node = new Node ( new_data ) ; Node last = head ; new_node . next = null ; if ( head == null ) { new_node . prev = null ; head = new_node ; return ; } while ( last . next != null ) last = last . next ; last . next = new_node ; new_node . prev = last ; }


"Doubly Linked List | Set 1 ( Introduction and Insertion ) | Adding a node at the front of the list ; 1. allocate node * 2. put in the data ; 3. Make next of new node as head and previous as NULL ; 4. change prev of head node to new node ; 5. move the head to point to the new node"
How can the above be solved in Java?

public void push ( int new_data ) { Node new_Node = new Node ( new_data ) ; new_Node . next = head ; new_Node . prev = null ; if ( head != null ) head . prev = new_Node ; head = new_Node ; }


"Doubly Linked List | Set 1 ( Introduction and Insertion ) | Given a node as prev_node , insert a new node after the given node ; 1. check if the given prev_node is NULL ; 2. allocate node * 3. put in the data ; 4. Make next of new node as next of prev_node ; 5. Make the next of prev_node as new_node ; 6. Make prev_node as previous of new_node ; 7. Change previous of new_node 's next node"
How can the above be solved in Java?

public void InsertAfter ( Node prev_Node , int new_data ) { if ( prev_Node == null ) { System . out . println ( " The ▁ given ▁ previous ▁ node ▁ cannot ▁ be ▁ NULL ▁ " ) ; return ; } Node new_node = new Node ( new_data ) ; new_node . next = prev_Node . next ; prev_Node . next = new_node ; new_node . prev = prev_Node ; if ( new_node . next != null ) new_node . next . prev = new_node ; }


"Droll Numbers | Java program for the above approach ; Function to check droll numbers ; To store sum of even prime factors ; To store sum of odd prime factors ; Add the number of 2 s that divide n in sum_even ; N must be odd at this point . So we can skip one element ( Note i = i + 2 ) ; While i divides n , print i and divide n ; This condition is to handle the case when n is a prime number greater than 2 ; Condition to check droll number ; Driver code ; Given Number N ; Function Call"
How can the above be solved in Java?

class GFG { static boolean isDroll ( int n ) { if ( n == 1 ) return false ; int sum_even = 0 ; int sum_odd = 0 ; while ( n % 2 == 0 ) { sum_even += 2 ; n = n / 2 ; } for ( int i = 3 ; i <= Math . sqrt ( n ) ; i = i + 2 ) { while ( n % i == 0 ) { sum_odd += i ; n = n / i ; } } if ( n > 2 ) sum_odd += n ; return sum_even == sum_odd ; } public static void main ( String [ ] args ) { int n = 72 ; if ( isDroll ( n ) ) System . out . println ( " Yes " ) ; else System . out . println ( " No " ) ; } }


"Dual pivot Quicksort | Java program to implement dual pivot QuickSort ; piv [ ] stores left pivot and right pivot . piv [ 0 ] means left pivot and piv [ 1 ] means right pivot ; p is the left pivot , and q is the right pivot . ; If elements are less than the left pivot ; If elements are greater than or equal to the right pivot ; Bring pivots to their appropriate positions . ; Returning the indices of the pivots because we cannot return two elements from a function , we do that using an array . ; Driver code"
How can the above be solved in Java?

class GFG { static void swap ( int [ ] arr , int i , int j ) { int temp = arr [ i ] ; arr [ i ] = arr [ j ] ; arr [ j ] = temp ; } static void dualPivotQuickSort ( int [ ] arr , int low , int high ) { if ( low < high ) { int [ ] piv ; piv = partition ( arr , low , high ) ; dualPivotQuickSort ( arr , low , piv [ 0 ] - 1 ) ; dualPivotQuickSort ( arr , piv [ 0 ] + 1 , piv [ 1 ] - 1 ) ; dualPivotQuickSort ( arr , piv [ 1 ] + 1 , high ) ; } } static int [ ] partition ( int [ ] arr , int low , int high ) { if ( arr [ low ] > arr [ high ] ) swap ( arr , low , high ) ; int j = low + 1 ; int g = high - 1 , k = low + 1 , p = arr [ low ] , q = arr [ high ] ; while ( k <= g ) { if ( arr [ k ] < p ) { swap ( arr , k , j ) ; j ++ ; } else if ( arr [ k ] >= q ) { while ( arr [ g ] > q && k < g ) g -- ; swap ( arr , k , g ) ; g -- ; if ( arr [ k ] < p ) { swap ( arr , k , j ) ; j ++ ; } } k ++ ; } j -- ; g ++ ; swap ( arr , low , j ) ; swap ( arr , high , g ) ; return new int [ ] { j , g } ; } public static void main ( String [ ] args ) { int [ ] arr = { 24 , 8 , 42 , 75 , 29 , 77 , 38 , 57 } ; dualPivotQuickSort ( arr , 0 , 7 ) ; System . out . print ( " Sorted ▁ array : ▁ " ) ; for ( int i = 0 ; i < 8 ; i ++ ) System . out . print ( arr [ i ] + " ▁ " ) ; System . out . println ( ) ; } }


"Dudeney Numbers | Java implementation of the approach ; Function that returns true if n is a Dudeney number ; If n is not a perfect cube ; Last digit ; Update the digit sum ; Remove the last digit ; If cube root of n is not equal to the sum of its digits ; Driver code"
How can the above be solved in Java?

import java . lang . Math ; class GFG { static boolean isDudeney ( int n ) { int cube_rt = ( int ) ( Math . round ( ( Math . pow ( n , 1.0 / 3.0 ) ) ) ) ; if ( cube_rt * cube_rt * cube_rt != n ) return false ; int dig_sum = 0 ; int temp = n ; while ( temp > 0 ) { int rem = temp % 10 ; dig_sum += rem ; temp /= 10 ; } if ( cube_rt != dig_sum ) return false ; return true ; } public static void main ( String [ ] args ) { int n = 17576 ; if ( isDudeney ( n ) ) System . out . println ( " Yes " ) ; else System . out . println ( " No " ) ; } }


"Duffinian Numbers | Java program for the above approach ; Recursive function to return gcd of a and b ; Function to calculate the sum of all divisors of a given number ; Sum of divisors ; Find all divisors of num ; if ' i ' is divisor of ' n ' ; If both divisors are same then add it once ; Add 1 and n to result as above loop considers proper divisors greater than 1. ; Function to check if n is an Duffinian number ; Calculate the sum of divisors ; If number is prime return false ; Find the gcd of n and sum of divisors of n ; Returns true if N and sumDivisors are relatively prime ; Driver code ; Given Number ; Function Call"
How can the above be solved in Java?

class GFG { static int gcd ( int a , int b ) { if ( b == 0 ) return a ; return gcd ( b , a % b ) ; } static int divSum ( int n ) { int result = 0 ; for ( int i = 2 ; i <= Math . sqrt ( n ) ; i ++ ) { if ( n % i == 0 ) { if ( i == ( n / i ) ) result += i ; else result += ( i + n / i ) ; } } return ( result + n + 1 ) ; } static boolean isDuffinian ( int n ) { int sumDivisors = divSum ( n ) ; if ( sumDivisors == n + 1 ) return false ; int hcf = gcd ( n , sumDivisors ) ; return hcf == 1 ; } public static void main ( String [ ] args ) { int n = 36 ; if ( isDuffinian ( n ) ) { System . out . println ( " Yes " ) ; } else { System . out . println ( " No " ) ; } } }


"Duplicates in an array in O ( n ) time and by using O ( 1 ) extra space | Set | Java program to print all elements that appear more than once . ; Function to find repeating elements ; Flag variable used to represent whether repeating element is found or not . ; Check if current element is repeating or not . If it is repeating then value will be greater than or equal to n . ; Check if it is first repetition or not . If it is first repetition then value at index arr [ i ] is less than 2 * n . Print arr [ i ] if it is first repetition . ; Add n to index arr [ i ] to mark presence of arr [ i ] or to mark repetition of arr [ i ] . ; If flag variable is not set then no repeating element is found . So print - 1. ; Driver Code"
How can the above be solved in Java?

import java . io . * ; class GFG { static void printDuplicates ( int arr [ ] , int n ) { int i ; int fl = 0 ; for ( i = 0 ; i < n ; i ++ ) { if ( arr [ arr [ i ] % n ] >= n ) { if ( arr [ arr [ i ] % n ] < 2 * n ) { System . out . print ( arr [ i ] % n + " ▁ " ) ; fl = 1 ; } } arr [ arr [ i ] % n ] += n ; } if ( ! ( fl > 0 ) ) System . out . println ( " - 1" ) ; } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 6 , 3 , 1 , 3 , 6 , 6 } ; int arr_size = arr . length ; printDuplicates ( arr , arr_size ) ; } }


"Dyck path | Java program to count number of Dyck Paths ; Returns count Dyck paths in n x n grid ; Compute value of 2 nCn ; return 2 nCn / ( n + 1 ) ; Driver code"
How can the above be solved in Java?

class GFG { public static int countDyckPaths ( int n ) { int res = 1 ; for ( int i = 0 ; i < n ; ++ i ) { res *= ( 2 * n - i ) ; res /= ( i + 1 ) ; } return res / ( n + 1 ) ; } public static void main ( String args [ ] ) { int n = 4 ; System . out . println ( " Number ▁ of ▁ Dyck ▁ Paths ▁ is ▁ " + countDyckPaths ( n ) ) ; } }


"Dynamic Connectivity | Set 1 ( Incremental ) | Java implementation of incremental connectivity ; Finding the root of node i ; union of two nodes a and b ; union based on rank ; Returns true if two nodes have same root ; Performing an operation according to query type ; type 1 query means checking if node x and y are connected or not ; If roots of x and y is same then yes is the answer ; type 2 query refers union of x and y ; If x and y have different roots then union them ; Driver Code ; No . of nodes ; The following two arrays are used to implement disjoint set data structure . arr [ ] holds the parent nodes while rank array holds the rank of subset ; initializing both array and rank ; number of queries"
How can the above be solved in Java?

import java . util . * ; class GFG { static int root ( int arr [ ] , int i ) { while ( arr [ i ] != i ) { arr [ i ] = arr [ arr [ i ] ] ; i = arr [ i ] ; } return i ; } static void weighted_union ( int arr [ ] , int rank [ ] , int a , int b ) { int root_a = root ( arr , a ) ; int root_b = root ( arr , b ) ; if ( rank [ root_a ] < rank [ root_b ] ) { arr [ root_a ] = arr [ root_b ] ; rank [ root_b ] += rank [ root_a ] ; } else { arr [ root_b ] = arr [ root_a ] ; rank [ root_a ] += rank [ root_b ] ; } } static boolean areSame ( int arr [ ] , int a , int b ) { return ( root ( arr , a ) == root ( arr , b ) ) ; } static void query ( int type , int x , int y , int arr [ ] , int rank [ ] ) { if ( type == 1 ) { if ( areSame ( arr , x , y ) == true ) System . out . println ( " Yes " ) ; else System . out . println ( " No " ) ; } else if ( type == 2 ) { if ( areSame ( arr , x , y ) == false ) weighted_union ( arr , rank , x , y ) ; } } public static void main ( String [ ] args ) { int n = 7 ; int [ ] arr = new int [ n ] ; int [ ] rank = new int [ n ] ; for ( int i = 0 ; i < n ; i ++ ) { arr [ i ] = i ; rank [ i ] = 1 ; } int q = 11 ; query ( 1 , 0 , 1 , arr , rank ) ; query ( 2 , 0 , 1 , arr , rank ) ; query ( 2 , 1 , 2 , arr , rank ) ; query ( 1 , 0 , 2 , arr , rank ) ; query ( 2 , 0 , 2 , arr , rank ) ; query ( 2 , 2 , 3 , arr , rank ) ; query ( 2 , 3 , 4 , arr , rank ) ; query ( 1 , 0 , 5 , arr , rank ) ; query ( 2 , 4 , 5 , arr , rank ) ; query ( 2 , 5 , 6 , arr , rank ) ; query ( 1 , 2 , 6 , arr , rank ) ; } }


"Dynamic Convex hull | Adding Points to an Existing Convex Hull | Java program to add given a point p to a given convext hull . The program assumes that the point of given convext hull are in anti - clockwise order . ; checks whether the point crosses the convex hull or not ; Returns the square of distance between two input points ; Checks whether the point is inside the convex hull or not ; Initialize the centroid of the convex hull ; Multiplying with n to avoid floating point arithmetic . ; if the mid and the given point lies always on the same side w . r . t every edge of the convex hull , then the point lies inside the convex hull ; Adds a point p to given convex hull a [ ] ; If point is inside p ; point having minimum distance from the point p ; Find the upper tangent ; Find the lower tangent ; Initialize result ; making the final hull by traversing points from up to low of given convex hull . ; Modify the original vector ; Driver code ; the set of points in the convex hull ; Print the modified Convex Hull"
How can the above be solved in Java?

import java . io . * ; import java . util . * ; class GFG { static int orientation ( ArrayList < Integer > a , ArrayList < Integer > b , ArrayList < Integer > c ) { int res = ( b . get ( 1 ) - a . get ( 1 ) ) * ( c . get ( 0 ) - b . get ( 0 ) ) - ( c . get ( 1 ) - b . get ( 1 ) ) * ( b . get ( 0 ) - a . get ( 0 ) ) ; if ( res == 0 ) return 0 ; if ( res > 0 ) return 1 ; return - 1 ; } static int sqDist ( ArrayList < Integer > p1 , ArrayList < Integer > p2 ) { return ( p1 . get ( 0 ) - p2 . get ( 0 ) ) * ( p1 . get ( 0 ) - p2 . get ( 0 ) ) + ( p1 . get ( 1 ) - p2 . get ( 1 ) ) * ( p1 . get ( 1 ) - p2 . get ( 1 ) ) ; } static boolean inside ( ArrayList < ArrayList < Integer > > A , ArrayList < Integer > p ) { ArrayList < Integer > mid = new ArrayList < Integer > ( Arrays . asList ( 0 , 0 ) ) ; int n = A . size ( ) ; for ( int i = 0 ; i < n ; i ++ ) { mid . set ( 0 , mid . get ( 0 ) + A . get ( i ) . get ( 0 ) ) ; mid . set ( 1 , mid . get ( 1 ) + A . get ( i ) . get ( 1 ) ) ; } for ( int i = 0 , j ; i < n ; i ++ ) { j = ( i + 1 ) % n ; int x1 = A . get ( i ) . get ( 0 ) * n , x2 = A . get ( j ) . get ( 0 ) * n ; int y1 = A . get ( i ) . get ( 1 ) * n , y2 = A . get ( j ) . get ( 1 ) * n ; int a1 = y1 - y2 ; int b1 = x2 - x1 ; int c1 = x1 * y2 - y1 * x2 ; int for_mid = a1 * mid . get ( 0 ) + b1 * mid . get ( 1 ) + c1 ; int for_p = a1 * p . get ( 0 ) * n + b1 * p . get ( 1 ) * n + c1 ; if ( for_mid * for_p < 0 ) return false ; } return true ; } static void addPoint ( ArrayList < ArrayList < Integer > > a , ArrayList < Integer > p ) { if ( inside ( a , p ) ) return ; int ind = 0 ; int n = a . size ( ) ; for ( int i = 1 ; i < n ; i ++ ) { if ( sqDist ( p , a . get ( i ) ) < sqDist ( p , a . get ( ind ) ) ) { ind = i ; } } int up = ind ; while ( orientation ( p , a . get ( up ) , a . get ( ( up + 1 ) % n ) ) >= 0 ) up = ( up + 1 ) % n ; int low = ind ; while ( orientation ( p , a . get ( low ) , a . get ( ( n + low - 1 ) % n ) ) <= 0 ) low = ( n + low - 1 ) % n ; ArrayList < ArrayList < Integer > > ret = new...


"Dynamic Programming on Trees | Set 2 | Java code to find the maximum path length considering any node as root ; Function to pre - calculate the array in [ ] which stores the maximum height when travelled via branches ; Initially every node has 0 height ; Traverse in the subtree of u ; If child is same as parent ; dfs called ; Recursively calculate the max height ; Function to pre - calculate the array ouut [ ] which stores the maximum height when traveled via parent ; Stores the longest and second longest branches ; Traverse in the subtress of u ; Compare and store the longest and second longest ; Traverse in the subtree of u ; If longest branch has the node , then consider the second longest branch ; Recursively calculate out [ i ] ; dfs function call ; Function to print all the maximum heights from every node ; Traversal to calculate in [ ] array ; Traversal to calculate out [ ] array ; Print all maximum heights ; Driver Code ; Initialize the tree given in the diagram ; Function to print the maximum height from every node"
How can the above be solved in Java?

import java . io . * ; import java . util . * ; class GFG { static final int MAX_NODES = 100 ; static int in [ ] = new int [ MAX_NODES ] ; static int out [ ] = new int [ MAX_NODES ] ; static void dfs1 ( ArrayList < ArrayList < Integer > > v , int u , int parent ) { in [ u ] = 0 ; for ( int j = 0 ; j < v . get ( u ) . size ( ) ; j ++ ) { int child = v . get ( u ) . get ( j ) ; if ( child == parent ) continue ; dfs1 ( v , child , u ) ; in [ u ] = Math . max ( in [ u ] , 1 + in [ child ] ) ; } } static void dfs2 ( ArrayList < ArrayList < Integer > > v , int u , int parent ) { int mx1 = - 1 , mx2 = - 1 ; for ( int j = 0 ; j < v . get ( u ) . size ( ) ; j ++ ) { int child = v . get ( u ) . get ( j ) ; if ( child == parent ) continue ; if ( in [ child ] >= mx1 ) { mx2 = mx1 ; mx1 = in [ child ] ; } else if ( in [ child ] > mx2 ) mx2 = in [ child ] ; } for ( int j = 0 ; j < v . get ( u ) . size ( ) ; j ++ ) { int child = v . get ( u ) . get ( j ) ; if ( child == parent ) continue ; int longest = mx1 ; if ( mx1 == in [ child ] ) longest = mx2 ; out [ child ] = 1 + Math . max ( out [ u ] , 1 + longest ) ; dfs2 ( v , child , u ) ; } } static void addEdge ( ArrayList < ArrayList < Integer > > adj , int u , int v ) { adj . get ( u ) . add ( v ) ; adj . get ( v ) . add ( u ) ; } static void printHeights ( ArrayList < ArrayList < Integer > > v , int n ) { dfs1 ( v , 1 , 0 ) ; dfs2 ( v , 1 , 0 ) ; for ( int i = 1 ; i < n ; i ++ ) System . out . println ( " The ▁ maximum ▁ height ▁ when ▁ node ▁ " + i + " ▁ is ▁ considered ▁ as ▁ root ▁ is ▁ " + Math . max ( in [ i ] , out [ i ] ) ) ; } public static void main ( String [ ] args ) { int V = 12 ; ArrayList < ArrayList < Integer > > adj = new ArrayList < ArrayList < Integer > > ( V + 1 ) ; for ( int i = 0 ; i < V ; i ++ ) adj . add ( new ArrayList < Integer > ( ) ) ; addEdge ( adj , 1 , 2 ) ; addEdge ( adj , 1 , 3 ) ; addEdge ( adj , 1 , 4 ) ; addEdge ( adj , 2 , 5 ) ; addEdge ( adj , 2 , 6 ) ; addEdge ( adj , 3 , 7 ) ; addEdge ( adj , 7 , 10 ) ; addEdge ( adj , 7 , 11 ) ;...


"Dynamic Programming on Trees | Set | Java code to find the maximum path sum ; function for dfs traversal and to store the maximum value in dp [ ] for every node till the leaves ; initially dp [ u ] is always a [ u ] ; stores the maximum value from nodes ; traverse the tree ; if child is parent , then we continue without recursing further ; call dfs for further traversal ; store the maximum of previous visited node and present visited node ; add the maximum value returned to the parent node ; function that returns the maximum value ; Driver Code ; number of nodes ; adjacency list ; create undirected edges initialize the tree given in the diagram ; values of node 1 , 2 , 3. ... 14 ; function call"
How can the above be solved in Java?

import java . util . Vector ; class GFG { static int [ ] dp = new int [ 100 ] ; static void dfs ( int [ ] a , Vector < Integer > [ ] v , int u , int parent ) { dp [ u ] = a [ u - 1 ] ; int maximum = 0 ; for ( int child : v [ u ] ) { if ( child == parent ) continue ; dfs ( a , v , child , u ) ; maximum = Math . max ( maximum , dp [ child ] ) ; } dp [ u ] += maximum ; } static int maximumValue ( int [ ] a , Vector < Integer > [ ] v ) { dfs ( a , v , 1 , 0 ) ; return dp [ 1 ] ; } public static void main ( String [ ] args ) { int n = 14 ; @ SuppressWarnings ( " unchecked " ) Vector < Integer > [ ] v = new Vector [ n + 1 ] ; for ( int i = 0 ; i < v . length ; i ++ ) v [ i ] = new Vector < > ( ) ; v [ 1 ] . add ( 2 ) ; v [ 2 ] . add ( 1 ) ; v [ 1 ] . add ( 3 ) ; v [ 3 ] . add ( 1 ) ; v [ 1 ] . add ( 4 ) ; v [ 4 ] . add ( 1 ) ; v [ 2 ] . add ( 5 ) ; v [ 5 ] . add ( 2 ) ; v [ 2 ] . add ( 6 ) ; v [ 6 ] . add ( 2 ) ; v [ 3 ] . add ( 7 ) ; v [ 7 ] . add ( 3 ) ; v [ 4 ] . add ( 8 ) ; v [ 8 ] . add ( 4 ) ; v [ 4 ] . add ( 9 ) ; v [ 9 ] . add ( 4 ) ; v [ 4 ] . add ( 10 ) ; v [ 10 ] . add ( 4 ) ; v [ 5 ] . add ( 11 ) ; v [ 11 ] . add ( 5 ) ; v [ 5 ] . add ( 12 ) ; v [ 12 ] . add ( 5 ) ; v [ 7 ] . add ( 13 ) ; v [ 13 ] . add ( 7 ) ; v [ 7 ] . add ( 14 ) ; v [ 14 ] . add ( 7 ) ; int a [ ] = { 3 , 2 , 1 , 10 , 1 , 3 , 9 , 1 , 5 , 3 , 4 , 5 , 9 , 8 } ; System . out . println ( maximumValue ( a , v ) ) ; } }


"Dynamic Programming | Wildcard Pattern Matching | Linear Time and Constant Space | Java program to implement wildcard pattern matching algorithm ; Function that matches input text with given wildcard pattern ; empty pattern can only match with empty string . Base Case : ; step - 1 : initialize markers : ; For step - ( 2 , 5 ) ; For step - ( 3 ) ; For step - ( 4 ) ; For step - ( 5 ) ; For step - ( 6 ) ; For step - ( 7 ) ; Final Check ; Driver code"
How can the above be solved in Java?

class GFG { static boolean strmatch ( char txt [ ] , char pat [ ] , int n , int m ) { if ( m == 0 ) return ( n == 0 ) ; int i = 0 , j = 0 , index_txt = - 1 , index_pat = - 1 ; while ( i < n ) { if ( j < m && txt [ i ] == pat [ j ] ) { i ++ ; j ++ ; } else if ( j < m && pat [ j ] == ' ? ' ) { i ++ ; j ++ ; } else if ( j < m && pat [ j ] == ' * ' ) { index_txt = i ; index_pat = j ; j ++ ; } else if ( index_pat != - 1 ) { j = index_pat + 1 ; i = index_txt + 1 ; index_txt ++ ; } else { return false ; } } while ( j < m && pat [ j ] == ' * ' ) { j ++ ; } if ( j == m ) { return true ; } return false ; } public static void main ( String [ ] args ) { char str [ ] = " baaabab " . toCharArray ( ) ; char pattern [ ] = " * * * * * ba * * * * * ab " . toCharArray ( ) ; char pattern [ ] = " ba * * * * * ab " ; char pattern [ ] = " ba * ab " ; char pattern [ ] = " a * ab " ; if ( strmatch ( str , pattern , str . length , pattern . length ) ) System . out . println ( " Yes " ) ; else System . out . println ( " No " ) ; char pattern2 [ ] = " a * * * * * ab " . toCharArray ( ) ; if ( strmatch ( str , pattern2 , str . length , pattern2 . length ) ) System . out . println ( " Yes " ) ; else System . out . println ( " No " ) ; } }


"Economical Numbers | Java implementation to find Economical Numbers till n ; Array to store all prime less than and equal to MAX . ; Utility function for sieve of sundaram ; In general Sieve of Sundaram , produces primes smaller than ( 2 * x + 2 ) for a number given number x . Since we want primes smaller than MAX , we reduce MAX to half ; Main logic of Sundaram . Mark all numbers which do not generate prime number by doing 2 * i + 1 ; Since 2 is a prime number ; Print other primes . Remaining primes are of the form 2 * i + 1 such that marked [ i ] is false . ; Function to check if a number is a Economical number ; Count digits in original number ; Count all digits in prime factors of n pDigit is going to hold this value . ; Count powers of p in n ; If primes [ i ] is a prime factor , ; Count the power of prime factors ; Add its digits to pDigit . ; Add digits of power of prime factors to pDigit . ; If n != 1 then one prime factor still to be summed up ; ; If digits in prime factors is less than digits in original number then return true . Else return false . ; Driver code ; Finding all prime numbers before limit . These numbers are used to find prime factors ."
How can the above be solved in Java?

import java . util . * ; class GFG { static int MAX = 10000 ; static Vector < Integer > primes = new Vector < Integer > ( ) ; static void sieveSundaram ( ) { boolean [ ] marked = new boolean [ MAX / 2 + 1 ] ; for ( int i = 1 ; i <= ( Math . sqrt ( MAX ) - 1 ) / 2 ; i ++ ) for ( int j = ( i * ( i + 1 ) ) << 1 ; j <= MAX / 2 ; j = j + 2 * i + 1 ) marked [ j ] = true ; primes . add ( 2 ) ; for ( int i = 1 ; i <= MAX / 2 ; i ++ ) if ( marked [ i ] == false ) primes . add ( 2 * i + 1 ) ; } static boolean isEconomical ( int n ) { if ( n == 1 ) return false ; int original_no = n ; int sumDigits = 0 ; while ( original_no > 0 ) { sumDigits ++ ; original_no = original_no / 10 ; } int pDigit = 0 , count_exp = 0 , p = 0 ; for ( int i = 0 ; primes . get ( i ) <= n / 2 ; i ++ ) { while ( n % primes . get ( i ) == 0 ) { p = primes . get ( i ) ; n = n / p ; count_exp ++ ; } while ( p > 0 ) { pDigit ++ ; p = p / 10 ; } while ( count_exp > 1 ) { pDigit ++ ; count_exp = count_exp / 10 ; } } if ( n != 1 ) { while ( n > 0 ) { pDigit ++ ; n = n / 10 ; } } return ( pDigit < sumDigits ) ; } public static void main ( String [ ] args ) { sieveSundaram ( ) ; for ( int i = 1 ; i < 200 ; i ++ ) if ( isEconomical ( i ) ) System . out . print ( i + " ▁ " ) ; } }


"Edit Distance | DP |  ; If any String is empty , return the remaining characters of other String ; To check if the recursive tree for given n & m has already been executed ; If characters are equal , execute recursive function for n - 1 , m - 1 ; If characters are nt equal , we need to find the minimum cost out of all 3 operations . ; temp variables ; Driver program"
How can the above be solved in Java?

import java . util . * ; class GFG { static int minDis ( String s1 , String s2 , int n , int m , int [ ] [ ] dp ) { if ( n == 0 ) return m ; if ( m == 0 ) return n ; if ( dp [ n ] [ m ] != - 1 ) return dp [ n ] [ m ] ; if ( s1 . charAt ( n - 1 ) == s2 . charAt ( m - 1 ) ) { if ( dp [ n - 1 ] [ m - 1 ] == - 1 ) { return dp [ n ] [ m ] = minDis ( s1 , s2 , n - 1 , m - 1 , dp ) ; } else return dp [ n ] [ m ] = dp [ n - 1 ] [ m - 1 ] ; } else { int m1 , m2 , m3 ; if ( dp [ n - 1 ] [ m ] != - 1 ) { m1 = dp [ n - 1 ] [ m ] ; } else { m1 = minDis ( s1 , s2 , n - 1 , m , dp ) ; } if ( dp [ n ] [ m - 1 ] != - 1 ) { m2 = dp [ n ] [ m - 1 ] ; } else { m2 = minDis ( s1 , s2 , n , m - 1 , dp ) ; } if ( dp [ n - 1 ] [ m - 1 ] != - 1 ) { m3 = dp [ n - 1 ] [ m - 1 ] ; } else { m3 = minDis ( s1 , s2 , n - 1 , m - 1 , dp ) ; } return dp [ n ] [ m ] = 1 + Math . min ( m1 , Math . min ( m2 , m3 ) ) ; } } public static void main ( String [ ] args ) { String str1 = " voldemort " ; String str2 = " dumbledore " ; int n = str1 . length ( ) , m = str2 . length ( ) ; int [ ] [ ] dp = new int [ n + 1 ] [ m + 1 ] ; for ( int i = 0 ; i < n + 1 ; i ++ ) Arrays . fill ( dp [ i ] , - 1 ) ; System . out . print ( minDis ( str1 , str2 , n , m , dp ) ) ; } }


"Edit Distance | DP | A Space efficient Dynamic Programming based Java program to find minimum number operations to convert str1 to str2 ; Create a DP array to memoize result of previous computations ; Base condition when second String is empty then we remove all characters ; Start filling the DP This loop run for every character in second String ; This loop compares the char from second String with first String characters ; if first String is empty then we have to perform add character operation to get second String ; if character from both String is same then we do not perform any operation . here i % 2 is for bound the row number . ; if character from both String is not same then we take the minimum from three specified operation ; after complete fill the DP array if the len2 is even then we end up in the 0 th row else we end up in the 1 th row so we take len2 % 2 to get row ; Driver program"
How can the above be solved in Java?

 import java . util . * ; class GFG { static void EditDistDP ( String str1 , String str2 ) { int len1 = str1 . length ( ) ; int len2 = str2 . length ( ) ; int [ ] [ ] DP = new int [ 2 ] [ len1 + 1 ] ; for ( int i = 0 ; i <= len1 ; i ++ ) DP [ 0 ] [ i ] = i ; for ( int i = 1 ; i <= len2 ; i ++ ) { for ( int j = 0 ; j <= len1 ; j ++ ) { if ( j == 0 ) DP [ i % 2 ] [ j ] = i ; else if ( str1 . charAt ( j - 1 ) == str2 . charAt ( i - 1 ) ) { DP [ i % 2 ] [ j ] = DP [ ( i - 1 ) % 2 ] [ j - 1 ] ; } else { DP [ i % 2 ] [ j ] = 1 + Math . min ( DP [ ( i - 1 ) % 2 ] [ j ] , Math . min ( DP [ i % 2 ] [ j - 1 ] , DP [ ( i - 1 ) % 2 ] [ j - 1 ] ) ) ; } } } System . out . print ( DP [ len2 % 2 ] [ len1 ] + "
"); } public static void main ( String [ ] args ) { String str1 = " food " ; String str2 = " money " ; EditDistDP ( str1 , str2 ) ; } }


"Edit distance and LCS ( Longest Common Subsequence ) | Java program to find Edit Distance ( when only twooperations are allowed , insert and delete ) using LCS . ; Find LCS ; Edit distance is delete operations + insert operations . ; Driver program to test above function"
How can the above be solved in Java?

class GFG { static int editDistanceWith2Ops ( String X , String Y ) { int m = X . length ( ) , n = Y . length ( ) ; int L [ ] [ ] = new int [ m + 1 ] [ n + 1 ] ; for ( int i = 0 ; i <= m ; i ++ ) { for ( int j = 0 ; j <= n ; j ++ ) { if ( i == 0 j == 0 ) { L [ i ] [ j ] = 0 ; } else if ( X . charAt ( i - 1 ) == Y . charAt ( j - 1 ) ) { L [ i ] [ j ] = L [ i - 1 ] [ j - 1 ] + 1 ; } else { L [ i ] [ j ] = Math . max ( L [ i - 1 ] [ j ] , L [ i ] [ j - 1 ] ) ; } } } int lcs = L [ m ] [ n ] ; return ( m - lcs ) + ( n - lcs ) ; } public static void main ( String [ ] args ) { String X = " abc " , Y = " acd " ; System . out . println ( editDistanceWith2Ops ( X , Y ) ) ; } }


"Efficient Program to Compute Sum of Series 1 / 1 ! + 1 / 2 ! + 1 / 3 ! + 1 / 4 ! + . . + 1 / n ! | A simple Java program to compute sum of series 1 / 1 ! + 1 / 2 ! + . . + 1 / n ! ; An Efficient Function to return value of 1 / 1 ! + 1 / 2 ! + . . + 1 / n ! ; Update factorial ; Update series sum ; Driver program"
How can the above be solved in Java?

import java . io . * ; class GFG { static double sum ( int n ) { double sum = 0 ; int fact = 1 ; for ( int i = 1 ; i <= n ; i ++ ) { fact *= i ; sum += 1.0 / fact ; } return sum ; } public static void main ( String [ ] args ) { int n = 5 ; System . out . println ( sum ( n ) ) ; } }


"Efficient Program to Compute Sum of Series 1 / 1 ! + 1 / 2 ! + 1 / 3 ! + 1 / 4 ! + . . + 1 / n ! | A simple Java program to compute sum of series 1 / 1 ! + 1 / 2 ! + . . + 1 / n ! ; Utility function to find ; A Simple Function to return value of 1 / 1 ! + 1 / 2 ! + . . + 1 / n ! ; Driver program"
How can the above be solved in Java?

import java . io . * ; class GFG { static int factorial ( int n ) { int res = 1 ; for ( int i = 2 ; i <= n ; i ++ ) res *= i ; return res ; } static double sum ( int n ) { double sum = 0 ; for ( int i = 1 ; i <= n ; i ++ ) sum += 1.0 / factorial ( i ) ; return sum ; } public static void main ( String [ ] args ) { int n = 5 ; System . out . println ( sum ( n ) ) ; } }


"Efficient method for 2 's complement of a binary string | An efficient Java program to find 2 's complement ; Method to find two 's complement ; Traverse the string to get first '1' from the last of string ; If there exists no '1' concat 1 at the starting of string ; Continue traversal after the position of first '1' ; Just flip the values ; return the modified string ; Driver method"
How can the above be solved in Java?

class Test { static String findTwoscomplement ( StringBuffer str ) { int n = str . length ( ) ; int i ; for ( i = n - 1 ; i >= 0 ; i -- ) if ( str . charAt ( i ) == '1' ) break ; if ( i == - 1 ) return "1" + str ; for ( int k = i - 1 ; k >= 0 ; k -- ) { if ( str . charAt ( k ) == '1' ) str . replace ( k , k + 1 , "0" ) ; else str . replace ( k , k + 1 , "1" ) ; } return str . toString ( ) ; } public static void main ( String [ ] args ) { StringBuffer str = new StringBuffer ( "00000101" ) ; System . out . println ( findTwoscomplement ( str ) ) ; } }


"Efficient method to store a Lower Triangular Matrix using row | Java program for the above approach ; Dimensions of a matrix ; Structure of the efficient matrix ; Function to set the values in the Matrix ; Function to store the values in the Matrix ; Function to display the elements of the matrix ; Traverse the matrix ; Function to generate an efficient matrix ; Declare efficient Matrix ; Initialize the Matrix ; Set the values in matrix ; Return the matrix ; Driver Code ; Stores the efficient matrix ; Print the Matrix"
How can the above be solved in Java?

 class GFG { static int N = 5 ; static class Matrix { int [ ] A ; int size ; } ; static void Set ( Matrix mat , int i , int j , int x ) { if ( i >= j ) mat . A [ i * ( i - 1 ) / 2 + j - 1 ] = x ; } static int Get ( Matrix mat , int i , int j ) { if ( i >= j ) { return mat . A [ i * ( i - 1 ) / 2 + j - 1 ] ; } else { return 0 ; } } static void Display ( Matrix mat ) { int i , j ; for ( i = 1 ; i <= mat . size ; i ++ ) { for ( j = 1 ; j <= mat . size ; j ++ ) { if ( i >= j ) { System . out . printf ( " % d ▁ " , mat . A [ i * ( i - 1 ) / 2 + j - 1 ] ) ; } else { System . out . printf ( "0 ▁ " ) ; } } System . out . printf ( "
"); } } static Matrix createMat ( int Mat [ ] [ ] ) { Matrix mat = new Matrix ( ) ; mat . size = N ; mat . A = new int [ ( mat . size * ( mat . size + 1 ) ) / 2 ] ; int i , j ; for ( i = 1 ; i <= mat . size ; i ++ ) { for ( j = 1 ; j <= mat . size ; j ++ ) { Set ( mat , i , j , Mat [ i - 1 ] [ j - 1 ] ) ; } } return mat ; } public static void main ( String [ ] args ) { int Mat [ ] [ ] = { { 1 , 0 , 0 , 0 , 0 } , { 1 , 2 , 0 , 0 , 0 } , { 1 , 2 , 3 , 0 , 0 } , { 1 , 2 , 3 , 4 , 0 } , { 1 , 2 , 3 , 4 , 5 } } ; Matrix mat = createMat ( Mat ) ; Display ( mat ) ; } }


"Efficient program to calculate e ^ x | Java efficient program to calculate e raise to the power x ; Function returns approximate value of e ^ x using sum of first n terms of Taylor Series ; initialize sum of series ; driver program"
How can the above be solved in Java?

import java . io . * ; class GFG { static float exponential ( int n , float x ) { float sum = 1 ; for ( int i = n - 1 ; i > 0 ; -- i ) sum = 1 + x * sum / i ; return sum ; } public static void main ( String [ ] args ) { int n = 10 ; float x = 1 ; System . out . println ( " e ^ x ▁ = ▁ " + exponential ( n , x ) ) ; } }


"Efficient program to print the number of factors of n numbers | JAVA Code For Efficient program to print the number of factors of n numbers ; function to generate all prime factors of numbers from 1 to 10 ^ 6 ; Initializes all the positions with their value . ; Initializes all multiples of 2 with 2 ; A modified version of Sieve of Eratosthenes to store the smallest prime factor that divides every number . ; check if it has no prime factor . ; Initializes of j starting from i * i ; if it has no prime factor before , then stores the smallest prime divisor ; function to calculate number of factors ; stores the smallest prime number that divides n ; stores the count of number of times a prime number divides n . ; reduces to the next number after prime factorization of n ; false when prime factorization is done ; if the same prime number is dividing n , then we increase the count ; if its a new prime factor that is factorizing n , then we again set c = 1 and change dup to the new prime factor , and apply the formula explained above . ; prime factorizes a number ; for the last prime factor ; Driver program to test above function ; array to store prime factors ; generate prime factors of number upto 10 ^ 6"
How can the above be solved in Java?

import java . util . * ; class GFG { static int MAX = 1000001 ; static int factor [ ] ; static void generatePrimeFactors ( ) { factor [ 1 ] = 1 ; for ( int i = 2 ; i < MAX ; i ++ ) factor [ i ] = i ; for ( int i = 4 ; i < MAX ; i += 2 ) factor [ i ] = 2 ; for ( int i = 3 ; i * i < MAX ; i ++ ) { if ( factor [ i ] == i ) { for ( int j = i * i ; j < MAX ; j += i ) { if ( factor [ j ] == j ) factor [ j ] = i ; } } } } static int calculateNoOFactors ( int n ) { if ( n == 1 ) return 1 ; int ans = 1 ; int dup = factor [ n ] ; int c = 1 ; int j = n / factor [ n ] ; while ( j != 1 ) { if ( factor [ j ] == dup ) c += 1 ; else { dup = factor [ j ] ; ans = ans * ( c + 1 ) ; c = 1 ; } j = j / factor [ j ] ; } ans = ans * ( c + 1 ) ; return ans ; } public static void main ( String [ ] args ) { factor = new int [ MAX ] ; factor [ 0 ] = 0 ; generatePrimeFactors ( ) ; int a [ ] = { 10 , 30 , 100 , 450 , 987 } ; int q = a . length ; for ( int i = 0 ; i < q ; i ++ ) System . out . print ( calculateNoOFactors ( a [ i ] ) + " ▁ " ) ; } }


"Efficiently check if a string has all unique characters without using any additional data structure | A space efficient Java program to check if all characters of string are unique . ; Returns true if all characters of str are unique . Assumptions : ( 1 ) str contains only characters from ' a ' to ' z ' ( 2 ) integers are stored using 32 bits ; An integer to store presence / absence of 26 characters using its 32 bits . ; If bit corresponding to current character is already set ; set bit in checker ; driver code"
How can the above be solved in Java?

class GFG { static boolean areChractersUnique ( String str ) { int checker = 0 ; for ( int i = 0 ; i < str . length ( ) ; ++ i ) { int val = ( str . charAt ( i ) - ' a ' ) ; if ( ( checker & ( 1 << val ) ) > 0 ) return false ; checker |= ( 1 << val ) ; } return true ; } public static void main ( String [ ] args ) { String s = " aaabbccdaa " ; if ( areChractersUnique ( s ) ) System . out . print ( " Yes " ) ; else System . out . print ( " No " ) ; } }


"Efficiently check if a string has all unique characters without using any additional data structure | Driver code"
How can the above be solved in Java?

import java . util . Arrays ; class GFG { static boolean unique ( String s ) { Arrays . sort ( s . toCharArray ( ) ) ; for ( int i = 0 ; i < s . length ( ) ; i ++ ) { if ( s . charAt ( i ) == s . charAt ( i + 1 ) ) { return false ; } } return true ; } public static void main ( String [ ] args ) { if ( unique ( " abcdd " ) == true ) { System . out . println ( " String ▁ is ▁ Unique " ) ; } else { System . out . println ( " String ▁ is ▁ not ▁ Unique " ) ; } } }


"Efficiently compute sums of diagonals of a matrix | A simple java program to find sum of diagonals ; Condition for principal diagonal ; Condition for secondary diagonal ; Driver code"
How can the above be solved in Java?

import java . io . * ; public class GFG { static void printDiagonalSums ( int [ ] [ ] mat , int n ) { int principal = 0 , secondary = 0 ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = 0 ; j < n ; j ++ ) { if ( i == j ) principal += mat [ i ] [ j ] ; if ( ( i + j ) == ( n - 1 ) ) secondary += mat [ i ] [ j ] ; } } System . out . println ( " Principal ▁ Diagonal : " + principal ) ; System . out . println ( " Secondary ▁ Diagonal : " + secondary ) ; } static public void main ( String [ ] args ) { int [ ] [ ] a = { { 1 , 2 , 3 , 4 } , { 5 , 6 , 7 , 8 } , { 1 , 2 , 3 , 4 } , { 5 , 6 , 7 , 8 } } ; printDiagonalSums ( a , 4 ) ; } }


"Efficiently compute sums of diagonals of a matrix | An efficient java program to find sum of diagonals ; Driver code"
How can the above be solved in Java?

import java . io . * ; public class GFG { static void printDiagonalSums ( int [ ] [ ] mat , int n ) { int principal = 0 , secondary = 0 ; for ( int i = 0 ; i < n ; i ++ ) { principal += mat [ i ] [ i ] ; secondary += mat [ i ] [ n - i - 1 ] ; } System . out . println ( " Principal ▁ Diagonal : " + principal ) ; System . out . println ( " Secondary ▁ Diagonal : " + secondary ) ; } static public void main ( String [ ] args ) { int [ ] [ ] a = { { 1 , 2 , 3 , 4 } , { 5 , 6 , 7 , 8 } , { 1 , 2 , 3 , 4 } , { 5 , 6 , 7 , 8 } } ; printDiagonalSums ( a , 4 ) ; } }


"Efficiently find first repeated character in a string without using any additional data structure in one traversal | Efficiently check First repeated character in Java program ; Returns - 1 if all characters of str are unique . Assumptions : ( 1 ) str contains only characters from ' a ' to ' z ' ( 2 ) integers are stored using 32 bits ; An integer to store presence / absence of 26 characters using its 32 bits . ; If bit corresponding to current character is already set ; set bit in checker ; Driver code"
How can the above be solved in Java?

public class First_Repeated_char { static int FirstRepeated ( String str ) { int checker = 0 ; for ( int i = 0 ; i < str . length ( ) ; ++ i ) { int val = ( str . charAt ( i ) - ' a ' ) ; if ( ( checker & ( 1 << val ) ) > 0 ) return i ; checker |= ( 1 << val ) ; } return - 1 ; } public static void main ( String args [ ] ) { String s = " abcfdeacf " ; int i = FirstRepeated ( s ) ; if ( i != - 1 ) System . out . println ( " Char ▁ = ▁ " + s . charAt ( i ) + " ▁ and ▁ Index ▁ = ▁ " + i ) ; else System . out . println ( " No ▁ repeated ▁ Char " ) ; } }


"Efficiently merging two sorted arrays with O ( 1 ) extra space |  ; Find maximum element of both array ; Increment one two avoid collision of 0 and maximum element of array in modulo operation ; Recover back original element to compare ; Update element by adding multiplication with new number ; Update element by adding multiplication with new number ; Process those elements which are left in array a ; Process those elements which are left in array a ; Finally update elements by dividing with maximum element ; Finally update elements by dividing with maximum element ; Driver code ; Length of a ; length of b ; Function Call"
How can the above be solved in Java?

import java . io . * ; class GFG { static void mergeArray ( int a [ ] , int b [ ] , int n , int m ) { int mx = 0 ; for ( int i = 0 ; i < n ; i ++ ) { mx = Math . max ( mx , a [ i ] ) ; } for ( int i = 0 ; i < m ; i ++ ) { mx = Math . max ( mx , b [ i ] ) ; } mx ++ ; int i = 0 , j = 0 , k = 0 ; while ( i < n && j < m && k < ( n + m ) ) { int e1 = a [ i ] % mx ; int e2 = b [ j ] % mx ; if ( e1 <= e2 ) { if ( k < n ) a [ k ] += ( e1 * mx ) ; else b [ k - n ] += ( e1 * mx ) ; i ++ ; k ++ ; } else { if ( k < n ) a [ k ] += ( e2 * mx ) ; else b [ k - n ] += ( e2 * mx ) ; j ++ ; k ++ ; } } while ( i < n ) { int el = a [ i ] % mx ; if ( k < n ) a [ k ] += ( el * mx ) ; else b [ k - n ] += ( el * mx ) ; i ++ ; k ++ ; } while ( j < m ) { int el = b [ j ] % mx ; if ( k < n ) b [ k ] += ( el * mx ) ; else b [ k - n ] += ( el * mx ) ; j ++ ; k ++ ; } for ( int in = 0 ; in < n ; in ++ ) a [ in ] = a [ in ] / mx ; for ( int in = 0 ; in < m ; in ++ ) b [ in ] = b [ in ] / mx ; return ; } public static void main ( String [ ] args ) { int a [ ] = { 3 , 5 , 6 , 8 , 12 } ; int b [ ] = { 1 , 4 , 9 , 13 } ; int n = a . length ; int m = b . length ; mergeArray ( a , b , n , m ) ; System . out . print ( " First ▁ array ▁ : ▁ " ) ; for ( int i = 0 ; i < n ; i ++ ) System . out . print ( a [ i ] + " ▁ " ) ; System . out . println ( ) ; System . out . print ( " Second ▁ array ▁ : ▁ " ) ; for ( int i = 0 ; i < m ; i ++ ) System . out . print ( b [ i ] + " ▁ " ) ; System . out . println ( ) ; } }


"Efficiently merging two sorted arrays with O ( 1 ) extra space |  ; length of first arr1 ; length of second arr2 ; Now traverse the array1 and if arr2 first element is less than arr1 then swap ; swap ; we will store the firstElement of array2 and left shift all the element and store the firstElement in arr2 [ k - 1 ] ; read the arr1 ; read the arr2 ; Driver Code"
How can the above be solved in Java?

import java . io . * ; class GFG { public static void mergeArray ( int [ ] arr1 , int [ ] arr2 ) { int n = arr1 . length ; int m = arr2 . length ; for ( int i = 0 ; i < n ; i ++ ) { if ( arr1 [ i ] > arr2 [ 0 ] ) { int temp = arr1 [ i ] ; arr1 [ i ] = arr2 [ 0 ] ; arr2 [ 0 ] = temp ; int firstElement = arr2 [ 0 ] ; int k ; for ( k = 1 ; k < m && arr2 [ k ] < firstElement ; k ++ ) { arr2 [ k - 1 ] = arr2 [ k ] ; } arr2 [ k - 1 ] = firstElement ; } } for ( int i : arr1 ) { System . out . print ( i + " ▁ " ) ; } System . out . println ( ) ; for ( int i : arr2 ) { System . out . print ( i + " ▁ " ) ; } } public static void main ( String [ ] args ) { int [ ] arr1 = { 1 , 3 , 5 , 7 } ; int [ ] arr2 = { 0 , 2 , 6 , 8 , 9 } ; mergeArray ( arr1 , arr2 ) ; } }


"Efficiently merging two sorted arrays with O ( 1 ) extra space | Java program for Merging two sorted arrays with O ( 1 ) extra space ; Function to find next gap . ; comparing elements in the first array . ; comparing elements in both arrays . ; comparing elements in the second array . ; Driver Code ; Function Call"
How can the above be solved in Java?

public class MergeTwoSortedArrays { private static int nextGap ( int gap ) { if ( gap <= 1 ) return 0 ; return ( gap / 2 ) + ( gap % 2 ) ; } private static void merge ( int [ ] arr1 , int [ ] arr2 , int n , int m ) { int i , j , gap = n + m ; for ( gap = nextGap ( gap ) ; gap > 0 ; gap = nextGap ( gap ) ) { for ( i = 0 ; i + gap < n ; i ++ ) if ( arr1 [ i ] > arr1 [ i + gap ] ) { int temp = arr1 [ i ] ; arr1 [ i ] = arr1 [ i + gap ] ; arr1 [ i + gap ] = temp ; } for ( j = gap > n ? gap - n : 0 ; i < n && j < m ; i ++ , j ++ ) if ( arr1 [ i ] > arr2 [ j ] ) { int temp = arr1 [ i ] ; arr1 [ i ] = arr2 [ j ] ; arr2 [ j ] = temp ; } if ( j < m ) { for ( j = 0 ; j + gap < m ; j ++ ) if ( arr2 [ j ] > arr2 [ j + gap ] ) { int temp = arr2 [ j ] ; arr2 [ j ] = arr2 [ j + gap ] ; arr2 [ j + gap ] = temp ; } } } } public static void main ( String [ ] args ) { int [ ] a1 = { 10 , 27 , 38 , 43 , 82 } ; int [ ] a2 = { 3 , 9 } ; merge ( a1 , a2 , a1 . length , a2 . length ) ; System . out . print ( " First ▁ Array : ▁ " ) ; for ( int i = 0 ; i < a1 . length ; i ++ ) { System . out . print ( a1 [ i ] + " ▁ " ) ; } System . out . println ( ) ; System . out . print ( " Second ▁ Array : ▁ " ) ; for ( int i = 0 ; i < a2 . length ; i ++ ) { System . out . print ( a2 [ i ] + " ▁ " ) ; } } }


"Egg Dropping Puzzle with 2 Eggs and K Floors | Java program to find optimal number of trials for k floors and 2 eggs . ; Driver code"
How can the above be solved in Java?

import java . io . * ; class GFG { static int twoEggDrop ( int k ) { return ( int ) Math . ceil ( ( - 1.0 + Math . sqrt ( 1 + 8 * k ) ) / 2.0 ) ; } public static void main ( String [ ] args ) { int k = 100 ; System . out . println ( twoEggDrop ( k ) ) ; } }


"Egg Dropping Puzzle | DP |  ; Function to get minimum number of trials needed in worst case with n eggs and k floors ; If there are no floors , then no trials needed . OR if there is one floor , one trial needed . ; We need k trials for one egg and k floors ; Consider all droppings from 1 st floor to kth floor and return the minimum of these values plus 1. ; Driver code"
How can the above be solved in Java?

public class GFG { static int eggDrop ( int n , int k ) { if ( k == 1 k == 0 ) return k ; if ( n == 1 ) return k ; int min = Integer . MAX_VALUE ; int x , res ; for ( x = 1 ; x <= k ; x ++ ) { res = Math . max ( eggDrop ( n - 1 , x - 1 ) , eggDrop ( n , k - x ) ) ; if ( res < min ) min = res ; } return min + 1 ; } public static void main ( String args [ ] ) { int n = 2 , k = 10 ; System . out . print ( " Minimum ▁ number ▁ of ▁ " + " trials ▁ in ▁ worst ▁ case ▁ with ▁ " + n + " ▁ eggs ▁ and ▁ " + k + " ▁ floors ▁ is ▁ " + eggDrop ( n , k ) ) ; } }


"Egg Dropping Puzzle | DP | A Dynamic Programming based Java Program for the Egg Dropping Puzzle ; A utility function to get maximum of two integers ; Function to get minimum number of trials needed in worst case with n eggs and k floors ; A 2D table where entry eggFloor [ i ] [ j ] will represent minimum number of trials needed for i eggs and j floors . ; We need one trial for one floor and 0 trials for 0 floors ; We always need j trials for one egg and j floors . ; Fill rest of the entries in table using optimal substructure property ; eggFloor [ n ] [ k ] holds the result ; Driver program to test to pront printDups"
How can the above be solved in Java?

class EggDrop { static int max ( int a , int b ) { return ( a > b ) ? a : b ; } static int eggDrop ( int n , int k ) { int eggFloor [ ] [ ] = new int [ n + 1 ] [ k + 1 ] ; int res ; int i , j , x ; for ( i = 1 ; i <= n ; i ++ ) { eggFloor [ i ] [ 1 ] = 1 ; eggFloor [ i ] [ 0 ] = 0 ; } for ( j = 1 ; j <= k ; j ++ ) eggFloor [ 1 ] [ j ] = j ; for ( i = 2 ; i <= n ; i ++ ) { for ( j = 2 ; j <= k ; j ++ ) { eggFloor [ i ] [ j ] = Integer . MAX_VALUE ; for ( x = 1 ; x <= j ; x ++ ) { res = 1 + max ( eggFloor [ i - 1 ] [ x - 1 ] , eggFloor [ i ] [ j - x ] ) ; if ( res < eggFloor [ i ] [ j ] ) eggFloor [ i ] [ j ] = res ; } } } return eggFloor [ n ] [ k ] ; } public static void main ( String args [ ] ) { int n = 2 , k = 10 ; System . out . println ( " Minimum ▁ number ▁ of ▁ trials ▁ in ▁ worst " + " ▁ case ▁ with ▁ " + n + " ▁ eggs ▁ and ▁ " + k + " ▁ floors ▁ is ▁ " + eggDrop ( n , k ) ) ; } }


"Eggs dropping puzzle ( Binomial Coefficient and Binary Search Solution ) | Java program to find minimum number of trials in worst case . ; Find sum of binomial coefficients xCi ( where i varies from 1 to n ) . If the sum becomes more than K ; Do binary search to find minimum number of trials in worst case . ; Initialize low and high as 1 st and last floors ; Do binary search , for every mid , find sum of binomial coefficients and check if the sum is greater than k or not . ; Driver code"
How can the above be solved in Java?

class Geeks { static int binomialCoeff ( int x , int n , int k ) { int sum = 0 , term = 1 ; for ( int i = 1 ; i <= n && sum < k ; ++ i ) { term *= x - i + 1 ; term /= i ; sum += term ; } return sum ; } static int minTrials ( int n , int k ) { int low = 1 , high = k ; while ( low < high ) { int mid = ( low + high ) / 2 ; if ( binomialCoeff ( mid , n , k ) < k ) low = mid + 1 ; else high = mid ; } return low ; } public static void main ( String args [ ] ) { System . out . println ( minTrials ( 2 , 10 ) ) ; } }


"Eggs dropping puzzle | Set 2 | Java implementation of the approach ; Function to return the minimum number of trials needed in the worst case with n eggs and k floors ; Fill all the entries in table using optimal substructure property ; Return the minimum number of moves ; Driver code"
How can the above be solved in Java?

class GFG { static int eggDrop ( int n , int k ) { int dp [ ] [ ] = new int [ k + 1 ] [ n + 1 ] ; int x = 0 ; while ( dp [ x ] [ n ] < k ) { x ++ ; for ( int i = 1 ; i <= n ; i ++ ) dp [ x ] [ i ] = dp [ x - 1 ] [ i - 1 ] + dp [ x - 1 ] [ i ] + 1 ; } return x ; } public static void main ( String args [ ] ) { int n = 2 , k = 36 ; System . out . println ( eggDrop ( n , k ) ) ; } }


"Element equal to the sum of all the remaining elements | Java implementation of the above approach ; Function to find the element ; sum is use to store sum of all elements of array ; iterate over all elements ; Driver code"
How can the above be solved in Java?

import java . io . * ; class GFG { static int findEle ( int arr [ ] , int n ) { int sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) sum += arr [ i ] ; for ( int i = 0 ; i < n ; i ++ ) if ( arr [ i ] == sum - arr [ i ] ) return arr [ i ] ; return - 1 ; } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 2 , 3 , 6 } ; int n = arr . length ; System . out . print ( findEle ( arr , n ) ) ; } }


"Elements greater than the previous and next element in an Array | Java program to print elements greater than the previous and next element in an Array ; Function to print elements greater than the previous and next element in an Array ; Traverse array from index 1 to n - 2 and check for the given condition ; Driver Code"
How can the above be solved in Java?

class GfG { static void printElements ( int arr [ ] , int n ) { for ( int i = 1 ; i < n - 1 ; i ++ ) { if ( arr [ i ] > arr [ i - 1 ] && arr [ i ] > arr [ i + 1 ] ) System . out . print ( arr [ i ] + " ▁ " ) ; } } public static void main ( String [ ] args ) { int arr [ ] = { 2 , 3 , 1 , 5 , 4 , 9 , 8 , 7 , 5 } ; int n = arr . length ; printElements ( arr , n ) ; } }


"Elements of Array which can be expressed as power of prime numbers | Java program to print all elements of Array which can be expressed as power of prime numbers ; Function to mark all the exponent of prime numbers ; If number is prime then marking all of its exponent true ; Function to display all required elements ; Function to print the required numbers ; To find the largest number ; Function call to mark all the Exponential prime nos . ; Function call ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { static void ModifiedSieveOfEratosthenes ( int N , boolean Expo_Prime [ ] ) { boolean [ ] primes = new boolean [ N ] ; Arrays . fill ( primes , true ) ; for ( int i = 2 ; i < N ; i ++ ) { if ( primes [ i ] ) { int no = i ; while ( no <= N ) { Expo_Prime [ no ] = true ; no *= i ; } for ( int j = i * i ; j < N ; j += i ) primes [ j ] = false ; } } } static void Display ( int arr [ ] , boolean Expo_Prime [ ] , int n ) { for ( int i = 0 ; i < n ; i ++ ) if ( Expo_Prime [ arr [ i ] ] ) System . out . print ( arr [ i ] + " ▁ " ) ; } static void FindExpoPrime ( int arr [ ] , int n ) { int max = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( max < arr [ i ] ) max = arr [ i ] ; } boolean [ ] Expo_Prime = new boolean [ max + 1 ] ; ModifiedSieveOfEratosthenes ( max + 1 , Expo_Prime ) ; Display ( arr , Expo_Prime , n ) ; } public static void main ( String [ ] args ) { int arr [ ] = { 4 , 6 , 9 , 16 , 1 , 3 , 12 , 36 , 625 , 1000 } ; int n = arr . length ; FindExpoPrime ( arr , n ) ; } }


"Elements of Array which can be expressed as power of some integer to given exponent K | Java implementation to print elements of the Array which can be expressed as power of some integer to given exponent K ; Method returns Nth power of A ; Smaller eps , denotes more accuracy ; Initializing difference between two roots by Integer . MAX_VALUE ; x ^ K denotes current value of x ; loop untill we reach desired accuracy ; calculating current value from previous value by newton 's method ; Function to check whether its k root is an integer or not ; Function to find the numbers ; Driver code"
How can the above be solved in Java?

class GFG { static double nthRoot ( long A , long N ) { double xPre = 7 ; double eps = 1e-3 ; double delX = Integer . MAX_VALUE ; double xK = 0 ; while ( delX > eps ) { xK = ( ( N - 1.0 ) * xPre + ( double ) A / Math . pow ( xPre , N - 1 ) ) / ( double ) N ; delX = Math . abs ( xK - xPre ) ; xPre = xK ; } return xK ; } static boolean check ( long no , int k ) { double kth_root = nthRoot ( no , k ) ; long num = ( long ) kth_root ; if ( Math . abs ( num - kth_root ) < 1e-4 ) return true ; return false ; } static void printExpo ( long arr [ ] , int n , int k ) { for ( int i = 0 ; i < n ; i ++ ) { if ( check ( arr [ i ] , k ) ) System . out . print ( arr [ i ] + " ▁ " ) ; } } public static void main ( String [ ] args ) { int K = 6 ; long arr [ ] = { 46656 , 64 , 256 , 729 , 16 , 1000 } ; int n = arr . length ; printExpo ( arr , n , K ) ; } }


"Elements that occurred only once in the array | Java implementation of above approach ; Function to find the elements that appeared only once in the array ; Sort the array ; Check for first element ; Check for all the elements if it is different its adjacent elements ; Check for the last element ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { static void occurredOnce ( int arr [ ] , int n ) { Arrays . sort ( arr ) ; if ( arr [ 0 ] != arr [ 1 ] ) System . out . println ( arr [ 0 ] + " ▁ " ) ; for ( int i = 1 ; i < n - 1 ; i ++ ) if ( arr [ i ] != arr [ i + 1 ] && arr [ i ] != arr [ i - 1 ] ) System . out . print ( arr [ i ] + " ▁ " ) ; if ( arr [ n - 2 ] != arr [ n - 1 ] ) System . out . print ( arr [ n - 1 ] + " ▁ " ) ; } public static void main ( String args [ ] ) { int arr [ ] = { 7 , 7 , 8 , 8 , 9 , 1 , 1 , 4 , 2 , 2 } ; int n = arr . length ; occurredOnce ( arr , n ) ; } }


"Elements that occurred only once in the array | Java implementation to find elements that appeared only once ; Function to find the elements that appeared only once in the array ; Check if the first and last element is equal . If yes , remove those elements ; Start traversing the remaining elements ; Check if current element is equal to the element at immediate previous index If yes , check the same for next element ; Else print the current element ; Check for the last element ; Driver code"
How can the above be solved in Java?

class GFG { static void occurredOnce ( int arr [ ] , int n ) { int i = 1 , len = n ; if ( arr [ 0 ] == arr [ len - 1 ] ) { i = 2 ; len -- ; } for ( ; i < n ; i ++ ) if ( arr [ i ] == arr [ i - 1 ] ) i ++ ; else System . out . print ( arr [ i - 1 ] + " ▁ " ) ; if ( arr [ n - 1 ] != arr [ 0 ] && arr [ n - 1 ] != arr [ n - 2 ] ) System . out . print ( arr [ n - 1 ] ) ; } public static void main ( String args [ ] ) { int arr [ ] = { 7 , 7 , 8 , 8 , 9 , 1 , 1 , 4 , 2 , 2 } ; int n = arr . length ; occurredOnce ( arr , n ) ; } }


"Elements that occurred only once in the array | Java implementation to find elements that appeared only once ; Function to find the elements that appeared only once in the array ; Store all the elements in the map with their occurrence ; Traverse the map and print all the elements with occurrence 1 ; Driver code"
How can the above be solved in Java?

import java . util . * ; import java . io . * ; class GFG { static void occurredOnce ( int [ ] arr , int n ) { HashMap < Integer , Integer > mp = new HashMap < > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( mp . containsKey ( arr [ i ] ) ) mp . put ( arr [ i ] , 1 + mp . get ( arr [ i ] ) ) ; else mp . put ( arr [ i ] , 1 ) ; } for ( Map . Entry entry : mp . entrySet ( ) ) { if ( Integer . parseInt ( String . valueOf ( entry . getValue ( ) ) ) == 1 ) System . out . print ( entry . getKey ( ) + " ▁ " ) ; } } public static void main ( String args [ ] ) { int [ ] arr = { 7 , 7 , 8 , 8 , 9 , 1 , 1 , 4 , 2 , 2 } ; int n = arr . length ; occurredOnce ( arr , n ) ; } }


"Elements to be added so that all elements of a range are present in array | Java implementation of the approach ; Function to count numbers to be added ; Make a hash of elements and store minimum and maximum element ; Traverse all elements from minimum to maximum and count if it is not in the hash ; Drivers code"
How can the above be solved in Java?

import java . util . HashSet ; class GFG { static int countNum ( int arr [ ] , int n ) { HashSet < Integer > s = new HashSet < > ( ) ; int count = 0 , maxm = Integer . MIN_VALUE , minm = Integer . MAX_VALUE ; for ( int i = 0 ; i < n ; i ++ ) { s . add ( arr [ i ] ) ; if ( arr [ i ] < minm ) minm = arr [ i ] ; if ( arr [ i ] > maxm ) maxm = arr [ i ] ; } for ( int i = minm ; i <= maxm ; i ++ ) if ( ! s . contains ( i ) ) count ++ ; return count ; } public static void main ( String [ ] args ) { int arr [ ] = { 3 , 5 , 8 , 6 } ; int n = arr . length ; System . out . println ( countNum ( arr , n ) ) ; } }


"Elements to be added so that all elements of a range are present in array | java program for above implementation ; Function to count numbers to be added ; Sort the array ; Check if elements are consecutive or not . If not , update count ; Drivers code"
How can the above be solved in Java?

import java . io . * ; import java . util . * ; public class GFG { static int countNum ( int [ ] arr , int n ) { int count = 0 ; Arrays . sort ( arr ) ; for ( int i = 0 ; i < n - 1 ; i ++ ) if ( arr [ i ] != arr [ i + 1 ] && arr [ i ] != arr [ i + 1 ] - 1 ) count += arr [ i + 1 ] - arr [ i ] - 1 ; return count ; } static public void main ( String [ ] args ) { int [ ] arr = { 3 , 5 , 8 , 6 } ; int n = arr . length ; System . out . println ( countNum ( arr , n ) ) ; } }


"Emirp numbers | Java program to print Emirp numbers less than n ; Function to find reverse of any number ; Sieve method used for generating emirp number ( use of sieve of Eratosthenes ) ; Create a boolean array " prime [ 0 . . n ] " and initialize all entries it as true . A value in prime [ i ] will finally be false if i is Not a prime , else true . ; If prime [ p ] is not changed , then it is a prime ; Update all multiples of p ; Traverse all prime numbers ; Find reverse a number ; A number is emrip if it is not a palindrome number and its reverse is also prime . ; Mark reverse prime as false so that it 's  not printed again ; Driver code"
How can the above be solved in Java?

import java . util . Arrays ; class GFG { static int reverse ( int x ) { int rev = 0 ; while ( x > 0 ) { rev = ( rev * 10 ) + x % 10 ; x = x / 10 ; } return rev ; } static void printEmirp ( int n ) { boolean prime [ ] = new boolean [ n + 1 ] ; Arrays . fill ( prime , true ) ; for ( int p = 2 ; p * p <= n ; p ++ ) { if ( prime [ p ] == true ) { for ( int i = p * 2 ; i <= n ; i += p ) prime [ i ] = false ; } } for ( int p = 2 ; p <= n ; p ++ ) { if ( prime [ p ] ) { int rev = reverse ( p ) ; if ( p != rev && rev <= n && prime [ rev ] ) { System . out . print ( p + " ▁ " + rev + " ▁ " ) ; prime [ rev ] = false ; } } } } public static void main ( String [ ] args ) { int n = 100 ; printEmirp ( n ) ; } }


"Encoding a word into Pig Latin | Java program to encode a word to a Pig Latin . ; the index of the first vowel is stored . ; Pig Latin is possible only if vowels is present ; Take all characters after index ( including index ) . Append all characters which are before index . Finally append " ay " ; Driver code"
How can the above be solved in Java?

class GFG { static boolean isVowel ( char c ) { return ( c == ' A ' c == ' E ' c == ' I ' c == ' O ' c == ' U ' c == ' a ' c == ' e ' c == ' i ' c == ' o ' c == ' u ' ) ; } static String pigLatin ( String s ) { int len = s . length ( ) ; int index = - 1 ; for ( int i = 0 ; i < len ; i ++ ) { if ( isVowel ( s . charAt ( i ) ) ) { index = i ; break ; } } if ( index == - 1 ) return " - 1" ; return s . substring ( index ) + s . substring ( 0 , index ) + " ay " ; } public static void main ( String [ ] args ) { String str = pigLatin ( " graphic " ) ; if ( str == " - 1" ) System . out . print ( " No ▁ vowels ▁ found . " + " Pig ▁ Latin ▁ not ▁ possible " ) ; else System . out . print ( str ) ; } }


"Encryption and Decryption of String according to given technique | Java implementation for Custom Encryption and Decryption of String ; Function to encrypt the String ; Matrix to generate the Encrypted String ; Fill the matrix row - wise ; Loop to generate encrypted String ; Function to decrypt the String ; Matrix to generate the Encrypted String ; Fill the matrix column - wise ; Loop to generate decrypted String ; Driver Code ; Encryption of String ; Decryption of String"
How can the above be solved in Java?

 class GFG { static String encryption ( char [ ] s ) { int l = s . length ; int b = ( int ) Math . ceil ( Math . sqrt ( l ) ) ; int a = ( int ) Math . floor ( Math . sqrt ( l ) ) ; String encrypted = " " ; if ( b * a < l ) { if ( Math . min ( b , a ) == b ) { b = b + 1 ; } else { a = a + 1 ; } } char [ ] [ ] arr = new char [ a ] [ b ] ; int k = 0 ; for ( int j = 0 ; j < a ; j ++ ) { for ( int i = 0 ; i < b ; i ++ ) { if ( k < l ) { arr [ j ] [ i ] = s [ k ] ; } k ++ ; } } for ( int j = 0 ; j < b ; j ++ ) { for ( int i = 0 ; i < a ; i ++ ) { encrypted = encrypted + arr [ i ] [ j ] ; } } return encrypted ; } static String decryption ( char [ ] s ) { int l = s . length ; int b = ( int ) Math . ceil ( Math . sqrt ( l ) ) ; int a = ( int ) Math . floor ( Math . sqrt ( l ) ) ; String decrypted = " " ; char [ ] [ ] arr = new char [ a ] [ b ] ; int k = 0 ; for ( int j = 0 ; j < b ; j ++ ) { for ( int i = 0 ; i < a ; i ++ ) { if ( k < l ) { arr [ j ] [ i ] = s [ k ] ; } k ++ ; } } for ( int j = 0 ; j < a ; j ++ ) { for ( int i = 0 ; i < b ; i ++ ) { decrypted = decrypted + arr [ i ] [ j ] ; } } return decrypted ; } public static void main ( String [ ] args ) { String s = " Geeks ▁ For ▁ Geeks " ; String encrypted ; String decrypted ; encrypted = encryption ( s . toCharArray ( ) ) ; System . out . print ( encrypted + "
"); decrypted = decryption ( encrypted . toCharArray ( ) ) ; System . out . print ( decrypted ) ; } }


"Enlightened Numbers | Java implementation of the above approach ; Function to check if N is a Composite Number ; Corner cases ; This is checked so that we can skip middle five numbers in below loop ; Function to return concatenation of distinct prime factors of a given number n ; Handle prime factor 2 explicitly so that can optimally handle other prime factors . ; n must be odd at this point . So we can skip one element ( Note i = i + 2 ) ; While i divides n , print i and divide n ; This condition is to handle the case when n is a prime number greater than 2 ; Function to check if a number is is an enlightened number ; number should not be prime ; converting N to string ; function call ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { static boolean isComposite ( int n ) { if ( n <= 3 ) return false ; if ( n % 2 == 0 n % 3 == 0 ) return true ; for ( int i = 5 ; i * i <= n ; i = i + 6 ) if ( n % i == 0 || n % ( i + 2 ) == 0 ) return true ; return false ; } static String concatenatePrimeFactors ( int n ) { String concatenate = " " ; if ( n % 2 == 0 ) { concatenate += "2" ; while ( n % 2 == 0 ) n = n / 2 ; } for ( int i = 3 ; i <= Math . sqrt ( n ) ; i = i + 2 ) { if ( n % i == 0 ) { concatenate += i ; while ( n % i == 0 ) n = n / i ; } } if ( n > 2 ) concatenate += n ; return concatenate ; } static boolean isEnlightened ( int N ) { if ( ! isComposite ( N ) ) return false ; String num = String . valueOf ( N ) ; String prefixConc = concatenatePrimeFactors ( N ) ; return num . startsWith ( prefixConc ) ; } public static void main ( String args [ ] ) { int n = 250 ; if ( isEnlightened ( n ) ) System . out . println ( " Yes " ) ; else System . out . println ( " No " ) ; } }


"Enneacontagon Number | Java program for above approach ; Finding the nth enneacontagon number ; Driver code"
How can the above be solved in Java?

class GFG { public static int enneacontagonNum ( int n ) { return ( 88 * n * n - 86 * n ) / 2 ; } public static void main ( String [ ] args ) { int n = 3 ; System . out . println ( "3rd ▁ enneacontagon ▁ Number ▁ is ▁ = ▁ " + enneacontagonNum ( n ) ) ; } }


"Entringer Number | JAVA Code For Entringer Number ; Return Entringer Number E ( n , k ) ; Base Case ; Base Case ; Recursive step ; Driver program to test above function"
How can the above be solved in Java?

import java . util . * ; class GFG { static int zigzag ( int n , int k ) { if ( n == 0 && k == 0 ) return 1 ; if ( k == 0 ) return 0 ; return zigzag ( n , k - 1 ) + zigzag ( n - 1 , n - k ) ; } public static void main ( String [ ] args ) { int n = 4 , k = 3 ; System . out . println ( zigzag ( n , k ) ) ; } }


"Entringer Number | JAVA Code For Entringer Number ; Return Entringer Number E ( n , k ) ; Base cases ; Finding dp [ i ] [ j ] ; Driver program to test above function"
How can the above be solved in Java?

import java . util . * ; class GFG { static int zigzag ( int n , int k ) { int dp [ ] [ ] = new int [ n + 1 ] [ k + 1 ] ; dp [ 0 ] [ 0 ] = 1 ; for ( int i = 1 ; i <= n ; i ++ ) dp [ i ] [ 0 ] = 0 ; for ( int i = 1 ; i <= n ; i ++ ) { for ( int j = 1 ; j <= Math . min ( i , k ) ; j ++ ) dp [ i ] [ j ] = dp [ i ] [ j - 1 ] + dp [ i - 1 ] [ i - j ] ; } return dp [ n ] [ k ] ; } public static void main ( String [ ] args ) { int n = 4 , k = 3 ; System . out . println ( zigzag ( n , k ) ) ; } }


"Equal Sum and XOR of three Numbers | Java implementation of the approach ; Function to calculate power of 3 ; Function to return the count of the unset bit ( zeros ) ; Check the bit is 0 or not ; Right shifting ( dividing by 2 ) ; Driver Code"
How can the above be solved in Java?

import java . util . * ; class GFG { static long calculate ( int bit_cnt ) { long res = 1 ; while ( bit_cnt -- > 0 ) { res = res * 3 ; } return res ; } static int unset_bit_count ( long n ) { int count = 0 ; while ( n > 0 ) { if ( ( n & 1 ) == 0 ) count ++ ; n = n >> 1 ; } return count ; } public static void main ( String [ ] args ) { long n ; n = 2 ; int count = unset_bit_count ( n ) ; long ans = calculate ( count ) ; System . out . println ( ans ) ; } }


"Equal Sum and XOR | Java program to print count of values such that n + i = n ^ i ; function to count number of values less than equal to n that satisfy the given condition ; Traverse all numbers from 0 to n and increment result only when given condition is satisfied . ; Driver program to test above function"
How can the above be solved in Java?

import java . util . * ; class GFG { public static int countValues ( int n ) { int countV = 0 ; for ( int i = 0 ; i <= n ; i ++ ) if ( ( n + i ) == ( n ^ i ) ) countV ++ ; return countV ; } public static void main ( String [ ] args ) { int n = 12 ; System . out . println ( countValues ( n ) ) ; } }


"Equal Sum and XOR | Java program to print count of values such that n + i = n ^ i ; function to count number of values less than equal to n that satisfy the given condition ; unset_bits keeps track of count of un - set bits in binary representation of n ; Return 2 ^ unset_bits ; Driver program to test above function"
How can the above be solved in Java?

import java . util . * ; class GFG { public static int countValues ( int n ) { int unset_bits = 0 ; while ( n > 0 ) { if ( ( n & 1 ) == 0 ) unset_bits ++ ; n = n >> 1 ; } return 1 << unset_bits ; } public static void main ( String [ ] args ) { int n = 12 ; System . out . println ( countValues ( n ) ) ; } }


"Equally divide into two sets such that one set has maximum distinct elements | Java program to equally divide n elements into two sets such that second set has maximum distinct elements . ; Driver code"
How can the above be solved in Java?

import java . util . * ; class Geeks { static int distribution ( int arr [ ] , int n ) { Arrays . sort ( arr ) ; int count = 1 ; for ( int i = 1 ; i < n ; i ++ ) if ( arr [ i ] > arr [ i - 1 ] ) count ++ ; return Math . min ( count , n / 2 ) ; } public static void main ( String args [ ] ) { int arr [ ] = { 1 , 1 , 2 , 1 , 3 , 4 } ; int n = arr . length ; System . out . println ( distribution ( arr , n ) ) ; } }


"Equally divide into two sets such that one set has maximum distinct elements | Java program to equally divide n elements into two sets such that second set has maximum distinct elements . ; Insert all the resources in the set There will be unique resources in the set ; return minimum of distinct resources and n / 2 ; Driver code"
How can the above be solved in Java?

 import java . util . * ; class GFG { static int distribution ( int arr [ ] , int n ) { Set < Integer > resources = new HashSet < Integer > ( ) ; for ( int i = 0 ; i < n ; i ++ ) resources . add ( arr [ i ] ) ; return Math . min ( resources . size ( ) , n / 2 ) ; } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 1 , 2 , 1 , 3 , 4 } ; int n = arr . length ; System . out . print ( distribution ( arr , n ) + "
"); } }