"Chinese Remainder Theorem | Set 1 ( Introduction ) | A Java program to demonstrate the working of Chinese remainder Theorem ; k is size of num [ ] and rem [ ] . Returns the smallest number x such that : x % num [ 0 ] = rem [ 0 ] , x % num [ 1 ] = rem [ 1 ] , ... ... ... ... ... ... x % num [ k - 2 ] = rem [ k - 1 ] Assumption : Numbers in num [ ] are pairwise coprime ( gcd for every pair is 1 ) ; As per the Chinese remainder theorem , this loop will always break . ; Check if remainder of x % num [ j ] is rem [ j ] or not ( for all j from 0 to k - 1 ) ; If all remainders matched , we found x ; Else try next number ; Driver method"
How can the above be solved in Java?

import java . io . * ; class GFG { static int findMinX ( int num [ ] , int rem [ ] , int k ) { while ( true ) { int j ; for ( j = 0 ; j < k ; j ++ ) if ( x % num [ j ] != rem [ j ] ) break ; if ( j == k ) return x ; x ++ ; } } public static void main ( String args [ ] ) { int num [ ] = { 3 , 4 , 5 } ; int rem [ ] = { 2 , 3 , 1 } ; int k = num . length ; System . out . println ( " x ▁ is ▁ " + findMinX ( num , rem , k ) ) ; } }


"Chinese Remainder Theorem | Set 2 ( Inverse Modulo based Implementation ) | A Java program to demonstrate working of Chinise remainder Theorem ; Returns modulo inverse of a with respect to m using extended Euclid Algorithm . Refer below post for details : https : www . geeksforgeeks . org / multiplicative - inverse - under - modulo - m / ; Apply extended Euclid Algorithm ; q is quotient ; m is remainder now , process same as euclid 's algo ; Make x1 positive ; k is size of num [ ] and rem [ ] . Returns the smallest number x such that : x % num [ 0 ] = rem [ 0 ] , x % num [ 1 ] = rem [ 1 ] , ... ... ... ... ... ... x % num [ k - 2 ] = rem [ k - 1 ] Assumption : Numbers in num [ ] are pairwise coprime ( gcd for every pair is 1 ) ; Compute product of all numbers ; Initialize result ; Apply above formula ; Driver method"
How can the above be solved in Java?

import java . io . * ; class GFG { static int inv ( int a , int m ) { int m0 = m , t , q ; int x0 = 0 , x1 = 1 ; if ( m == 1 ) return 0 ; while ( a > 1 ) { q = a / m ; t = m ; m = a % m ; a = t ; t = x0 ; x0 = x1 - q * x0 ; x1 = t ; } if ( x1 < 0 ) x1 += m0 ; return x1 ; } static int findMinX ( int num [ ] , int rem [ ] , int k ) { int prod = 1 ; for ( int i = 0 ; i < k ; i ++ ) prod *= num [ i ] ; int result = 0 ; for ( int i = 0 ; i < k ; i ++ ) { int pp = prod / num [ i ] ; result += rem [ i ] * inv ( pp , num [ i ] ) * pp ; } return result % prod ; } public static void main ( String args [ ] ) { int num [ ] = { 3 , 4 , 5 } ; int rem [ ] = { 2 , 3 , 1 } ; int k = num . length ; System . out . println ( " x ▁ is ▁ " + findMinX ( num , rem , k ) ) ; } }


"Chocolate Distribution Problem | JAVA Code For Chocolate Distribution Problem ; arr [ 0. . n - 1 ] represents sizes of packets . m is number of students . Returns minimum difference between maximum and minimum values of distribution . ; if there are no chocolates or number of students is 0 ; Sort the given packets ; Number of students cannot be more than number of packets ; Largest number of chocolates ; Find the subarray of size m such that difference between last ( maximum in case of sorted ) and first ( minimum in case of sorted ) elements of subarray is minimum . ; Driver program to test above function ; int m = 7 ; Number of students"
How can the above be solved in Java?

import java . util . * ; class GFG { static int findMinDiff ( int arr [ ] , int n , int m ) { if ( m == 0 n == 0 ) return 0 ; Arrays . sort ( arr ) ; if ( n < m ) return - 1 ; int min_diff = Integer . MAX_VALUE ; for ( int i = 0 ; i + m - 1 < n ; i ++ ) { int diff = arr [ i + m - 1 ] - arr [ i ] ; if ( diff < min_diff ) min_diff = diff ; } return min_diff ; } public static void main ( String [ ] args ) { int arr [ ] = { 12 , 4 , 7 , 9 , 2 , 23 , 25 , 41 , 30 , 40 , 28 , 42 , 30 , 44 , 48 , 43 , 50 } ; int n = arr . length ; System . out . println ( " Minimum ▁ difference ▁ is ▁ " + findMinDiff ( arr , n , m ) ) ; } }


"Chocolate Distribution Problem | Set 2 | Java program for above approach ; Function to return minimum number of chocolates ; decreasing sequence ; add the chocolates received by that person ; end point of decreasing sequence ; val = 1 ; reset value at that index ; increasing sequence ; flat sequence ; add value of chocolates at position n - 1 ; helper function to get sum of decreasing sequence ; value obtained from decreasing sequence also the count of values in the sequence ; assigning max of values obtained from increasing and decreasing sequences ; sum of count - 1 values & peak value sum of natural numbers : ( n * ( n + 1 ) ) / 2 ; Driver code"
How can the above be solved in Java?

import java . io . * ; class GFG { public static int minChocolates ( int [ ] a , int n ) { int i = 0 , j = 0 ; int res = 0 , val = 1 ; while ( j < n - 1 ) { if ( a [ j ] > a [ j + 1 ] ) { j += 1 ; continue ; } if ( i == j ) res += val ; else { res += get_sum ( val , i , j ) ; } if ( a [ j ] < a [ j + 1 ] ) val += 1 ; else val = 1 ; j += 1 ; i = j ; } if ( i == j ) res += val ; else res += get_sum ( val , i , j ) ; return res ; } public static int get_sum ( int peak , int start , int end ) { int count = end - start + 1 ; peak = ( peak > count ) ? peak : count ; int s = peak + ( ( ( count - 1 ) * count ) >> 1 ) ; return s ; } } public static void main ( String [ ] args ) { int [ ] a = { 5 , 5 , 4 , 3 , 2 , 1 } ; int n = a . length ; System . out . print ( " Minimum ▁ number ▁ of ▁ chocolates ▁ = ▁ " + minChocolates ( a , n ) ) ; }


"Chocolate Distribution Problem | Set 2 | Java program for the above approach ; FUnction to print minimum number of candies required ; Distribute 1 chocolate to each ; Traverse from left to right ; Traverse from right to left ; Initialize sum ; Find total sum ; Return sum ; Driver Code ; Given array ; Size of the given array"
How can the above be solved in Java?

 import java . util . * ; class GFG { static void minChocolates ( int A [ ] , int N ) { int [ ] B = new int [ N ] ; for ( int i = 0 ; i < N ; i ++ ) { B [ i ] = 1 ; } for ( int i = 1 ; i < N ; i ++ ) { if ( A [ i ] > A [ i - 1 ] ) B [ i ] = B [ i - 1 ] + 1 ; else B [ i ] = 1 ; } for ( int i = N - 2 ; i >= 0 ; i -- ) { if ( A [ i ] > A [ i + 1 ] ) B [ i ] = Math . max ( B [ i + 1 ] + 1 , B [ i ] ) ; else B [ i ] = Math . max ( B [ i ] , 1 ) ; } int sum = 0 ; for ( int i = 0 ; i < N ; i ++ ) { sum += B [ i ] ; } System . out . print ( sum + "
"); } public static void main ( String [ ] args ) { int A [ ] = { 23 , 14 , 15 , 14 , 56 , 29 , 14 } ; int N = A . length ; minChocolates ( A , N ) ; } }


"Cholesky Decomposition : Matrix Decomposition | Java program to decompose a matrix using Cholesky Decomposition ; Decomposing a matrix into Lower Triangular ; summation for diagonals ; Evaluating L ( i , j ) using L ( j , j ) ; Displaying Lower Triangular and its Transpose ; Lower Triangular ; Transpose of Lower Triangular ; Driver Code"
How can the above be solved in Java?

class GFG { static void Cholesky_Decomposition ( int [ ] [ ] matrix , int n ) { int [ ] [ ] lower = new int [ n ] [ n ] ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = 0 ; j <= i ; j ++ ) { int sum = 0 ; if ( j == i ) { for ( int k = 0 ; k < j ; k ++ ) sum += ( int ) Math . pow ( lower [ j ] [ k ] , 2 ) ; lower [ j ] [ j ] = ( int ) Math . sqrt ( matrix [ j ] [ j ] - sum ) ; } else { for ( int k = 0 ; k < j ; k ++ ) sum += ( lower [ i ] [ k ] * lower [ j ] [ k ] ) ; lower [ i ] [ j ] = ( matrix [ i ] [ j ] - sum ) / lower [ j ] [ j ] ; } } } System . out . println ( " ▁ Lower ▁ Triangular 	 ▁ Transpose " ) ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = 0 ; j < n ; j ++ ) System . out . print ( lower [ i ] [ j ] + " 	 " ) ; System . out . print ( " " ) ; for ( int j = 0 ; j < n ; j ++ ) System . out . print ( lower [ j ] [ i ] + " 	 " ) ; System . out . println ( ) ; } } public static void main ( String [ ] args ) { int n = 3 ; int [ ] [ ] matrix = new int [ ] [ ] { { 4 , 12 , - 16 } , { 12 , 37 , - 43 } , { - 16 , - 43 , 98 } } ; Cholesky_Decomposition ( matrix , n ) ; } }


"Choose X such that ( A xor X ) + ( B xor X ) is minimized | Java implementation of above approach ; finding X ; finding Sum ; Driver Code"
How can the above be solved in Java?

import java . io . * ; class GFG { public static int findX ( int A , int B ) { return A & B ; } public static int findSum ( int A , int B ) { return A ^ B ; } public static void main ( String [ ] args ) { int A = 2 , B = 3 ; System . out . print ( " X ▁ = ▁ " + findX ( A , B ) + " , ▁ Sum ▁ = ▁ " + findSum ( A , B ) ) ; } }


"Choose X such that ( A xor X ) + ( B xor X ) is minimized | Java implementation of the approach ; Function to return the integer X such that ( A xor X ) + ( B ^ X ) is minimized ; While either A or B is non - zero ; Position at which both A and B have a set bit ; Inserting a set bit in x ; Right shifting both numbers to traverse all the bits ; Driver code"
How can the above be solved in Java?

class GFG { static int findX ( int A , int B ) { int j = 0 , x = 0 ; while ( A != 0 B != 0 ) { if ( ( A % 2 == 1 ) && ( B % 2 == 1 ) ) { x += ( 1 << j ) ; } A >>= 1 ; B >>= 1 ; j += 1 ; } return x ; } public static void main ( String [ ] args ) { int A = 2 , B = 3 ; int X = findX ( A , B ) ; System . out . println ( " X ▁ = ▁ " + X + " , ▁ Sum ▁ = ▁ " + ( ( A ^ X ) + ( B ^ X ) ) ) ; } }


"Choose an integer K such that maximum of the xor values of K with all Array elements is minimized | Java implementation to find Minimum possible value of the maximum xor in an array by choosing some integer ; Function to calculate Minimum possible value of the Maximum XOR in an array ; Base case ; Divide elements into two sections ; Traverse all elements of current section and divide in two groups ; Check if one of the sections is empty ; Explore both the possibilities using recursion ; Function to calculate minimum XOR value ; Start recursion from the most significant pos position ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { static int calculate ( Vector < Integer > section , int pos ) { if ( pos < 0 ) return 0 ; Vector < Integer > on_section = new Vector < Integer > ( ) , off_section = new Vector < Integer > ( ) ; for ( int el : section ) { if ( ( ( el >> pos ) & 1 ) == 0 ) off_section . add ( el ) ; else on_section . add ( el ) ; } if ( off_section . size ( ) == 0 ) return calculate ( on_section , pos - 1 ) ; if ( on_section . size ( ) == 0 ) return calculate ( off_section , pos - 1 ) ; return Math . min ( calculate ( off_section , pos - 1 ) , calculate ( on_section , pos - 1 ) ) + ( 1 << pos ) ; } static int minXorValue ( int a [ ] , int n ) { Vector < Integer > section = new Vector < Integer > ( ) ; for ( int i = 0 ; i < n ; i ++ ) section . add ( a [ i ] ) ; return calculate ( section , 30 ) ; } public static void main ( String [ ] args ) { int N = 4 ; int A [ ] = { 3 , 2 , 5 , 6 } ; System . out . print ( minXorValue ( A , N ) ) ; } }


"Choose k array elements such that difference of maximum and minimum is minimized | Java program to find minimum difference of maximum and minimum of K number . ; Return minimum difference of maximum and minimum of k elements of arr [ 0. . n - 1 ] . ; Sorting the array . ; Find minimum value among all K size subarray . ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { static int minDiff ( int arr [ ] , int n , int k ) { int result = Integer . MAX_VALUE ; Arrays . sort ( arr ) ; for ( int i = 0 ; i <= n - k ; i ++ ) result = Math . min ( result , arr [ i + k - 1 ] - arr [ i ] ) ; return result ; } public static void main ( String [ ] args ) { int arr [ ] = { 10 , 100 , 300 , 200 , 1000 , 20 , 30 } ; int n = arr . length ; int k = 3 ; System . out . println ( minDiff ( arr , n , k ) ) ; } }


"Choose maximum weight with given weight and value ratio | Java program to choose item with maximum sum of weight under given constraint ; memoized recursive method to return maximum weight with K as ratio of weight and values ; base cases : if no item is remaining ; first make pair with last chosen item and difference between weight and values ; choose maximum value from following two 1 ) not selecting the current item and calling recursively 2 ) selection current item , including the weight and updating the difference before calling recursively ; method returns maximum sum of weight with K as ration of sum of weight and their values ; Driver method"
How can the above be solved in Java?

import java . awt . Point ; import java . util . HashMap ; class Test { static int maxWeightRec ( int wt [ ] , int val [ ] , int K , HashMap < Point , Integer > hm , int last , int diff ) { if ( last == - 1 ) { if ( diff == 0 ) return 0 ; else return Integer . MIN_VALUE ; } Point tmp = new Point ( last , diff ) ; if ( hm . containsKey ( tmp ) ) return hm . get ( tmp ) ; hm . put ( tmp , Math . max ( maxWeightRec ( wt , val , K , hm , last - 1 , diff ) , wt [ last ] + maxWeightRec ( wt , val , K , hm , last - 1 , diff + wt [ last ] - val [ last ] * K ) ) ) ; return hm . get ( tmp ) ; } static int maxWeight ( int wt [ ] , int val [ ] , int K , int N ) { HashMap < Point , Integer > hm = new HashMap < > ( ) ; return maxWeightRec ( wt , val , K , hm , N - 1 , 0 ) ; } public static void main ( String args [ ] ) { int wt [ ] = { 4 , 8 , 9 } ; int val [ ] = { 2 , 4 , 6 } ; int K = 2 ; System . out . println ( maxWeight ( wt , val , K , wt . length ) ) ; } }


"Choose n elements such that their mean is maximum | Java implementation of the approach ; Utility function to print the contents of an array ; Function to print the array with maximum mean ; Sort the original array ; Construct new array ; Print the resultant array ; Driver code"
How can the above be solved in Java?

import java . util . Arrays ; class GfG { static void printArray ( int arr [ ] , int n ) { for ( int i = 0 ; i < n ; i ++ ) System . out . print ( arr [ i ] + " ▁ " ) ; } static void printMaxMean ( int arr [ ] , int n ) { int newArr [ ] = new int [ n ] ; Arrays . sort ( arr , 0 , 2 * n ) ; for ( int i = 0 ; i < n ; i ++ ) newArr [ i ] = arr [ i + n ] ; printArray ( newArr , n ) ; } public static void main ( String [ ] args ) { int arr [ ] = { 4 , 8 , 3 , 1 , 3 , 7 , 0 , 4 } ; int n = arr . length ; printMaxMean ( arr , n / 2 ) ; } }


"Choose points from two ranges such that no point lies in both the ranges | Java implementation of the approach ; Function to find the required points ; Driver code"
How can the above be solved in Java?

class GFG { static void findPoints ( int l1 , int r1 , int l2 , int r2 ) { int x = ( l1 != l2 ) ? Math . min ( l1 , l2 ) : - 1 ; int y = ( r1 != r2 ) ? Math . max ( r1 , r2 ) : - 1 ; System . out . println ( x + " ▁ " + y ) ; } public static void main ( String [ ] args ) { int l1 = 5 , r1 = 10 , l2 = 1 , r2 = 7 ; findPoints ( l1 , r1 , l2 , r2 ) ; } }


"Choose two elements from the given array such that their sum is not present in any of the arrays | Java implementation of the approach ; find maximum element in an array ; Function to find the numbers from the given arrays such that their sum is not present in any of the given array ; Find the maximum element from both the arrays ; Driver code"
How can the above be solved in Java?

class GFG { static int max_element ( int a [ ] , int n ) { int m = Integer . MIN_VALUE ; for ( int i = 0 ; i < n ; i ++ ) m = Math . max ( m , a [ i ] ) ; return m ; } static void findNum ( int a [ ] , int n , int b [ ] , int m ) { int x = max_element ( a , n ) ; int y = max_element ( b , m ) ; System . out . print ( x + " ▁ " + y ) ; } public static void main ( String args [ ] ) { int a [ ] = { 3 , 2 , 2 } ; int n = a . length ; int b [ ] = { 1 , 5 , 7 , 7 , 9 } ; int m = b . length ; findNum ( a , n , b , m ) ; } }


"Circle and Lattice Points | Java program to find countLattice points on a circle ; Function to count Lattice points on a circle ; Initialize result as 4 for ( r , 0 ) , ( - r . 0 ) , ( 0 , r ) and ( 0 , - r ) ; Check every value that can be potential x ; Find a potential y ; checking whether square root is an integer or not . Count increments by 4 for four different quadrant values ; Driver code"
How can the above be solved in Java?

class GFG { static int countLattice ( int r ) { if ( r <= 0 ) return 0 ; int result = 4 ; for ( int x = 1 ; x < r ; x ++ ) { int ySquare = r * r - x * x ; int y = ( int ) Math . sqrt ( ySquare ) ; if ( y * y == ySquare ) result += 4 ; } return result ; } public static void main ( String arg [ ] ) { int r = 5 ; System . out . println ( countLattice ( r ) ) ; } }


"Circular Convolution using Matrix Method | Java program to compute circular convolution of two arrays ; Function to find circular convolution ; Finding the maximum size between the two input sequence sizes ; Copying elements of x to row_vec and padding zeros if size of x < maxSize ; Copying elements of h to col_vec and padding zeros if size of h is less than maxSize ; Generating 2D matrix of circularly shifted elements ; Computing result by matrix multiplication and printing results ; Driver program"
How can the above be solved in Java?

class GFG { final static int MAX_SIZE = 10 ; static void convolution ( int [ ] x , int [ ] h , int n , int m ) { int row_vec [ ] = new int [ MAX_SIZE ] ; int col_vec [ ] = new int [ MAX_SIZE ] ; int out [ ] = new int [ MAX_SIZE ] ; int circular_shift_mat [ ] [ ] = new int [ MAX_SIZE ] [ MAX_SIZE ] ; int maxSize = n > m ? n : m ; for ( int i = 0 ; i < maxSize ; i ++ ) { if ( i >= n ) { row_vec [ i ] = 0 ; } else { row_vec [ i ] = x [ i ] ; } } for ( int i = 0 ; i < maxSize ; i ++ ) { if ( i >= m ) { col_vec [ i ] = 0 ; } else { col_vec [ i ] = h [ i ] ; } } int k = 0 , d = 0 ; for ( int i = 0 ; i < maxSize ; i ++ ) { int curIndex = k - d ; for ( int j = 0 ; j < maxSize ; j ++ ) { circular_shift_mat [ j ] [ i ] = row_vec [ curIndex % maxSize ] ; curIndex ++ ; } k = maxSize ; d ++ ; } for ( int i = 0 ; i < maxSize ; i ++ ) { for ( int j = 0 ; j < maxSize ; j ++ ) { out [ i ] += circular_shift_mat [ i ] [ j ] * col_vec [ j ] ; } System . out . print ( out [ i ] + " ▁ " ) ; } } public static void main ( String [ ] args ) { int x [ ] = { 5 , 7 , 3 , 2 } ; int n = x . length ; int h [ ] = { 1 , 5 } ; int m = h . length ; convolution ( x , h , n , m ) ; } }


"Circular Matrix ( Construct a matrix with numbers 1 to m * n in spiral way ) | Java program to fill a matrix with values from 1 to n * n in spiral fashion . ; Fills a [ m ] [ n ] with values from 1 to m * n in spiral fashion . ; Initialize value to be filled in matrix ; k - starting row index m - ending row index l - starting column index n - ending column index ; Print the first row from the remaining rows ; Print the last column from the remaining columns ; Print the last row from the remaining rows ; Print the first column from the remaining columns ; Driver program to test above functions"
How can the above be solved in Java?

class GFG { static int MAX = 100 ; static void spiralFill ( int m , int n , int a [ ] [ ] ) { int val = 1 ; int k = 0 , l = 0 ; while ( k < m && l < n ) { for ( int i = l ; i < n ; ++ i ) { a [ k ] [ i ] = val ++ ; } k ++ ; for ( int i = k ; i < m ; ++ i ) { a [ i ] [ n - 1 ] = val ++ ; } n -- ; if ( k < m ) { for ( int i = n - 1 ; i >= l ; -- i ) { a [ m - 1 ] [ i ] = val ++ ; } m -- ; } if ( l < n ) { for ( int i = m - 1 ; i >= k ; -- i ) { a [ i ] [ l ] = val ++ ; } l ++ ; } } } public static void main ( String [ ] args ) { int m = 4 , n = 4 ; int a [ ] [ ] = new int [ MAX ] [ MAX ] ; spiralFill ( m , n , a ) ; for ( int i = 0 ; i < m ; i ++ ) { for ( int j = 0 ; j < n ; j ++ ) { System . out . print ( a [ i ] [ j ] + " ▁ " ) ; } System . out . println ( " " ) ; } } }


"Circular Singly Linked List | Insertion |  ; Creating a node dynamically ; Assigning the data ; Adjusting the links"
How can the above be solved in Java?

static Node addBegin ( Node last , int data ) { if ( last == null ) return addToEmpty ( last , data ) ; Node temp = new Node ( ) ; temp . data = data ; temp . next = last . next ; last . next = temp ; return last ; }


"Circular Singly Linked List | Insertion |  ; This function is only for empty list ; Creating a node dynamically . ; Assigning the data . ; Note : list was empty . We link single node to itself ."
How can the above be solved in Java?

static Node addToEmpty ( Node last , int data ) { if ( last != null ) return last ; Node temp = ( Node * ) malloc ( sizeof ( Node ) ) ; temp . data = data ; last = temp ; temp . next = last ; return last ; }


"Circumradius of a Cyclic Quadrilateral using the length of Sides | Java program to find circumradius of a cyclic quadrilateral using sides ; Function to return the circumradius of a cyclic quadrilateral using sides ; Find semiperimeter ; Calculate the radius ; Driver Code ; Function call ; Print the radius"
How can the above be solved in Java?

import java . util . * ; class GFG { static double Circumradius ( int a , int b , int c , int d ) { double s = ( a + b + c + d ) / 2.0 ; double radius = Math . sqrt ( ( ( a * b ) + ( c * d ) ) * ( ( a * c ) + ( b * d ) ) * ( ( a * d ) + ( b * c ) ) / ( ( s - a ) * ( s - b ) * ( s - c ) * ( s - d ) ) ) ; return radius / 4 ; } public static void main ( String [ ] args ) { int A = 3 ; int B = 4 ; int C = 5 ; int D = 6 ; double ans = Circumradius ( A , B , C , D ) ; System . out . format ( " % .2f " , ans ) ; } }


"Circumradius of the rectangle | Java Program to find the radius of the circumcircle of the given rectangle ; Function to find the radius of the circumcircle ; the sides cannot be negative ; Radius of the circumcircle ; Return the radius ; Driver code ; Get the sides of the triangle ; Find the radius of the circumcircle"
How can the above be solved in Java?

import java . util . * ; import java . lang . * ; import java . io . * ; class GFG { static float findRadiusOfcircumcircle ( float l , float b ) { if ( l < 0 b < 0 ) return - 1 ; float radius = ( float ) Math . sqrt ( Math . pow ( l , 2 ) + Math . pow ( b , 2 ) ) / 2 ; return radius ; } public static void main ( String args [ ] ) { float l = 4 , b = 3 ; System . out . println ( findRadiusOfcircumcircle ( l , b ) ) ; } }


"Climb n | Java program to count total number of ways to reach n - th stair with all jumps allowed ; Function to calculate leaps ; Driver code"
How can the above be solved in Java?

class GFG { static int calculateLeaps ( int n ) { if ( n == 0 n == 1 ) { return 1 ; } else { int leaps = 0 ; for ( int i = 0 ; i < n ; i ++ ) leaps += calculateLeaps ( i ) ; return leaps ; } } public static void main ( String [ ] args ) { System . out . println ( calculateLeaps ( 4 ) ) ; } }


"Clockwise rotation of Linked List | Java implementation of the approach ; Link list node ; A utility function to push a node ; allocate node ; put in the data ; link the old list off the new node ; move the head to point to the new node ; A utility function to print linked list ; Function that rotates the given linked list clockwise by k and returns the updated head pointer ; If the linked list is empty ; len is used to store length of the linked list tmp will point to the last node after this loop ; If k is greater than the size of the linked list ; Subtract from length to convert it into left rotation ; If no rotation needed then return the head node ; current will either point to kth or null after this loop ; If current is null then k is equal to the count of nodes in the list Don 't change the list in this case ; current points to the kth node ; Change next of last node to previous head ; Change head to ( k + 1 ) th node ; Change next of kth node to null ; Return the updated head pointer ; Driver code ; The constructed linked list is : 1.2 . 3.4 . 5 ; Rotate the linked list ; Print the rotated linked list"
How can the above be solved in Java?

class GFG { static class Node { int data ; Node next ; } static Node push ( Node head_ref , int new_data ) { Node new_node = new Node ( ) ; new_node . data = new_data ; new_node . next = ( head_ref ) ; ( head_ref ) = new_node ; return head_ref ; } static void printList ( Node node ) { while ( node != null ) { System . out . print ( node . data + " ▁ - > ▁ " ) ; node = node . next ; } System . out . print ( " null " ) ; } static Node rightRotate ( Node head , int k ) { if ( head == null ) return head ; Node tmp = head ; int len = 1 ; while ( tmp . next != null ) { tmp = tmp . next ; len ++ ; } if ( k > len ) k = k % len ; k = len - k ; if ( k == 0 k == len ) return head ; Node current = head ; int cnt = 1 ; while ( cnt < k && current != null ) { current = current . next ; cnt ++ ; } if ( current == null ) return head ; Node kthnode = current ; tmp . next = head ; head = kthnode . next ; kthnode . next = null ; return head ; } public static void main ( String args [ ] ) { Node head = null ; head = push ( head , 5 ) ; head = push ( head , 4 ) ; head = push ( head , 3 ) ; head = push ( head , 2 ) ; head = push ( head , 1 ) ; int k = 2 ; Node updated_head = rightRotate ( head , k ) ; printList ( updated_head ) ; } }


"Closest ( or Next ) smaller and greater numbers with same number of set bits | Java Implementation of getNext with Same number of bits 1 's is below ; Function to find next smallest number bigger than n ; Compute c0 and c1 ; If there is no bigger number with the same no . of 1 's ; Driver Code ; input 1 ; input 2"
How can the above be solved in Java?

import java . io . * ; class GFG { static int getNext ( int n ) { int c = n ; int c0 = 0 ; int c1 = 0 ; while ( ( ( c & 1 ) == 0 ) && ( c != 0 ) ) { c0 ++ ; c >>= 1 ; } while ( ( c & 1 ) == 1 ) { c1 ++ ; c >>= 1 ; } if ( c0 + c1 == 31 c0 + c1 == 0 ) return - 1 ; return n + ( 1 << c0 ) + ( 1 << ( c1 - 1 ) ) - 1 ; } public static void main ( String [ ] args ) { int n = 5 ; System . out . println ( getNext ( n ) ) ; n = 8 ; System . out . println ( getNext ( n ) ) ; } }


"Closest greater element for every array element from another array | Java to find result from target array for closest element ; Function for printing resultant array ; change arr [ ] to Set ; vector for result ; calculate resultant array ; check upper bound element ; if no element found push - 1 ; Else push the element ; add to resultant ; Driver Code"
How can the above be solved in Java?

import java . util . * ; class GFG { static void closestResult ( Integer [ ] a , int [ ] b , int n ) { TreeSet < Integer > vect = new TreeSet < > ( Arrays . asList ( a ) ) ; Vector < Integer > c = new Vector < > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { Integer up = vect . higher ( b [ i ] ) ; if ( up == null ) c . add ( - 1 ) ; else c . add ( up ) ; } System . out . print ( " Result ▁ = ▁ " ) ; for ( int i : c ) System . out . print ( i + " ▁ " ) ; } public static void main ( String [ ] args ) { Integer [ ] a = { 2 , 5 , 6 , 1 , 8 , 9 } ; int [ ] b = { 2 , 1 , 0 , 5 , 4 , 9 } ; int n = a . length ; closestResult ( a , b , n ) ; } }


"Closest leaf to a given node in Binary Tree | A binary tree node ;  ; This function finds closest leaf to root . This distance is stored at * minDist . ; base case ; If this is a leaf node , then check if it is closer than the closest so far ; Recur for left and right subtrees ; This function finds if there is closer leaf to x through parent node . ; Base cases ; Search x in left subtree of root ; If left subtree has x ; Find closest leaf in right subtree ; Search x in right subtree of root ; If right subtree has x ; Find closest leaf in left subtree ; Returns minimum distance of a leaf from given node x ; Initialize result ( minimum distance from a leaf ) ; Find closest leaf down to x ; See if there is a closer leaf through parent ; Driver program ; Let us create Binary Tree shown in above example"
How can the above be solved in Java?

class Node { int key ; Node left , right ; public Node ( int key ) { this . key = key ; left = right = null ; } } class Distance { int minDis = Integer . MAX_VALUE ; } class BinaryTree { Node root ; void findLeafDown ( Node root , int lev , Distance minDist ) { if ( root == null ) return ; if ( root . left == null && root . right == null ) { if ( lev < ( minDist . minDis ) ) minDist . minDis = lev ; return ; } findLeafDown ( root . left , lev + 1 , minDist ) ; findLeafDown ( root . right , lev + 1 , minDist ) ; } int findThroughParent ( Node root , Node x , Distance minDist ) { if ( root == null ) return - 1 ; if ( root == x ) return 0 ; int l = findThroughParent ( root . left , x , minDist ) ; if ( l != - 1 ) { findLeafDown ( root . right , l + 2 , minDist ) ; return l + 1 ; } int r = findThroughParent ( root . right , x , minDist ) ; if ( r != - 1 ) { findLeafDown ( root . left , r + 2 , minDist ) ; return r + 1 ; } return - 1 ; } int minimumDistance ( Node root , Node x ) { Distance d = new Distance ( ) ; findLeafDown ( x , 0 , d ) ; findThroughParent ( root , x , d ) ; return d . minDis ; } public static void main ( String [ ] args ) { BinaryTree tree = new BinaryTree ( ) ; tree . root = new Node ( 1 ) ; tree . root . left = new Node ( 12 ) ; tree . root . right = new Node ( 13 ) ; tree . root . right . left = new Node ( 14 ) ; tree . root . right . right = new Node ( 15 ) ; tree . root . right . left . left = new Node ( 21 ) ; tree . root . right . left . right = new Node ( 22 ) ; tree . root . right . right . left = new Node ( 23 ) ; tree . root . right . right . right = new Node ( 24 ) ; tree . root . right . left . left . left = new Node ( 1 ) ; tree . root . right . left . left . right = new Node ( 2 ) ; tree . root . right . left . right . left = new Node ( 3 ) ; tree . root . right . left . right . right = new Node ( 4 ) ; tree . root . right . right . left . left = new Node ( 5 ) ; tree . root . right . right . left . right = new Node ( 6 ) ; tree . root . right . right . right . left = new Node (...


"Closest numbers from a list of unsorted integers | Java program to find minimum difference an unsorted array . ; Returns minimum difference between any two pair in arr [ 0. . n - 1 ] ; Sort array elements ; Compare differences of adjacent pairs to find the minimum difference . ; Traverse array again and print all pairs with difference as minDiff . ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { static void printMinDiffPairs ( int arr [ ] , int n ) { if ( n <= 1 ) return ; Arrays . sort ( arr ) ; int minDiff = arr [ 1 ] - arr [ 0 ] ; for ( int i = 2 ; i < n ; i ++ ) minDiff = Math . min ( minDiff , arr [ i ] - arr [ i - 1 ] ) ; for ( int i = 1 ; i < n ; i ++ ) { if ( ( arr [ i ] - arr [ i - 1 ] ) == minDiff ) { System . out . print ( " ( " + arr [ i - 1 ] + " , ▁ " + arr [ i ] + " ) , " ) ; } } } public static void main ( String [ ] args ) { int arr [ ] = { 5 , 3 , 2 , 4 , 1 } ; int n = arr . length ; printMinDiffPairs ( arr , n ) ; } }


"Closest perfect square and its distance | Java program to find the closest perfect square taking minimum steps to reach from a number ; Function to check if a number is perfect square or not ; Function to find the closest perfect square taking minimum steps to reach from a number ; Variables to store first perfect square number above and below N ; Finding first perfect square number greater than N ; Finding first perfect square number less than N ; Variables to store the differences ; Driver code"
How can the above be solved in Java?

class GFG { static boolean isPerfect ( int N ) { if ( ( Math . sqrt ( N ) - Math . floor ( Math . sqrt ( N ) ) ) != 0 ) return false ; return true ; } static void getClosestPerfectSquare ( int N ) { if ( isPerfect ( N ) ) { System . out . println ( N + " ▁ " + "0" ) ; return ; } int aboveN = - 1 , belowN = - 1 ; int n1 ; n1 = N + 1 ; while ( true ) { if ( isPerfect ( n1 ) ) { aboveN = n1 ; break ; } else n1 ++ ; } n1 = N - 1 ; while ( true ) { if ( isPerfect ( n1 ) ) { belowN = n1 ; break ; } else n1 -- ; } int diff1 = aboveN - N ; int diff2 = N - belowN ; if ( diff1 > diff2 ) System . out . println ( belowN + " ▁ " + diff2 ) ; else System . out . println ( aboveN + " ▁ " + diff1 ) ; } public static void main ( String args [ ] ) { int N = 1500 ; getClosestPerfectSquare ( N ) ; } }


"Clustering / Partitioning an array such that sum of square differences is minimum | Java program to find minimum cost k partitions of array . ; Initialize answer as infinite . ; function to generate all possible answers . and compute minimum of all costs . i -- > is index of previous partition par -- > is current number of partitions a [ ] and n -- > Input array and its size current_ans -- > Cost of partitions made so far . ; If number of partitions is more than k ; If we have mad k partitions and have reached last element ; 1 ) Partition array at different points 2 ) For every point , increase count of partitions , " par " by 1. 3 ) Before recursive call , add cost of the partition to current_ans ; Driver code"
How can the above be solved in Java?

import java . io . * ; class GFG { static int inf = 1000000000 ; static int ans = inf ; static void solve ( int i , int par , int a [ ] , int n , int k , int current_ans ) { if ( par > k ) return ; if ( par == k && i == n - 1 ) { ans = Math . min ( ans , current_ans ) ; return ; } for ( int j = i + 1 ; j < n ; j ++ ) solve ( j , par + 1 , a , n , k , current_ans + ( a [ j ] - a [ i + 1 ] ) * ( a [ j ] - a [ i + 1 ] ) ) ; } public static void main ( String [ ] args ) { int k = 2 ; int a [ ] = { 1 , 5 , 8 , 10 } ; int n = a . length ; solve ( - 1 , 0 , a , n , k , 0 ) ; System . out . println ( ans ) ; } }


"Clustering / Partitioning an array such that sum of square differences is minimum | Java program to find minimum cost k partitions of array . ; Returns minimum cost of partitioning a [ ] in k clusters . ; Create a dp [ ] [ ] table and initialize all values as infinite . dp [ i ] [ j ] is going to store optimal partition cost for arr [ 0. . i - 1 ] and j partitions ; Fill dp [ ] [ ] in bottom up manner ; Current ending position ( After i - th iteration result for a [ 0. . i - 1 ] is computed . ; j is number of partitions ; Picking previous partition for current i . ; Driver code"
How can the above be solved in Java?

import java . io . * ; class GFG { static int inf = 1000000000 ; static int minCost ( int a [ ] , int n , int k ) { int dp [ ] [ ] = new int [ n + 1 ] [ k + 1 ] ; for ( int i = 0 ; i <= n ; i ++ ) for ( int j = 0 ; j <= k ; j ++ ) dp [ i ] [ j ] = inf ; dp [ 0 ] [ 0 ] = 0 ; for ( int i = 1 ; i <= n ; i ++ ) for ( int j = 1 ; j <= k ; j ++ ) for ( int m = i - 1 ; m >= 0 ; m -- ) dp [ i ] [ j ] = Math . min ( dp [ i ] [ j ] , dp [ m ] [ j - 1 ] + ( a [ i - 1 ] - a [ m ] ) * ( a [ i - 1 ] - a [ m ] ) ) ; return dp [ n ] [ k ] ; } public static void main ( String [ ] args ) { int k = 2 ; int a [ ] = { 1 , 5 , 8 , 10 } ; int n = a . length ; System . out . println ( minCost ( a , n , k ) ) ; } }


"Co | Java program to represent a number as sum of a co - prime pair such that difference between them is minimum ; Utility function ; function to check if pair is co - prime or not ; function to find and print co - prime pair ; Driver Code"
How can the above be solved in Java?

class GFG { static int __gcd ( int a , int b ) { return b == 0 ? a : __gcd ( b , a % b ) ; } static boolean coprime ( int a , int b ) { return ( __gcd ( a , b ) == 1 ) ; } static void pairSum ( int n ) { int mid = n / 2 ; for ( int i = mid ; i >= 1 ; i -- ) { if ( coprime ( i , n - i ) == true ) { System . out . print ( i + " ▁ " + ( n - i ) ) ; break ; } } } public static void main ( String args [ ] ) { int n = 11 ; pairSum ( n ) ; } }


"Cocktail Sort | Sorts arrar a [ 0. . n - 1 ] using Cocktail sort ; reset the swapped flag on entering the loop , because it might be true from a previous iteration . ; loop from bottom to top same as the bubble sort ; if nothing moved , then array is sorted . ; otherwise , reset the swapped flag so that it can be used in the next stage ; move the end point back by one , because item at the end is in its rightful spot ; from top to bottom , doing the same comparison as in the previous stage ; increase the starting point , because the last stage would have moved the next smallest number to its rightful spot . ; Prints the array ; Driver code"
How can the above be solved in Java?

public class CocktailSort { void cocktailSort ( int a [ ] ) { boolean swapped = true ; int start = 0 ; int end = a . length ; while ( swapped == true ) { swapped = false ; for ( int i = start ; i < end - 1 ; ++ i ) { if ( a [ i ] > a [ i + 1 ] ) { int temp = a [ i ] ; a [ i ] = a [ i + 1 ] ; a [ i + 1 ] = temp ; swapped = true ; } } if ( swapped == false ) break ; swapped = false ; end = end - 1 ; for ( int i = end - 1 ; i >= start ; i -- ) { if ( a [ i ] > a [ i + 1 ] ) { int temp = a [ i ] ; a [ i ] = a [ i + 1 ] ; a [ i + 1 ] = temp ; swapped = true ; } } start = start + 1 ; } } void printArray ( int a [ ] ) { int n = a . length ; for ( int i = 0 ; i < n ; i ++ ) System . out . print ( a [ i ] + " ▁ " ) ; System . out . println ( ) ; } public static void main ( String [ ] args ) { CocktailSort ob = new CocktailSort ( ) ; int a [ ] = { 5 , 1 , 4 , 2 , 8 , 0 , 2 } ; ob . cocktailSort ( a ) ; System . out . println ( " Sorted ▁ array " ) ; ob . printArray ( a ) ; } }


"Coin game of two corners ( Greedy Approach ) | Java program to find coins to be picked to make sure that we never loose . ; Returns optimal value possible that a player can collect from an array of coins of size n . Note than n must be even ; Find sum of odd positioned coins ; Find sum of even positioned coins ; Print even or odd coins depending upon which sum is greater . ; Driver Code"
How can the above be solved in Java?

class GFG { static void printCoins ( int arr [ ] , int n ) { int oddSum = 0 ; for ( int i = 0 ; i < n ; i += 2 ) oddSum += arr [ i ] ; int evenSum = 0 ; for ( int i = 1 ; i < n ; i += 2 ) evenSum += arr [ i ] ; int start = ( ( oddSum > evenSum ) ? 0 : 1 ) ; for ( int i = start ; i < n ; i += 2 ) System . out . print ( arr [ i ] + " ▁ " ) ; } public static void main ( String [ ] args ) { int arr1 [ ] = { 8 , 15 , 3 , 7 } ; int n = arr1 . length ; printCoins ( arr1 , n ) ; System . out . println ( ) ; int arr2 [ ] = { 2 , 2 , 2 , 2 } ; n = arr2 . length ; printCoins ( arr2 , n ) ; System . out . println ( ) ; int arr3 [ ] = { 20 , 30 , 2 , 2 , 2 , 10 } ; n = arr3 . length ; printCoins ( arr3 , n ) ; } }


"Coin game winner where every player has three choices | Java program to find winner of game if player can pick 1 , x , y coins ; To find winner of game ; To store results ; Initial values ; Computing other values . ; If A losses any of i - 1 or i - x or i - y game then he will definitely win game i ; Else A loses game . ; If dp [ n ] is true then A will game otherwise he losses ; Driver program to test findWinner ( ) ;"
How can the above be solved in Java?

import java . util . Arrays ; public class GFG { static boolean findWinner ( int x , int y , int n ) { boolean [ ] dp = new boolean [ n + 1 ] ; Arrays . fill ( dp , false ) ; dp [ 0 ] = false ; dp [ 1 ] = true ; for ( int i = 2 ; i <= n ; i ++ ) { if ( i - 1 >= 0 && dp [ i - 1 ] == false ) dp [ i ] = true ; else if ( i - x >= 0 && dp [ i - x ] == false ) dp [ i ] = true ; else if ( i - y >= 0 && dp [ i - y ] == false ) dp [ i ] = true ; else dp [ i ] = false ; } return dp [ n ] ; } public static void main ( String args [ ] ) { int x = 3 , y = 4 , n = 5 ; if ( findWinner ( x , y , n ) == true ) System . out . println ( ' A ' ) ; else System . out . println ( ' B ' ) ; } }


"Collect all coins in minimum number of steps | Java Code to Collect all coins in minimum number of steps ; recursive method to collect coins from height array l to r , with height h already collected ; if l is more than r , no steps needed ; loop over heights to get minimum height index ; choose minimum from , 1 ) collecting coins using all vertical lines ( total r - l ) 2 ) collecting coins using lower horizontal lines and recursively on left and right segments ; method returns minimum number of step to collect coin from stack , with height in height [ ] array ; Driver program to test above function"
How can the above be solved in Java?

import java . util . * ; class GFG { public static int minStepsRecur ( int height [ ] , int l , int r , int h ) { if ( l >= r ) return 0 ; int m = l ; for ( int i = l ; i < r ; i ++ ) if ( height [ i ] < height [ m ] ) m = i ; return Math . min ( r - l , minStepsRecur ( height , l , m , height [ m ] ) + minStepsRecur ( height , m + 1 , r , height [ m ] ) + height [ m ] - h ) ; } public static int minSteps ( int height [ ] , int N ) { return minStepsRecur ( height , 0 , N , 0 ) ; } public static void main ( String [ ] args ) { int height [ ] = { 2 , 1 , 2 , 5 , 1 } ; int N = height . length ; System . out . println ( minSteps ( height , N ) ) ; } }


"Collect maximum points in a grid using two traversals | A Memoization based program to find maximum collection using two traversals of a grid ; checks whether a given input is valid or not ; Driver function to collect Math . max value ; if P1 or P2 is at an invalid cell ; if both traversals reach their destinations ; If both traversals are at last row but not at their destination ; If subproblem is already solved ; Initialize answer for this subproblem ; this variable is used to store gain of current cell ( s ) ; Recur for all possible cases , then store and return the one with max value ; This is mainly a wrapper over recursive function getMaxUtil ( ) . This function creates a table for memoization and calls getMaxUtil ( ) ; Create a memoization table and initialize all entries as - 1 ; Calculation maximum value using memoization based function getMaxUtil ( ) ; Driver code"
How can the above be solved in Java?

class GFG { static final int R = 5 ; static final int C = 4 ; static boolean isValid ( int x , int y1 , int y2 ) { return ( x >= 0 && x < R && y1 >= 0 && y1 < C && y2 >= 0 && y2 < C ) ; } static int getMaxUtil ( int arr [ ] [ ] , int mem [ ] [ ] [ ] , int x , int y1 , int y2 ) { if ( ! isValid ( x , y1 , y2 ) ) return Integer . MIN_VALUE ; if ( x == R - 1 && y1 == 0 && y2 == C - 1 ) return ( y1 == y2 ) ? arr [ x ] [ y1 ] : arr [ x ] [ y1 ] + arr [ x ] [ y2 ] ; if ( x == R - 1 ) return Integer . MIN_VALUE ; if ( mem [ x ] [ y1 ] [ y2 ] != - 1 ) return mem [ x ] [ y1 ] [ y2 ] ; int ans = Integer . MIN_VALUE ; int temp = ( y1 == y2 ) ? arr [ x ] [ y1 ] : arr [ x ] [ y1 ] + arr [ x ] [ y2 ] ; ans = Math . max ( ans , temp + getMaxUtil ( arr , mem , x + 1 , y1 , y2 - 1 ) ) ; ans = Math . max ( ans , temp + getMaxUtil ( arr , mem , x + 1 , y1 , y2 + 1 ) ) ; ans = Math . max ( ans , temp + getMaxUtil ( arr , mem , x + 1 , y1 , y2 ) ) ; ans = Math . max ( ans , temp + getMaxUtil ( arr , mem , x + 1 , y1 - 1 , y2 ) ) ; ans = Math . max ( ans , temp + getMaxUtil ( arr , mem , x + 1 , y1 - 1 , y2 - 1 ) ) ; ans = Math . max ( ans , temp + getMaxUtil ( arr , mem , x + 1 , y1 - 1 , y2 + 1 ) ) ; ans = Math . max ( ans , temp + getMaxUtil ( arr , mem , x + 1 , y1 + 1 , y2 ) ) ; ans = Math . max ( ans , temp + getMaxUtil ( arr , mem , x + 1 , y1 + 1 , y2 - 1 ) ) ; ans = Math . max ( ans , temp + getMaxUtil ( arr , mem , x + 1 , y1 + 1 , y2 + 1 ) ) ; return ( mem [ x ] [ y1 ] [ y2 ] = ans ) ; } static int geMaxCollection ( int arr [ ] [ ] ) { int [ ] [ ] [ ] mem = new int [ R ] [ C ] [ C ] ; for ( int i = 0 ; i < R ; i ++ ) { for ( int j = 0 ; j < C ; j ++ ) { for ( int l = 0 ; l < C ; l ++ ) mem [ i ] [ j ] [ l ] = - 1 ; } } return getMaxUtil ( arr , mem , 0 , 0 , C - 1 ) ; } public static void main ( String [ ] args ) { int arr [ ] [ ] = { { 3 , 6 , 8 , 2 } , { 5 , 2 , 4 , 3 } , { 1 , 1 , 20 , 10 } , { 1 , 1 , 20 , 10 } , { 1 , 1 , 20 , 10 } , } ; System . out . print ( " Maximum ▁ collection ▁ is ▁ " + geMaxCollection ( arr...


"Color N boxes using M colors such that K boxes have different color from the box on its left | Java Program to Paint N boxes using M colors such that K boxes have color different from color of box on its left ; This function returns the required number of ways where idx is the current index and diff is number of boxes having different color from box on its left ; Base Case ; If already computed ; Either paint with same color as previous one ; Or paint with remaining ( M - 1 ) colors ; Driver code ; Multiply M since first box can be painted with any of the M colors and start solving from 2 nd box"
How can the above be solved in Java?

class GFG { static int M = 1001 ; static int MOD = 998244353 ; static int [ ] [ ] dp = new int [ M ] [ M ] ; static int solve ( int idx , int diff , int N , int M , int K ) { if ( idx > N ) { if ( diff == K ) return 1 ; return 0 ; } if ( dp [ idx ] [ diff ] != - 1 ) return dp [ idx ] [ diff ] ; int ans = solve ( idx + 1 , diff , N , M , K ) ; ans += ( M - 1 ) * solve ( idx + 1 , diff + 1 , N , M , K ) ; return dp [ idx ] [ diff ] = ans % MOD ; } public static void main ( String [ ] args ) { int N = 3 , M = 3 , K = 0 ; for ( int i = 0 ; i <= M ; i ++ ) for ( int j = 0 ; j <= M ; j ++ ) dp [ i ] [ j ] = - 1 ; System . out . println ( ( M * solve ( 2 , 0 , N , M , K ) ) ) ; } }


"Color a grid such that all same color cells are connected either horizontally or vertically | Java program to color a grid such that all same color cells are connected either horizontally or vertically ; Current color ; Final grid ; If even row ; Traverse from left to right ; If color has been exhausted , move to the next color ; Color the grid at this position ; Reduce the color count ; Traverse from right to left for odd rows ; Print the grid ; Driver Code"
How can the above be solved in Java?

import java . util . * ; class GFG { static void solve ( List < Integer > arr , int r , int c ) { int idx = 1 ; int [ ] [ ] dp = new int [ r ] ; for ( int i = 0 ; i < r ; i ++ ) { if ( i % 2 == 0 ) { for ( int j = 0 ; j < c ; j ++ ) { if ( arr . get ( idx - 1 ) == 0 ) idx ++ ; dp [ i ] [ j ] = idx ; arr . set ( idx - 1 , arr . get ( idx - 1 ) - 1 ) ; } } else { for ( int j = c - 1 ; j >= 0 ; j -- ) { if ( arr . get ( idx - 1 ) == 0 ) idx ++ ; dp [ i ] [ j ] = idx ; arr . set ( idx - 1 , arr . get ( idx - 1 ) - 1 ) ; } } } for ( int i = 0 ; i < r ; ++ i ) { for ( int j = 0 ; j < c ; ++ j ) { System . out . print ( dp [ i ] [ j ] + " ▁ " ) ; } System . out . println ( ) ; } } public static void main ( String [ ] args ) { int r = 3 , c = 5 ; int n = 5 ; List < Integer > arr = Arrays . asList ( 1 , 2 , 3 , 4 , 5 ) ; solve ( arr , r , c ) ; } }


"Comb Sort | Java program for implementation of Comb Sort ; To find gap between elements ; Shrink gap by Shrink factor ; Function to sort arr [ ] using Comb Sort ; initialize gap ; Initialize swapped as true to make sure that loop runs ; Keep running while gap is more than 1 and last iteration caused a swap ; Find next gap ; Initialize swapped as false so that we can check if swap happened or not ; Compare all elements with current gap ; Swap arr [ i ] and arr [ i + gap ] ; Set swapped ; Driver method"
How can the above be solved in Java?

class CombSort { int getNextGap ( int gap ) { gap = ( gap * 10 ) / 13 ; if ( gap < 1 ) return 1 ; return gap ; } void sort ( int arr [ ] ) { int n = arr . length ; int gap = n ; boolean swapped = true ; while ( gap != 1 swapped == true ) { gap = getNextGap ( gap ) ; swapped = false ; for ( int i = 0 ; i < n - gap ; i ++ ) { if ( arr [ i ] > arr [ i + gap ] ) { int temp = arr [ i ] ; arr [ i ] = arr [ i + gap ] ; arr [ i + gap ] = temp ; swapped = true ; } } } } public static void main ( String args [ ] ) { CombSort ob = new CombSort ( ) ; int arr [ ] = { 8 , 4 , 1 , 56 , 3 , - 44 , 23 , - 6 , 28 , 0 } ; ob . sort ( arr ) ; System . out . println ( " sorted ▁ array " ) ; for ( int i = 0 ; i < arr . length ; ++ i ) System . out . print ( arr [ i ] + " ▁ " ) ; } }


"Combinations where every element appears twice and distance between appearances is equal to the value | Java program to find all combinations where every element appears twice and distance between appearances is equal to the value ; Find all combinations that satisfies given constraints ; if all elements are filled , print the solution ; try all possible combinations for element elem ; if position i and ( i + elem + 1 ) are not occupied in the vector ; place elem at position i and ( i + elem + 1 ) ; recurse for next element ; backtrack ( remove elem from position i and ( i + elem + 1 ) ) ; create a vector of double the size of given number with ; all its elements initialized by 1 ; start from element 1 ; Driver method ; given number"
How can the above be solved in Java?

import java . util . Vector ; class Test { static void allCombinationsRec ( Vector < Integer > arr , int elem , int n ) { if ( elem > n ) { for ( int i : arr ) System . out . print ( i + " ▁ " ) ; System . out . println ( ) ; return ; } for ( int i = 0 ; i < 2 * n ; i ++ ) { if ( arr . get ( i ) == - 1 && ( i + elem + 1 ) < 2 * n && arr . get ( i + elem + 1 ) == - 1 ) { arr . set ( i , elem ) ; arr . set ( i + elem + 1 , elem ) ; allCombinationsRec ( arr , elem + 1 , n ) ; arr . set ( i , - 1 ) ; arr . set ( i + elem + 1 , - 1 ) ; } } } static void allCombinations ( int n ) { Vector < Integer > arr = new Vector < > ( ) ; for ( int i = 0 ; i < 2 * n ; i ++ ) { arr . add ( - 1 ) ; } int elem = 1 ; allCombinationsRec ( arr , elem , n ) ; } public static void main ( String [ ] args ) { int n = 3 ; allCombinations ( n ) ; } }


"Combinatorics on ordered trees | java code to find the number of ordered trees with given number of edges and leaves ; Function returns value of Binomial Coefficient C ( n , k ) ; Calculate value of Binomial Coefficient in bottom up manner ; Base Cases ; Calculate value using previously stored values ; Function to calculate the number of trees with exactly k leaves . ; Function to calculate total number of nodes of degree d in these trees . ; Function to calculate the number of trees in which the root has degree r . ; Driver program to test above functions ; Number of trees having 3 edges and exactly 2 leaves ; Number of nodes of degree 3 in a tree having 4 edges ; Number of trees having 3 edges where root has degree 2"
How can the above be solved in Java?

import java . io . * ; class GFG { static int binomialCoeff ( int n , int k ) { int [ ] [ ] C = new int [ n + 1 ] [ k + 1 ] ; int i , j ; for ( i = 0 ; i <= n ; i ++ ) { for ( j = 0 ; j <= Math . min ( i , k ) ; j ++ ) { if ( j == 0 j == i ) C [ i ] [ j ] = 1 ; else C [ i ] [ j ] = C [ i - 1 ] [ j - 1 ] + C [ i - 1 ] [ j ] ; } } return C [ n ] [ k ] ; } static int k_Leaves ( int n , int k ) { int ans = ( binomialCoeff ( n , k ) * binomialCoeff ( n , k - 1 ) ) / n ; System . out . println ( " Number ▁ of ▁ trees ▁ " + " having ▁ 4 ▁ edges ▁ and ▁ exactly ▁ 2 ▁ " + " leaves ▁ : ▁ " + ans ) ; return 0 ; } static int numberOfNodes ( int n , int d ) { int ans = binomialCoeff ( 2 * n - 1 - d , n - 1 ) ; System . out . println ( " Number ▁ of ▁ nodes ▁ " + " of ▁ degree ▁ 1 ▁ in ▁ a ▁ tree ▁ having ▁ 4 ▁ " + " edges ▁ : ▁ " + ans ) ; return 0 ; } static int rootDegreeR ( int n , int r ) { int ans = r * binomialCoeff ( 2 * n - 1 - r , n - 1 ) ; ans = ans / n ; System . out . println ( " Number ▁ of ▁ trees ▁ " + " having ▁ 4 ▁ edges ▁ where ▁ root ▁ has " + " ▁ degree ▁ 2 ▁ : ▁ " + ans ) ; return 0 ; } public static void main ( String [ ] args ) { k_Leaves ( 3 , 2 ) ; numberOfNodes ( 3 , 1 ) ; rootDegreeR ( 3 , 2 ) ; } }


"Common Divisors of Two Numbers | Java implementation of program ; map to store the count of each prime factor of a ; method that calculate the count of each prime factor of a number ; method to calculate all common divisors of two given numbers a , b -- > input integer numbers ; Find count of each prime factor of a ; stores number of common divisors ; Find the count of prime factors of b using distinct prime factors of a ; prime factor of common divisor has minimum cnt of both a and b ; Driver method"
How can the above be solved in Java?

import java . util . * ; import java . io . * ; class GFG { static HashMap < Integer , Integer > ma = new HashMap < > ( ) ; static void primeFactorize ( int a ) { for ( int i = 2 ; i * i <= a ; i += 2 ) { int cnt = 0 ; while ( a % i == 0 ) { cnt ++ ; a /= i ; } ma . put ( i , cnt ) ; } if ( a > 1 ) ma . put ( a , 1 ) ; } static int commDiv ( int a , int b ) { primeFactorize ( a ) ; int res = 1 ; for ( Map . Entry < Integer , Integer > m : ma . entrySet ( ) ) { int cnt = 0 ; int key = m . getKey ( ) ; int value = m . getValue ( ) ; while ( b % key == 0 ) { b /= key ; cnt ++ ; } res *= ( Math . min ( cnt , value ) + 1 ) ; } return res ; } public static void main ( String args [ ] ) { int a = 12 , b = 24 ; System . out . println ( commDiv ( a , b ) ) ; } }


"Common Divisors of Two Numbers | Java implementation of program ; method to calculate gcd of two numbers ; method to calculate all common divisors of two given numbers a , b -- > input integer numbers ; find gcd of a , b ; Count divisors of n . ; if ' i ' is factor of n ; check if divisors are equal ; Driver method"
How can the above be solved in Java?

class Test { static int gcd ( int a , int b ) { if ( a == 0 ) return b ; return gcd ( b % a , a ) ; } static int commDiv ( int a , int b ) { int n = gcd ( a , b ) ; int result = 0 ; for ( int i = 1 ; i <= Math . sqrt ( n ) ; i ++ ) { if ( n % i == 0 ) { if ( n / i == i ) result += 1 ; else result += 2 ; } } return result ; } public static void main ( String args [ ] ) { int a = 12 , b = 24 ; System . out . println ( commDiv ( a , b ) ) ; } }


"Common characters in n strings | Java Program to find all the common characters in n strings ; primary array for common characters we assume all characters are seen before . ; for each string ; secondary array for common characters Initially marked false ; for every character of ith string ; if character is present in all strings before , mark it . ; copy whole secondary array into primary ; displaying common characters ; Driver code"
How can the above be solved in Java?

import java . util . * ; import java . lang . * ; class GFG { static int MAX_CHAR = 26 ; public static void commonCharacters ( String str [ ] , int n ) { Boolean [ ] prim = new Boolean [ MAX_CHAR ] ; Arrays . fill ( prim , new Boolean ( true ) ) ; for ( int i = 0 ; i < n ; i ++ ) { Boolean [ ] sec = new Boolean [ MAX_CHAR ] ; Arrays . fill ( sec , new Boolean ( false ) ) ; for ( int j = 0 ; j < str [ i ] . length ( ) ; j ++ ) { if ( prim [ str [ i ] . charAt ( j ) - ' a ' ] ) sec [ str [ i ] . charAt ( j ) - ' a ' ] = true ; } System . arraycopy ( sec , 0 , prim , 0 , MAX_CHAR ) ; } for ( int i = 0 ; i < 26 ; i ++ ) if ( prim [ i ] ) { System . out . print ( Character . toChars ( i + 97 ) ) ; System . out . print ( " ▁ " ) ; } } public static void main ( String [ ] args ) { String str [ ] = { " geeksforgeeks " , " gemkstones " , " acknowledges " , " aguelikes " } ; int n = str . length ; commonCharacters ( str , n ) ; } }


"Common divisors of N numbers | Java program to find all common divisors of N numbers ; Function to calculate gcd of two numbers ; Function to print all the common divisors ; Variable to find the gcd of N numbers ; Set to store all the common divisors ; Finding GCD of the given N numbers ; Finding divisors of the HCF of n numbers ; Print all the divisors ; Driver 's Code ; Function to print all the common divisors"
How can the above be solved in Java?

import java . util . * ; class GFG { static int gcd ( int a , int b ) { if ( a == 0 ) return b ; return gcd ( b % a , a ) ; } static void printAllDivisors ( int arr [ ] , int N ) { int g = arr [ 0 ] ; HashSet < Integer > divisors = new HashSet < Integer > ( ) ; for ( int i = 1 ; i < N ; i ++ ) { g = gcd ( arr [ i ] , g ) ; } for ( int i = 1 ; i * i <= g ; i ++ ) { if ( g % i == 0 ) { divisors . add ( i ) ; if ( g / i != i ) divisors . add ( g / i ) ; } } for ( int it : divisors ) System . out . print ( it + " ▁ " ) ; } public static void main ( String [ ] args ) { int arr [ ] = { 6 , 90 , 12 , 18 , 30 , 24 } ; int n = arr . length ; printAllDivisors ( arr , n ) ; } }


"Compare numbers represented by Linked Lists | Java implementation of the approach ; Structure for a linked list node ; A helper function to remove zeros from the start of the linked list ; A helper function to find the length of linked list ; Given a reference ( pointer to pointer ) to the head of a list and an int , push a new node on the front of the list . ; Allocate node ; Set the data ; Link the old list after the new node ; Set the head to point to the new node ; Function to compare the numbers represented as linked lists ; Remover leading zeroes from the linked lists ; Since the number represented by a has a greater length , it will be greater ; If the lengths of two numbers are equal we have to check their magnitudes ; If we reach here , then a and b are not null and their data is same , so move to next nodes in both lists ; If linked lists are identical , then we need to return zero ; Driver code ; The constructed linked lists are : a : 5 -> 6 -> 7 b : 2 -> 3 -> 3"
How can the above be solved in Java?

class GFG { static class Node { int data ; Node next ; } ; static Node removeLeadingZeros ( Node a ) { if ( a != null && a . data == 0 ) return removeLeadingZeros ( a . next ) ; else return a ; } static int getSize ( Node a ) { int sz = 0 ; while ( a != null ) { a = a . next ; sz ++ ; } return sz ; } static Node push ( Node head_ref , int new_data ) { Node new_node = new Node ( ) ; new_node . data = new_data ; new_node . next = head_ref ; head_ref = new_node ; return head_ref ; } static int compare ( Node a , Node b ) { a = removeLeadingZeros ( a ) ; b = removeLeadingZeros ( b ) ; int lenA = getSize ( a ) ; int lenB = getSize ( b ) ; if ( lenA > lenB ) { return 1 ; } else if ( lenB > lenA ) { return - 1 ; } while ( a != null && b != null ) { if ( a . data > b . data ) return 1 ; else if ( a . data < b . data ) return - 1 ; a = a . next ; b = b . next ; } return 0 ; } public static void main ( String [ ] args ) { Node a = null ; a = push ( a , 7 ) ; a = push ( a , 6 ) ; a = push ( a , 5 ) ; Node b = null ; b = push ( b , 3 ) ; b = push ( b , 3 ) ; b = push ( b , 2 ) ; System . out . println ( compare ( a , b ) ) ; } }


"Compare sum of first N | Java implementation of the approach ; Function that returns true if sum of first n - 1 elements of the array is equal to the last element ; Find the sum of first n - 1 elements of the array ; If sum equals to the last element ; Driver code"
How can the above be solved in Java?

import java . io . * ; class GFG { static boolean isSumEqual ( int ar [ ] , int n ) { int sum = 0 ; for ( int i = 0 ; i < n - 1 ; i ++ ) sum += ar [ i ] ; if ( sum == ar [ n - 1 ] ) return true ; return false ; } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 2 , 3 , 4 , 10 } ; int n = arr . length ; if ( isSumEqual ( arr , n ) ) System . out . println ( " Yes " ) ; else System . out . println ( " No " ) ; } }


"Compare two Version numbers | Java program to compare two version number ; Method to compare two versions . Returns 1 if v2 is smaller , - 1 if v1 is smaller , 0 if equal ; vnum stores each numeric part of version ; loop until both String are processed ; Storing numeric part of version 1 in vnum1 ; storing numeric part of version 2 in vnum2 ; if equal , reset variables and go for next numeric part ; Driver method to check above comparison function"
How can the above be solved in Java?

import java . util . * ; class GFG { static int versionCompare ( String v1 , String v2 ) { int vnum1 = 0 , vnum2 = 0 ; for ( int i = 0 , j = 0 ; ( i < v1 . length ( ) || j < v2 . length ( ) ) ; ) { while ( i < v1 . length ( ) && v1 . charAt ( i ) != ' . ' ) { vnum1 = vnum1 * 10 + ( v1 . charAt ( i ) - '0' ) ; i ++ ; } while ( j < v2 . length ( ) && v2 . charAt ( j ) != ' . ' ) { vnum2 = vnum2 * 10 + ( v2 . charAt ( j ) - '0' ) ; j ++ ; } if ( vnum1 > vnum2 ) return 1 ; if ( vnum2 > vnum1 ) return - 1 ; vnum1 = vnum2 = 0 ; i ++ ; j ++ ; } return 0 ; } public static void main ( String [ ] args ) { String version1 = "1.0.3" ; String version2 = "1.0.7" ; if ( versionCompare ( version1 , version2 ) < 0 ) System . out . println ( version1 + " ▁ is ▁ smaller " ) ; else if ( versionCompare ( version1 , version2 ) > 0 ) System . out . println ( version2 + " ▁ is ▁ smaller " ) ; else System . out . println ( " Both ▁ version ▁ are ▁ equal " ) ; } }


"Compare two integers without using any Comparison operator | Java program to compare two integers without any comparison operator . ; function return true if A ^ B > 0 else false ; Driver program"
How can the above be solved in Java?

import java . util . * ; class solution { static boolean EqualNumber ( int A , int B ) { if ( ( A ^ B ) != 0 ) return true ; else return false ; } public static void main ( String args [ ] ) { int A = 5 , B = 6 ; if ( EqualNumber ( A , B ) == false ) System . out . println ( 1 ) ; else System . out . println ( 0 ) ; } }


"Comparing leading zeros in binary representations of two numbers | Java program to find the number with more leading zeroes . ; Function to compare the no . of leading zeros ; if both have same no . of leading zeros ; if y has more leading zeros ; Driver Code"
How can the above be solved in Java?

class GFG { static void LeadingZeros ( int x , int y ) { if ( ( x ^ y ) <= ( x & y ) ) System . out . print ( " Equal "); else if ( ( x & ( ~ y ) ) > y ) System . out . print ( y ) ; else System . out . print ( x ) ; } public static void main ( String [ ] args ) { int x = 10 , y = 16 ; LeadingZeros ( x , y ) ; } }


"Complement of a number with any base b | Java program to find complement of a number with any base b ; Function to find ( b - 1 ) 's complement ; Calculate number of digits in the given number ; Largest digit in the number system with base b ; Largest number in the number system with base b ; return Complement ; Function to find b 's complement ; b ' s ▁ complement ▁ = ▁ ( b - 1 ) ' s complement + 1 ; Driver code"
How can the above be solved in Java?

class GFG { static int prevComplement ( int n , int b ) { int maxDigit , maxNum = 0 , digits = 0 , num = n ; while ( n != 0 ) { digits ++ ; n = n / 10 ; } maxDigit = b - 1 ; while ( ( digits -- ) > 0 ) { maxNum = maxNum * 10 + maxDigit ; } return maxNum - num ; } static int complement ( int n , int b ) { return prevComplement ( n , b ) + 1 ; } public static void main ( String args [ ] ) { System . out . println ( prevComplement ( 25 , 7 ) ) ; System . out . println ( complement ( 25 , 7 ) ) ; } }


"Composite numbers with digit sum 1 | Java implementation of the above approach ; Function that returns true if number n is a composite number ; Corner cases ; This is checked so that we can skip middle five numbers in below loop ; Function that returns true if the eventual digit sum of number nm is 1 ; Loop till the sum is not single digit number ; Intitialize the sum as zero ; Find the sum of digits ; If sum is eventually 1 ; Function to print the required numbers from the given range ; If i is one of the required numbers ; Driver code"
How can the above be solved in Java?

public class GFG { static boolean isComposite ( int n ) { if ( n <= 1 ) return false ; 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 boolean isDigitSumOne ( int nm ) { while ( nm > 9 ) { int sum_digit = 0 ; while ( nm > 0 ) { int digit = nm % 10 ; sum_digit = sum_digit + digit ; nm = nm / 10 ; } nm = sum_digit ; } if ( nm == 1 ) return true ; else return false ; } static void printValidNums ( int l , int r ) { for ( int i = l ; i <= r ; i ++ ) { if ( isComposite ( i ) && isDigitSumOne ( i ) ) System . out . print ( i + " ▁ " ) ; } } public static void main ( String arg [ ] ) { int l = 10 , r = 100 ; printValidNums ( l , r ) ; } }


"Compress the array into Ranges | Java program to compress the array ranges ; Function to compress the array ranges ; start iteration from the ith array element ; loop until arr [ i + 1 ] == arr [ i ] and increment j ; if the program do not enter into the above while loop this means that ( i + 1 ) th element is not consecutive to i th element ; increment i for next iteration ; print the consecutive range found ; move i jump directly to j + 1 ; Driver code"
How can the above be solved in Java?

import java . util . Arrays ; class GFG { static void compressArr ( int arr [ ] , int n ) { int i = 0 , j = 0 ; Arrays . sort ( arr ) ; while ( i < n ) { j = i ; while ( ( j + 1 < n ) && ( arr [ j + 1 ] == arr [ j ] + 1 ) ) { j ++ ; } if ( i == j ) { System . out . print ( arr [ i ] + " ▁ " ) ; i ++ ; } else { System . out . print ( arr [ i ] + " - " + arr [ j ] + " ▁ " ) ; i = j + 1 ; } } } public static void main ( String [ ] args ) { int n = 7 ; int arr [ ] = { 1 , 3 , 4 , 5 , 6 , 9 , 10 } ; compressArr ( arr , n ) ; } }


"Compute average of two numbers without overflow | Java code to compute average of two numbers ; Function to compute average of two numbers ; Driver code ; Assigning maximum integer value ; Average of two equal numbers is the same number ; Function to get the average of 2 numbers"
How can the above be solved in Java?

import java . io . * ; class GFG { static int compute_average ( int a , int b ) { return ( a + b ) / 2 ; } public static void main ( String [ ] args ) { int a = Integer . MAX_VALUE ; int b = Integer . MAX_VALUE ; System . out . println ( " Actual ▁ average ▁ : ▁ " + Integer . MAX_VALUE ) ; System . out . println ( " Computed ▁ average ▁ : ▁ " + compute_average ( a , b ) ) ; } }


"Compute n ! under modulo p | Java program to Returns n % p using Sieve of Eratosthenes ; Returns largest power of p that divides n ! ; Initialize result ; Calculate x = n / p + n / ( p ^ 2 ) + n / ( p ^ 3 ) + ... . ; Utility function to do modular exponentiation . It returns ( x ^ y ) % p ; Initialize result Update x if it is more than or equal to p ; If y is odd , multiply x with result ; y must be even now y = y >> 1 ; y = y / 2 ; Returns n ! % p ; Use Sieve of Eratosthenes to find all primes smaller than n ; Consider all primes found by Sieve ; Find the largest power of prime ' i ' that divides n ; Multiply result with ( i ^ k ) % p ; Driver method"
How can the above be solved in Java?

import java . util . Arrays ; public class GFG { static int largestPower ( int n , int p ) { int x = 0 ; while ( n > 0 ) { n /= p ; x += n ; } return x ; } static int power ( int x , int y , int p ) { int res = 1 ; x = x % p ; s while ( y > 0 ) { if ( y % 2 == 1 ) { res = ( res * x ) % p ; } x = ( x * x ) % p ; } return res ; } static int modFact ( int n , int p ) { if ( n >= p ) { return 0 ; } int res = 1 ; boolean isPrime [ ] = new boolean [ n + 1 ] ; Arrays . fill ( isPrime , true ) ; for ( int i = 2 ; i * i <= n ; i ++ ) { if ( isPrime [ i ] ) { for ( int j = 2 * i ; j <= n ; j += i ) { isPrime [ j ] = false ; } } } for ( int i = 2 ; i <= n ; i ++ ) { if ( isPrime [ i ] ) { int k = largestPower ( n , i ) ; res = ( res * power ( i , k , p ) ) % p ; } } return res ; } static public void main ( String [ ] args ) { int n = 25 , p = 29 ; System . out . println ( modFact ( n , p ) ) ; } }


"Compute n ! under modulo p | Java program to compute n ! % p using Wilson 's Theorem ; Utility function to do modular exponentiation . It returns ( x ^ y ) % p ; int res = 1 ; Initialize result x = x % p ; Update x if it is more than or equal to p ; If y is odd , multiply x with result ; y must be even now y = y >> 1 ; y = y / 2 ; Function to find modular inverse of a under modulo p using Fermat 's method. Assumption: p is prime ; Returns n ! % p using Wilson 's Theorem ; n ! % p is 0 if n >= p ; Initialize result as ( p - 1 ) ! which is - 1 or ( p - 1 ) ; Multiply modulo inverse of all numbers from ( n + 1 ) to p ; Driver Code"
How can the above be solved in Java?

class GFG { static int power ( int x , int y , int p ) { while ( y > 0 ) { if ( ( y & 1 ) > 0 ) res = ( res * x ) % p ; x = ( x * x ) % p ; } return res ; } static int modInverse ( int a , int p ) { return power ( a , p - 2 , p ) ; } static int modFact ( int n , int p ) { if ( p <= n ) return 0 ; int res = ( p - 1 ) ; for ( int i = n + 1 ; i < p ; i ++ ) res = ( res * modInverse ( i , p ) ) % p ; return res ; } public static void main ( String [ ] args ) { int n = 25 , p = 29 ; System . out . println ( modFact ( n , p ) ) ; } }


"Compute n ! under modulo p | Simple method to compute n ! % p ; Returns value of n ! % p ; Driver Code"
How can the above be solved in Java?

import java . io . * ; class GFG { static int modFact ( int n , int p ) { if ( n >= p ) return 0 ; int result = 1 ; for ( int i = 1 ; i <= n ; i ++ ) result = ( result * i ) % p ; return result ; } public static void main ( String [ ] args ) { int n = 25 , p = 29 ; System . out . print ( modFact ( n , p ) ) ; } }


"Compute nCr % p | Set 2 ( Lucas Theorem ) | A Lucas Theorem based solution to compute nCr % p ; Returns nCr % p . In this Lucas Theorem based program , this function is only called for n < p and r < p . ; The array C is going to store last row of pascal triangle at the end . And last entry of last row is nCr ; One by constructs remaining rows of Pascal Triangle from top to bottom ; Fill entries of current row using previous row values ; nCj = ( n - 1 ) Cj + ( n - 1 ) C ( j - 1 ) ; ; Lucas Theorem based function that returns nCr % p This function works like decimal to binary conversion recursive function . First we compute last digits of n and r in base p , then recur for remaining digits ; Base case ; Compute last digits of n and r in base p ; Compute result for last digits computed above , and for remaining digits . Multiply the two results and compute the result of multiplication in modulo p . return ( nCrModpLucas ( n / p , r / p , p ) * Last digits of n and r nCrModpDP ( ni , ri , p ) ) % p ; Remaining digits ; Driver program"
How can the above be solved in Java?

class GFG { static int nCrModpDP ( int n , int r , int p ) { int [ ] C = new int [ r + 1 ] ; for ( int i = 1 ; i <= n ; i ++ ) { for ( int j = Math . min ( i , r ) ; j > 0 ; j -- ) C [ j ] = ( C [ j ] + C [ j - 1 ] ) % p ; } return C [ r ] ; } static int nCrModpLucas ( int n , int r , int p ) { if ( r == 0 ) return 1 ; int ni = n % p ; int ri = r % p ; } public static void main ( String [ ] args ) { int n = 1000 , r = 900 , p = 13 ; System . out . println ( " Value ▁ of ▁ nCr ▁ % ▁ p ▁ is ▁ " + nCrModpLucas ( n , r , p ) ) ; } }


"Compute power of power k times % m | Java program for computing x ^ x ^ x ^ x . . % m ; Create an array to store phi or totient values ; Function to calculate Euler Totient values ; indicates not evaluated yet and initializes for product formula . ; Compute other Phi values ; If phi [ p ] is not computed already , then number p is prime ; Phi of a prime number p is always equal to p - 1. ; Update phi values of all multiples of p ; Add contribution of p to its multiple i by multiplying with ( 1 - 1 / p ) ; Iterative Function to calculate ( x ^ y ) % p in O ( log y ) ; x = x % p ; Update x if it is more than or equal to p ; If y is odd , multiply x with result ; y must be even now y = y >> 1 ; y = y / 2 ; Function to calculate ( x ^ x ^ x ^ x ... k times ) % m ; to store different mod values ; run loop in reverse to calculate result ; Driver Code ; compute euler totient function values ; Calling function to compute answer"
How can the above be solved in Java?

class GFG { static int N = 1000000 ; static long phi [ ] = new long [ N + 5 ] ; static void computeTotient ( ) { for ( int i = 1 ; i <= N ; i ++ ) phi [ i ] = i ; for ( int p = 2 ; p <= N ; p ++ ) { if ( phi [ p ] == p ) { phi [ p ] = p - 1 ; for ( int i = 2 * p ; i <= N ; i += p ) { phi [ i ] = ( phi [ i ] / p ) * ( p - 1 ) ; } } } } static long power ( long x , long y , long p ) { while ( y > 0 ) { if ( ( y & 1 ) > 0 ) res = ( res * x ) % p ; x = ( x * x ) % p ; } return res ; } static long calculate ( long x , long k , long mod ) { long arr [ ] = new long [ N ] ; long count = 0 ; while ( mod > 1 ) { arr [ ( int ) count ++ ] = mod ; mod = phi [ ( int ) mod ] ; } long result = 1 ; long loop = count + 1 ; arr [ ( int ) count ] = 1 ; for ( int i = ( int ) Math . min ( k , loop ) - 1 ; i >= 0 ; i -- ) result = power ( x , result , arr [ i ] ) ; return result ; } public static void main ( String args [ ] ) { computeTotient ( ) ; long x = 3 , k = 2 , m = 3 ; System . out . println ( calculate ( x , k , m ) ) ; } }


"Compute power of power k times % m | Java program for computing x ^ x ^ x ^ x . . % m ; Function to compute the given value ; compute power k times ; Driver Code ; Calling function"
How can the above be solved in Java?

class GFG { static int calculate ( int x , int k , int m ) { int result = x ; k -- ; while ( k -- > 0 ) { result = ( int ) Math . pow ( result , x ) ; if ( result > m ) result %= m ; } return result ; } public static void main ( String args [ ] ) { int x = 5 , k = 2 , m = 3 ; System . out . println ( calculate ( x , k , m ) ) ; } }


"Compute sum of digits in all numbers from 1 to n | A Simple JAVA program to compute sum of digits in numbers from 1 to n ; Returns sum of all digits in numbers from 1 to n ; initialize result ; One by one compute sum of digits in every number from 1 to n ; A utility function to compute sum of digits in a given number x ; Driver Program"
How can the above be solved in Java?

import java . io . * ; class GFG { static int sumOfDigitsFrom1ToN ( int n ) { int result = 0 ; for ( int x = 1 ; x <= n ; x ++ ) result += sumOfDigits ( x ) ; return result ; } static int sumOfDigits ( int x ) { int sum = 0 ; while ( x != 0 ) { sum += x % 10 ; x = x / 10 ; } return sum ; } public static void main ( String args [ ] ) { int n = 328 ; System . out . println ( " Sum ▁ of ▁ digits ▁ in ▁ numbers " + " ▁ from ▁ 1 ▁ to ▁ " + n + " ▁ is ▁ " + sumOfDigitsFrom1ToN ( n ) ) ; } }


"Compute sum of digits in all numbers from 1 to n | JAVA program to compute sum of digits in numbers from 1 to n ; Function to computer sum of digits in numbers from 1 to n . Comments use example of 328 to explain the code ; base case : if n < 10 return sum of first n natural numbers ; d = number of digits minus one in n . For 328 , d is 2 ; computing sum of digits from 1 to 10 ^ d - 1 , d = 1 a [ 0 ] = 0 ; d = 2 a [ 1 ] = sum of digit from 1 to 9 = 45 d = 3 a [ 2 ] = sum of digit from 1 to 99 = a [ 1 ] * 10 + 45 * 10 ^ 1 = 900 d = 4 a [ 3 ] = sum of digit from 1 to 999 = a [ 2 ] * 10 + 45 * 10 ^ 2 = 13500 ; computing 10 ^ d ; Most significant digit ( msd ) of n , For 328 , msd is 3 which can be obtained using 328 / 100 ; EXPLANATION FOR FIRST and SECOND TERMS IN BELOW LINE OF CODE First two terms compute sum of digits from 1 to 299 ( sum of digits in range 1 - 99 stored in a [ d ] ) + ( sum of digits in range 100 - 199 , can be calculated as 1 * 100 + a [ d ] ( sum of digits in range 200 - 299 , can be calculated as 2 * 100 + a [ d ] The above sum can be written as 3 * a [ d ] + ( 1 + 2 ) * 100 EXPLANATION FOR THIRD AND FOURTH TERMS IN BELOW LINE OF CODE The last two terms compute sum of digits in number from 300 to 328. The third term adds 3 * 29 to sum as digit 3 occurs in all numbers from 300 to 328. The fourth term recursively calls for 28 ; Driver Program"
How can the above be solved in Java?

import java . io . * ; import java . math . * ; class GFG { static int sumOfDigitsFrom1ToN ( int n ) { if ( n < 10 ) return ( n * ( n + 1 ) / 2 ) ; int d = ( int ) ( Math . log10 ( n ) ) ; int a [ ] = new int [ d + 1 ] ; a [ 0 ] = 0 ; a [ 1 ] = 45 ; for ( int i = 2 ; i <= d ; i ++ ) a [ i ] = a [ i - 1 ] * 10 + 45 * ( int ) ( Math . ceil ( Math . pow ( 10 , i - 1 ) ) ) ; int p = ( int ) ( Math . ceil ( Math . pow ( 10 , d ) ) ) ; int msd = n / p ; return ( msd * a [ d ] + ( msd * ( msd - 1 ) / 2 ) * p + msd * ( 1 + n % p ) + sumOfDigitsFrom1ToN ( n % p ) ) ; } public static void main ( String args [ ] ) { int n = 328 ; System . out . println ( " Sum ▁ of ▁ digits ▁ in ▁ numbers ▁ " + " from ▁ 1 ▁ to ▁ " + n + " ▁ is ▁ " + sumOfDigitsFrom1ToN ( n ) ) ; } }


"Compute sum of digits in all numbers from 1 to n | JAVA program to compute sum of digits in numbers from 1 to n ; Function to computer sum of digits in numbers from 1 to n ; Driver Program"
How can the above be solved in Java?

import java . io . * ; import java . math . * ; class GFG { static int sumOfDigitsFrom1ToNUtil ( int n , int a [ ] ) { if ( n < 10 ) return ( n * ( n + 1 ) / 2 ) ; int d = ( int ) ( Math . log10 ( n ) ) ; int p = ( int ) ( Math . ceil ( Math . pow ( 10 , d ) ) ) ; int msd = n / p ; return ( msd * a [ d ] + ( msd * ( msd - 1 ) / 2 ) * p + msd * ( 1 + n % p ) + sumOfDigitsFrom1ToNUtil ( n % p , a ) ) ; } static int sumOfDigitsFrom1ToN ( int n ) { int d = ( int ) ( Math . log10 ( n ) ) ; int a [ ] = new int [ d + 1 ] ; a [ 0 ] = 0 ; a [ 1 ] = 45 ; for ( int i = 2 ; i <= d ; i ++ ) a [ i ] = a [ i - 1 ] * 10 + 45 * ( int ) ( Math . ceil ( Math . pow ( 10 , i - 1 ) ) ) ; return sumOfDigitsFrom1ToNUtil ( n , a ) ; } public static void main ( String args [ ] ) { int n = 328 ; System . out . println ( " Sum ▁ of ▁ digits ▁ in ▁ numbers ▁ " + " from ▁ 1 ▁ to ▁ " + n + " ▁ is ▁ " + sumOfDigitsFrom1ToN ( n ) ) ; } }


"Compute the maximum power with a given condition | Java program for Compute maximum power to which K can be raised so that given condition remains true ; Function to return the largest power ; If n is greater than given M ; If n == m ; Checking for the next power ; Driver Code"
How can the above be solved in Java?

class GFG { static int calculate ( int n , int k , int m , int power ) { if ( n > m ) { if ( power == 0 ) return 0 ; else return power - 1 ; } else if ( n == m ) return power ; else return calculate ( n * k , k , m , power + 1 ) ; } public static void main ( String [ ] args ) { int N = 1 , K = 2 , M = 5 ; System . out . println ( calculate ( N , K , M , 0 ) ) ; } }


"Compute the minimum or maximum of two integers without branching | JAVA implementation of above approach ; Function to find minimum of x and y ; Function to find maximum of x and y ; Driver code"
How can the above be solved in Java?

class GFG { static int CHAR_BIT = 4 ; static int INT_BIT = 8 ; static int min ( int x , int y ) { return y + ( ( x - y ) & ( ( x - y ) >> ( INT_BIT * CHAR_BIT - 1 ) ) ) ; } static int max ( int x , int y ) { return x - ( ( x - y ) & ( ( x - y ) >> ( INT_BIT * CHAR_BIT - 1 ) ) ) ; } public static void main ( String [ ] args ) { int x = 15 ; int y = 6 ; System . out . println ( " Minimum ▁ of ▁ " + x + " ▁ and ▁ " + y + " ▁ is ▁ " + min ( x , y ) ) ; System . out . println ( " Maximum ▁ of ▁ " + x + " ▁ and ▁ " + y + " ▁ is ▁ " + max ( x , y ) ) ; } }


"Compute the minimum or maximum of two integers without branching | Java program for the above approach ; absbit32 function ; max function ; min function ; Driver code"
How can the above be solved in Java?

import java . io . * ; class GFG { public static int absbit32 ( int x , int y ) { int sub = x - y ; int mask = ( sub >> 31 ) ; return ( sub ^ mask ) - mask ; } public static int max ( int x , int y ) { int abs = absbit32 ( x , y ) ; return ( x + y + abs ) / 2 ; } public static int min ( int x , int y ) { int abs = absbit32 ( x , y ) ; return ( x + y - abs ) / 2 ; } public static void main ( String [ ] args ) { System . out . println ( max ( 2 , 3 ) ) ; System . out . println ( max ( 2 , - 3 ) ) ; System . out . println ( max ( - 2 , - 3 ) ) ; System . out . println ( min ( 2 , 3 ) ) ; System . out . println ( min ( 2 , - 3 ) ) ; System . out . println ( min ( - 2 , - 3 ) ) ; } }


"Compute the minimum or maximum of two integers without branching | Java program to Compute the minimum or maximum of two integers without branching ; Function to find minimum of x and y ; Function to find maximum of x and y ; Driver program to test above functions"
How can the above be solved in Java?

public class AWS { static int min ( int x , int y ) { return y ^ ( ( x ^ y ) & - ( x << y ) ) ; } static int max ( int x , int y ) { return x ^ ( ( x ^ y ) & - ( x << y ) ) ; } public static void main ( String [ ] args ) { int x = 15 ; int y = 6 ; System . out . print ( " Minimum ▁ of ▁ " + x + " ▁ and ▁ " + y + " ▁ is ▁ " ) ; System . out . println ( min ( x , y ) ) ; System . out . print ( " Maximum ▁ of ▁ " + x + " ▁ and ▁ " + y + " ▁ is ▁ " ) ; System . out . println ( max ( x , y ) ) ; } }


"Concatenate suffixes of a String | Java implementation of the approach ; Function to print the expansion of the string ; Take sub - string from i to n - 1 ; Print the sub - string ; Driver code"
How can the above be solved in Java?

public class GFG { static void printExpansion ( String str ) { for ( int i = str . length ( ) - 1 ; i >= 0 ; i -- ) { String subStr = str . substring ( i ) ; System . out . print ( subStr ) ; } } public static void main ( String args [ ] ) { String str = " geeks " ; printExpansion ( str ) ; } }


import java . util . * ; class solution { static void printExpansion ( String str ) { String suff = " " ; for ( int i = str . length ( ) - 1 ; i >= 0 ; i -- ) { suff = suff + str . charAt ( i ) ; System . out . print ( suff ) ; } } public static void main ( String args [ ] ) { String str = " geeks " ; printExpansion ( str ) ; } }


"Concatenate the Array of elements into a single element | Java program for the above approach ; Function to find the integer value obtained by joining array elements together ; Stores the resulting integer value ; Traverse the array arr [ ] ; Stores the count of digits of arr [ i ] ; Update ans ; Increment ans by arr [ i ] ; Return the ans ; Driver Code ; Input ; Function call"
How can the above be solved in Java?

import java . util . * ; class GFG { static int ConcatenateArr ( int [ ] arr , int N ) { int ans = arr [ 0 ] ; for ( int i = 1 ; i < N ; i ++ ) { int l = ( int ) Math . floor ( Math . log10 ( arr [ i ] ) + 1 ) ; ans = ans * ( int ) Math . pow ( 10 , l ) ; ans += arr [ i ] ; } return ans ; } public static void main ( String args [ ] ) { int arr [ ] = { 1 , 23 , 456 } ; int N = arr . length ; System . out . println ( ConcatenateArr ( arr , N ) ) ; } }


"Concatenate the strings in an order which maximises the occurrence of subsequence " ab " | Java implementation of the approach ; Custom sort function to sort the given string in the order which maximises the final score ; To store the count of occurrences of ' a ' and ' b ' in s1 ; Count the number of occurrences of ' a ' and ' b ' in s1 ; To store the count of occurrences of ' a ' and ' b ' in s2 ; Count the number of occurrences of ' a ' and ' b ' in s2 ; Since the number of subsequences ' ab ' is more when s1 is placed before s2 we return 1 so that s1 occurs before s2 in the combined string ; Function that return the concatenated string as S [ 0 ] + S [ 1 ] + ... + S [ N - 1 ] ; To store the concatenated string ; Concatenate every string in the order of appearance ; Return the concatenated string ; Function to return the maximum required score ; Sort the strings in the order which maximizes the score that we can get ; Get the concatenated string combined string ; Calculate the score of the combined string i . e . the count of occurrences of " ab " as subsequences ; Number of ' a ' has increased by one ; There are count_a number of ' a ' that can form subsequence ' ab ' with this ' b ' ; Driver code"
How can the above be solved in Java?

import java . util . * ; class Gfg { public static boolean customSort ( String s1 , String s2 ) { int count_a1 = 0 , count_b1 = 0 ; for ( int i = 0 ; i < s1 . length ( ) ; i ++ ) { if ( s1 . charAt ( i ) == ' a ' ) { count_a1 ++ ; } else { count_b1 ++ ; } } int count_a2 = 0 , count_b2 = 0 ; for ( int i = 0 ; i < s2 . length ( ) ; i ++ ) { if ( s2 . charAt ( i ) == ' a ' ) { count_a2 ++ ; } else { count_b2 ++ ; } } if ( count_a1 * count_b2 > count_b1 * count_a2 ) { return true ; } else { return false ; } } public static String concatenateStrings ( String S [ ] , int N ) { String str = " " ; for ( int i = 0 ; i < N ; i ++ ) { str += S [ i ] ; } return str ; } public static int getMaxScore ( String S [ ] , int N ) { Arrays . sort ( S ) ; String combined_string = concatenateStrings ( S , N ) ; int final_score = 0 , count_a = 0 ; for ( int i = 0 ; i < combined_string . length ( ) ; i ++ ) { if ( combined_string . charAt ( i ) == ' a ' ) { count_a ++ ; } else { final_score += count_a ; } } return final_score ; } public static void main ( String [ ] args ) { String S [ ] = { " aa " , " bb " , " aab " , " bab " } ; int N = S . length ; System . out . println ( getMaxScore ( S , N ) - 10 ) ; } }


"Concatenated string with uncommon characters of two strings | Java program Find concatenated string with uncommon characters of given strings ; Result ; creating a hashMap to add characters in string s2 ; Find characters of s1 that are not present in s2 and append to result ; Find characters of s2 that are not present in s1 . ; Driver code"
How can the above be solved in Java?

import java . util . * ; import java . lang . * ; import java . io . * ; class gfg { public static String concatenatedString ( String s1 , String s2 ) { String res = " " ; int i ; HashMap < Character , Integer > m = new HashMap < Character , Integer > ( ) ; for ( i = 0 ; i < s2 . length ( ) ; i ++ ) m . put ( s2 . charAt ( i ) , 1 ) ; for ( i = 0 ; i < s1 . length ( ) ; i ++ ) if ( ! m . containsKey ( s1 . charAt ( i ) ) ) res += s1 . charAt ( i ) ; else m . put ( s1 . charAt ( i ) , 2 ) ; for ( i = 0 ; i < s2 . length ( ) ; i ++ ) if ( m . get ( s2 . charAt ( i ) ) == 1 ) res += s2 . charAt ( i ) ; return res ; } public static void main ( String [ ] args ) { String s1 = " abcs " ; String s2 = " cxzca " ; System . out . println ( concatenatedString ( s1 , s2 ) ) ; } }


"Concentration of juice after mixing n glasses in equal proportion | Java implementation of the approach ; Function to return the concentration of the resultant mixture ; Driver code"
How can the above be solved in Java?

class GFG { static double mixtureConcentration ( int n , int [ ] p ) { double res = 0 ; for ( int i = 0 ; i < n ; i ++ ) res += p [ i ] ; res /= n ; return res ; } public static void main ( String [ ] args ) { int [ ] arr = { 0 , 20 , 20 } ; int n = arr . length ; System . out . println ( String . format ( " % .4f " , mixtureConcentration ( n , arr ) ) ) ; } }


"Concentric Hexagonal Numbers | Java program to find nth concentric hexagon number ; Function to find nth concentric hexagon number ; Driver Code ; Function call"
How can the above be solved in Java?

class GFG { static int concentric_Haxagon ( int n ) { return 3 * ( int ) Math . pow ( n , 2 ) / 2 ; } public static void main ( String [ ] args ) { int n = 3 ; System . out . println ( concentric_Haxagon ( n ) ) ; } }


"Connect Nodes at same Level ( Level Order Traversal ) | Connect nodes at same level using level order traversal . ; Node class ; Sets nextRight of all nodes of a tree ; null marker to represent end of current level ; Do Level order of tree using NULL markers ; next element in queue represents next node at current Level ; push left and right children of current node ; if queue is not empty , push NULL to mark nodes at this level are visited ; Driver program to test above functions ; Constructed binary tree is 10 / \ 8 2 / \ 3 90 ; Populates nextRight pointer in all nodes ; Let us check the values of nextRight pointers"
How can the above be solved in Java?

 import java . util . LinkedList ; import java . util . Queue ; public class Connect_node_same_level { static class Node { int data ; Node left , right , nextRight ; Node ( int data ) { this . data = data ; left = null ; right = null ; nextRight = null ; } } ; static void connect ( Node root ) { Queue < Node > q = new LinkedList < Node > ( ) ; q . add ( root ) ; q . add ( null ) ; while ( ! q . isEmpty ( ) ) { Node p = q . peek ( ) ; q . remove ( ) ; if ( p != null ) { p . nextRight = q . peek ( ) ; if ( p . left != null ) q . add ( p . left ) ; if ( p . right != null ) q . add ( p . right ) ; } else if ( ! q . isEmpty ( ) ) q . add ( null ) ; } } public static void main ( String args [ ] ) { Node root = new Node ( 10 ) ; root . left = new Node ( 8 ) ; root . right = new Node ( 2 ) ; root . left . left = new Node ( 3 ) ; root . right . right = new Node ( 90 ) ; connect ( root ) ; System . out . println ( "Following are populated nextRight pointers in
" + " the ▁ tree ▁ ( -1 ▁ is ▁ printed ▁ if ▁ there ▁ is ▁ no ▁ nextRight ) " ) ; System . out . println ( " nextRight ▁ of ▁ " + root . data + " ▁ is ▁ " + ( ( root . nextRight != null ) ? root . nextRight . data : - 1 ) ) ; System . out . println ( " nextRight ▁ of ▁ " + root . left . data + " ▁ is ▁ " + ( ( root . left . nextRight != null ) ? root . left . nextRight . data : - 1 ) ) ; System . out . println ( " nextRight ▁ of ▁ " + root . right . data + " ▁ is ▁ " + ( ( root . right . nextRight != null ) ? root . right . nextRight . data : - 1 ) ) ; System . out . println ( " nextRight ▁ of ▁ " + root . left . left . data + " ▁ is ▁ " + ( ( root . left . left . nextRight != null ) ? root . left . left . nextRight . data : - 1 ) ) ; System . out . println ( " nextRight ▁ of ▁ " + root . right . right . data + " ▁ is ▁ " + ( ( root . right . right . nextRight != null ) ? root . right . right . nextRight . data : - 1 ) ) ; } }


"Connect a graph by M edges such that the graph does not contain any cycle and Bitwise AND of connected vertices is maximum | Java program for the above approach ; Function to find the maximum Bitwise AND of connected components possible by connecting a graph using M edges ; Stores total number of ways to connect the graph ; Stores the maximum Bitwise AND ; Iterate over the range [ 0 , 2 ^ n ] ; Store the Bitwise AND of the connected vertices ; Store the count of the connected vertices ; Check for all the bits ; If i - th bit is set ; If the first vertex is added ; Set andans equal to arr [ i ] ; Calculate Bitwise AND of arr [ i ] with andans ; Increase the count of connected vertices ; If number of connected vertices is ( m + 1 ) , no cycle is formed ; Find the maximum Bitwise AND value possible ; Return the maximum Bitwise AND possible ; Driver Code"
How can the above be solved in Java?

import java . util . * ; class GFG { static int maximumAND ( int arr [ ] , int n , int m ) { int tot = 1 << n ; int mx = 0 ; for ( int bm = 0 ; bm < tot ; bm ++ ) { int andans = 0 ; int count = 0 ; for ( int i = 0 ; i < n ; ++ i ) { if ( ( ( bm >> i ) & 1 ) != 0 ) { if ( count == 0 ) { andans = arr [ i ] ; } else { andans = andans & arr [ i ] ; } count ++ ; } } if ( count == ( m + 1 ) ) { mx = Math . max ( mx , andans ) ; } } return mx ; } public static void main ( String args [ ] ) { int arr [ ] = { 1 , 2 , 3 , 4 } ; int N = arr . length ; int M = 2 ; System . out . println ( maximumAND ( arr , N , M ) ) ; } }


"Connect n ropes with minimum cost | A class for Min Heap ; Array of elements in heap ; Current number of elements in min heap ; maximum possible size of min heap ; Constructor : Builds a heap from a given array a [ ] of given size ; A recursive method to heapify a subtree with the root at given index This method assumes that the subtrees are already heapified ; to get index of left child of node at index i ; to get index of right child of node at index i ; Method to remove minimum element ( or root ) from min heap ; Store the minimum value , and remove it from heap ; Inserts a new key ' k ' ; First insert the new key at the end ; Fix the min heap property if it is violated ; A utility function to check if size of heap is 1 or not ; A utility function to swap two elements ; The main function that returns the minimum cost to connect n ropes of lengths stored in len [ 0. . n - 1 ] ; Initialize result ; Create a min heap of capacity equal to n and put all ropes in it ; Iterate while size of heap doesn 't become 1 ; Extract two minimum length ropes from min heap ; Update total cost ; Insert a new rope in min heap with length equal to sum of two extracted minimum lengths ; Finally return total minimum cost for connecting all ropes ; Driver code"
How can the above be solved in Java?

class MinHeap { int [ ] harr ; int heap_size ; int capacity ; public MinHeap ( int a [ ] , int size ) { heap_size = size ; capacity = size ; harr = a ; int i = ( heap_size - 1 ) / 2 ; while ( i >= 0 ) { MinHeapify ( i ) ; i -- ; } } void MinHeapify ( int i ) { int l = left ( i ) ; int r = right ( i ) ; int smallest = i ; if ( l < heap_size && harr [ l ] < harr [ i ] ) smallest = l ; if ( r < heap_size && harr [ r ] < harr [ smallest ] ) smallest = r ; if ( smallest != i ) { swap ( i , smallest ) ; MinHeapify ( smallest ) ; } } int parent ( int i ) { return ( i - 1 ) / 2 ; } int left ( int i ) { return ( 2 * i + 1 ) ; } int right ( int i ) { return ( 2 * i + 2 ) ; } int extractMin ( ) { if ( heap_size <= 0 ) return Integer . MAX_VALUE ; if ( heap_size == 1 ) { heap_size -- ; return harr [ 0 ] ; } int root = harr [ 0 ] ; harr [ 0 ] = harr [ heap_size - 1 ] ; heap_size -- ; MinHeapify ( 0 ) ; return root ; } void insertKey ( int k ) { if ( heap_size == capacity ) { System . out . println ( " Overflow : ▁ Could ▁ not ▁ insertKey " ) ; return ; } heap_size ++ ; int i = heap_size - 1 ; harr [ i ] = k ; while ( i != 0 && harr [ parent ( i ) ] > harr [ i ] ) { swap ( i , parent ( i ) ) ; i = parent ( i ) ; } } boolean isSizeOne ( ) { return ( heap_size == 1 ) ; } void swap ( int x , int y ) { int temp = harr [ x ] ; harr [ x ] = harr [ y ] ; harr [ y ] = temp ; } static int minCost ( int len [ ] , int n ) { int cost = 0 ; MinHeap minHeap = new MinHeap ( len , n ) ; while ( ! minHeap . isSizeOne ( ) ) { int min = minHeap . extractMin ( ) ; int sec_min = minHeap . extractMin ( ) ; cost += ( min + sec_min ) ; minHeap . insertKey ( min + sec_min ) ; } return cost ; } public static void main ( String args [ ] ) { int len [ ] = { 4 , 3 , 2 , 6 } ; int size = len . length ; System . out . println ( " Total ▁ cost ▁ for ▁ connecting ▁ ropes ▁ is ▁ " + minCost ( len , size ) ) ; } } ;


"Connect n ropes with minimum cost | Java program to connect n ropes with minimum cost ; Create a priority queue ; Initialize result ; While size of priority queue is more than 1 ; Extract shortest two ropes from pq ; Connect the ropes : update result and insert the new rope to pq ; Driver program to test above function"
How can the above be solved in Java?

import java . util . * ; class ConnectRopes { static int minCost ( int arr [ ] , int n ) { PriorityQueue < Integer > pq = new PriorityQueue < Integer > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { pq . add ( arr [ i ] ) ; } int res = 0 ; while ( pq . size ( ) > 1 ) { int first = pq . poll ( ) ; int second = pq . poll ( ) ; res += first + second ; pq . add ( first + second ) ; } return res ; } public static void main ( String args [ ] ) { int len [ ] = { 4 , 3 , 2 , 6 } ; int size = len . length ; System . out . println ( " Total ▁ cost ▁ for ▁ connecting " + " ▁ ropes ▁ is ▁ " + minCost ( len , size ) ) ; } }


"Connect nodes at same level using constant extra space | A binary tree node ; This function returns the leftmost child of nodes at the same level as p . This function is used to getNExt right of p 's right child  If right child of is NULL then this can also be used for the   left child  ; Traverse nodes at p ' s ▁ level ▁ and ▁ find ▁ and ▁ return ▁ ▁ the ▁ first ▁ node ' s first child ; If all the nodes at p 's level are leaf nodes then return NULL ; Sets nextRight of all nodes of a tree with root as p ; Set nextRight for root ; set nextRight of all levels one by one ; Connect all childrem nodes of p and children nodes of all other nodes at same level as p ; Set the nextRight pointer for p 's left child ; If q has right child , then right child is nextRight of p and we also need to set nextRight of right child ; Set nextRight for other nodes in pre order fashion ; start from the first node of next level ; Driver program to test above functions ; Constructed binary tree is 10 / \ 8 2 / \ 3 90 ; Populates nextRight pointer in all nodes ; Let us check the values of nextRight pointers"
How can the above be solved in Java?

class Node { int data ; Node left , right , nextRight ; Node ( int item ) { data = item ; left = right = nextRight = null ; } } class BinaryTree { Node root ; Node getNextRight ( Node p ) { Node temp = p . nextRight ; while ( temp != null ) { if ( temp . left != null ) return temp . left ; if ( temp . right != null ) return temp . right ; temp = temp . nextRight ; } return null ; } void connect ( Node p ) { Node temp = null ; if ( p == null ) return ; p . nextRight = null ; while ( p != null ) { Node q = p ; while ( q != null ) { if ( q . left != null ) { if ( q . right != null ) q . left . nextRight = q . right ; else q . left . nextRight = getNextRight ( q ) ; } if ( q . right != null ) q . right . nextRight = getNextRight ( q ) ; q = q . nextRight ; } if ( p . left != null ) p = p . left ; else if ( p . right != null ) p = p . right ; else p = getNextRight ( p ) ; } } public static void main ( String args [ ] ) { BinaryTree tree = new BinaryTree ( ) ; tree . root = new Node ( 10 ) ; tree . root . left = new Node ( 8 ) ; tree . root . right = new Node ( 2 ) ; tree . root . left . left = new Node ( 3 ) ; tree . root . right . right = new Node ( 90 ) ; tree . connect ( tree . root ) ; int a = tree . root . nextRight != null ? tree . root . nextRight . data : - 1 ; int b = tree . root . left . nextRight != null ? tree . root . left . nextRight . data : - 1 ; int c = tree . root . right . nextRight != null ? tree . root . right . nextRight . data : - 1 ; int d = tree . root . left . left . nextRight != null ? tree . root . left . left . nextRight . data : - 1 ; int e = tree . root . right . right . nextRight != null ? tree . root . right . right . nextRight . data : - 1 ; System . out . println ( " Following ▁ are ▁ populated ▁ nextRight ▁ pointers ▁ in ▁ " + " ▁ the ▁ tree ( -1 ▁ is ▁ printed ▁ if ▁ there ▁ is ▁ no ▁ nextRight ) " ) ; System . out . println ( " nextRight ▁ of ▁ " + tree . root . data + " ▁ is ▁ " + a ) ; System . out . println ( " nextRight ▁ of ▁ " + tree . root . left . data + " ▁ is ▁ " + b...