"Find remainder when a number A raised to N factorial is divided by P | package whatever do not write package name here ; Function to calculate ( A ^ N ! ) % P in O ( log y ) ; Initialize result ; Update x if it is more than or Equal to p ; In case x is divisible by p ; ; If y is odd , multiply x with result ; y must be even now ; Returning modular power ; Function to calculate resultant remainder ; Initializing ans to store final remainder ; Calculating remainder ; Returning resultant remainder ; Driver Code ; Given Input ; Function Call"
How can the above be solved in Java?

import java . io . * ; class GFG { static long power ( long x , long y , long p ) { long res = 1 ; x = x % p ; if ( x == 0 ) return 0 ; while ( y > 0 ) { if ( ( y & 1 ) == 1 ) res = ( res * x ) % p ; y = y >> 1 ; x = ( x * x ) % p ; } return res ; } static long remainder ( long n , long a , long p ) { long ans = a % p ; for ( long i = 1 ; i <= n ; i ++ ) ans = power ( ans , i , p ) ; return ans ; } public static void main ( String [ ] args ) { long A = 2 , N = 1 , P = 2 ; System . out . println ( remainder ( N , A , P ) ) ; } }


"Find right sibling of a binary tree with parent pointers | Java program to print right sibling of a node ; A Binary Tree Node ; Constructor ; Method to find right sibling ; GET Parent pointer whose right child is not a parent or itself of this node . There might be case when parent has no right child , but , current node is left child of the parent ( second condition is for that ) . ; Move to the required child , where right sibling can be present ; find right sibling in the given subtree ( from current node ) , when level will be 0 ; Iterate through subtree ; if no child are there , we cannot have right sibling in this path ; This is the case when we reach 9 node in the tree , where we need to again recursively find the right sibling ; Driver Program to test above functions ; passing 10"
How can the above be solved in Java?

public class Right_Sibling { static class Node { int data ; Node left , right , parent ; public Node ( int data , Node parent ) { this . data = data ; left = null ; right = null ; this . parent = parent ; } } ; static Node findRightSibling ( Node node , int level ) { if ( node == null node . parent == null ) return null ; while ( node . parent . right == node || ( node . parent . right == null && node . parent . left == node ) ) { if ( node . parent == null ) return null ; node = node . parent ; level -- ; } node = node . parent . right ; while ( level < 0 ) { if ( node . left != null ) node = node . left ; else if ( node . right != null ) node = node . right ; else break ; level ++ ; } if ( level == 0 ) return node ; return findRightSibling ( node , level ) ; } public static void main ( String args [ ] ) { Node root = new Node ( 1 , null ) ; root . left = new Node ( 2 , root ) ; root . right = new Node ( 3 , root ) ; root . left . left = new Node ( 4 , root . left ) ; root . left . right = new Node ( 6 , root . left ) ; root . left . left . left = new Node ( 7 , root . left . left ) ; root . left . left . left . left = new Node ( 10 , root . left . left . left ) ; root . left . right . right = new Node ( 9 , root . left . right ) ; root . right . right = new Node ( 5 , root . right ) ; root . right . right . right = new Node ( 8 , root . right . right ) ; root . right . right . right . right = new Node ( 12 , root . right . right . right ) ; System . out . println ( findRightSibling ( root . left . left . left . left , 0 ) . data ) ; } }


"Find root of a number using Newton 's method | Java implementation of the approach ; Function to return the square root of a number using Newtons method ; Assuming the sqrt of n as n only ; The closed guess will be stored in the root ; To count the number of iterations ; Calculate more closed x ; Check for closeness ; Update root ; Driver code"
How can the above be solved in Java?

class GFG { static double squareRoot ( double n , double l ) { double x = n ; double root ; int count = 0 ; while ( true ) { count ++ ; root = 0.5 * ( x + ( n / x ) ) ; if ( Math . abs ( root - x ) < l ) break ; x = root ; } return root ; } public static void main ( String [ ] args ) { double n = 327 ; double l = 0.00001 ; System . out . println ( squareRoot ( n , l ) ) ; } }


"Find root of the tree where children id sum for every node is given | Find root of tree where children sum for every node id is given . ; Every node appears once as an id , and every node except for the root appears once in a sum . So if we subtract all the sums from all the ids , we 're left  with the root id. ; Driver code"
How can the above be solved in Java?

 class GFG { static class pair { int first , second ; public pair ( int first , int second ) { this . first = first ; this . second = second ; } } static int findRoot ( pair arr [ ] , int n ) { int root = 0 ; for ( int i = 0 ; i < n ; i ++ ) { root += ( arr [ i ] . first - arr [ i ] . second ) ; } return root ; } public static void main ( String [ ] args ) { pair arr [ ] = { new pair ( 1 , 5 ) , new pair ( 2 , 0 ) , new pair ( 3 , 0 ) , new pair ( 4 , 0 ) , new pair ( 5 , 5 ) , new pair ( 6 , 5 ) } ; int n = arr . length ; System . out . printf ( "%d
", findRoot(arr, n)); } }


"Find row number of a binary matrix having maximum number of 1 s | Java program to find row with maximum 1 in row sorted binary matrix ; function for finding row with maximum 1 ; find left most position of 1 in a row find 1 st zero in a row ; Driver code"
How can the above be solved in Java?

class GFG { static final int N = 4 ; static void findMax ( int arr [ ] [ ] ) { int row = 0 , i , j ; for ( i = 0 , j = N - 1 ; i < N ; i ++ ) { while ( j >= 0 && arr [ i ] [ j ] == 1 ) { row = i ; j -- ; } } System . out . print ( " Row ▁ number ▁ = ▁ " + ( row + 1 ) ) ; System . out . print ( " , ▁ MaxCount ▁ = ▁ " + ( N - 1 - j ) ) ; } public static void main ( String [ ] args ) { int arr [ ] [ ] = { { 0 , 0 , 0 , 1 } , { 0 , 0 , 0 , 1 } , { 0 , 0 , 0 , 0 } , { 0 , 1 , 1 , 1 } } ; findMax ( arr ) ; } }


"Find shortest unique prefix for every word in a given list | Set 2 ( Using Sorting ) | Java program to print shortest unique prefixes for every word . ; create an array to store the results ; sort the array of strings ; compare the first string with its only right neighbor ; Store the unique prefix of a [ 1 ] from its left neighbor ; compute common prefix of a [ i ] unique from its right neighbor ; compare the new prefix with previous prefix ; store the prefix of a [ i + 1 ] unique from its left neighbour ; compute the unique prefix for the last string in sorted array ; Driver Function to test other function"
How can the above be solved in Java?

import java . io . * ; import java . util . * ; class GFG { public String [ ] uniquePrefix ( String [ ] a ) { int size = a . length ; String [ ] res = new String [ size ] ; Arrays . sort ( a ) ; int j = 0 ; while ( j < Math . min ( a [ 0 ] . length ( ) - 1 , a [ 1 ] . length ( ) - 1 ) ) { if ( a [ 0 ] . charAt ( j ) == a [ 1 ] . charAt ( j ) ) j ++ ; else break ; } int ind = 0 ; res [ ind ++ ] = a [ 0 ] . substring ( 0 , j + 1 ) ; String temp_prefix = a [ 1 ] . substring ( 0 , j + 1 ) ; for ( int i = 1 ; i < size - 1 ; i ++ ) { j = 0 ; while ( j < Math . min ( a [ i ] . length ( ) - 1 , a [ i + 1 ] . length ( ) - 1 ) ) { if ( a [ i ] . charAt ( j ) == a [ i + 1 ] . charAt ( j ) ) j ++ ; else break ; } String new_prefix = a [ i ] . substring ( 0 , j + 1 ) ; if ( temp_prefix . length ( ) > new_prefix . length ( ) ) res [ ind ++ ] = temp_prefix ; else res [ ind ++ ] = new_prefix ; temp_prefix = a [ i + 1 ] . substring ( 0 , j + 1 ) ; } j = 0 ; String sec_last = a [ size - 2 ] ; String last = a [ size - 1 ] ; while ( j < Math . min ( sec_last . length ( ) - 1 , last . length ( ) - 1 ) ) { if ( sec_last . charAt ( j ) == last . charAt ( j ) ) j ++ ; else break ; } res [ ind ] = last . substring ( 0 , j + 1 ) ; return res ; } public static void main ( String [ ] args ) { GFG gfg = new GFG ( ) ; String [ ] input = { " zebra " , " dog " , " duck " , " dove " } ; String [ ] output = gfg . uniquePrefix ( input ) ; System . out . println ( " The ▁ shortest ▁ unique ▁ prefixes " + " ▁ in ▁ sorted ▁ order ▁ are ▁ : " ) ; for ( int i = 0 ; i < output . length ; i ++ ) System . out . print ( output [ i ] + " ▁ " ) ; } }


"Find side of Square which makes minimal area to fit two identical rectangles inside it | Java program of the above approach ; If ' a ' and ' b ' same then double ' a ' or ' b ' and return ( 2 * a ) or ( 2 * b ) ; Check if a != b ; If a > b ; Double the smaller value that is ' b ' and store it to ' newB ' ; Find the difference of ' newB ▁ and ▁ ' a ' ; If ' newB ' < a ; Then add the difference of ' newB ' and ' a ' to the ' b ' to make ' b ' and ' a ' as same ; Return side of the square a or b ; If ' newB ' > a then then add the difference of ' newB ' and ' a ' to the ' a ' to make ' a ' and ' newB ' as same ; Return side of the square a or newB ; If a < b ; Double the smaller value that is ' a ' and store it to ' newA ' ; Find the difference of ' newA ▁ and ▁ ' b ' ; If ' newA ' < b ; Then add the difference of ' newA ' and ' b ' to the ' a ' to make ' a ' and ' b ' as same ; Return side of the square a or b ; If ' newA ' > b then then add the difference of ' newA ' and ' b ' to the ' b ' to make ' b ' and ' newA ' as same ; Return side of the square b or newA ; Driver code ; Size of rectangle"
How can the above be solved in Java?

class GFG { public static int minimalSquareSide ( int a , int b ) { if ( a == b ) { return 2 * a ; } if ( a != b ) { if ( a > b ) { int newB = b + b ; int diff = Math . abs ( newB - a ) ; if ( newB < a ) { b = newB + diff ; if ( a == b ) return a ; return 0 ; } else { a = a + diff ; if ( a == newB ) return a ; return 0 ; } } else { int newA = a + a ; int diff = Math . abs ( newA - b ) ; if ( newA < b ) { a = diff + newA ; if ( a == b ) return a ; return 0 ; } else { b = b + diff ; if ( b == newA ) return b ; return 0 ; } } } return 0 ; } public static void main ( String [ ] args ) { int H , W ; H = 3 ; W = 1 ; System . out . println ( minimalSquareSide ( H , W ) ) ; } }


"Find size of the largest ' + ' formed by all ones in a binary matrix | Java program to find the size of the largest ' + ' formed by all 1 's in given binary matrix ; size of binary square matrix ; Function to find the size of the largest ' + ' formed by all 1 's in given binary matrix ; left [ j ] [ j ] , right [ i ] [ j ] , top [ i ] [ j ] and bottom [ i ] [ j ] store maximum number of consecutive 1 's present to the left,  right, top and bottom of mat[i][j]  including cell(i, j) respectively ; initialize above four matrix ; initialize first row of top ; initialize last row of bottom ; initialize first column of left ; initialize last column of right ; fill all cells of above four matrix ; calculate left matrix ( filled left to right ) ; calculate top matrix ; calculate new value of j to calculate value of bottom ( i , j ) and right ( i , j ) ; calculate bottom matrix ; calculate right matrix ; revert back to old j ; n stores length of longest + found so far ; compute longest + ; find minimum of left ( i , j ) , right ( i , j ) , top ( i , j ) , bottom ( i , j ) ; largest + would be formed by a cell that has maximum value ; 4 directions of length n - 1 and 1 for middle cell ; matrix contains all 0 's ; Driver function to test above functions"
How can the above be solved in Java?


"Find smallest and largest element from square matrix diagonals | Java program to find smallest and largest elements of both diagonals ; Function to find smallest and largest element from principal and secondary diagonal ; take length of matrix ; declare and initialism variables with appropriate value ; take new smallest value ; take new largest value ; Condition for secondary diagonal is mat [ n - 1 - i ] [ i ] take new smallest value ; take new largest value ; Driver code ; Declare and initialize 5 X5 matrix"
How can the above be solved in Java?

public class GFG { static void diagonalsMinMax ( int [ ] [ ] mat ) { int n = mat . length ; if ( n == 0 ) return ; int principalMin = mat [ 0 ] [ 0 ] , principalMax = mat [ 0 ] [ 0 ] ; int secondaryMin = mat [ n - 1 ] [ 0 ] , secondaryMax = mat [ n - 1 ] [ 0 ] ; for ( int i = 0 ; i < n ; i ++ ) { if ( mat [ i ] [ i ] < principalMin ) { principalMin = mat [ i ] [ i ] ; } if ( mat [ i ] [ i ] > principalMax ) { principalMax = mat [ i ] [ i ] ; } if ( mat [ n - 1 - i ] [ i ] < secondaryMin ) { secondaryMin = mat [ n - 1 - i ] [ i ] ; } if ( mat [ n - 1 - i ] [ i ] > secondaryMax ) { secondaryMax = mat [ n - 1 - i ] [ i ] ; } } System . out . println ( " Principal ▁ Diagonal ▁ Smallest ▁ Element : ▁ " + principalMin ) ; System . out . println ( " Principal ▁ Diagonal ▁ Greatest ▁ Element ▁ : ▁ " + principalMax ) ; System . out . println ( " Secondary ▁ Diagonal ▁ Smallest ▁ Element : ▁ " + secondaryMin ) ; System . out . println ( " Secondary ▁ Diagonal ▁ Greatest ▁ Element : ▁ " + secondaryMax ) ; } static public void main ( String [ ] args ) { int [ ] [ ] matrix = { { 1 , 2 , 3 , 4 , - 10 } , { 5 , 6 , 7 , 8 , 6 } , { 1 , 2 , 11 , 3 , 4 } , { 5 , 6 , 70 , 5 , 8 } , { 4 , 9 , 7 , 1 , - 5 } } ; diagonalsMinMax ( matrix ) ; } }


"Find smallest and largest element from square matrix diagonals | Java program to find smallest and largest elements of both diagonals ; Function to find smallest and largest element from principal and secondary diagonal ; take length of matrix ; declare and initialize variables with appropriate value ; Condition for principal diagonal ; take new smallest value ; take new largest value ; Condition for secondary diagonal ; take new smallest value ; take new largest value ; Driver code ; Declare and initialize 5 X5 matrix"
How can the above be solved in Java?

public class GFG { static void diagonalsMinMax ( int [ ] [ ] mat ) { int n = mat . length ; if ( n == 0 ) return ; int principalMin = mat [ 0 ] [ 0 ] , principalMax = mat [ 0 ] [ 0 ] ; int secondaryMin = mat [ n - 1 ] [ 0 ] , secondaryMax = mat [ n - 1 ] [ 0 ] ; for ( int i = 1 ; i < n ; i ++ ) { for ( int j = 1 ; j < n ; j ++ ) { if ( i == j ) { if ( mat [ i ] [ j ] < principalMin ) { principalMin = mat [ i ] [ j ] ; } if ( mat [ i ] [ j ] > principalMax ) { principalMax = mat [ i ] [ j ] ; } } if ( ( i + j ) == ( n - 1 ) ) { if ( mat [ i ] [ j ] < secondaryMin ) { secondaryMin = mat [ i ] [ j ] ; } if ( mat [ i ] [ j ] > secondaryMax ) { secondaryMax = mat [ i ] [ j ] ; } } } } System . out . println ( " Principal ▁ Diagonal ▁ Smallest ▁ Element : ▁ " + principalMin ) ; System . out . println ( " Principal ▁ Diagonal ▁ Greatest ▁ Element ▁ : ▁ " + principalMax ) ; System . out . println ( " Secondary ▁ Diagonal ▁ Smallest ▁ Element : ▁ " + secondaryMin ) ; System . out . println ( " Secondary ▁ Diagonal ▁ Greatest ▁ Element : ▁ " + secondaryMax ) ; } static public void main ( String [ ] args ) { int [ ] [ ] matrix = { { 1 , 2 , 3 , 4 , - 10 } , { 5 , 6 , 7 , 8 , 6 } , { 1 , 2 , 11 , 3 , 4 } , { 5 , 6 , 70 , 5 , 8 } , { 4 , 9 , 7 , 1 , - 5 } } ; diagonalsMinMax ( matrix ) ; } }


"Find smallest number K such that K % p = 0 and q % K = 0 | Java implementation of the approach ; Function to return the minimum value K such that K % p = 0 and q % k = 0 ; If K is possible ; No such K is possible ; Driver code"
How can the above be solved in Java?

import java . io . * ; class GFG { static int getMinVal ( int p , int q ) { if ( q % p == 0 ) return p ; return - 1 ; } public static void main ( String [ ] args ) { int p = 24 , q = 48 ; System . out . println ( getMinVal ( p , q ) ) ; } }


"Find smallest number formed by inverting digits of given number N | Java program for the above approach ; Function to invert the digits of integer N to form minimum possible number ; Initialize the array ; Iterate till the number N exists ; Last digit of the number N ; Checking if the digit is smaller than 9 - digit ; Store the smaller digit in the array ; Reduce the number each time ; Check if the digit starts with 0 or not ; Print the answer ; Driver Code ; Given Number ; Function Call"
How can the above be solved in Java?

class GFG { static void number ( int num ) { int a [ ] = new int [ 20 ] ; int r , i = 0 , j ; while ( num > 0 ) { r = num % 10 ; if ( 9 - r > r ) a [ i ] = r ; else a [ i ] = 9 - r ; i ++ ; num = num / 10 ; } if ( a [ i - 1 ] == 0 ) { System . out . print ( "9" ) ; i -- ; } for ( j = i - 1 ; j >= 0 ; j -- ) System . out . print ( a [ j ] ) ; } public static void main ( String [ ] args ) { int num = 4545 ; number ( num ) ; } }


"Find smallest number n such that n XOR n + 1 equals to given k . | Java to find n such that XOR of n and n + 1 is equals to given n ; function to return the required n ; if k is of form 2 ^ i - 1 ; Driver code"
How can the above be solved in Java?

class GFG { static int xorCalc ( int k ) { if ( k == 1 ) return 2 ; if ( ( ( k + 1 ) & k ) == 0 ) return k / 2 ; return 1 ; } public static void main ( String [ ] args ) { int k = 31 ; System . out . println ( xorCalc ( k ) ) ; } }


"Find smallest number with given digits and sum of digits | Java program for the above approach ; Function to print the minimum integer having only digits P and Q and the sum of digits as N ; If Q is greater that P then swap the values of P and Q ; If P and Q are both zero or if Q is zero and N is not divisible by P then there is no possible integer which satisfies the given conditions ; Loop to find the maximum value of count_P that also satisfy P * count_P + Q * count_Q = N ; If N is 0 , their is a valid integer possible that satisfies all the requires conditions ; Print Answer ; Driver code ; Function Call"
How can the above be solved in Java?

import java . io . * ; class GFG { static void printMinInteger ( int P , int Q , int N ) { if ( Q > P ) { int temp ; temp = P ; P = Q ; Q = temp ; } if ( Q == 0 && ( P == 0 N % P != 0 ) ) { System . out . println ( " Not ▁ Possible " ) ; return ; } int count_P = 0 , count_Q = 0 ; while ( N > 0 ) { if ( N % P == 0 ) { count_P += N / P ; N = 0 ; } else { N = N - Q ; count_Q ++ ; } } if ( N == 0 ) { for ( int i = 0 ; i < count_Q ; i ++ ) System . out . print ( Q ) ; for ( int i = 0 ; i < count_P ; i ++ ) System . out . print ( P ) ; } else { System . out . println ( " Not ▁ Possible " ) ; } } public static void main ( String [ ] args ) { int N = 32 ; int P = 7 ; int Q = 4 ; printMinInteger ( P , Q , N ) ; } }


"Find smallest number with given number of digits and sum of digits under given constraints | Java implementation of the approach ; Function to find the number having sum of digits as s and d number of digits such that the difference between the maximum and the minimum digit the minimum possible ; To store the final number ; To store the value that is evenly distributed among all the digits ; To store the remaining sum that still remains to be distributed among d digits ; rem stores the value that still remains to be distributed To keep the difference of digits minimum last rem digits are incremented by 1 ; In the last rem digits one is added to the value obtained by equal distribution ; Driver function"
How can the above be solved in Java?

import java . util . * ; class GFG { static String findNumber ( int s , int d ) { String num = " " ; int val = s / d ; int rem = s % d ; int i ; for ( i = 1 ; i <= d - rem ; i ++ ) { num = num + String . valueOf ( val ) ; } if ( rem > 0 ) { val ++ ; for ( i = d - rem + 1 ; i <= d ; i ++ ) { num = num + String . valueOf ( val ) ; } } return num ; } public static void main ( String [ ] args ) { int s = 25 , d = 4 ; System . out . print ( findNumber ( s , d ) ) ; } }


"Find smallest perfect square number A such that N + A is also a perfect square number | Java code to find out the smallest perfect square X which when added to N yields another perfect square number . ; X is the smallest perfect square number ; Loop from 1 to square root of N ; Condition to check whether i is factor of N or not ; Condition to check whether factors satisfies the equation or not ; Stores minimum value ; Return if X * X if X is not equal to 1e9 else return - 1 ; Driver code"
How can the above be solved in Java?

public class GFG { static long SmallestPerfectSquare ( long N ) { long X = ( long ) 1e9 ; long ans ; for ( int i = 1 ; i < Math . sqrt ( N ) ; i ++ ) { if ( N % i == 0 ) { long a = i ; long b = N / i ; if ( ( b - a != 0 ) && ( ( b - a ) % 2 == 0 ) ) { X = Math . min ( X , ( b - a ) / 2 ) ; } } } if ( X != 1e9 ) ans = X * X ; else ans = - 1 ; return ans ; } public static void main ( String [ ] args ) { long N = 3 ; System . out . println ( SmallestPerfectSquare ( N ) ) ; } }


"Find smallest positive number Y such that Bitwise AND of X and Y is Zero | Java program to find smallest number Y for a given value of X such that X AND Y is zero ; Method to find smallest number Y for a given value of X such that X AND Y is zero ; Convert the number into its binary form ; Case 1 : If all bits are ones , then return the next number ; Case 2 : find the first 0 - bit index and return the Y ; Driver code"
How can the above be solved in Java?

import java . lang . * ; public class Main { static long findSmallestNonZeroY ( long A_num ) { String A_binary = Long . toBinaryString ( A_num ) ; long B = 1 ; int len = A_binary . length ( ) ; int no_ones = Long . bitCount ( A_num ) ; if ( len == no_ones ) { return A_num + 1 ; } for ( int i = 0 ; i < len ; i ++ ) { char ch = A_binary . charAt ( len - i - 1 ) ; if ( ch == '0' ) { B = ( long ) Math . pow ( 2.0 , ( double ) i ) ; break ; } } return B ; } public static void main ( String [ ] args ) { long X = findSmallestNonZeroY ( 10 ) ; System . out . println ( X ) ; } }


"Find smallest value of K such that bitwise AND of numbers in range [ N , N | Java program for the above approach ; Function is to find the largest no which gives the sequence n & ( n - 1 ) & ( n - 2 ) & ... . . & ( n - k ) = 0. ; Since , we need the largest no , we start from n itself , till 0 ; Driver Code"
How can the above be solved in Java?

import java . io . * ; class GFG { public static int findSmallestNumK ( int n ) { int cummAnd = n ; int i = n - 1 ; while ( cummAnd != 0 ) { cummAnd = cummAnd & i ; if ( cummAnd == 0 ) { return i ; } i -- ; } return - 1 ; } public static void main ( String [ ] args ) { int N = 17 ; int lastNum = findSmallestNumK ( N ) ; int K = lastNum == - 1 ? lastNum : N - lastNum ; System . out . println ( K ) ; } }


"Find smallest values of x and y such that ax | Java program to find the smallest values of x and y that satisfy " ax ▁ - ▁ by ▁ = ▁ 0" ; To find GCD using Eculcid 's algorithm ; Prints smallest values of x and y that satisfy " ax ▁ - ▁ by ▁ = ▁ 0" ; Find LCM ; Driver code"
How can the above be solved in Java?

class GFG { static int gcd ( int a , int b ) { if ( b == 0 ) return a ; return ( gcd ( b , a % b ) ) ; } static void findSmallest ( int a , int b ) { int lcm = ( a * b ) / gcd ( a , b ) ; System . out . print ( " x ▁ = ▁ " + lcm / a + " y = " + lcm / b); } public static void main ( String [ ] args ) { int a = 25 , b = 35 ; findSmallest ( a , b ) ; } }


"Find sub | Java implementation of the approach ; Function to return the sum of the sub - matrix ; Function that returns true if it is possible to find the sub - matrix with required sum ; 2 - D array to store the sum of all the sub - matrices ; Filling of dp [ ] [ ] array ; Checking for each possible sub - matrix of size k X k ; Sub - matrix with the given sum not found ; Driver code ; Function call"
How can the above be solved in Java?

class GfG { static int N = 4 ; static int getSum ( int r1 , int r2 , int c1 , int c2 , int dp [ ] [ ] ) { return dp [ r2 ] [ c2 ] - dp [ r2 ] [ c1 ] - dp [ r1 ] [ c2 ] + dp [ r1 ] [ c1 ] ; } static boolean sumFound ( int K , int S , int grid [ ] [ ] ) { int dp [ ] [ ] = new int [ N + 1 ] [ N + 1 ] ; for ( int i = 0 ; i < N ; i ++ ) { for ( int j = 0 ; j < N ; j ++ ) { dp [ i + 1 ] [ j + 1 ] = dp [ i + 1 ] [ j ] + dp [ i ] [ j + 1 ] - dp [ i ] [ j ] + grid [ i ] [ j ] ; } } for ( int i = 0 ; i < N ; i ++ ) { for ( int j = 0 ; j < N ; j ++ ) { int sum = getSum ( i , i + K , j , j + K , dp ) ; if ( sum == S ) { return true ; } } } return false ; } public static void main ( String [ ] args ) { int grid [ ] [ ] = { { 1 , 2 , 3 , 4 } , { 5 , 6 , 7 , 8 } , { 9 , 10 , 11 , 12 } , { 13 , 14 , 15 , 16 } } ; int K = 2 ; int S = 14 ; if ( sumFound ( K , S , grid ) ) { System . out . println ( " Yes " ) ; } else { System . out . println ( " No " ) ; } } }


"Find sub | Java program to find substring with given power ; Function to print indexes of substring with power as given power . ; Create an empty map ; Maintains sum of powers of characters so far . ; Add current character power to curr_power . ; If curr_power is equal to target power we found a substring starting from index 0 and ending at index i . ; If curr_power - power already exists in map then we have found a subarray with target power . ; If we reach here , then no substring exists . ; Driver Code"
How can the above be solved in Java?

import java . util . * ; class GFG { static void findSubstring ( String str , int power ) { HashMap < Integer , Integer > map = new HashMap < > ( ) ; int curr_power = 0 ; int len = str . length ( ) ; for ( int i = 0 ; i < len ; i ++ ) { curr_power = curr_power + ( str . charAt ( i ) - ' a ' + 1 ) ; if ( curr_power == power ) { System . out . println ( " Substring ▁ from ▁ index ▁ 0" + " ▁ to ▁ " + i + " ▁ has ▁ power ▁ " + power ) ; return ; } if ( map . containsKey ( curr_power - power ) ) { System . out . println ( " Substring ▁ from ▁ index ▁ " + ( map . get ( curr_power - power ) + 1 ) + " ▁ to ▁ " + i + " ▁ has ▁ power ▁ " + power ) ; return ; } map . put ( curr_power , i ) ; } System . out . println ( " No ▁ substring ▁ with ▁ given ▁ power ▁ exists . " ) ; } public static void main ( String [ ] args ) { String str = " geeksforgeeks " ; int power = 36 ; findSubstring ( str , power ) ; } }


"Find subarray of Length K with Maximum Peak | Java implementation to Find subarray of Length K with Maximum Peak ; Function to find the subarray ; Make prefix array to store the prefix sum of peak count ; Count peak for previous index ; Check if this element is a peak ; Increment the count ; Check if number of peak in the sub array whose l = i is greater or not ; Print the result ; Driver code"
How can the above be solved in Java?

 class GFG { static void findSubArray ( int [ ] a , int n , int k ) { int [ ] pref = new int [ n ] ; pref [ 0 ] = 0 ; for ( int i = 1 ; i < n - 1 ; ++ i ) { pref [ i ] = pref [ i - 1 ] ; if ( a [ i ] > a [ i - 1 ] && a [ i ] > a [ i + 1 ] ) pref [ i ] ++ ; } int peak = 0 , left = 0 ; for ( int i = 0 ; i + k - 1 < n ; ++ i ) if ( pref [ i + k - 2 ] - pref [ i ] > peak ) { peak = pref [ i + k - 2 ] - pref [ i ] ; left = i ; } System . out . print ( " Left ▁ = ▁ " + ( left + 1 ) + "
"); System . out . print ( " Right ▁ = ▁ " + ( left + k ) + "
"); System . out . print ( " Peak ▁ = ▁ " + peak + "
"); } public static void main ( String [ ] args ) { int arr [ ] = { 3 , 2 , 3 , 2 , 1 } ; int n = arr . length ; int k = 3 ; findSubArray ( arr , n , k ) ; } }


"Find subarray with given sum | Set 1 ( Nonnegative Numbers ) |  ; Returns true if the there is a subarray of arr [ ] with a sum equal to ' sum ' otherwise returns false . Also , prints the result ; Pick a starting point ; try all subarrays starting with ' i ' ; Driver Code"
How can the above be solved in Java?

class SubarraySum { int subArraySum ( int arr [ ] , int n , int sum ) { int curr_sum , i , j ; for ( i = 0 ; i < n ; i ++ ) { curr_sum = arr [ i ] ; for ( j = i + 1 ; j <= n ; j ++ ) { if ( curr_sum == sum ) { int p = j - 1 ; System . out . println ( " Sum ▁ found ▁ between ▁ indexes ▁ " + i + " ▁ and ▁ " + p ) ; return 1 ; } if ( curr_sum > sum j == n ) break ; curr_sum = curr_sum + arr [ j ] ; } } System . out . println ( " No ▁ subarray ▁ found " ) ; return 0 ; } public static void main ( String [ ] args ) { SubarraySum arraysum = new SubarraySum ( ) ; int arr [ ] = { 15 , 2 , 4 , 8 , 9 , 5 , 10 , 23 } ; int n = arr . length ; int sum = 23 ; arraysum . subArraySum ( arr , n , sum ) ; } }


"Find subarray with given sum | Set 1 ( Nonnegative Numbers ) |  ; Returns true if the there is a subarray of arr [ ] with sum equal to ' sum ' otherwise returns false . Also , prints the result ; Initialize curr_sum as value of first element and starting point as 0 ; Pick a starting point ; If curr_sum exceeds the sum , then remove the starting elements ; If curr_sum becomes equal to sum , then return true ; Add this element to curr_sum ; If we reach here , then no subarray ; Driver Code"
How can the above be solved in Java?

class SubarraySum { int subArraySum ( int arr [ ] , int n , int sum ) { int curr_sum = arr [ 0 ] , start = 0 , i ; for ( i = 1 ; i <= n ; i ++ ) { while ( curr_sum > sum && start < i - 1 ) { curr_sum = curr_sum - arr [ start ] ; start ++ ; } if ( curr_sum == sum ) { int p = i - 1 ; System . out . println ( " Sum ▁ found ▁ between ▁ indexes ▁ " + start + " ▁ and ▁ " + p ) ; return 1 ; } if ( i < n ) curr_sum = curr_sum + arr [ i ] ; } System . out . println ( " No ▁ subarray ▁ found " ) ; return 0 ; } public static void main ( String [ ] args ) { SubarraySum arraysum = new SubarraySum ( ) ; int arr [ ] = { 15 , 2 , 4 , 8 , 9 , 5 , 10 , 23 } ; int n = arr . length ; int sum = 23 ; arraysum . subArraySum ( arr , n , sum ) ; } }


"Find subarray with given sum | Set 2 ( Handles Negative Numbers ) | Java program to print subarray with sum as given sum ; Function to print subarray with sum as given sum ; cur_sum to keep track of cummulative sum till that point ; check whether cur_sum - sum = 0 , if 0 it means the sub array is starting from index 0 - so stop ; if hashMap already has the value , means we already have subarray with the sum - so stop ; if value is not present then add to hashmap ; if end is - 1 : means we have reached end without the sum ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { public static void subArraySum ( int [ ] arr , int n , int sum ) { int cur_sum = 0 ; int start = 0 ; int end = - 1 ; HashMap < Integer , Integer > hashMap = new HashMap < > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { cur_sum = cur_sum + arr [ i ] ; if ( cur_sum - sum == 0 ) { start = 0 ; end = i ; break ; } if ( hashMap . containsKey ( cur_sum - sum ) ) { start = hashMap . get ( cur_sum - sum ) + 1 ; end = i ; break ; } hashMap . put ( cur_sum , i ) ; } if ( end == - 1 ) { System . out . println ( " No ▁ subarray ▁ with ▁ given ▁ sum ▁ exists " ) ; } else { System . out . println ( " Sum ▁ found ▁ between ▁ indexes ▁ " + start + " ▁ to ▁ " + end ) ; } } public static void main ( String [ ] args ) { int [ ] arr = { 10 , 2 , - 2 , - 20 , 10 } ; int n = arr . length ; int sum = - 10 ; subArraySum ( arr , n , sum ) ; } }


"Find subfactorial of a number | / Java program for the above approach ; Function to find the subfactorial of the number ; Initialize variables ; Iterating over range N ; Fact variable store factorial of the i ; If count is even ; Increase the value of count by 1 ; Driver Code"
How can the above be solved in Java?

import java . util . * ; class GFG { static double subfactorial ( int N ) { double res = 0 , fact = 1 ; int count = 0 ; for ( int i = 1 ; i <= N ; i ++ ) { fact = fact * i ; if ( count % 2 == 0 ) res = res - ( 1 / fact ) ; else res = res + ( 1 / fact ) ; count ++ ; } return fact * ( 1 + res ) ; } public static void main ( String [ ] args ) { int N = 4 ; System . out . println ( ( int ) ( subfactorial ( N ) ) ) ; } }


"Find subsequences with maximum Bitwise AND and Bitwise OR | Java implementation of the above approach ; Function to find the maximum sum ; Maximum AND is maximum element ; Maximum OR is bitwise OR of all . ; Driver code"
How can the above be solved in Java?

import java . util . Arrays ; class GFG { static void maxSum ( int [ ] a , int n ) { int maxAnd = Arrays . stream ( a ) . max ( ) . getAsInt ( ) ; int maxOR = 0 ; for ( int i = 0 ; i < n ; i ++ ) { maxOR |= a [ i ] ; } System . out . println ( ( maxAnd + maxOR ) ) ; } public static void main ( String [ ] args ) { int n = 4 ; int [ ] a = { 3 , 5 , 6 , 1 } ; maxSum ( a , n ) ; } }


"Find substrings that contain all vowels | Java program to find all substring that contain all vowels ; Returns true if x is vowel . ; Function to check whether a character is vowel or not ; Function to FindSubstrings of string ; To store vowels ; If current character is vowel then insert into hash , ; If all vowels are present in current substring ; Driver Code"
How can the above be solved in Java?

import java . util . HashSet ; public class GFG { static boolean isVowel ( char x ) { return ( x == ' a ' x == ' e ' x == ' i ' x == ' o ' x == ' u ' ) ; } static void findSubstring ( String str ) { HashSet < Character > hash = new HashSet < Character > ( ) ; int start = 0 ; for ( int i = 0 ; i < str . length ( ) ; i ++ ) { if ( isVowel ( str . charAt ( i ) ) == true ) { hash . add ( str . charAt ( i ) ) ; if ( hash . size ( ) == 5 ) System . out . print ( str . substring ( start , i + 1 ) + " ▁ " ) ; } else { start = i + 1 ; hash . clear ( ) ; } } } public static void main ( String [ ] args ) { String str = " aeoibsddaeiouudb " ; findSubstring ( str ) ; } }


"Find substrings that contain all vowels | Java program to find all substring that contain all vowels ; Returns true if x is vowel . ; Function to check whether a character is vowel or not ; Outer loop picks starting character and inner loop picks ending character . ; If current character is not vowel , then no more result substrings possible starting from str [ i ] . ; If vowel , then we insert it in hash ; If all vowels are present in current substring ; Driver code"
How can the above be solved in Java?

import java . util . HashSet ; public class GFG { static boolean isVowel ( char x ) { return ( x == ' a ' x == ' e ' x == ' i ' x == ' o ' x == ' u ' ) ; } static void findSubstring ( String str ) { HashSet < Character > hash = new HashSet < Character > ( ) ; int n = str . length ( ) ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = i ; j < n ; j ++ ) { if ( isVowel ( str . charAt ( j ) ) == false ) break ; hash . add ( str . charAt ( j ) ) ; if ( hash . size ( ) == 5 ) System . out . print ( str . substring ( i , j + 1 ) + " ▁ " ) ; } hash . clear ( ) ; } } public static void main ( String [ ] args ) { String str = " aeoibsddaeiouudb " ; findSubstring ( str ) ; } }


"Find sum in range L to R in given sequence of integers | Java program to find the sum in given range L to R ; Function to find the sum within the given range ; Generating array from given sequence ; Calculate the desired sum ; return the sum ; Driver code ; Initialise the range"
How can the above be solved in Java?

import java . util . * ; class GFG { public static int findSum ( int L , int R ) { ArrayList < Integer > arr = new ArrayList < > ( ) ; int i = 0 ; int x = 2 ; while ( i <= R ) { arr . add ( i + x ) ; if ( i + 1 <= R ) arr . add ( i + 1 + x ) ; x *= - 1 ; i += 2 ; } int sum = 0 ; for ( i = L ; i <= R ; ++ i ) sum += arr . get ( i ) ; return sum ; } public static void main ( String [ ] args ) { int L = 0 , R = 5 ; System . out . println ( findSum ( L , R ) ) ; } }


"Find sum of N | Java program to find sum in Nth group ; calculate sum of Nth group ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { static int nth_group ( int n ) { return n * ( 2 * ( int ) Math . pow ( n , 2 ) + 1 ) ; } public static void main ( String arr [ ] ) { int N = 5 ; System . out . println ( nth_group ( N ) ) ; } }


"Find sum of a number and its maximum prime factor | Java program to find sum of n and it 's largest prime factor ; Function to return the sum of n and it 's largest prime factor ; Initialise maxPrime to - 1. ; n must be odd at this point , thus skip the even numbers and iterate only odd numbers ; This condition is to handle the case when n is a prime number greater than 2 ; finally return the sum . ; Driver Code"
How can the above be solved in Java?

import java . io . * ; class GFG { static int maxPrimeFactors ( int n ) { int num = n ; int maxPrime = - 1 ; while ( n % 2 == 0 ) { maxPrime = 2 ; n /= 2 ; } for ( int i = 3 ; i <= Math . sqrt ( n ) ; i += 2 ) { while ( n % i == 0 ) { maxPrime = i ; n = n / i ; } } if ( n > 2 ) { maxPrime = n ; } int sum = maxPrime + num ; return sum ; } public static void main ( String [ ] args ) { int n = 19 ; System . out . println ( maxPrimeFactors ( n ) ) ; } }


"Find sum of all elements in a matrix except the elements in row and / or column of given cell ? | An efficient Java program to compute sum for given array of cell indexes ; A structure to represent a cell index ; r is row , varies from 0 to R - 1 ; c is column , varies from 0 to C - 1 ; Compute sum of all elements , sum of every row and sum every column ; Compute the desired sum for all given cell indexes ; Driver Code"
How can the above be solved in Java?

class GFG { static int R = 3 ; static int C = 3 ; static class Cell { int r ; int c ; public Cell ( int r , int c ) { this . r = r ; this . c = c ; } } ; static void printSums ( int mat [ ] [ ] , Cell arr [ ] , int n ) { int sum = 0 ; int [ ] row = new int [ R ] ; int [ ] col = new int [ C ] ; for ( int i = 0 ; i < R ; i ++ ) { for ( int j = 0 ; j < C ; j ++ ) { sum += mat [ i ] [ j ] ; col [ j ] += mat [ i ] [ j ] ; row [ i ] += mat [ i ] [ j ] ; } } for ( int i = 0 ; i < n ; i ++ ) { int ro = arr [ i ] . r , co = arr [ i ] . c ; System . out . println ( sum - row [ ro ] - col [ co ] + mat [ ro ] [ co ] ) ; } } public static void main ( String [ ] args ) { int mat [ ] [ ] = { { 1 , 1 , 2 } , { 3 , 4 , 6 } , { 5 , 3 , 2 } } ; Cell arr [ ] = { new Cell ( 0 , 0 ) , new Cell ( 1 , 1 ) , new Cell ( 0 , 1 ) } ; int n = arr . length ; printSums ( mat , arr , n ) ; } }


"Find sum of all elements in a matrix except the elements in row and / or column of given cell ? | Java implementation of the approach ; A structure to represent a cell index ; r is row , varies from 0 to R - 1 ; c is column , varies from 0 to C - 1 ; Constructor ; A simple solution to find sums for a given array of cell indexes ; Iterate through all cell indexes ; Compute sum for current cell index ; Driver code"
How can the above be solved in Java?

class GFG { static int R = 3 ; static int C = 3 ; static class Cell { int r ; int c ; public Cell ( int r , int c ) { this . r = r ; this . c = c ; } } ; static void printSums ( int mat [ ] [ ] , Cell arr [ ] , int n ) { for ( int i = 0 ; i < n ; i ++ ) { int sum = 0 , r = arr [ i ] . r , c = arr [ i ] . c ; for ( int j = 0 ; j < R ; j ++ ) { for ( int k = 0 ; k < C ; k ++ ) { if ( j != r && k != c ) { sum += mat [ j ] [ k ] ; } } } System . out . println ( sum ) ; } } public static void main ( String [ ] args ) { int mat [ ] [ ] = { { 1 , 1 , 2 } , { 3 , 4 , 6 } , { 5 , 3 , 2 } } ; Cell arr [ ] = { new Cell ( 0 , 0 ) , new Cell ( 1 , 1 ) , new Cell ( 0 , 1 ) } ; int n = arr . length ; printSums ( mat , arr , n ) ; } }


"Find sum of all left leaves in a given Binary Tree | A binary tree Node has key , pointer to left and right children ; A utility function to check if a given node is leaf or not ; This function returns sum of all left leaves in a given binary tree ; Initialize result ; Update result if root is not NULL ; If left of root is NULL , then add key of left child ; Else recur for left child of root ; Recur for right child of root and update res ; return result ; Driver program"
How can the above be solved in Java?

class Node { int data ; Node left , right ; Node ( int item ) { data = item ; left = right = null ; } } class BinaryTree { Node root ; boolean isLeaf ( Node node ) { if ( node == null ) return false ; if ( node . left == null && node . right == null ) return true ; return false ; } int leftLeavesSum ( Node node ) { int res = 0 ; if ( node != null ) { if ( isLeaf ( node . left ) ) res += node . left . data ; else res += leftLeavesSum ( node . left ) ; res += leftLeavesSum ( node . right ) ; } return res ; } public static void main ( String args [ ] ) { BinaryTree tree = new BinaryTree ( ) ; tree . root = new Node ( 20 ) ; tree . root . left = new Node ( 9 ) ; tree . root . right = new Node ( 49 ) ; tree . root . left . right = new Node ( 12 ) ; tree . root . left . left = new Node ( 5 ) ; tree . root . right . left = new Node ( 23 ) ; tree . root . right . right = new Node ( 52 ) ; tree . root . left . right . right = new Node ( 12 ) ; tree . root . right . right . left = new Node ( 50 ) ; System . out . println ( " The ▁ sum ▁ of ▁ leaves ▁ is ▁ " + tree . leftLeavesSum ( tree . root ) ) ; } }


"Find sum of all left leaves in a given Binary Tree | A binary tree Node has key , pointer to left and right children ; Passing sum as accumulator and implementing pass by reference of sum variable ; Pass in a sum variable as an accumulator ; Check whether this node is a leaf node and is left . ; Pass true for left and false for right ; A wrapper over above recursive function ; use the above recursive function to evaluate sum ; Driver program ; Let us construct the Binary Tree shown in the above figure"
How can the above be solved in Java?

class Node { int data ; Node left , right ; Node ( int item ) { data = item ; left = right = null ; } } class Sum { int sum = 0 ; } class BinaryTree { Node root ; void leftLeavesSumRec ( Node node , boolean isleft , Sum summ ) { if ( node == null ) return ; if ( node . left == null && node . right == null && isleft ) summ . sum = summ . sum + node . data ; leftLeavesSumRec ( node . left , true , summ ) ; leftLeavesSumRec ( node . right , false , summ ) ; } int leftLeavesSum ( Node node ) { Sum suum = new Sum ( ) ; leftLeavesSumRec ( node , false , suum ) ; return suum . sum ; } public static void main ( String args [ ] ) { BinaryTree tree = new BinaryTree ( ) ; tree . root = new Node ( 20 ) ; tree . root . left = new Node ( 9 ) ; tree . root . right = new Node ( 49 ) ; tree . root . left . right = new Node ( 12 ) ; tree . root . left . left = new Node ( 5 ) ; tree . root . right . left = new Node ( 23 ) ; tree . root . right . right = new Node ( 52 ) ; tree . root . left . right . right = new Node ( 12 ) ; tree . root . right . right . left = new Node ( 50 ) ; System . out . println ( " The ▁ sum ▁ of ▁ leaves ▁ is ▁ " + tree . leftLeavesSum ( tree . root ) ) ; } }


"Find sum of all left leaves in a given Binary Tree | Java program to find sum of all left leaves ; A binary tree node ; A constructor to create a new Node ; Return the sum of left leaf nodes ; Using a stack_ for Depth - First Traversal of the tree ; sum holds the sum of all the left leaves ; Check if currentNode 's left  child is a leaf node ; if currentNode is a leaf , add its data to the sum ; Driver Code"
How can the above be solved in Java?

 import java . util . * ; class GFG { static class Node { int key ; Node left , right ; Node ( int key_ ) { this . key = key_ ; this . left = null ; this . right = null ; } } ; static int sumOfLeftLeaves ( Node root ) { if ( root == null ) return 0 ; Stack < Node > stack_ = new Stack < > ( ) ; stack_ . push ( root ) ; int sum = 0 ; while ( stack_ . size ( ) > 0 ) { Node currentNode = stack_ . peek ( ) ; stack_ . pop ( ) ; if ( currentNode . left != null ) { stack_ . add ( currentNode . left ) ; if ( currentNode . left . left == null && currentNode . left . right == null ) { sum = sum + currentNode . left . key ; } } if ( currentNode . right != null ) stack_ . add ( currentNode . right ) ; } return sum ; } public static void main ( String [ ] args ) { Node root = new Node ( 20 ) ; root . left = new Node ( 9 ) ; root . right = new Node ( 49 ) ; root . right . left = new Node ( 23 ) ; root . right . right = new Node ( 52 ) ; root . right . right . left = new Node ( 50 ) ; root . left . left = new Node ( 5 ) ; root . left . right = new Node ( 12 ) ; root . left . right . right = new Node ( 12 ) ; System . out . print ( " Sum ▁ of ▁ left ▁ leaves ▁ is ▁ " + sumOfLeftLeaves ( root ) + "
"); } }


"Find sum of all left leaves in a given Binary Tree | Java program to find sum of all left leaves ; A binary tree node ; constructor to create a new Node ; Return the sum of left leaf nodes ; A queue of pairs to do bfs traversal and keep track if the node is a left or right child if boolean value is true then it is a left child . ; do bfs traversal ; if temp is a leaf node and left child of its parent ; if it is not leaf then push its children nodes into queue ; boolean value is true here because it is left child of its parent ; boolean value is false here because it is right child of its parent ; Driver Code"
How can the above be solved in Java?

 import java . util . * ; class GFG { static class Node { int key ; Node left , right ; Node ( int key_ ) { key = key_ ; left = null ; right = null ; } } ; static class pair { Node first ; boolean second ; public pair ( Node first , boolean second ) { this . first = first ; this . second = second ; } } static int sumOfLeftLeaves ( Node root ) { if ( root == null ) return 0 ; Queue < pair > q = new LinkedList < > ( ) ; q . add ( new pair ( root , false ) ) ; int sum = 0 ; while ( ! q . isEmpty ( ) ) { Node temp = q . peek ( ) . first ; boolean is_left_child = q . peek ( ) . second ; q . remove ( ) ; if ( is_left_child ) sum = sum + temp . key ; if ( temp . left != null && temp . right != null && is_left_child ) sum = sum - temp . key ; if ( temp . left != null ) { q . add ( new pair ( temp . left , true ) ) ; } if ( temp . right != null ) { q . add ( new pair ( temp . right , false ) ) ; } } return sum ; } public static void main ( String [ ] args ) { Node root = new Node ( 20 ) ; root . left = new Node ( 9 ) ; root . right = new Node ( 49 ) ; root . right . left = new Node ( 23 ) ; root . right . right = new Node ( 52 ) ; root . right . right . left = new Node ( 50 ) ; root . left . left = new Node ( 5 ) ; root . left . right = new Node ( 12 ) ; root . left . right . right = new Node ( 12 ) ; System . out . print ( " Sum ▁ of ▁ left ▁ leaves ▁ is ▁ " + sumOfLeftLeaves ( root ) + "
"); } }


"Find sum of all nodes of the given perfect binary tree | Java code to find sum of all nodes of the given perfect binary tree ; function to find sum of all of the nodes of given perfect binary tree ; no of leaf nodes ; sum of nodes at last level ; sum of all nodes ; Driver Code"
How can the above be solved in Java?

import java . io . * ; import java . lang . Math ; class GFG { static double sumNodes ( int l ) { double leafNodeCount = Math . pow ( 2 , l - 1 ) ; double sumLastLevel = 0 ; sumLastLevel = ( leafNodeCount * ( leafNodeCount + 1 ) ) / 2 ; double sum = sumLastLevel * l ; return sum ; } public static void main ( String [ ] args ) { int l = 3 ; System . out . println ( sumNodes ( l ) ) ; } }


"Find sum of all nodes of the given perfect binary tree | Java program to implement the above approach ; function to find sum of all of the nodes of given perfect binary tree ; no of leaf nodes ; list of vector to store nodes of all of the levels ; initialize ; store the nodes of last level i . e . , the leaf nodes ; store nodes of rest of the level by moving in bottom - up manner ; loop to calculate values of parent nodes from the children nodes of lower level ; store the value of parent node as sum of children nodes ; traverse the list of vector and calculate the sum ; Driver Code"
How can the above be solved in Java?

import java . util . * ; class GFG { static int sumNodes ( int l ) { int leafNodeCount = ( int ) Math . pow ( 2 , l - 1 ) ; Vector < Vector < Integer > > vec = new Vector < Vector < Integer > > ( ) ; for ( int i = 1 ; i <= l ; i ++ ) vec . add ( new Vector < Integer > ( ) ) ; for ( int i = 1 ; i <= leafNodeCount ; i ++ ) vec . get ( l - 1 ) . add ( i ) ; for ( int i = l - 2 ; i >= 0 ; i -- ) { int k = 0 ; while ( k < vec . get ( i + 1 ) . size ( ) - 1 ) { vec . get ( i ) . add ( vec . get ( i + 1 ) . get ( k ) + vec . get ( i + 1 ) . get ( k + 1 ) ) ; k += 2 ; } } int sum = 0 ; for ( int i = 0 ; i < l ; i ++ ) { for ( int j = 0 ; j < vec . get ( i ) . size ( ) ; j ++ ) sum += vec . get ( i ) . get ( j ) ; } return sum ; } public static void main ( String args [ ] ) { int l = 3 ; System . out . println ( sumNodes ( l ) ) ; } }


"Find sum of all unique elements in the array for K queries | Java implementation to find the sum of all unique elements of the array after Q queries ; Function to find the sum of unique elements after Q Query ; Updating the array after processing each query ; Making it to 0 - indexing ; Iterating over the array to get the final array ; Variable to store the sum ; Hash to maintain perviously occured elements ; Loop to find the maximum sum ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { static int uniqueSum ( int A [ ] , int R [ ] [ ] , int N , int M ) { for ( int i = 0 ; i < M ; ++ i ) { int l = R [ i ] [ 0 ] , r = R [ i ] [ 1 ] + 1 ; l -- ; r -- ; A [ l ] ++ ; if ( r < N ) A [ r ] -- ; } for ( int i = 1 ; i < N ; ++ i ) { A [ i ] += A [ i - 1 ] ; } int ans = 0 ; HashSet < Integer > s = new HashSet < Integer > ( ) ; for ( int i = 0 ; i < N ; ++ i ) { if ( ! s . contains ( A [ i ] ) ) ans += A [ i ] ; s . add ( A [ i ] ) ; } return ans ; } public static void main ( String [ ] args ) { int A [ ] = { 0 , 0 , 0 , 0 , 0 , 0 } ; int R [ ] [ ] = { { 1 , 3 } , { 4 , 6 } , { 3 , 4 } , { 3 , 3 } } ; int N = A . length ; int M = R . length ; System . out . print ( uniqueSum ( A , R , N , M ) ) ; } }


"Find sum of digits in factorial of a number | Java program to find sum of digits in factorial of a number ; Function to multiply x with large number stored in vector v . Result is stored in v . ; Calculate res + prev carry ; updation at ith position ; Returns sum of digits in n ! ; One by one multiply i to current vector and update the vector . ; Find sum of digits in vector v [ ] ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { static ArrayList < Integer > v = new ArrayList < Integer > ( ) ; static void multiply ( int x ) { int carry = 0 ; int size = v . size ( ) ; for ( int i = 0 ; i < size ; i ++ ) { int res = carry + v . get ( i ) * x ; v . set ( i , res % 10 ) ; carry = res / 10 ; } while ( carry != 0 ) { v . add ( carry % 10 ) ; carry /= 10 ; } } static int findSumOfDigits ( int n ) { for ( int i = 1 ; i <= n ; i ++ ) multiply ( i ) ; int sum = 0 ; int size = v . size ( ) ; for ( int i = 0 ; i < size ; i ++ ) sum += v . get ( i ) ; return sum ; } public static void main ( String [ ] args ) { int n = 1000 ; System . out . println ( findSumOfDigits ( n ) ) ; } }


"Find sum of even factors of a number | Formula based Java program to find sum of all divisors of n . ; Returns sum of all factors of n . ; If n is odd , then there are no even factors . ; Traversing through all prime factors . ; While i divides n , print i and divide n ; here we remove the 2 ^ 0 that is 1. All other factors ; This condition is to handle the case when n is a prime number . ; Driver function"
How can the above be solved in Java?

import java . util . * ; import java . lang . * ; public class GfG { public static int sumofFactors ( int n ) { if ( n % 2 != 0 ) return 0 ; int res = 1 ; for ( int i = 2 ; i <= Math . sqrt ( n ) ; i ++ ) { int count = 0 , curr_sum = 1 ; int curr_term = 1 ; while ( n % i == 0 ) { count ++ ; n = n / i ; if ( i == 2 && count == 1 ) curr_sum = 0 ; curr_term *= i ; curr_sum += curr_term ; } res *= curr_sum ; } if ( n >= 2 ) res *= ( 1 + n ) ; return res ; } public static void main ( String argc [ ] ) { int n = 18 ; System . out . println ( sumofFactors ( n ) ) ; } }


"Find sum of even index binomial coefficients | Java Program to find sum even indexed Binomial Coefficient . ; Returns value of even indexed Binomial Coefficient Sum which is 2 raised to power n - 1. ; Driver Code"
How can the above be solved in Java?

import java . io . * ; class GFG { static int evenbinomialCoeffSum ( int n ) { return ( 1 << ( n - 1 ) ) ; } public static void main ( String [ ] args ) { int n = 4 ; System . out . println ( evenbinomialCoeffSum ( n ) ) ; } }


"Find sum of even index binomial coefficients | Java Program to find sum of even index term ; Return the sum of even index term ; Calculate value of Binomial Coefficient in bottom up manner ; Base Cases ; else Calculate value using previously stored values ; finding sum of even index term . ; Driver Program"
How can the above be solved in Java?

import java . io . * ; import java . math . * ; class GFG { static int evenSum ( int n ) { int C [ ] [ ] = new int [ n + 1 ] [ n + 1 ] ; int i , j ; for ( i = 0 ; i <= n ; i ++ ) { for ( j = 0 ; j <= Math . min ( i , n ) ; j ++ ) { if ( j == 0 j == i ) C [ i ] [ j ] = 1 ; else C [ i ] [ j ] = C [ i - 1 ] [ j - 1 ] + C [ i - 1 ] [ j ] ; } } int sum = 0 ; for ( i = 0 ; i <= n ; i += 2 ) sum += C [ n ] [ i ] ; return sum ; } public static void main ( String args [ ] ) { int n = 4 ; System . out . println ( evenSum ( n ) ) ; } }


"Find sum of exponents of prime factors of numbers 1 to N | Java program for the above approach ; Function to implement sieve of erastosthenes ; Create a boolean array and initialize all entries as false ; Initializing smallest factor equal to 2 for all the even numbers ; Iterate for odd numbers less then equal to n ; s ( i ) for a prime is the number itself ; For all multiples of current prime number ; i is the smallest prime factor for number " i * j " ; Function to generate prime factors and its power ; s [ i ] is going to store smallest prime factor of i ; Current prime factor of N ; Power of current prime factor ; Calculating prime factors and their powers sum ; Increment the count and continue the process ; Add count to the sum ; Reinitialize count ; Return the result ; Function to find the sum of all the power of prime factors of N ; Iterate for in [ 2 , N ] ; Driver Code ; Given Number N ; Function Call"
How can the above be solved in Java?

 class GFG { static void sieveOfEratosthenes ( int N , int s [ ] ) { boolean [ ] prime = new boolean [ N + 1 ] ; for ( int i = 2 ; i <= N ; i += 2 ) s [ i ] = 2 ; for ( int i = 3 ; i <= N ; i += 2 ) { if ( prime [ i ] == false ) { s [ i ] = i ; for ( int j = i ; j * i <= N ; j += 2 ) { if ( prime [ i * j ] == false ) { prime [ i * j ] = true ; s [ i * j ] = i ; } } } } } static int generatePrimeFactors ( int N ) { int [ ] s = new int [ N + 1 ] ; int sum = 0 ; sieveOfEratosthenes ( N , s ) ; int curr = s [ N ] ; int cnt = 1 ; while ( N > 1 ) { N /= s [ N ] ; if ( curr == s [ N ] ) { cnt ++ ; continue ; } sum = sum + cnt ; curr = s [ N ] ; cnt = 1 ; } return sum ; } static void findSum ( int N ) { int sum = 0 ; for ( int i = 2 ; i <= N ; i ++ ) { sum += generatePrimeFactors ( i ) ; } System . out . print ( sum + "
"); } public static void main ( String [ ] args ) { int N = 4 ; findSum ( N ) ; } }


"Find sum of f ( s ) for all the chosen sets from the given array | Java implementation of the approach ; To store the factorial and the factorial mod inverse of a number ; Function to find ( a ^ m1 ) % mod ; Function to find factorial of all the numbers ; Function to find the factorial mod inverse of all the numbers ; Function to return nCr ; Function to find sum of f ( s ) for all the chosen sets from the given array ; Sort the given array ; Calculate the factorial and modinverse of all elements ; For all the possible sets Calculate max ( S ) and min ( S ) ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { static int N = 100005 ; static int mod = 1000000007 ; static int temp = 391657242 ; static int [ ] factorial = new int [ N ] ; static int [ ] modinverse = new int [ N ] ; static int power ( int a , int m1 ) { if ( m1 == 0 ) return 1 ; else if ( m1 == 1 ) return a ; else if ( m1 == 2 ) return ( a * a ) % mod ; else if ( ( m1 & 1 ) != 0 ) return ( a * power ( power ( a , m1 / 2 ) , 2 ) ) % mod ; else return power ( power ( a , m1 / 2 ) , 2 ) % mod ; } static void factorialfun ( ) { factorial [ 0 ] = 1 ; for ( int i = 1 ; i < N ; i ++ ) factorial [ i ] = ( factorial [ i - 1 ] * i ) % mod ; } static void modinversefun ( ) { modinverse [ N - 1 ] = power ( factorial [ N - 1 ] , mod - 2 ) % mod ; for ( int i = N - 2 ; i >= 0 ; i -- ) modinverse [ i ] = ( modinverse [ i + 1 ] * ( i + 1 ) ) % mod ; } static int binomial ( int n , int r ) { if ( r > n ) return 0 ; int a = ( factorial [ n ] * modinverse [ n - r ] ) % mod ; a = ( a * modinverse [ r ] ) % mod ; return a ; } static int max_min ( int a [ ] , int n , int k ) { Arrays . sort ( a ) ; factorialfun ( ) ; modinversefun ( ) ; int ans = 0 ; k -- ; for ( int i = 0 ; i < n ; i ++ ) { int x = n - i - 1 ; if ( x >= k ) ans -= binomial ( x , k ) * a [ i ] % mod ; int y = i ; if ( y >= k ) ans += binomial ( y , k ) * a [ i ] % mod ; ans = ( ans + mod ) % mod ; } return ans % temp ; } public static void main ( String args [ ] ) { int [ ] a = { 1 , 1 , 3 , 4 } ; int k = 2 ; int n = a . length ; System . out . println ( max_min ( a , n , k ) ) ; } }


"Find sum of factorials in an array | Java implementation of the approach ; Function to return the factorial of n ; Function to return the sum of factorials of the array elements ; To store the required sum ; Add factorial of all the elements ; Driver Code"
How can the above be solved in Java?

class GFG { static int factorial ( int n ) { int f = 1 ; for ( int i = 1 ; i <= n ; i ++ ) { f *= i ; } return f ; } static int sumFactorial ( int [ ] arr , int n ) { int s = 0 ; for ( int i = 0 ; i < n ; i ++ ) { s += factorial ( arr [ i ] ) ; } return s ; } public static void main ( String [ ] args ) { int [ ] arr = { 7 , 3 , 5 , 4 , 8 } ; int n = arr . length ; System . out . println ( sumFactorial ( arr , n ) ) ; } }


"Find sum of inverse of the divisors when sum of divisors and the number is given | Java implementation of above approach ; Function to return the sum of inverse of divisors ; Calculating the answer ; Return the answer ; Driver code ; Function call"
How can the above be solved in Java?

import java . math . * ; import java . io . * ; class GFG { static double SumofInverseDivisors ( int N , int Sum ) { double ans = ( double ) ( Sum ) * 1.0 / ( double ) ( N ) ; return ans ; } public static void main ( String [ ] args ) { int N = 9 ; int Sum = 13 ; System . out . println ( SumofInverseDivisors ( N , Sum ) ) ; } }


"Find sum of modulo K of first N natural number | Java program to find sum of modulo K of first N natural numbers . ; Return sum of modulo K of first N natural numbers . ; Counting the number of times 1 , 2 , . . , K - 1 , 0 sequence occurs . ; Finding the number of elements left which are incomplete of sequence Leads to Case 1 type . ; adding multiplication of number of times 1 , 2 , . . , K - 1 , 0 sequence occurs and sum of first k natural number and sequence from case 1. ; Driver program"
How can the above be solved in Java?

import java . io . * ; class GFG { static int findSum ( int N , int K ) { int ans = 0 ; int y = N / K ; int x = N % K ; ans = ( K * ( K - 1 ) / 2 ) * y + ( x * ( x + 1 ) ) / 2 ; return ans ; } static public void main ( String [ ] args ) { int N = 10 , K = 2 ; System . out . println ( findSum ( N , K ) ) ; } }


"Find sum of modulo K of first N natural number | Java program to find sum of modulo K of first N natural numbers . ; Return sum of modulo K of first N natural numbers . ; Iterate from 1 to N && evaluating and adding i % K . ; Driver program"
How can the above be solved in Java?

import java . io . * ; class GFG { static int findSum ( int N , int K ) { int ans = 0 ; for ( int i = 1 ; i <= N ; i ++ ) ans += ( i % K ) ; return ans ; } static public void main ( String [ ] args ) { int N = 10 , K = 2 ; System . out . println ( findSum ( N , K ) ) ; } }


"Find sum of non | Java Find the sum of all non - repeated elements in an array ; Find the sum of all non - repeated elements in an array ; sort all elements of array ; Driver code"
How can the above be solved in Java?

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


"Find sum of odd factors of a number | Formula based Java program to find sum of all divisors of n . ; Returns sum of all factors of n . ; Traversing through all prime factors . ; ignore even factors by removing all powers of 2 ; While i divides n , print i and divide n ; This condition is to handle the case when n is a prime number . ; Driver code"
How can the above be solved in Java?

import java . io . * ; import java . math . * ; class GFG { static int sumofoddFactors ( int n ) { int res = 1 ; while ( n % 2 == 0 ) n = n / 2 ; for ( int i = 3 ; i <= Math . sqrt ( n ) ; i ++ ) { int count = 0 , curr_sum = 1 ; int curr_term = 1 ; while ( n % i == 0 ) { count ++ ; n = n / i ; curr_term *= i ; curr_sum += curr_term ; } res *= curr_sum ; } if ( n >= 2 ) res *= ( 1 + n ) ; return res ; } public static void main ( String args [ ] ) throws IOException { int n = 30 ; System . out . println ( sumofoddFactors ( n ) ) ; } }


"Find sum of product of every number and its frequency in given range | Java program to find sum of product of every number and square of its frequency in the given range ; Function to solve queries ; Calculating answer for every query ; The end points of the ith query ; Hashmap for storing frequency ; Incrementing the frequency ; Adding the contribution of ith number ; Print answer ; Driver code ; Calling function"
How can the above be solved in Java?

import java . util . * ; class GFG { public static void answerQueries ( int [ ] arr , int n , int [ ] [ ] queries ) { for ( int i = 0 ; i < queries . length ; i ++ ) { int ans = 0 ; int l = queries [ i ] [ 0 ] - 1 ; int r = queries [ i ] [ 1 ] - 1 ; Map < Integer , Integer > freq = new HashMap < > ( ) ; for ( int j = l ; j < r + 1 ; j ++ ) { freq . put ( arr [ j ] , freq . getOrDefault ( arr [ j ] , 0 ) + 1 ) ; } for ( int k : freq . keySet ( ) ) { ans += k * freq . get ( k ) ; } System . out . println ( ans ) ; } } public static void main ( String args [ ] ) { int [ ] arr = { 1 , 2 , 1 } ; int n = arr . length ; int [ ] [ ] queries = { { 1 , 2 } , { 1 , 3 } } ; answerQueries ( arr , n , queries ) ; } }


"Find sum of product of number in given series | Java program to find sum of product of number in given series ; function to calculate ( a ^ b ) % 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 ; function to return required answer ; modulo inverse of denominator ; calculating commentator part ; calculating t ! ; accumulating the final answer ; Driver program ; function call to print required sum"
How can the above be solved in Java?

public class GFG { static long MOD = 1000000007 ; static long power ( long x , long y , long p ) { long res = 1 ; x = x % p ; while ( y > 0 ) { if ( ( y & 1 ) != 0 ) res = ( res * x ) % p ; x = ( x * x ) % p ; } return res ; } static long sumProd ( long n , long t ) { long dino = power ( t + 1 , MOD - 2 , MOD ) ; long ans = 1 ; for ( long i = n + t + 1 ; i > n ; -- i ) ans = ( ans % MOD * i % MOD ) % MOD ; long tfact = 1 ; for ( int i = 1 ; i <= t ; ++ i ) tfact = ( tfact * i ) % MOD ; ans = ans * dino - tfact + MOD ; return ans % MOD ; } public static void main ( String [ ] args ) { long n = 3 , t = 2 ; System . out . println ( sumProd ( n , t ) ) ; } }


"Find sum of the series 1 + 22 + 333 + 4444 + ... ... upto n terms | Java Program to find Sum of first n terms ; Returning the final sum ; Driver code ; no . of terms to find the sum"
How can the above be solved in Java?

import java . util . * ; class solution { static int calculateSum ( int n ) { return ( ( int ) Math . pow ( 10 , n + 1 ) * ( 9 * n - 1 ) + 10 ) / ( int ) Math . pow ( 9 , 3 ) - n * ( n + 1 ) / 18 ; } public static void main ( String ar [ ] ) { int n = 3 ; System . out . println ( " Sum = ▁ " + calculateSum ( n ) ) ; } }


"Find sum of the series 1 | Java program to find sum of first n terms of the given series ; when n is odd ; when n is not odd ; Driver code ; no . of terms to find the sum"
How can the above be solved in Java?

import java . util . * ; class GFG { static int calculateSum ( int n ) { if ( n % 2 == 1 ) return ( n + 1 ) / 2 ; return - n / 2 ; } public static void main ( String ar [ ] ) { int n = 8 ; System . out . println ( calculateSum ( n ) ) ; } }


"Find sum of the series ? 3 + ? 12 + ... ... ... upto N terms | Java implementation of above approach ; Function to find the sum ; Apply AP formula ; Driver code ; number of terms"
How can the above be solved in Java?

import java . io . * ; class GFG { static double findSum ( long n ) { return Math . sqrt ( 3 ) * ( n * ( n + 1 ) / 2 ) ; } public static void main ( String [ ] args ) { long n = 10 ; System . out . println ( findSum ( n ) ) ; } }


"Find temperature of missing days using given sum and average | Java program for the above approach ; Function for finding the temperature ; Store Day1 - Day2 in diff ; Remaining from s will be Day1 ; Print Day1 and Day2 ; Driver Code ; Functions"
How can the above be solved in Java?

class GFG { static void findTemperature ( int x , int y , int s ) { double Day1 , Day2 ; double diff = ( x - y ) * 6 ; Day2 = ( diff + s ) / 2 ; Day1 = s - Day2 ; System . out . println ( " Day1 ▁ : ▁ " + Day1 ) ; System . out . println ( " Day2 ▁ : ▁ " + Day2 ) ; } public static void main ( String [ ] args ) { int x = 5 , y = 10 , s = 40 ; findTemperature ( x , y , s ) ; } }


"Find the Batting Average of a batsman | Java program to calculate the average of a batsman ; Function to find the average of a batsman ; Calculate number of dismissals ; Check for 0 times out ; Calculate batting average ; Driver code"
How can the above be solved in Java?

class GFG { static int averageRuns ( int runs , int matches , int notout ) { int out = matches - notout ; if ( out == 0 ) return - 1 ; int avg = ( runs ) / out ; return avg ; } public static void main ( String [ ] args ) { int runs = 10000 ; int matches = 250 ; int notout = 50 ; int avg = averageRuns ( runs , matches , notout ) ; if ( avg == - 1 ) System . out . print ( " NA " ) ; else System . out . print ( avg ) ; } }


"Find the Deepest Node in a Binary Tree | A Java program to find value of the deepest node in a given binary tree ; A tree node with constructor ; Utility function to find height of a tree , rooted at ' root ' . ; levels : current Level Utility function to print all nodes at a given level . ; Driver Codede ; Calculating height of tree ; Printing the deepest node"
How can the above be solved in Java?

class GFG { static class Node { int data ; Node left , right ; Node ( int key ) { data = key ; left = null ; right = null ; } } ; static int height ( Node root ) { if ( root == null ) return 0 ; int leftHt = height ( root . left ) ; int rightHt = height ( root . right ) ; return Math . max ( leftHt , rightHt ) + 1 ; } static void deepestNode ( Node root , int levels ) { if ( root == null ) return ; if ( levels == 1 ) System . out . print ( root . data + " ▁ " ) ; else if ( levels > 1 ) { deepestNode ( root . left , levels - 1 ) ; deepestNode ( root . right , levels - 1 ) ; } } public static void main ( String args [ ] ) { Node root = new Node ( 1 ) ; root . left = new Node ( 2 ) ; root . right = new Node ( 3 ) ; root . left . left = new Node ( 4 ) ; root . right . left = new Node ( 5 ) ; root . right . right = new Node ( 6 ) ; root . right . left . right = new Node ( 7 ) ; root . right . right . right = new Node ( 8 ) ; root . right . left . right . left = new Node ( 9 ) ; int levels = height ( root ) ; deepestNode ( root , levels ) ; } }


"Find the Deepest Node in a Binary Tree | A Java program to find value of the deepest node in a given binary tree ; A tree node with constructor ; constructor ; Funtion to return the deepest node ; Creating a Queue ; Iterates untill queue become empty ; Driver code"
How can the above be solved in Java?

import java . util . * ; public class Node { int data ; Node left , right ; Node ( int key ) { data = key ; left = null ; right = null ; } } ; class Gfg { public static Node deepestNode ( Node root ) { Node tmp = null ; if ( root == null ) return null ; Queue < Node > q = new LinkedList < Node > ( ) ; q . offer ( root ) ; while ( ! q . isEmpty ( ) ) { tmp = q . poll ( ) ; if ( tmp . left != null ) q . offer ( tmp . left ) ; if ( tmp . right != null ) q . offer ( tmp . right ) ; } return tmp ; } public static void main ( String [ ] args ) { Node root = new Node ( 1 ) ; root . left = new Node ( 2 ) ; root . right = new Node ( 3 ) ; root . left . left = new Node ( 4 ) ; root . right . left = new Node ( 5 ) ; root . right . right = new Node ( 6 ) ; root . right . left . right = new Node ( 7 ) ; root . right . right . right = new Node ( 8 ) ; root . right . left . right . left = new Node ( 9 ) ; Node deepNode = deepestNode ( root ) ; System . out . println ( deepNode . data ) ; } }


"Find the Deepest Node in a Binary Tree | Java program to find value of the deepest node in a given binary tree ; A tree node ; maxLevel : keeps track of maximum level seen so far . res : Value of deepest node so far . level : Level of root ; Update level and resue ; Returns value of deepest node ; Initialze result and max level ; Updates value " res " and " maxLevel " Note that res and maxLen are passed by reference . ; Driver code"
How can the above be solved in Java?

class GFG { static class Node { int data ; Node left , right ; Node ( int key ) { data = key ; left = null ; right = null ; } } static int maxLevel = - 1 ; static int res = - 1 ; static void find ( Node root , int level ) { if ( root != null ) { find ( root . left , ++ level ) ; if ( level > maxLevel ) { res = root . data ; maxLevel = level ; } find ( root . right , level ) ; } } static int deepestNode ( Node root ) { int res = - 1 ; int maxLevel = - 1 ; find ( root , 0 ) ; return res ; } public static void main ( String [ ] args ) { Node root = new Node ( 1 ) ; root . left = new Node ( 2 ) ; root . right = new Node ( 3 ) ; root . left . left = new Node ( 4 ) ; root . right . left = new Node ( 5 ) ; root . right . right = new Node ( 6 ) ; root . right . left . right = new Node ( 7 ) ; root . right . right . right = new Node ( 8 ) ; root . right . left . right . left = new Node ( 9 ) ; System . out . println ( deepestNode ( root ) ) ; } }


"Find the Diameter or Longest chord of a Circle | Java program to find the longest chord or diameter of the circle whose radius is given ; Function to find the longest chord ; Driver code ; Get the radius ; Find the diameter"
How can the above be solved in Java?

class GFG { static void diameter ( double r ) { System . out . println ( " The ▁ length ▁ of ▁ the ▁ longest ▁ chord " + " ▁ or ▁ diameter ▁ of ▁ the ▁ circle ▁ is ▁ " + 2 * r ) ; } public static void main ( String [ ] args ) { double r = 4 ; diameter ( r ) ; } }


"Find the GCD of an array made up of numeric strings | JAVA program for the above approach ; Recursive function to return gcd of A and B ; Base case ; Length of A is greater ; Calculate GCD ; Store the GCD of the length of the Strings ; Driver Code ; Function call"
How can the above be solved in Java?

import java . util . * ; class GFG { static int GCD ( int lena , int lenb ) { if ( lena == 0 ) return lenb ; if ( lenb == 0 ) return lena ; if ( lena == lenb ) return lena ; if ( lena > lenb ) return GCD ( lena - lenb , lenb ) ; return GCD ( lena , lenb - lena ) ; } static String StringGCD ( String a , String b ) { int gcd = GCD ( a . length ( ) , b . length ( ) ) ; if ( a . substring ( 0 , gcd ) . equals ( b . substring ( 0 , gcd ) ) ) { int x = ( ( int ) b . length ( ) / gcd ) ; int y = ( ( int ) a . length ( ) / gcd ) ; String r = " " , s = " " ; while ( x -- > 0 ) s += a ; while ( y -- > 0 ) r += b ; if ( s . equals ( r ) ) return a . substring ( 0 , gcd ) ; } return " - 1" ; } public static void main ( String [ ] args ) { String a = " geeksgeeks " ; String b = " geeks " ; System . out . print ( StringGCD ( a , b ) ) ; } }


"Find the GCD that lies in given range | Java Program to find the Greatest Common divisor of two number which is in given range ; Return the greatest common divisor of two numbers ; Return the gretest common divisor of a and b which lie in the given range . ; Loop from 1 to sqrt ( GCD ( a , b ) . ; if i divides the GCD ( a , b ) , then find maximum of three numbers res , i and g / i ; Driven Program"
How can the above be solved in Java?

import java . io . * ; class GFG { static int gcd ( int a , int b ) { if ( b == 0 ) return a ; return gcd ( b , a % b ) ; } static int maxDivisorRange ( int a , int b , int l , int h ) { int g = gcd ( a , b ) ; int res = - 1 ; for ( int i = l ; i * i <= g && i <= h ; i ++ ) if ( g % i == 0 ) res = Math . max ( res , Math . max ( i , g / i ) ) ; return res ; } public static void main ( String [ ] args ) { int a = 3 , b = 27 , l = 1 , h = 5 ; System . out . println ( maxDivisorRange ( a , b , l , h ) ) ; } }


"Find the K | Java program to Find the kth Permutation Sequence of first n natural numbers ; Function to find the index of number at first position of kth sequence of set of size n ; n_actual_fact = n ! ; First position of the kth sequence will be occupied by the number present at index = k / ( n - 1 ) ! ; Function to find the kth permutation of n numbers ; Store final answer ; Insert all natural number upto n in set ; Mark the first position ; Subtract 1 to get 0 based indexing ; itr now points to the number at index in set s ; Remove current number from the set ; Driver code"
How can the above be solved in Java?

 import java . util . * ; class GFG { static int findFirstNumIndex ( int k , int n ) { if ( n == 1 ) return 0 ; n -- ; int first_num_index ; int n_partial_fact = n ; while ( k >= n_partial_fact && n > 1 ) { n_partial_fact = n_partial_fact * ( n - 1 ) ; n -- ; } first_num_index = k / n_partial_fact ; k = k % n_partial_fact ; return first_num_index ; } static String findKthPermutation ( int n , int k ) { String ans = " " ; HashSet < Integer > s = new HashSet < > ( ) ; for ( int i = 1 ; i <= n ; i ++ ) s . add ( i ) ; Vector < Integer > v = new Vector < > ( ) ; v . addAll ( s ) ; int itr = v . elementAt ( 0 ) ; k = k - 1 ; for ( int i = 0 ; i < n ; i ++ ) { int index = findFirstNumIndex ( k , n - i ) ; if ( index < v . size ( ) ) { ans += ( ( v . elementAt ( index ) . toString ( ) ) ) ; v . remove ( index ) ; } else ans += String . valueOf ( itr + 2 ) ; itr = v . elementAt ( 0 ) ; } return ans ; } public static void main ( String [ ] args ) { int n = 3 , k = 4 ; String kth_perm_seq = findKthPermutation ( n , k ) ; System . out . print ( kth_perm_seq + "
"); } }


"Find the K | Java programme to find the K 'th minimum element from an array concatenated M times ; Function to find the K - th minimum element from an array concatenated M times ; Sort the elements in ascending order ; Return the K 'th Min element  present at ( (K-1) / M ) index ; Driver Code"
How can the above be solved in Java?

import java . util . * ; class GFG1 { static int KthMinValAfterMconcatenate ( int [ ] A , int N , int M , int K ) { Arrays . sort ( A ) ; return ( A [ ( ( K - 1 ) / M ) ] ) ; } public static void main ( String [ ] args ) { int [ ] A = { 3 , 1 , 2 } ; int M = 3 , K = 4 ; int N = A . length ; System . out . println ( KthMinValAfterMconcatenate ( A , N , M , K ) ) ; } }


"Find the Kth node in the DFS traversal of a given subtree in a Tree | Java program to find the Kth node in the DFS traversal of the subtree of given vertex V in a Tree ; To store nodes ; To store the current index of vertex in DFS ; To store the starting index and ending index of vertex in the DFS traversal array ; To store the DFS of vertex 1 ; Function to add edge between two nodes ; Initialize the vectors ; Function to perform DFS of a vertex 1. stores the DFS of the vertex 1 in vector p , 2. store the start index of DFS of every vertex 3. store the end index of DFS of every vertex ; store staring index of node ch ; store ending index ; Function to find the Kth node in DFS of vertex V ; Check if kth number exits or not ; Driver code ; Number of nodes ; Add edges ; Store DFS of 1 st node"
How can the above be solved in Java?

import java . util . * ; class GFG { static int N = 100005 ; static int n ; static ArrayList < ArrayList < Integer > > tree = new ArrayList < > ( ) ; static int currentIdx ; static int [ ] startIdx ; static int [ ] endIdx ; static int [ ] p ; static void Add_edge ( int u , int v ) { tree . get ( u ) . add ( v ) ; tree . get ( v ) . add ( u ) ; } static void intisalise ( ) { startIdx = new int [ n + 1 ] ; endIdx = new int [ n + 1 ] ; p = new int [ n + 1 ] ; } static void Dfs ( int ch , int par ) { p [ currentIdx ] = ch ; startIdx [ ch ] = currentIdx ++ ; for ( int c : tree . get ( ch ) ) { if ( c != par ) Dfs ( c , ch ) ; } endIdx [ ch ] = currentIdx - 1 ; } static int findNode ( int v , int k ) { k += startIdx [ v ] - 1 ; if ( k <= endIdx [ v ] ) return p [ k ] ; return - 1 ; } public static void main ( String [ ] args ) { n = 9 ; for ( int i = 0 ; i <= n ; i ++ ) tree . add ( new ArrayList < Integer > ( ) ) ; Add_edge ( 1 , 2 ) ; Add_edge ( 1 , 3 ) ; Add_edge ( 1 , 4 ) ; Add_edge ( 3 , 5 ) ; Add_edge ( 3 , 7 ) ; Add_edge ( 5 , 6 ) ; Add_edge ( 5 , 8 ) ; Add_edge ( 7 , 9 ) ; intisalise ( ) ; Dfs ( 1 , 0 ) ; int v = 3 , k = 4 ; System . out . println ( findNode ( v , k ) ) ; } }


"Find the Kth number which is not divisible by N | Java implementation for above approach ; Function to find the Kth not divisible by N ; Lowest possible value ; Highest possible value ; To store the Kth non divisible number of N ; Using binary search ; Calculating mid value ; Sol would have the value by subtracting all multiples of n till mid ; Check if sol is greater than k ; H should be reduced to find minimum possible value ; Check if sol is less than k then L will be mid + 1 ; Check if sol is equal to k ; ans will be mid ; H would be reduced to find any more possible value ; Print the answer ; Driver code ; Function Call"
How can the above be solved in Java?

class GFG { public static void kthNonDivisible ( int N , int K ) { int L = 1 ; int H = Integer . MAX_VALUE ; int ans = 0 ; while ( L <= H ) { int mid = ( L + H ) / 2 ; int sol = mid - mid / N ; if ( sol > K ) { H = mid - 1 ; } else if ( sol < K ) { L = mid + 1 ; } else { ans = mid ; H = mid - 1 ; } } System . out . print ( ans ) ; } public static void main ( String [ ] args ) { int N = 3 ; int K = 7 ; kthNonDivisible ( N , K ) ; } }


"Find the Kth number which is not divisible by N | Java implementation to find the K 'th non-divisible number of N ; Function to find the Kth not divisible by N ; Driver Code ; Function Call"
How can the above be solved in Java?

class GFG { static int kthNonDivisible ( int N , int K ) { return ( int ) ( K + Math . floor ( ( K - 1 ) / ( N - 1 ) ) ) ; } public static void main ( String [ ] args ) { int N = 3 ; int K = 6 ; System . out . print ( kthNonDivisible ( N , K ) ) ; } }


"Find the Kth pair in ordered list of all possible sorted pairs of the Array | Java program to find the K - th pair in a lexicographically sorted array ; Function to find the k - th pair ; Sorting the array ; Iterating through the array ; Finding the number of same elements ; Checking if N * T is less than the remaining K . If it is , then arr [ i ] is the first element in the required pair ; Printing the K - th pair ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { static void kthpair ( int n , int k , int arr [ ] ) { int i , t = 0 ; Arrays . sort ( arr ) ; -- k ; for ( i = 0 ; i < n ; i += t ) { for ( t = 1 ; arr [ i ] == arr [ i + t ] ; ++ t ) ; if ( t * n > k ) break ; k = k - t * n ; } System . out . print ( arr [ i ] + " ▁ " + arr [ k / t ] ) ; } public static void main ( String [ ] args ) { int n = 3 , k = 2 ; int arr [ ] = { 3 , 1 , 5 } ; kthpair ( n , k , arr ) ; } }


"Find the Kth position element of the given sequence | Java implementation of the approach ; Function to return the kth number from the required sequence ; Count of odd integers in the sequence ; kth number is even ; It is odd ; Driver code"
How can the above be solved in Java?

class GFG { static int kthNum ( int n , int k ) { int a = ( n + 1 ) / 2 ; if ( k > a ) return ( 2 * ( k - a ) ) ; return ( 2 * k - 1 ) ; } public static void main ( String [ ] args ) { int n = 7 , k = 7 ; System . out . println ( kthNum ( n , k ) ) ; } }


"Find the Kth smallest element in the sorted generated array | Java implementation of the approach ; Pair class implementation to use Pair ; Function to return the Kth element in B [ ] ; Initialize the count Array ; Reduce N repeatedly to half its value ; Add count to start ; Subtract same count after end index ; Store each element of Array [ ] with their count ; If Kth element is in range of element [ i ] return element [ i ] ; If K is out of bound ; Driver code"
How can the above be solved in Java?

import java . util . Vector ; class GFG { static class Pair { private int first ; private int second ; Pair ( int first , int second ) { this . first = first ; this . second = second ; } public int getFirst ( ) { return first ; } public int getSecond ( ) { return second ; } } static int solve ( int [ ] Array , int N , int K ) { int [ ] count_Arr = new int [ N + 2 ] ; int factor = 1 ; int size = N ; while ( size > 0 ) { int start = 1 ; int end = size ; count_Arr [ 1 ] += factor * N ; count_Arr [ end + 1 ] -= factor * N ; factor ++ ; size /= 2 ; } for ( int i = 2 ; i <= N ; i ++ ) count_Arr [ i ] += count_Arr [ i - 1 ] ; Vector < Pair > element = new Vector < > ( ) ; for ( int i = 0 ; i < N ; i ++ ) { Pair x = new Pair ( Array [ i ] , count_Arr [ i + 1 ] ) ; element . add ( x ) ; } int start = 1 ; for ( int i = 0 ; i < N ; i ++ ) { int end = start + element . elementAt ( 0 ) . getSecond ( ) - 1 ; if ( K >= start && K <= end ) return element . elementAt ( i ) . getFirst ( ) ; start += element . elementAt ( i ) . getSecond ( ) ; } return - 1 ; } public static void main ( String [ ] args ) { int [ ] arr = { 2 , 4 , 5 , 1 } ; int N = arr . length ; int K = 13 ; System . out . println ( solve ( arr , N , K ) ) ; } }


"Find the Kth smallest odd length palindrome number | Java program for the above approach ; Function to find the Kth smallest odd length palindrome ; Store the original number K ; Removing the last digit of K ; Generate the palindrome by appending the reverse of K except last digit to itself ; Find the remainder ; Add the digit to palin ; Divide K by 10 ; Return the resultant palindromic number formed ; Driver Code"
How can the above be solved in Java?

import java . util . * ; import java . lang . * ; class GFG { static int oddLengthPalindrome ( int k ) { int palin = k ; k = k / 10 ; while ( k > 0 ) { int rev = k % 10 ; palin = ( palin * 10 ) + rev ; k = k / 10 ; } return palin ; } public static void main ( String [ ] args ) { int k = 504 ; System . out . println ( oddLengthPalindrome ( k ) ) ; } }


"Find the Largest Cube formed by Deleting minimum Digits from a number | Java code to implement maximum perfect cube formed after deleting minimum digits ; Returns vector of Pre Processed perfect cubes ; convert the cube to String and push into preProcessedCubes vector ; Utility function for findLargestCube ( ) . Returns the Largest cube number that can be formed ; reverse the preProcessed cubes so that we have the largest cube in the beginning of the vector ; iterate over all cubes ; check if the current digit of the cube matches with that of the number num ; if control reaches here , the its not possible to form a perfect cube ; wrapper for findLargestCubeUtil ( ) ; pre process perfect cubes ; convert number n to String ; Driver Code"
How can the above be solved in Java?

import java . util . * ; class GFG { static Vector < String > preProcess ( int n ) { Vector < String > preProcessedCubes = new Vector < > ( ) ; for ( int i = 1 ; i * i * i <= n ; i ++ ) { int iThCube = i * i * i ; String cubeString = String . valueOf ( iThCube ) ; preProcessedCubes . add ( cubeString ) ; } return preProcessedCubes ; } static String findLargestCubeUtil ( String num , Vector < String > preProcessedCubes ) { Collections . reverse ( preProcessedCubes ) ; int totalCubes = preProcessedCubes . size ( ) ; for ( int i = 0 ; i < totalCubes ; i ++ ) { String currCube = preProcessedCubes . get ( i ) ; int digitsInCube = currCube . length ( ) ; int index = 0 ; int digitsInNumber = num . length ( ) ; for ( int j = 0 ; j < digitsInNumber ; j ++ ) { if ( num . charAt ( j ) == currCube . charAt ( index ) ) { index ++ ; } if ( digitsInCube == index ) { return currCube ; } } } return " Not ▁ Possible " ; } static void findLargestCube ( int n ) { Vector < String > preProcessedCubes = preProcess ( n ) ; String num = String . valueOf ( n ) ; String ans = findLargestCubeUtil ( num , preProcessedCubes ) ; System . out . println ( " Largest ▁ Cube ▁ that ▁ can ▁ be ▁ formed ▁ from ▁ " + n + " ▁ is ▁ " + ans ) ; } public static void main ( String [ ] args ) { int n ; n = 4125 ; findLargestCube ( n ) ; n = 876 ; findLargestCube ( n ) ; } }


"Find the Largest N digit perfect square number in Base B | Java implementation to find largest N digit perfect square number in base B ; Function to find the largest N digit number ; Largest n - digit perfect square ; Print the result ; Driver code"
How can the above be solved in Java?

import java . io . * ; import java . util . * ; class GFG { static double nDigitPerfectSquares ( int n , int b ) { double largest = Math . pow ( Math . ceil ( Math . sqrt ( Math . pow ( b , n ) ) ) - 1 , 2 ) ; return largest ; } public static void main ( String [ ] args ) { int N = 1 , B = 8 ; System . out . println ( nDigitPerfectSquares ( N , B ) ) ; } }


"Find the Largest divisor Subset in the Array | Java implementation of the approach ; Function to find the required subsequence ; Sort the array ; Keep a count of the length of the subsequence and the previous element ; Set the initial values ; Maximum length of the subsequence and the last element ; Run a loop for every element ; Check for all the divisors ; If the element is a divisor and the length of subsequence will increase by adding j as previous element of i ; Increase the count ; Update the max count ; Get the last index of the subsequence ; Print the element ; Move the index to the previous element ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { static void findSubSeq ( int arr [ ] , int n ) { Arrays . sort ( arr ) ; int count [ ] = new int [ n ] ; int prev [ ] = new int [ n ] ; int i , j ; for ( i = 0 ; i < n ; i ++ ) count [ i ] = 1 ; for ( j = 0 ; j < n ; j ++ ) prev [ j ] = - 1 ; int max = 0 ; int maxprev = - 1 ; for ( i = 0 ; i < n ; i ++ ) { for ( j = i - 1 ; j >= 0 ; j -- ) { if ( arr [ i ] % arr [ j ] == 0 && count [ j ] + 1 > count [ i ] ) { count [ i ] = count [ j ] + 1 ; prev [ i ] = j ; } } if ( max < count [ i ] ) { max = count [ i ] ; maxprev = i ; } } i = maxprev ; while ( i >= 0 ) { if ( arr [ i ] != - 1 ) System . out . print ( arr [ i ] + " ▁ " ) ; i = prev [ i ] ; } } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 2 , 3 , 4 , 5 } ; int n = arr . length ; findSubSeq ( arr , n ) ; } }


"Find the Largest number with given number of digits and sum of digits | Java program to find the largest number that can be formed from given sum of digits and number of digits ; Function to print the largest possible number with digit sum ' s ' and ' m ' number of digits ; If sum of digits is 0 , then a number is possible only if number of digits is 1 ; Sum greater than the maximum possible sum ; Create an array to store digits of result ; Fill from most significant digit to least significant digit ; Fill 9 first to make the number largest ; If remaining sum becomes less than 9 , then fill the remaining sum ; driver program"
How can the above be solved in Java?

class GFG { static void findLargest ( int m , int s ) { if ( s == 0 ) { System . out . print ( m == 1 ? " Largest ▁ number ▁ is ▁ 0" : " Not ▁ possible " ) ; return ; } if ( s > 9 * m ) { System . out . println ( " Not ▁ possible " ) ; return ; } int [ ] res = new int [ m ] ; for ( int i = 0 ; i < m ; i ++ ) { if ( s >= 9 ) { res [ i ] = 9 ; s -= 9 ; } else { res [ i ] = s ; s = 0 ; } } System . out . print ( " Largest ▁ number ▁ is ▁ " ) ; for ( int i = 0 ; i < m ; i ++ ) System . out . print ( res [ i ] ) ; } public static void main ( String [ ] args ) { int s = 9 , m = 2 ; findLargest ( m , s ) ; } }


"Find the Level of a Binary Tree with Width K | Java program to implement the above approach ; Structure of binary tree node ; Function to create new node ; Function returns required level of width k , if found else - 1 ; To store the node and the label and perform traversal ; Taking the last label of each level of the tree ; Check width of current level ; If the width is equal to k then return that level ; Taking the first label of each level of the tree ; If any level does not has width equal to k , return - 1 ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { static class Node { int data ; Node left , right ; } ; static class pair { Node first ; int second ; pair ( Node first , int second ) { this . first = first ; this . second = second ; } } static Node newNode ( int data ) { Node temp = new Node ( ) ; temp . data = data ; temp . left = temp . right = null ; return temp ; } static int findLevel ( Node root , int k , int level ) { Queue < pair > qt = new LinkedList < > ( ) ; qt . add ( new pair ( root , 0 ) ) ; int count = 1 , b = 0 , a = 0 ; while ( ! qt . isEmpty ( ) ) { pair temp = qt . peek ( ) ; qt . poll ( ) ; if ( count == 1 ) { b = temp . second ; } if ( temp . first . left != null ) { qt . add ( new pair ( temp . first . left , 2 * temp . second ) ) ; } if ( temp . first . right != null ) { qt . add ( new pair ( temp . first . right , 2 * temp . second + 1 ) ) ; } count -- ; if ( count == 0 ) { if ( ( b - a + 1 ) == k ) return level ; pair secondLabel = qt . peek ( ) ; a = secondLabel . second ; level += 1 ; count = qt . size ( ) ; } } return - 1 ; } public static void main ( String [ ] args ) { Node root = newNode ( 5 ) ; root . left = newNode ( 6 ) ; root . right = newNode ( 2 ) ; root . right . right = newNode ( 8 ) ; root . left . left = newNode ( 7 ) ; root . left . left . left = newNode ( 5 ) ; root . left . right = newNode ( 3 ) ; root . left . right . right = newNode ( 4 ) ; int k = 4 ; System . out . println ( findLevel ( root , k , 1 ) ) ; } }


"Find the Majority Element | Set 3 ( Bit Magic ) |  ; Number of bits in the integer ; Variable to calculate majority element ; Loop to iterate through all the bits of number ; Loop to iterate through all elements in array to count the total set bit at position i from right ; If the total set bits exceeds n / 2 , this bit should be present in majority Element . ; iterate through array get the count of candidate majority element ; Verify if the count exceeds n / 2 ; Driver Code"
How can the above be solved in Java?

class GFG { static void findMajority ( int arr [ ] , int n ) { int len = 32 ; int number = 0 ; for ( int i = 0 ; i < len ; i ++ ) { int count = 0 ; for ( int j = 0 ; j < n ; j ++ ) { if ( ( arr [ j ] & ( 1 << i ) ) != 0 ) count ++ ; } if ( count > ( n / 2 ) ) number += ( 1 << i ) ; } int count = 0 ; for ( int i = 0 ; i < n ; i ++ ) if ( arr [ i ] == number ) count ++ ; if ( count > ( n / 2 ) ) System . out . println ( number ) ; else System . out . println ( " Majority ▁ Element ▁ Not ▁ Present " ) ; } public static void main ( String [ ] args ) { int arr [ ] = { 3 , 3 , 4 , 2 , 4 , 4 , 2 , 4 , 4 } ; int n = arr . length ; findMajority ( arr , n ) ; } }


"Find the Maximum Alternate Subsequence Sum from a given array | Java program to find the maximum alternating subsequence sum for a given array ; Function to find maximum alternating subsequence sum ; Initialize sum to 0 ; Calculate the sum ; Return the final result ; Driver Code ; Array initialization ; Length of array"
How can the above be solved in Java?

import java . io . * ; import java . util . * ; class GFG { static int maxAlternatingSum ( int [ ] arr , int n ) { int max_sum = 0 ; int i = 0 ; while ( i < n ) { int current_max = arr [ i ] ; int k = i ; while ( k < n && ( ( arr [ i ] > 0 && arr [ k ] > 0 ) || ( arr [ i ] < 0 && arr [ k ] < 0 ) ) ) { current_max = Math . max ( current_max , arr [ k ] ) ; k += 1 ; } max_sum += current_max ; i = k ; } return max_sum ; } public static void main ( String args [ ] ) { int [ ] arr = { 1 , 2 , 3 , 4 , - 1 , - 2 } ; int n = arr . length ; System . out . println ( maxAlternatingSum ( arr , n ) ) ; } }


"Find the Maximum possible Sum for the given conditions | Java program to find the maximum possible Sum for the given conditions ; Function to find the maximum possible sum for the given conditions ; Sorting the array ; Variable to store the answer ; Iterating through the array ; If the value is greater than 0 ; If the value becomes 0 then break the loop because all the weights after this index will be 0 ; Print profit ; Driver code"
How can the above be solved in Java?

import java . util . Arrays ; import java . util . Collections ; public class GFG { static int maxProfit ( Integer [ ] arr ) { Arrays . sort ( arr , Collections . reverseOrder ( ) ) ; int ans = 0 ; for ( int i = 0 ; i < arr . length ; i ++ ) { if ( ( arr [ i ] - ( 1 * i ) ) > 0 ) ans += ( arr [ i ] - ( 1 * i ) ) ; if ( ( arr [ i ] - ( 1 * i ) ) == 0 ) break ; } return ans ; } public static void main ( String [ ] args ) { Integer arr [ ] = { 6 , 6 , 6 } ; System . out . println ( maxProfit ( arr ) ) ; } }


"Find the Mid | Java program to find the Mid - Alphabet for each index of the given Pair of Strings ; Function to find the mid alphabets ; For every character pair ; Get the average of the characters ; Driver code"
How can the above be solved in Java?

class GFG { static void findMidAlphabet ( String s1 , String s2 , int n ) { for ( int i = 0 ; i < n ; i ++ ) { int mid = ( s1 . charAt ( i ) + s2 . charAt ( i ) ) / 2 ; System . out . print ( ( char ) mid ) ; } } public static void main ( String [ ] args ) { String s1 = " akzbqzgw " ; String s2 = " efhctcsz " ; int n = s1 . length ( ) ; findMidAlphabet ( s1 , s2 , n ) ; } }


"Find the Minimum length Unsorted Subarray , sorting which makes the complete array sorted | Java program to find the Minimum length Unsorted Subarray , sorting which makes the complete array sorted ; step 1 ( a ) of above algo ; step 1 ( b ) of above algo ; step 2 ( a ) of above algo ; step 2 ( b ) of above algo ; step 2 ( c ) of above algo ; step 3 of above algo"
How can the above be solved in Java?

class Main { static void printUnsorted ( int arr [ ] , int n ) { int s = 0 , e = n - 1 , i , max , min ; for ( s = 0 ; s < n - 1 ; s ++ ) { if ( arr [ s ] > arr [ s + 1 ] ) break ; } if ( s == n - 1 ) { System . out . println ( " The ▁ complete ▁ array ▁ is ▁ sorted " ) ; return ; } for ( e = n - 1 ; e > 0 ; e -- ) { if ( arr [ e ] < arr [ e - 1 ] ) break ; } max = arr [ s ] ; min = arr [ s ] ; for ( i = s + 1 ; i <= e ; i ++ ) { if ( arr [ i ] > max ) max = arr [ i ] ; if ( arr [ i ] < min ) min = arr [ i ] ; } for ( i = 0 ; i < s ; i ++ ) { if ( arr [ i ] > min ) { s = i ; break ; } } for ( i = n - 1 ; i >= e + 1 ; i -- ) { if ( arr [ i ] < max ) { e = i ; break ; } } System . out . println ( " ▁ The ▁ unsorted ▁ subarray ▁ which " + " ▁ makes ▁ the ▁ given ▁ array ▁ sorted ▁ lies " + " ▁ between ▁ the ▁ indices ▁ " + s + " ▁ and ▁ " + e ) ; return ; } public static void main ( String args [ ] ) { int arr [ ] = { 10 , 12 , 20 , 30 , 25 , 40 , 32 , 31 , 35 , 50 , 60 } ; int arr_size = arr . length ; printUnsorted ( arr , arr_size ) ; } }


"Find the Missing Number in a sorted array | A binary search based program to find the only missing number in a sorted array of distinct elements within limited range . ; Driver Code"
How can the above be solved in Java?

import java . io . * ; class GFG { static int search ( int ar [ ] , int size ) { int a = 0 , b = size - 1 ; int mid = 0 ; while ( ( b - a ) > 1 ) { mid = ( a + b ) / 2 ; if ( ( ar [ a ] - a ) != ( ar [ mid ] - mid ) ) b = mid ; else if ( ( ar [ b ] - b ) != ( ar [ mid ] - mid ) ) a = mid ; } return ( ar [ a ] + 1 ) ; } public static void main ( String [ ] args ) { int ar [ ] = { 1 , 2 , 3 , 4 , 5 , 6 , 8 } ; int size = ar . length ; System . out . println ( " Missing ▁ number : ▁ " + search ( ar , size ) ) ; } }


"Find the Missing Number | Java implementation ; a represents the array n : Number of elements in array a ; Driver Code"
How can the above be solved in Java?

class GFG { static int getMissingNo ( int a [ ] , int n ) { int total = 1 ; for ( int i = 2 ; i <= ( n + 1 ) ; i ++ ) { total += i ; total -= a [ i - 2 ] ; } return total ; } public static void main ( String [ ] args ) { int [ ] arr = { 1 , 2 , 3 , 5 } ; System . out . println ( getMissingNo ( arr , arr . length ) ) ; } }


"Find the Missing Number | Java program to find missing Number ; Function to get the missing number ; Driver Code"
How can the above be solved in Java?

import java . util . * ; import java . util . Arrays ; class GFG { public static List < Integer > findDisappearedNumbers ( int [ ] nums ) { for ( int i = 0 ; i < nums . length ; i ++ ) { int index = Math . abs ( nums [ i ] ) ; if ( nums [ index - 1 ] > 0 ) { nums [ index - 1 ] *= - 1 ; } } List < Integer > res = new ArrayList < > ( ) ; for ( int i = 0 ; i < nums . length ; i ++ ) { if ( nums [ i ] > 0 ) { res . add ( i + 1 ) ; } } return res ; } public static void main ( String [ ] args ) { int [ ] a = { 1 , 2 , 4 , 5 , 6 } ; System . out . println ( findDisappearedNumbers ( a ) ) ; } }


"Find the Missing Number | Java program to find the missing Number ; getMissingNo function for finding missing number ; Driver code"
How can the above be solved in Java?

class GFG { static int getMissingNo ( int a [ ] , int n ) { int n_elements_sum = n * ( n + 1 ) / 2 ; int sum = 0 ; for ( int i = 0 ; i < n - 1 ; i ++ ) sum += a [ i ] ; return n_elements_sum - sum ; } public static void main ( String [ ] args ) { int a [ ] = { 1 , 2 , 4 , 5 , 6 } ; int n = a . length + 1 ; int miss = getMissingNo ( a , n ) ; System . out . print ( miss ) ; } }


"Find the Missing Point of Parallelogram | Java program to find missing point of a parallelogram ; main method ; coordinates of A ; coordinates of B ; coordinates of C"
How can the above be solved in Java?

import java . io . * ; class GFG { public static void main ( String [ ] args ) { int ax = 5 , ay = 0 ; int bx = 1 , by = 1 ; int cx = 2 , cy = 5 ; System . out . println ( ax + ( cx - bx ) + " , ▁ " + ay + ( cy - by ) ) ; } }