"Generate permutations with only adjacent swaps allowed | Java program to generate permutations with only one swap allowed . ; don 't swap the current position ; Swap with the next character and revert the changes . As explained above , swapping with previous is is not needed as it anyways happens for next character . ; Driver code"
How can the above be solved in Java?

class GFG { static void findPermutations ( char str [ ] , int index , int n ) { if ( index >= n || ( index + 1 ) >= n ) { System . out . println ( str ) ; return ; } findPermutations ( str , index + 1 , n ) ; swap ( str , index ) ; findPermutations ( str , index + 2 , n ) ; swap ( str , index ) ; } static void swap ( char arr [ ] , int index ) { char temp = arr [ index ] ; arr [ index ] = arr [ index + 1 ] ; arr [ index + 1 ] = temp ; } public static void main ( String [ ] args ) { char str [ ] = "12345" . toCharArray ( ) ; int n = str . length ; findPermutations ( str , 0 , n ) ; } }


"Generate string with Hamming Distance as half of the hamming distance between strings A and B | Java implementation of the above approach ; Function to find the required string ; Find the hamming distance between A and B ; If distance is odd , then resultant string is not possible ; Make the resultant string ; To store the final string ; Pick k characters from each string ; Pick K characters from string B ; Pick K characters from string A ; Append the res characters from string to the resultant string ; Print the resultant string ; Driver 's Code  ; Function to find the resultant string"
How can the above be solved in Java?

class GFG { static void findString ( String A , String B ) { int dist = 0 ; for ( int i = 0 ; i < A . length ( ) ; i ++ ) { if ( A . charAt ( i ) != B . charAt ( i ) ) dist ++ ; } if ( ( dist & 1 ) == 1 ) { System . out . println ( " Not ▁ Possible " ) ; } else { String res = " " ; int K = ( int ) dist / 2 ; for ( int i = 0 ; i < A . length ( ) ; i ++ ) { if ( A . charAt ( i ) != B . charAt ( i ) && K > 0 ) { res += B . charAt ( i ) ; K -- ; } else if ( A . charAt ( i ) != B . charAt ( i ) ) { res += A . charAt ( i ) ; } else { res += A . charAt ( i ) ; } } System . out . println ( res ) ; } } public static void main ( String [ ] args ) { String A = "1001010" ; String B = "0101010" ; findString ( A , B ) ; } }


"Generate two output strings depending upon occurrence of character in input string . | Java program to print two strings made of character occurring once and multiple times ; function to print two strings generated from single string one with characters occurring onces other with character occurring multiple of times ; initialize hashtable with zero entry ; perform hashing for input string ; generate string ( str1 ) consisting char occurring once and string ( str2 ) consisting char occurring multiple times ; print both strings ; driver program"
How can the above be solved in Java?

 class GFG { final static int MAX_CHAR = 256 ; static void printDuo ( String str ) { int countChar [ ] = new int [ MAX_CHAR ] ; int n = str . length ( ) ; for ( int i = 0 ; i < n ; i ++ ) { countChar [ str . charAt ( i ) - ' a ' ] ++ ; } String str1 = " " , str2 = " " ; for ( int i = 0 ; i < MAX_CHAR ; i ++ ) { if ( countChar [ i ] > 1 ) { str2 = str2 + ( char ) ( i + ' a ' ) ; } else if ( countChar [ i ] == 1 ) { str1 = str1 + ( char ) ( i + ' a ' ) ; } } System . out . print ( " String ▁ with ▁ characters ▁ occurring ▁ " + "once:
"); System . out . print ( str1 + "
"); System . out . print ( " String ▁ with ▁ characters ▁ occurring ▁ " + "multiple times:
"); System . out . print ( str2 + "
"); System . out . print ( " " ) ; } public static void main ( String [ ] args ) { String str = " lovetocode " ; printDuo ( str ) ; } }


"Generating N | Java program Generating N - bit Gray Code starting from K ; Function to Generating N - bit Gray Code starting from K ; Generate gray code of corresponding binary number of integer i . ; Driver code"
How can the above be solved in Java?

class GFG { static void genSequence ( int n , int val ) { for ( int i = 0 ; i < ( 1 << n ) ; i ++ ) { int x = i ^ ( i >> 1 ) ^ val ; System . out . print ( x + " ▁ " ) ; } } public static void main ( String [ ] args ) { int n = 3 , k = 2 ; genSequence ( n , k ) ; } }


"Generating distinct subsequences of a given string in lexicographic order | Java program to print all distinct subsequences of a string . ; Finds and stores result in st for a given string s . ; If current string is not already present . ; Traverse current string , one by one remove every character and recur . ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { static void generate ( Set < String > st , String s ) { if ( s . length ( ) == 0 ) { return ; } if ( ! st . contains ( s ) ) { st . add ( s ) ; for ( int i = 0 ; i < s . length ( ) ; i ++ ) { String t = s ; t = t . substring ( 0 , i ) + t . substring ( i + 1 ) ; generate ( st , t ) ; } } return ; } public static void main ( String args [ ] ) { String s = " xyz " ; TreeSet < String > st = new TreeSet < > ( ) ; generate ( st , s ) ; for ( String str : st ) { System . out . println ( str ) ; } } }


"Generating numbers that are divisor of their right | Java program to Generating numbers that are divisor of their right - rotations ; Function to check if N is a divisor of its right - rotation ; Function to generate m - digit numbers which are divisor of their right - rotation ; Driver code"
How can the above be solved in Java?

public class GFG { static boolean rightRotationDivisor ( int N ) { int lastDigit = N % 10 ; int rightRotation = ( int ) ( lastDigit * Math . pow ( 10 , ( int ) ( Math . log10 ( N ) ) ) + Math . floor ( N / 10 ) ) ; return ( rightRotation % N == 0 ) ; } static void generateNumbers ( int m ) { for ( int i = ( int ) Math . pow ( 10 , ( m - 1 ) ) ; i < Math . pow ( 10 , m ) ; i ++ ) if ( rightRotationDivisor ( i ) ) System . out . println ( i ) ; } public static void main ( String args [ ] ) { int m = 3 ; generateNumbers ( m ) ; } }


"Generating numbers that are divisor of their right | Java program to Generating numbers that are divisor of their right - rotations ; Function to generate m - digit numbers which are divisor of their right - rotation ; Driver code"
How can the above be solved in Java?

import java . util . * ; import java . io . * ; class GFG { static void generateNumbers ( int m ) { ArrayList < Integer > numbers = new ArrayList < > ( ) ; int k_max , x ; for ( int y = 0 ; y < 10 ; y ++ ) { k_max = ( int ) ( Math . pow ( 10 , m - 2 ) * ( 10 * y + 1 ) ) / ( int ) ( Math . pow ( 10 , m - 1 ) + y ) ; for ( int k = 1 ; k <= k_max ; k ++ ) { x = ( int ) ( y * ( Math . pow ( 10 , m - 1 ) - k ) ) / ( 10 * k - 1 ) ; if ( ( int ) ( y * ( Math . pow ( 10 , m - 1 ) - k ) ) % ( 10 * k - 1 ) == 0 ) numbers . add ( 10 * x + y ) ; } } Collections . sort ( numbers ) ; for ( int i = 0 ; i < numbers . size ( ) ; i ++ ) System . out . println ( numbers . get ( i ) ) ; } public static void main ( String args [ ] ) { int m = 3 ; generateNumbers ( m ) ; } }


"Generation of n numbers with given set of factors | Java program to generate n numbers with given factors ; Generate n numbers with factors in factor [ ] ; array of k to store next multiples of given factors ; Prints n numbers int output = 0 ; Next number to print as output ; Find the next smallest multiple ; Printing minimum in each iteration print the value if output is not equal to current value ( to avoid the duplicates ) ; incrementing the current value by the respective factor ; Driver code"
How can the above be solved in Java?

import java . io . * ; class GFG { static void generateNumbers ( int factor [ ] , int n , int k ) { int next [ ] = new int [ k ] ; for ( int i = 0 ; i < n ; ) { int toincrement = 0 ; for ( int j = 0 ; j < k ; j ++ ) if ( next [ j ] < next [ toincrement ] ) toincrement = j ; if ( output != next [ toincrement ] ) { output = next [ toincrement ] ; System . out . print ( next [ toincrement ] + " ▁ " ) ; i ++ ; } next [ toincrement ] += factor [ toincrement ] ; } } public static void main ( String [ ] args ) { int factor [ ] = { 3 , 5 , 7 } ; int n = 10 ; int k = factor . length ; generateNumbers ( factor , n , k ) ; } }


"Geometric mean ( Two Methods ) | Java Program to calculate the geometric mean of the given array elements . ; function to calculate geometric mean and return float value . ; declare sum variable and initialize it to 1. ; Compute the sum of all the elements in the array . ; compute geometric mean through formula antilog ( ( ( log ( 1 ) + log ( 2 ) + . . . + log ( n ) ) / n ) and return the value to main function . ; Driver function ; function call"
How can the above be solved in Java?

import java . io . * ; class GFG { static float geometricMean ( int [ ] arr , int n ) { float sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) sum = sum + ( float ) Math . log ( arr [ i ] ) ; sum = sum / n ; return ( float ) Math . exp ( sum ) ; } public static void main ( String [ ] args ) { int [ ] arr = { 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 } ; int n = arr . length ; System . out . println ( geometricMean ( arr , n ) ) ; } }


"Geometric mean ( Two Methods ) | Program to calculate the geometric mean of the given array elements . ; function to calculate geometric mean and return float value . ; declare product variable and initialize it to 1. ; Compute the product of all the elements in the array . ; compute geometric mean through formula pow ( product , 1 / n ) and return the value to main function . ; Driver function"
How can the above be solved in Java?

import java . math . * ; class GFG { static float geometricMean ( int arr [ ] , int n ) { float product = 1 ; for ( int i = 0 ; i < n ; i ++ ) product = product * arr [ i ] ; float gm = ( float ) Math . pow ( product , ( float ) 1 / n ) ; return gm ; } public static void main ( String args [ ] ) { int arr [ ] = { 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 } ; int n = arr . length ; System . out . println ( geometricMean ( arr , n ) ) ; } }


"Get K | Java implementation of above approach ; Function to return the K - th letter from new String . ; finding size = length of new string S ' ; get the K - th letter ; Driver program"
How can the above be solved in Java?

class GFG { static String K_thletter ( String S , int K ) { int N = S . length ( ) ; long size = 0 ; for ( int i = 0 ; i < N ; ++ i ) { if ( Character . isDigit ( S . charAt ( i ) ) ) { size = size * ( S . charAt ( i ) - '0' ) ; } else { size += 1 ; } } for ( int i = N - 1 ; i >= 0 ; -- i ) { K %= size ; if ( K == 0 && Character . isAlphabetic ( S . charAt ( i ) ) ) { return ( String ) " " + S . charAt ( i ) ; } if ( Character . isDigit ( S . charAt ( i ) ) ) { size = size / ( S . charAt ( i ) - '0' ) ; } else { size -= 1 ; } } return null ; } public static void main ( String [ ] args ) { String S = " geeks2for2" ; int K = 15 ; System . out . println ( K_thletter ( S , K ) ) ; } }


"Get Level of a node in a Binary Tree | A tree node structure ; Helper function for getLevel ( ) . It returns level of the data if data is present in tree , otherwise returns 0. ; Returns level of given data value ; Driver code ; Constructing tree given in the above figure"
How can the above be solved in Java?

class Node { int data ; Node left , right ; public Node ( int d ) { data = d ; left = right = null ; } } class BinaryTree { Node root ; int getLevelUtil ( Node node , int data , int level ) { if ( node == null ) return 0 ; if ( node . data == data ) return level ; int downlevel = getLevelUtil ( node . left , data , level + 1 ) ; if ( downlevel != 0 ) return downlevel ; downlevel = getLevelUtil ( node . right , data , level + 1 ) ; return downlevel ; } int getLevel ( Node node , int data ) { return getLevelUtil ( node , data , 1 ) ; } public static void main ( String [ ] args ) { BinaryTree tree = new BinaryTree ( ) ; tree . root = new Node ( 3 ) ; tree . root . left = new Node ( 2 ) ; tree . root . right = new Node ( 5 ) ; tree . root . left . left = new Node ( 1 ) ; tree . root . left . right = new Node ( 4 ) ; for ( int x = 1 ; x <= 5 ; x ++ ) { int level = tree . getLevel ( tree . root , x ) ; if ( level != 0 ) System . out . println ( " Level ▁ of ▁ " + x + " ▁ is ▁ " + tree . getLevel ( tree . root , x ) ) ; else System . out . println ( x + " ▁ is ▁ not ▁ present ▁ in ▁ tree " ) ; } } }


"Get level of a node in binary tree | iterative approach | Java program to print level of given node in binary tree iterative approach ; node of binary tree ; utility function to return level of given node ; extra NULL is pushed to keep track of all the nodes to be pushed before level is incremented by 1 ; Driver Code ; create a binary tree ; return level of node"
How can the above be solved in Java?

import java . io . * ; import java . util . * ; class GFG { static class node { int data ; node left , right ; node ( int data ) { this . data = data ; this . left = this . right = null ; } } static int getLevel ( node root , int data ) { Queue < node > q = new LinkedList < > ( ) ; int level = 1 ; q . add ( root ) ; q . add ( null ) ; while ( ! q . isEmpty ( ) ) { node temp = q . poll ( ) ; if ( temp == null ) { if ( q . peek ( ) != null ) { q . add ( null ) ; } level += 1 ; } else { if ( temp . data == data ) { return level ; } if ( temp . left != null ) { q . add ( temp . left ) ; } if ( temp . right != null ) { q . add ( temp . right ) ; } } } return 0 ; } public static void main ( String [ ] args ) { node root = new node ( 20 ) ; root . left = new node ( 10 ) ; root . right = new node ( 30 ) ; root . left . left = new node ( 5 ) ; root . left . right = new node ( 15 ) ; root . left . right . left = new node ( 12 ) ; root . right . left = new node ( 25 ) ; root . right . right = new node ( 40 ) ; int level = getLevel ( root , 30 ) ; if ( level != 0 ) System . out . println ( " level ▁ of ▁ node ▁ 30 ▁ is ▁ " + level ) ; else System . out . println ( " node ▁ 30 ▁ not ▁ found " ) ; level = getLevel ( root , 12 ) ; if ( level != 0 ) System . out . println ( " level ▁ of ▁ node ▁ 12 ▁ is ▁ " + level ) ; else System . out . println ( " node ▁ 12 ▁ not ▁ found " ) ; level = getLevel ( root , 25 ) ; if ( level != 0 ) System . out . println ( " level ▁ of ▁ node ▁ 25 ▁ is ▁ " + level ) ; else System . out . println ( " node ▁ 25 ▁ not ▁ found " ) ; level = getLevel ( root , 27 ) ; if ( level != 0 ) System . out . println ( " level ▁ of ▁ node ▁ 27 ▁ is ▁ " + level ) ; else System . out . println ( " node ▁ 27 ▁ not ▁ found " ) ; } }


"Get maximum items when other items of total cost of an item are free | Java implementation of the above approach ; Function to count the total number of items ; Sort the prices ; Choose the last element ; Initial count of item ; Sum to keep track of the total price of free items ; If total is less than or equal to z then we will add 1 to the answer ; Driver code"
How can the above be solved in Java?

import java . util . Arrays ; import java . io . * ; class GFG { static int items ( int n , int a [ ] ) { Arrays . sort ( a ) ; int z = a [ n - 1 ] ; int x = 1 ; int s = 0 ; for ( int i = 0 ; i < n - 1 ; i ++ ) { s += a [ i ] ; if ( s <= z ) x += 1 ; else break ; } return x ; } public static void main ( String [ ] args ) { int n = 5 ; int a [ ] = { 5 , 3 , 1 , 5 , 6 } ; System . out . println ( items ( n , a ) ) ; } }


"Get maximum left node in binary tree | Java program to print maximum element in left node . ; A Binary Tree Node ; Get max of left element using Inorder traversal ; Return maximum of three values 1 ) Recursive max in left subtree 2 ) Value in left node 3 ) Recursive max in right subtree ; Utility function to create a new tree node ; Driver program to test above functions ; Let us create binary tree shown in above diagram ; 7 / \ 6 5 / \ / \ 4 3 2 1"
How can the above be solved in Java?

import java . util . * ; class GfG { static class Node { int data ; Node left , right ; } static int maxOfLeftElement ( Node root ) { int res = Integer . MIN_VALUE ; if ( root == null ) return res ; if ( root . left != null ) res = root . left . data ; return Math . max ( maxOfLeftElement ( root . left ) , Math . max ( res , maxOfLeftElement ( root . right ) ) ) ; } static Node newNode ( int data ) { Node temp = new Node ( ) ; temp . data = data ; temp . left = null ; temp . right = null ; return temp ; } public static void main ( String [ ] args ) { Node root = newNode ( 7 ) ; root . left = newNode ( 6 ) ; root . right = newNode ( 5 ) ; root . left . left = newNode ( 4 ) ; root . left . right = newNode ( 3 ) ; root . right . left = newNode ( 2 ) ; root . right . right = newNode ( 1 ) ; System . out . println ( maxOfLeftElement ( root ) ) ; } }


"Gill 's 4th Order Method to solve Differential Equations | Java program to implement Gill 's method ; A sample differential equation " dy / dx ▁ = ▁ ( x ▁ - ▁ y ) /2" ; Finds value of y for a given x using step size h and initial value y0 at x0 ; Count number of iterations using step size or height h ; Value of K_i ; Initial value of y ( 0 ) ; Iterate for number of iteration ; Value of K1 ; Value of K2 ; Value of K3 ; Value of K4 ; Find the next value of y ( n + 1 ) using y ( n ) and values of K in the above steps ; Update next value of x ; Return the final value of dy / dx ; Driver Code"
How can the above be solved in Java?

class GFG { static double dydx ( double x , double y ) { return ( x - y ) / 2 ; } static double Gill ( double x0 , double y0 , double x , double h ) { int n = ( int ) ( ( x - x0 ) / h ) ; double k1 , k2 , k3 , k4 ; double y = y0 ; for ( int i = 1 ; i <= n ; i ++ ) { k1 = h * dydx ( x0 , y ) ; k2 = h * dydx ( x0 + 0.5 * h , y + 0.5 * k1 ) ; k3 = h * dydx ( x0 + 0.5 * h , y + 0.5 * ( - 1 + Math . sqrt ( 2 ) ) * k1 + k2 * ( 1 - 0.5 * Math . sqrt ( 2 ) ) ) ; k4 = h * dydx ( x0 + h , y - ( 0.5 * Math . sqrt ( 2 ) ) * k2 + k3 * ( 1 + 0.5 * Math . sqrt ( 2 ) ) ) ; y = y + ( 1.0 / 6 ) * ( k1 + ( 2 - Math . sqrt ( 2 ) ) * k2 + ( 2 + Math . sqrt ( 2 ) ) * k3 + k4 ) ; x0 = x0 + h ; } return y ; } public static void main ( String [ ] args ) { double x0 = 0 , y = 3.0 , x = 5.0 , h = 0.2 ; System . out . printf ( " y ( x ) ▁ = ▁ % .6f " , Gill ( x0 , y , x , h ) ) ; } }


"Giuga Numbers | Java program for the above approach ; Function to check if n is a composite number ; Corner cases ; This is checked to skip middle 5 numbers ; Function to check if N is a Giuga Number ; N should be composite to be a Giuga Number ; Print the number of 2 s that divide n ; N must be odd at this point . So we can skip one element ; While i divides n , print i and divide n ; This condition is to handle the case when n is a prime number > 2 ; Driver code ; Given Number N ; Function Call"
How can the above be solved in Java?

class GFG { static boolean isComposite ( int n ) { if ( n <= 1 ) return false ; if ( n <= 3 ) return false ; if ( n % 2 == 0 n % 3 == 0 ) return true ; for ( int i = 5 ; i * i <= n ; i = i + 6 ) if ( n % i == 0 || n % ( i + 2 ) == 0 ) return true ; return false ; } static boolean isGiugaNum ( int n ) { if ( ! ( isComposite ( n ) ) ) return false ; int N = n ; while ( n % 2 == 0 ) { if ( ( N / 2 - 1 ) % 2 != 0 ) return false ; n = n / 2 ; } for ( int i = 3 ; i <= Math . sqrt ( n ) ; i = i + 2 ) { while ( n % i == 0 ) { if ( ( N / i - 1 ) % i != 0 ) return false ; n = n / i ; } } if ( n > 2 ) if ( ( N / n - 1 ) % n != 0 ) return false ; return true ; } public static void main ( String [ ] args ) { int n = 30 ; if ( isGiugaNum ( n ) ) System . out . println ( " Yes " ) ; else System . out . println ( " No " ) ; } }


"Given 1 ' s , ▁ 2' s , 3 ' s ▁ . . . . . . k ' s print them in zig zag way . | Java program to print given number of 1 ' s , ▁ 2' s , 3 ' s ▁ . . . . k ' s in zig - zag way . ; function that prints given number of 1 ' s , ▁ ▁ 2' s , 3 ' s ▁ . . . . k ' s in zig - zag way . ; two - dimensional array to store numbers . ; for even row . ; for each column . ; storing element . ; decrement element at kth index . ; if array contains zero then increment index to make this next index ; for odd row . ; for each column . ; storing element . ; decrement element at kth index . ; if array contains zero then increment index to make this next index . ; printing the stored elements . ; Driver function"
How can the above be solved in Java?

import java . util . * ; import java . lang . * ; public class GfG { public static void ZigZag ( int rows , int columns , int numbers [ ] ) { int k = 0 ; int [ ] [ ] arr = new int [ rows ] [ columns ] ; for ( int i = 0 ; i < rows ; i ++ ) { if ( i % 2 == 0 ) { for ( int j = 0 ; j < columns && numbers [ k ] > 0 ; j ++ ) { arr [ i ] [ j ] = k + 1 ; numbers [ k ] -- ; if ( numbers [ k ] == 0 ) k ++ ; } } else { for ( int j = columns - 1 ; j >= 0 && numbers [ k ] > 0 ; j -- ) { arr [ i ] [ j ] = k + 1 ; numbers [ k ] -- ; if ( numbers [ k ] == 0 ) k ++ ; } } } for ( int i = 0 ; i < rows ; i ++ ) { for ( int j = 0 ; j < columns ; j ++ ) System . out . print ( arr [ i ] [ j ] + " ▁ " ) ; System . out . println ( ) ; } } public static void main ( String argc [ ] ) { int rows = 4 ; int columns = 5 ; int [ ] Numbers = new int [ ] { 3 , 4 , 2 , 2 , 3 , 1 , 5 } ; ZigZag ( rows , columns , Numbers ) ; } }


"Given N and Standard Deviation , find N elements | Java program to find n elements ; function to print series of n elements ; if S . D . is 0 then print all elements as 0. ; print n 0 's ; if S . D . is even ; print - SD , + SD , - SD , + SD ; if odd ; convert n to a float integer ; print one element to be 0 ; print ( n - 1 ) elements as xi derived from the formula ; driver function"
How can the above be solved in Java?

import java . util . * ; import java . lang . * ; public class GfG { public static void series ( int n , int d ) { if ( d == 0 ) { for ( int i = 0 ; i < n ; i ++ ) System . out . print ( "0 ▁ " ) ; System . out . println ( ) ; return ; } if ( n % 2 == 0 ) { for ( int i = 1 ; i <= n ; i ++ ) { System . out . print ( Math . pow ( - 1 , i ) * d + " ▁ " ) ; } System . out . println ( ) ; } else { float m = n ; float r = ( m / ( m - 1 ) ) ; float g = ( float ) ( d * ( float ) ( Math . sqrt ( r ) ) ) ; System . out . print ( "0 ▁ " ) ; for ( int i = 1 ; i < n ; i ++ ) { System . out . print ( Math . pow ( - 1 , i ) * g + " ▁ " ) ; } System . out . println ( ) ; } } public static void main ( String args [ ] ) { int n = 3 , d = 3 ; series ( n , d ) ; } }


"Given a Boolean Matrix , find k such that all elements in k ' th ▁ row ▁ are ▁ 0 ▁ and ▁ k ' th column are 1. | Java program to find i such that all entries in i ' th ▁ row ▁ are ▁ 0 ▁ and ▁ all ▁ entries ▁ in ▁ i ' t column are 1 ; Start from top - most rightmost corner ( We could start from other corners also ) ; Initialize result ; Find the index ( This loop runs at most 2 n times , we either increment row number or decrement column number ) ; If current element is false , then this row may be a solution ; Check for all elements in this row ; If all values are false , then store this row as result ; We reach here if we found a 1 in current row , so this row cannot be a solution , increment row number ; If current element is 1 ; Check for all elements in this column ; If all elements are 1 ; We reach here if we found a 0 in current column , so this column cannot be a solution , increment column number ; If we could not find result in above loop , then result doesn 't exist ; Check if above computed res is valid ; Driver program to test above functions"
How can the above be solved in Java?

class GFG { static int n = 5 ; static int find ( boolean arr [ ] [ ] ) { int i = 0 , j = n - 1 ; int res = - 1 ; while ( i < n && j >= 0 ) { if ( arr [ i ] [ j ] == false ) { while ( j >= 0 && ( arr [ i ] [ j ] == false i == j ) ) { j -- ; } if ( j == - 1 ) { res = i ; break ; } else { i ++ ; } } else { while ( i < n && ( arr [ i ] [ j ] == true i == j ) ) { i ++ ; } if ( i == n ) { res = j ; break ; } else { j -- ; } } } if ( res == - 1 ) { return res ; } for ( int k = 0 ; k < n ; k ++ ) { if ( res != k && arr [ k ] [ res ] != true ) { return - 1 ; } } for ( int l = 0 ; l < n ; l ++ ) { if ( res != l && arr [ res ] [ l ] != false ) { return - 1 ; } } return res ; } public static void main ( String [ ] args ) { boolean mat [ ] [ ] = { { false , false , true , true , false } , { false , false , false , true , false } , { true , true , true , true , false } , { false , false , false , false , false } , { true , true , true , true , true } } ; System . out . println ( find ( mat ) ) ; } }


"Given a binary string , count number of substrings that start and end with 1. | A O ( n ) C ++ program to count number of substrings starting and ending with 1 ; Traverse input string and count of 1 's in it ; Return count of possible pairs among m 1 's ; Driver program to test the above function"
How can the above be solved in Java?

class CountSubString { int countSubStr ( char str [ ] , int n ) { for ( int i = 0 ; i < n ; i ++ ) { if ( str [ i ] == '1' ) m ++ ; } return m * ( m - 1 ) / 2 ; } public static void main ( String [ ] args ) { CountSubString count = new CountSubString ( ) ; String string = "00100101" ; char str [ ] = string . toCharArray ( ) ; int n = str . length ; System . out . println ( count . countSubStr ( str , n ) ) ; } }


"Given a binary string , count number of substrings that start and end with 1. | A simple C ++ program to count number of substrings starting and ending with 1 ; Initialize result ; Pick a starting point ; Search for all possible ending point ; Driver program to test the above function"
How can the above be solved in Java?

class CountSubString { int countSubStr ( char str [ ] , int n ) { int res = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( str [ i ] == '1' ) { for ( int j = i + 1 ; j < n ; j ++ ) { if ( str [ j ] == '1' ) res ++ ; } } } return res ; } public static void main ( String [ ] args ) { CountSubString count = new CountSubString ( ) ; String string = "00100101" ; char str [ ] = string . toCharArray ( ) ; int n = str . length ; System . out . println ( count . countSubStr ( str , n ) ) ; } }


"Given a binary tree , how do you remove all the half nodes ? | Binary tree node ; For inorder traversal ; Removes all nodes with only one child and returns new root ( note that root may change ) ; if current nodes is a half node with left child NULL left , then it 's right child is  returned and replaces it in the given tree  ; if current nodes is a half node with right child NULL right , then it 's right child is  returned and replaces it in the given tree  ; 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 ; void printInorder ( Node node ) { if ( node != null ) { printInorder ( node . left ) ; System . out . print ( node . data + " ▁ " ) ; printInorder ( node . right ) ; } } Node RemoveHalfNodes ( Node node ) { if ( node == null ) return null ; node . left = RemoveHalfNodes ( node . left ) ; node . right = RemoveHalfNodes ( node . right ) ; if ( node . left == null && node . right == null ) return node ; if ( node . left == null ) { Node new_root = node . right ; return new_root ; } if ( node . right == null ) { Node new_root = node . left ; return new_root ; } return node ; } public static void main ( String args [ ] ) { BinaryTree tree = new BinaryTree ( ) ; Node NewRoot = null ; tree . root = new Node ( 2 ) ; tree . root . left = new Node ( 7 ) ; tree . root . right = new Node ( 5 ) ; tree . root . left . right = new Node ( 6 ) ; tree . root . left . right . left = new Node ( 1 ) ; tree . root . left . right . right = new Node ( 11 ) ; tree . root . right . right = new Node ( 9 ) ; tree . root . right . right . left = new Node ( 4 ) ; System . out . println ( " the ▁ inorder ▁ traversal ▁ of ▁ tree ▁ is ▁ " ) ; tree . printInorder ( tree . root ) ; NewRoot = tree . RemoveHalfNodes ( tree . root ) ; System . out . print ( " Inorder traversal of the modified tree "); tree . printInorder ( NewRoot ) ; } }


"Given a binary tree , print out all of its root | A binary tree node has data , pointer to left child and a pointer to right child ; Given a binary tree , print out all of its root - to - leaf paths , one per line . Uses a recursive helper to do the work . ; Recursive helper function -- given a node , and an array containing the path from the root node up to but not including this node , print out all the root - leaf paths . ; append this node to the path array ; it 's a leaf, so print the path that led to here  ; otherwise try both subtrees ; Utility that prints out an array on a line ; Driver program to test all above functions ; Print all root - to - leaf paths of the input tree"
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 ; void printPaths ( Node node ) { int path [ ] = new int [ 1000 ] ; printPathsRecur ( node , path , 0 ) ; } void printPathsRecur ( Node node , int path [ ] , int pathLen ) { if ( node == null ) return ; path [ pathLen ] = node . data ; pathLen ++ ; if ( node . left == null && node . right == null ) printArray ( path , pathLen ) ; else { printPathsRecur ( node . left , path , pathLen ) ; printPathsRecur ( node . right , path , pathLen ) ; } } void printArray ( int ints [ ] , int len ) { int i ; for ( i = 0 ; i < len ; i ++ ) System . out . print ( ints [ i ] + " ▁ " ) ; System . out . println ( " " ) ; } public static void main ( String [ ] args ) { BinaryTree tree = new BinaryTree ( ) ; tree . root = new Node ( 1 ) ; tree . root . left = new Node ( 2 ) ; tree . root . right = new Node ( 3 ) ; tree . root . left . left = new Node ( 4 ) ; tree . root . left . right = new Node ( 5 ) ; tree . printPaths ( tree . root ) ; } }


"Given a large number , check if a subsequence of digits is divisible by 8 | Java program to check if a subsequence of digits is divisible by 8. ; Function to calculate any permutation divisible by 8. If such permutation exists , the function will return that permutation else it will return - 1 ; Converting string to integer array for ease of computations ( Indexing in arr [ ] is considered to be starting from 1 ) ; Generating all possible permutations and checking if any such permutation is divisible by 8 ; Driver function"
How can the above be solved in Java?

import java . io . * ; class GFG { static boolean isSubSeqDivisible ( String str ) { int i , j , k , l = str . length ( ) ; int arr [ ] = new int [ l ] ; for ( i = 0 ; i < l ; i ++ ) arr [ i ] = str . charAt ( i ) - '0' ; for ( i = 0 ; i < l ; i ++ ) { for ( j = i ; j < l ; j ++ ) { for ( k = j ; k < l ; k ++ ) { if ( arr [ i ] % 8 == 0 ) return true ; else if ( ( arr [ i ] * 10 + arr [ j ] ) % 8 == 0 && i != j ) return true ; else if ( ( arr [ i ] * 100 + arr [ j ] * 10 + arr [ k ] ) % 8 == 0 && i != j && j != k && i != k ) return true ; } } } return false ; } public static void main ( String args [ ] ) { String str = "3144" ; if ( isSubSeqDivisible ( str ) ) System . out . println ( " Yes " ) ; else System . out . println ( " No " ) ; } }


"Given a large number , check if a subsequence of digits is divisible by 8 | Java program to check if given String has a subsequence divisible by 8 ; Driver code ; map key will be tens place digit of number that is divisible by 8 and value will be units place digit ; For filling the map let start with initial value 8 ; key is digit at tens place and value is digit at units place mp . add ( { key , value } ) if ( mp . containsKey ( ( no / 10 ) % 10 ) ) ; Create a hash to check if we visited a number ; Iterate from last index to 0 th index ; If 8 is present in String then 8 divided 8 hence print yes ; considering present character as the second digit of two digits no we check if the value of this key is marked in hash or not If marked then we a have a number divisible by 8 ; If no subsequence divisible by 8"
How can the above be solved in Java?

import java . util . * ; class GFG { public static void main ( String [ ] args ) { String str = "129365" ; HashMap < Integer , Integer > mp = new HashMap < Integer , Integer > ( ) ; int no = 8 ; while ( no < 100 ) { no = no + 8 ; mp . put ( ( no / 10 ) % 10 , no % 10 ) ; } boolean [ ] visited = new boolean [ 10 ] ; int i ; for ( i = str . length ( ) - 1 ; i >= 0 ; i -- ) { if ( str . charAt ( i ) == '8' ) { System . out . print ( " Yes " ) ; break ; } if ( visited [ mp . get ( str . charAt ( i ) - '0' ) ] ) { System . out . print ( " Yes " ) ; break ; } visited [ str . charAt ( i ) - '0' ] = true ; } if ( i == - 1 ) System . out . print ( " No " ) ; } }


"Given a large number , check if a subsequence of digits is divisible by 8 | Java program to find if there is a subsequence of digits divisible by 8. ; Function takes in an array of numbers , dynamically goes on the location and makes combination of numbers . ; Converting string to integer array for ease of computations ( Indexing in arr [ ] is considered to be starting from 1 ) ; If we consider the number in our combination , we add it to the previous combination ; If we exclude the number from our combination ; If at dp [ i ] [ 0 ] , we find value 1 / true , it shows that the number exists at the value of ' i ' ; Driver function"
How can the above be solved in Java?

import java . io . * ; import java . util . * ; class GFG { static boolean isSubSeqDivisible ( String str ) { int n = str . length ( ) ; int dp [ ] [ ] = new int [ n + 1 ] [ 10 ] ; int arr [ ] = new int [ n + 1 ] ; for ( int i = 1 ; i <= n ; i ++ ) arr [ i ] = ( int ) ( str . charAt ( i - 1 ) - '0' ) ; for ( int i = 1 ; i <= n ; i ++ ) { dp [ i ] [ arr [ i ] % 8 ] = 1 ; for ( int j = 0 ; j < 8 ; j ++ ) { if ( dp [ i - 1 ] [ j ] > dp [ i ] [ ( j * 10 + arr [ i ] ) % 8 ] ) dp [ i ] [ ( j * 10 + arr [ i ] ) % 8 ] = dp [ i - 1 ] [ j ] ; if ( dp [ i - 1 ] [ j ] > dp [ i ] [ j ] ) dp [ i ] [ j ] = dp [ i - 1 ] [ j ] ; } } for ( int i = 1 ; i <= n ; i ++ ) { if ( dp [ i ] [ 0 ] == 1 ) return true ; } return false ; } public static void main ( String args [ ] ) { String str = "3144" ; if ( isSubSeqDivisible ( str ) ) System . out . println ( " Yes " ) ; else System . out . println ( " No " ) ; } }


"Given a matrix of ' O ' and ' X ' , find the largest subsquare surrounded by ' X ' | Size of given matrix is N X N ; Initialize maxside with 0 ; Fill the dp matrix horizontally . for contiguous ' X ' increment the value of x , otherwise make it 0 ; Fill the dp matrix vertically . For contiguous ' X ' increment the value of y , otherwise make it 0 ; Now check , for every value of ( i , j ) if sub - square is possible , traverse back horizontally by value val , and check if vertical contiguous ' X ' enfing at ( i , j - val + 1 ) is greater than equal to val . Similarly , check if traversing back vertically , the horizontal contiguous ' X ' ending at ( i - val + 1 , j ) is greater than equal to val . ; store the final answer in maxval ; return the final answe . ; Driver code ; Function call"
How can the above be solved in Java?

class GFG { static int N = 6 ; static int maximumSubSquare ( int [ ] [ ] arr ) { int [ ] [ ] [ ] dp = new int [ 51 ] [ 51 ] [ 2 ] ; int [ ] [ ] maxside = new int [ 51 ] [ 51 ] ; for ( int [ ] row : maxside ) Arrays . fill ( row , 10 ) ; int x = 0 , y = 0 ; for ( int i = 0 ; i < N ; i ++ ) { x = 0 ; for ( int j = 0 ; j < N ; j ++ ) { if ( arr [ i ] [ j ] == ' X ' ) x += 1 ; else x = 0 ; dp [ i ] [ j ] [ 0 ] = x ; } } for ( int i = 0 ; i < N ; i ++ ) { for ( int j = 0 ; j < N ; j ++ ) { if ( arr [ j ] [ i ] == ' X ' ) y += 1 ; else y = 0 ; dp [ j ] [ i ] [ 1 ] = y ; } } int maxval = 0 , val = 0 ; for ( int i = 0 ; i < N ; i ++ ) { for ( int j = 0 ; j < N ; j ++ ) { val = Math . min ( dp [ i ] [ j ] [ 0 ] , dp [ i ] [ j ] [ 1 ] ) ; if ( dp [ i ] [ j - val + 1 ] [ 1 ] >= val && dp [ i - val + 1 ] [ j ] [ 0 ] >= val ) maxside [ i ] [ j ] = val ; else maxside [ i ] [ j ] = 0 ; maxval = Math . max ( maxval , maxside [ i ] [ j ] ) ; } } return maxval ; } public static void main ( String [ ] args ) { int mat [ ] [ ] = { { ' X ' , ' O ' , ' X ' , ' X ' , ' X ' , ' X ' } , { ' X ' , ' O ' , ' X ' , ' X ' , ' O ' , ' X ' } , { ' X ' , ' X ' , ' X ' , ' O ' , ' O ' , ' X ' } , { ' O ' , ' X ' , ' X ' , ' X ' , ' X ' , ' X ' } , { ' X ' , ' X ' , ' X ' , ' O ' , ' X ' , ' O ' } , { ' O ' , ' O ' , ' X ' , ' O ' , ' O ' , ' O ' } , } ; System . out . println ( maximumSubSquare ( mat ) ) ; } }


"Given a matrix of ‘ O ’ and ‘ X ’ , replace ' O ' with ' X ' if surrounded by ' X ' | A Java program to replace all ' O ' s with ' X ' ' s ▁ if ▁ surrounded ▁ by ▁ ' X ' ; Size of given matrix is M X N ; A recursive function to replace previous value ' prevV ' at ' ( x , ▁ y ) ' and all surrounding values of ( x , y ) with new value ' newV ' . ; Base cases ; Replace the color at ( x , y ) ; Recur for north , east , south and west ; Returns size of maximum size subsquare matrix surrounded by ' X ' ; Step 1 : Replace all ' O ' with ' - ' ; Call floodFill for all ' - ' lying on edges Left side ; Right side ; Top side ; Bottom side ; Step 3 : Replace all ' - ' with ' X ' ; Driver Code"
How can the above be solved in Java?

import java . io . * ; class GFG { static int M = 6 ; static int N = 6 ; static void floodFillUtil ( char mat [ ] [ ] , int x , int y , char prevV , char newV ) { if ( x < 0 x >= M y < 0 y >= N ) return ; if ( mat [ x ] [ y ] != prevV ) return ; mat [ x ] [ y ] = newV ; floodFillUtil ( mat , x + 1 , y , prevV , newV ) ; floodFillUtil ( mat , x - 1 , y , prevV , newV ) ; floodFillUtil ( mat , x , y + 1 , prevV , newV ) ; floodFillUtil ( mat , x , y - 1 , prevV , newV ) ; } static void replaceSurrounded ( char mat [ ] [ ] ) { for ( int i = 0 ; i < M ; i ++ ) for ( int j = 0 ; j < N ; j ++ ) if ( mat [ i ] [ j ] == ' O ' ) mat [ i ] [ j ] = ' - ' ; for ( int i = 0 ; i < M ; i ++ ) if ( mat [ i ] [ 0 ] == ' - ' ) floodFillUtil ( mat , i , 0 , ' - ' , ' O ' ) ; for ( int i = 0 ; i < M ; i ++ ) if ( mat [ i ] [ N - 1 ] == ' - ' ) floodFillUtil ( mat , i , N - 1 , ' - ' , ' O ' ) ; for ( int i = 0 ; i < N ; i ++ ) if ( mat [ 0 ] [ i ] == ' - ' ) floodFillUtil ( mat , 0 , i , ' - ' , ' O ' ) ; for ( int i = 0 ; i < N ; i ++ ) if ( mat [ M - 1 ] [ i ] == ' - ' ) floodFillUtil ( mat , M - 1 , i , ' - ' , ' O ' ) ; for ( int i = 0 ; i < M ; i ++ ) for ( int j = 0 ; j < N ; j ++ ) if ( mat [ i ] [ j ] == ' - ' ) mat [ i ] [ j ] = ' X ' ; } public static void main ( String [ ] args ) { char [ ] [ ] mat = { { ' X ' , ' O ' , ' X ' , ' O ' , ' X ' , ' X ' } , { ' X ' , ' O ' , ' X ' , ' X ' , ' O ' , ' X ' } , { ' X ' , ' X ' , ' X ' , ' O ' , ' X ' , ' X ' } , { ' O ' , ' X ' , ' X ' , ' X ' , ' X ' , ' X ' } , { ' X ' , ' X ' , ' X ' , ' O ' , ' X ' , ' O ' } , { ' O ' , ' O ' , ' X ' , ' O ' , ' O ' , ' O ' } } ; replaceSurrounded ( mat ) ; for ( int i = 0 ; i < M ; i ++ ) { for ( int j = 0 ; j < N ; j ++ ) System . out . print ( mat [ i ] [ j ] + " ▁ " ) ; System . out . println ( " " ) ; } } }


"Given a number N in decimal base , find number of its digits in any base ( base b ) | Java program to Find Number of digits in base b . ; function to print number of digits ; Calculating log using base changing property and then taking it floor and then adding 1. ; printing output ; Driver method ; taking inputs ; calling the method"
How can the above be solved in Java?

class GFG { static void findNumberOfDigits ( long n , int base ) { int dig = ( int ) ( Math . floor ( Math . log ( n ) / Math . log ( base ) ) + 1 ) ; System . out . println ( " The ▁ Number ▁ of ▁ digits ▁ of ▁ Number ▁ " + n + " ▁ in ▁ base ▁ " + base + " ▁ is ▁ " + dig ) ; } public static void main ( String [ ] args ) { long n = 1446 ; int base = 7 ; findNumberOfDigits ( n , base ) ; } }


"Given a number N in decimal base , find the sum of digits in any base B | Java Implementation to Compute Sum of Digits of Number N in Base B ; Function to compute sum of Digits of Number N in base B ; Initialize sum with 0 ; Compute unit digit of the number ; Add unit digit in sum ; Update value of Number ; Driver code"
How can the above be solved in Java?

class GFG { static int sumOfDigit ( int n , int b ) { int unitDigit , sum = 0 ; while ( n > 0 ) { unitDigit = n % b ; sum += unitDigit ; n = n / b ; } return sum ; } public static void main ( String [ ] args ) { int n = 50 ; int b = 2 ; System . out . print ( sumOfDigit ( n , b ) ) ; } }


"Given a number as a string , find the number of contiguous subsequences which recursively add up to 9 | Java program to count substrings with recursive sum equal to 9 ; To store result ; Consider every character as beginning of substring ; sum of digits in current substring ; One by one choose every character as an ending character ; Add current digit to sum , if sum becomes multiple of 5 then increment count . Let us do modular arithmetic to avoid overflow for big strings ; Driver Code"
How can the above be solved in Java?

import java . io . * ; class GFG { static int count9s ( String number ) { int count = 0 ; int n = number . length ( ) ; for ( int i = 0 ; i < n ; i ++ ) { int sum = number . charAt ( i ) - '0' ; if ( number . charAt ( i ) == '9' ) count ++ ; for ( int j = i + 1 ; j < n ; j ++ ) { sum = ( sum + number . charAt ( j ) - '0' ) % 9 ; if ( sum == 0 ) count ++ ; } } return count ; } public static void main ( String [ ] args ) { System . out . println ( count9s ( "4189" ) ) ; System . out . println ( count9s ( "1809" ) ) ; } }


"Given a number as a string , find the number of contiguous subsequences which recursively add up to 9 | Set 2 | Java program to count substrings with recursive sum equal to 9 ; to store no . of previous encountered modular sums ; no . of modular sum ( == 0 ) encountered till now = 1 ; if number is 0 increase ; no . of continuous_zero by 1 ; else continuous_zero is 0 ; increase d value of this mod_sum ; subtract no . of cases where there are only zeroes in substring ; driver program to test above function"
How can the above be solved in Java?

class GFG { static int count9s ( char number [ ] ) { int n = number . length ; int d [ ] = new int [ 9 ] ; d [ 0 ] = 1 ; int result = 0 ; int mod_sum = 0 , continuous_zero = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( ( number [ i ] - '0' ) == 0 ) { continuous_zero ++ ; } else { continuous_zero = 0 ; } mod_sum += ( number [ i ] - '0' ) ; mod_sum %= 9 ; result += d [ mod_sum ] ; d [ mod_sum ] ++ ; result -= continuous_zero ; } return result ; } public static void main ( String [ ] args ) { System . out . println ( count9s ( "01809" . toCharArray ( ) ) ) ; System . out . println ( count9s ( "1809" . toCharArray ( ) ) ) ; System . out . println ( count9s ( "4189" . toCharArray ( ) ) ) ; } }


"Given a number n , count all multiples of 3 and / or 5 in set { 1 , 2 , 3 , ... n } | Java program to find count of multiples of 3 and 5 in { 1 , 2 , 3 , . . n } ; Add multiples of 3 and 5. Since common multiples are counted twice in n / 3 + n / 15 , subtract common multiples ; Driver Code"
How can the above be solved in Java?

import java . io . * ; class GFG { static long countOfMultiples ( long n ) { return ( n / 3 + n / 5 - n / 15 ) ; } static public void main ( String [ ] args ) { System . out . println ( countOfMultiples ( 6 ) ) ; System . out . println ( countOfMultiples ( 16 ) ) ; } }


"Given a number n , find the first k digits of n ^ n | Java program to find the first k digits of n ^ n ; function that manually calculates n ^ n and then removes digits until k digits remain ; loop will terminate when there are only k digits left ; Driver code"
How can the above be solved in Java?

public class Digits { static long firstkdigits ( int n , int k ) { long product = 1 ; for ( int i = 0 ; i < n ; i ++ ) product *= n ; while ( ( int ) ( product / Math . pow ( 10 , k ) ) != 0 ) product = product / 10 ; return product ; } public static void main ( String [ ] args ) { int n = 15 ; int k = 4 ; System . out . println ( firstkdigits ( n , k ) ) ; } }


"Given a number n , find the first k digits of n ^ n | Java program to find the first k digits of n ^ n ; function that manually calculates n ^ n and then removes digits until k digits remain ; take log10 of n ^ n . log10 ( n ^ n ) = n * log10 ( n ) ; We will now try to separate the decimal and integral part of the / product . The floor function returns the smallest integer less than or equal to the argument . So in this case , product - floor ( product ) will give us the decimal part of product ; we will now exponentiate this back by raising 10 to the power of decimal part ; We now try to find the power of 10 by which we will have to multiply the decimal part to obtain our final answer ; driver function"
How can the above be solved in Java?

import java . util . * ; import java . lang . * ; import java . io . * ; class KDigitSquare { public static long firstkdigits ( int n , int k ) { double product = n * Math . log10 ( n ) ; double decimal_part = product - Math . floor ( product ) ; decimal_part = Math . pow ( 10 , decimal_part ) ; double digits = Math . pow ( 10 , k - 1 ) , i = 0 ; return ( ( long ) ( decimal_part * digits ) ) ; } public static void main ( String [ ] args ) { int n = 1450 ; int k = 6 ; System . out . println ( firstkdigits ( n , k ) ) ; } }


"Given a set , find XOR of the XOR 's of all subsets. | Java program to find XOR of XOR 's of all subsets ; Returns XOR of all XOR 's of given subset ; XOR is 1 only when n is 1 , else 0 ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { static int findXOR ( int Set [ ] , int n ) { if ( n == 1 ) return Set [ 0 ] ; else return 0 ; } public static void main ( String arg [ ] ) { int Set [ ] = { 1 , 2 , 3 } ; int n = Set . length ; System . out . print ( " XOR ▁ of ▁ XOR ' s ▁ of ▁ all ▁ subsets ▁ is ▁ " + findXOR ( Set , n ) ) ; } }


"Given a sorted and rotated array , find if there is a pair with a given sum | Java program to find a pair with a given sum in a sorted and rotated array ; This function returns true if arr [ 0. . n - 1 ] has a pair with sum equals to x . ; Find the pivot element ; l is now index of ; smallest element r is now index of largest ; element Keep moving either l or r till they meet ; If we find a pair with sum x , we return true ; If current pair sum is less , move to the higher sum ; Move to the lower sum side ; Driver program to test above function"
How can the above be solved in Java?

class PairInSortedRotated { static boolean pairInSortedRotated ( int arr [ ] , int n , int x ) { int i ; for ( i = 0 ; i < n - 1 ; i ++ ) if ( arr [ i ] > arr [ i + 1 ] ) break ; int l = ( i + 1 ) % n ; int r = i ; while ( l != r ) { if ( arr [ l ] + arr [ r ] == x ) return true ; if ( arr [ l ] + arr [ r ] < x ) l = ( l + 1 ) % n ; else r = ( n + r - 1 ) % n ; } return false ; } public static void main ( String [ ] args ) { int arr [ ] = { 11 , 15 , 6 , 8 , 9 , 10 } ; int sum = 16 ; int n = arr . length ; if ( pairInSortedRotated ( arr , n , sum ) ) System . out . print ( " Array ▁ has ▁ two ▁ elements " + " ▁ with ▁ sum ▁ 16" ) ; else System . out . print ( " Array ▁ doesn ' t ▁ have ▁ two " + " ▁ elements ▁ with ▁ sum ▁ 16 ▁ " ) ; } }


"Given a sorted and rotated array , find if there is a pair with a given sum | Java program to find number of pairs with a given sum in a sorted and rotated array . ; This function returns count of number of pairs with sum equals to x . ; Find the pivot element . Pivot element is largest element of array . ; l is index of smallest element . ; r is index of largest element . ; Variable to store count of number of pairs . ; Find sum of pair formed by arr [ l ] and arr [ r ] and update l , r and cnt accordingly . ; If we find a pair with sum x , then increment cnt , move l and r to next element . ; This condition is required to be checked , otherwise l and r will cross each other and loop will never terminate . ; If current pair sum is less , move to the higher sum side . ; If current pair sum is greater , move to the lower sum side . ; Driver Code"
How can the above be solved in Java?

import java . io . * ; class GFG { static int pairsInSortedRotated ( int arr [ ] , int n , int x ) { int i ; for ( i = 0 ; i < n - 1 ; i ++ ) if ( arr [ i ] > arr [ i + 1 ] ) break ; int l = ( i + 1 ) % n ; int r = i ; int cnt = 0 ; while ( l != r ) { if ( arr [ l ] + arr [ r ] == x ) { cnt ++ ; if ( l == ( r - 1 + n ) % n ) { return cnt ; } l = ( l + 1 ) % n ; r = ( r - 1 + n ) % n ; } else if ( arr [ l ] + arr [ r ] < x ) l = ( l + 1 ) % n ; else r = ( n + r - 1 ) % n ; } return cnt ; } public static void main ( String [ ] args ) { int arr [ ] = { 11 , 15 , 6 , 7 , 9 , 10 } ; int sum = 16 ; int n = arr . length ; System . out . println ( pairsInSortedRotated ( arr , n , sum ) ) ; } }


"Given a sorted array and a number x , find the pair in array whose sum is closest to x | Java program to find pair with sum closest to x ; Prints the pair with sum cloest to x ; To store indexes of result pair ; Initialize left and right indexes and difference between pair sum and x ; While there are elements between l and r ; Check if this pair is closer than the closest pair so far ; If this pair has more sum , move to smaller values . ; Move to larger values ; Driver program to test above function"
How can the above be solved in Java?

import java . io . * ; import java . util . * ; import java . lang . Math ; class CloseSum { static void printClosest ( int arr [ ] , int n , int x ) { int res_l = 0 , res_r = 0 ; int l = 0 , r = n - 1 , diff = Integer . MAX_VALUE ; while ( r > l ) { if ( Math . abs ( arr [ l ] + arr [ r ] - x ) < diff ) { res_l = l ; res_r = r ; diff = Math . abs ( arr [ l ] + arr [ r ] - x ) ; } if ( arr [ l ] + arr [ r ] > x ) r -- ; else l ++ ; } System . out . println ( " ▁ The ▁ closest ▁ pair ▁ is ▁ " + arr [ res_l ] + " ▁ and ▁ " + arr [ res_r ] ) ; } public static void main ( String [ ] args ) { int arr [ ] = { 10 , 22 , 28 , 29 , 30 , 40 } , x = 54 ; int n = arr . length ; printClosest ( arr , n , x ) ; } }


"Given a string , find its first non | JAVA program to find first non - repeating character ; this function return the index of first non - repeating character if found , or else it returns - 1 ; initializing all elements to - 1 ; sets all repeating characters to - 2 and non - repeating characters contain the index where they occur ; If this character is not - 1 or - 2 then it means that this character occurred only once so find the min index of all characters that occur only once , that 's our first index ; if res remains Integer . MAX_VALUE , it means there are no characters that repeat only once or the string is empty"
How can the above be solved in Java?

public class GFG { public static int firstNonRepeating ( String str ) { int [ ] fi = new int [ 256 ] ; for ( int i = 0 ; i < 256 ; i ++ ) fi [ i ] = - 1 ; for ( int i = 0 ; i < str . length ( ) ; i ++ ) { if ( fi [ str . charAt ( i ) ] == - 1 ) { fi [ str . charAt ( i ) ] = i ; } else { fi [ str . charAt ( i ) ] = - 2 ; } } int res = Integer . MAX_VALUE ; for ( int i = 0 ; i < 256 ; i ++ ) { if ( fi [ i ] >= 0 ) res = Math . min ( res , fi [ i ] ) ; } if ( res == Integer . MAX_VALUE ) return - 1 ; else return res ; } public static void main ( String args [ ] ) { String str ; str = " geeksforgeeks " ; int firstIndex = firstNonRepeating ( str ) ; if ( firstIndex == - 1 ) System . out . println ( " Either ▁ all ▁ characters ▁ are ▁ repeating ▁ or ▁ string ▁ is ▁ empty " ) ; else System . out . println ( " First ▁ non - repeating ▁ character ▁ is ▁ " + str . charAt ( firstIndex ) ) ; } }


"Given a string , find its first non | Java program to find first non - repeating character ; calculate count of characters in the passed string ; The method returns index of first non - repeating character in a string . If all characters are repeating then returns - 1 ; Driver method"
How can the above be solved in Java?

class GFG { static final int NO_OF_CHARS = 256 ; static char count [ ] = new char [ NO_OF_CHARS ] ; static void getCharCountArray ( String str ) { for ( int i = 0 ; i < str . length ( ) ; i ++ ) count [ str . charAt ( i ) ] ++ ; } static int firstNonRepeating ( String str ) { getCharCountArray ( str ) ; int index = - 1 , i ; for ( i = 0 ; i < str . length ( ) ; i ++ ) { if ( count [ str . charAt ( i ) ] == 1 ) { index = i ; break ; } } return index ; } public static void main ( String [ ] args ) { String str = " geeksforgeeks " ; int index = firstNonRepeating ( str ) ; System . out . println ( index == - 1 ? " Either ▁ all ▁ characters ▁ are ▁ repeating ▁ or ▁ string ▁ " + " is ▁ empty " : " First ▁ non - repeating ▁ character ▁ is ▁ " + str . charAt ( index ) ) ; } }


"Given an array A [ ] and a number x , check for pair in A [ ] with sum as x | Code in Java to tell if there exists a pair in array whose sum results in x . ; Function to print pairs ; initializing the rem values with 0 's. ; Perform the remainder operation only if the element is x , as numbers greater than x can 't  be used to get a sum x.  Updating the count of remainders. ; Traversing the remainder list from start to middle to find pairs ; The elements with remainders i and x - i will result to a sum of x . Once we get two elements which add up to x , we print x and break . ; Once we reach middle of remainder array , we have to do operations based on x . ; if x is even and we have more than 1 elements with remainder x / 2 , then we will have two distinct elements which add up to x . if we dont have more than 1 element , print " No " . ; When x is odd we continue the same process which we did in previous loop . ; Driver Code ; Function calling"
How can the above be solved in Java?

 import java . util . * ; class GFG { static void printPairs ( int a [ ] , int n , int x ) { int i ; int [ ] rem = new int [ x ] ; for ( i = 0 ; i < x ; i ++ ) { rem [ i ] = 0 ; } for ( i = 0 ; i < n ; i ++ ) { if ( a [ i ] < x ) { rem [ a [ i ] % x ] ++ ; } } for ( i = 1 ; i < x / 2 ; i ++ ) { if ( rem [ i ] > 0 && rem [ x - i ] > 0 ) { System . out . print ( " Yes " + "
"); break ; } } if ( i >= x / 2 ) { if ( x % 2 == 0 ) { if ( rem [ x / 2 ] > 1 ) { System . out . print ( " Yes " + "
"); } else { System . out . print ( " No " + "
"); } } else { if ( rem [ x / 2 ] > 0 && rem [ x - x / 2 ] > 0 ) { System . out . print ( " Yes " + "
"); } else { System . out . print ( " No " + "
"); } } } } public static void main ( String [ ] args ) { int A [ ] = { 1 , 4 , 45 , 6 , 10 , 8 } ; int n = 16 ; int arr_size = A . length ; printPairs ( A , arr_size , n ) ; } }


"Given an array A [ ] and a number x , check for pair in A [ ] with sum as x | Java implementation using Hashing ; function to check for the given sum in the array ; checking for condition ; Driver Code"
How can the above be solved in Java?

import java . io . * ; import java . util . HashSet ; class PairSum { static void printpairs ( int arr [ ] , int sum ) { HashSet < Integer > s = new HashSet < Integer > ( ) ; for ( int i = 0 ; i < arr . length ; ++ i ) { int temp = sum - arr [ i ] ; if ( s . contains ( temp ) ) { System . out . println ( " Pair ▁ with ▁ given ▁ sum ▁ " + sum + " ▁ is ▁ ( " + arr [ i ] + " , ▁ " + temp + " ) " ) ; } s . add ( arr [ i ] ) ; } } public static void main ( String [ ] args ) { int A [ ] = { 1 , 4 , 45 , 6 , 10 , 8 } ; int n = 16 ; printpairs ( A , n ) ; } }


"Given an array A [ ] and a number x , check for pair in A [ ] with sum as x | Java program to check if there exists a pair in array whose sum results in x . ; Function to find and print pair ; Driver code"
How can the above be solved in Java?

class GFG { static boolean chkPair ( int A [ ] , int size , int x ) { for ( int i = 0 ; i < ( size - 1 ) ; i ++ ) { for ( int j = ( i + 1 ) ; j < size ; j ++ ) { if ( A [ i ] + A [ j ] == x ) { System . out . println ( " Pair ▁ with ▁ a ▁ given ▁ sum ▁ " + x + " ▁ is ▁ ( " + A [ i ] + " , ▁ " + A [ j ] + " ) " ) ; return true ; } } } return false ; } public static void main ( String [ ] args ) { int A [ ] = { 0 , - 1 , 2 , - 3 , 1 } ; int x = - 2 ; int size = A . length ; if ( chkPair ( A , size , x ) ) { System . out . println ( " Valid ▁ pair ▁ exists " ) ; } else { System . out . println ( " No ▁ valid ▁ pair ▁ exists ▁ for ▁ " + x ) ; } } }


"Given an array and two integers l and r , find the kth largest element in the range [ l , r ] | Java implementation of the approach ; Function to calculate the prefix ; Creating one based indexing ; Initializing and creating prefix array ; Creating a prefix array for every possible value in a given range ; Function to return the kth largest element in the index range [ l , r ] ; Binary searching through the 2d array and only checking the range in which the sub array is a part ; Driver code ; Creating the prefix array for the given array ; Queries ; Perform queries"
How can the above be solved in Java?

import java . util . * ; class GFG { static int MAX = 1001 ; static int prefix [ ] [ ] = new int [ MAX ] [ MAX ] ; static int ar [ ] = new int [ MAX ] ; static void cal_prefix ( int n , int arr [ ] ) { int i , j ; for ( i = 0 ; i < n ; i ++ ) ar [ i + 1 ] = arr [ i ] ; for ( i = 1 ; i <= 1000 ; i ++ ) { for ( j = 0 ; j <= n ; j ++ ) prefix [ i ] [ j ] = 0 ; for ( j = 1 ; j <= n ; j ++ ) { prefix [ i ] [ j ] = prefix [ i ] [ j - 1 ] + ( int ) ( ar [ j ] <= i ? 1 : 0 ) ; } } } static int ksub ( int l , int r , int n , int k ) { int lo , hi , mid ; lo = 1 ; hi = 1000 ; while ( lo + 1 < hi ) { mid = ( lo + hi ) / 2 ; if ( prefix [ mid ] [ r ] - prefix [ mid ] [ l - 1 ] >= k ) hi = mid ; else lo = mid + 1 ; } if ( prefix [ lo ] [ r ] - prefix [ lo ] [ l - 1 ] >= k ) hi = lo ; return hi ; } public static void main ( String args [ ] ) { int arr [ ] = { 1 , 4 , 2 , 3 , 5 , 7 , 6 } ; int n = arr . length ; int k = 4 ; cal_prefix ( n , arr ) ; int queries [ ] [ ] = { { 1 , n , 1 } , { 2 , n - 2 , 2 } , { 3 , n - 1 , 3 } } ; int q = queries . length ; for ( int i = 0 ; i < q ; i ++ ) System . out . println ( ksub ( queries [ i ] [ 0 ] , queries [ i ] [ 1 ] , n , queries [ i ] [ 2 ] ) ) ; } }


"Given an array of pairs , find all symmetric pairs in it | A Java program to find all symmetric pairs in a given array of pairs ; Print all pairs that have a symmetric counterpart ; Creates an empty hashMap hM ; Traverse through the given array ; First and second elements of current pair ; Look for second element of this pair in hash ; If found and value in hash matches with first element of this pair , we found symmetry ; Else put sec element of this pair in hash ; Driver method"
How can the above be solved in Java?

import java . util . HashMap ; class SymmetricPairs { static void findSymPairs ( int arr [ ] [ ] ) { HashMap < Integer , Integer > hM = new HashMap < Integer , Integer > ( ) ; for ( int i = 0 ; i < arr . length ; i ++ ) { int first = arr [ i ] [ 0 ] ; int sec = arr [ i ] [ 1 ] ; Integer val = hM . get ( sec ) ; if ( val != null && val == first ) System . out . println ( " ( " + sec + " , ▁ " + first + " ) " ) ; else hM . put ( first , sec ) ; } } public static void main ( String arg [ ] ) { int arr [ ] [ ] = new int [ 5 ] [ 2 ] ; arr [ 0 ] [ 0 ] = 11 ; arr [ 0 ] [ 1 ] = 20 ; arr [ 1 ] [ 0 ] = 30 ; arr [ 1 ] [ 1 ] = 40 ; arr [ 2 ] [ 0 ] = 5 ; arr [ 2 ] [ 1 ] = 10 ; arr [ 3 ] [ 0 ] = 40 ; arr [ 3 ] [ 1 ] = 30 ; arr [ 4 ] [ 0 ] = 10 ; arr [ 4 ] [ 1 ] = 5 ; findSymPairs ( arr ) ; } }


"Given count of digits 1 , 2 , 3 , 4 , find the maximum sum possible | Java program to maximum possible sum ; Function to find the maximum possible sum ; To store required sum ; Number of 234 's can be formed ; Sum obtained with 234 s ; Remaining 2 's ; Sum obtained with 12 s ; Return the required sum ; Driver code"
How can the above be solved in Java?

class GFG { static int Maxsum ( int c1 , int c2 , int c3 , int c4 ) { int sum = 0 ; int two34 = Math . min ( c2 , Math . min ( c3 , c4 ) ) ; sum = two34 * 234 ; c2 -= two34 ; sum += Math . min ( c2 , c1 ) * 12 ; return sum ; } public static void main ( String [ ] args ) { int c1 = 5 , c2 = 2 , c3 = 3 , c4 = 4 ; System . out . println ( Maxsum ( c1 , c2 , c3 , c4 ) ) ; } }


"Given level order traversal of a Binary Tree , check if the Tree is a Min | Java program to check if a given tree is Binary Heap or not ; Returns true if given level order traversal is Min Heap . ; First non leaf node is at index ( n / 2 - 1 ) . Check whether each parent is greater than child ; Left child will be at index 2 * i + 1 Right child will be at index 2 * i + 2 ; If parent is greater than right child ; Driver code"
How can the above be solved in Java?

import java . io . * ; import java . util . * ; public class detheap { static boolean isMinHeap ( int [ ] level ) { int n = level . length - 1 ; for ( int i = ( n / 2 - 1 ) ; i >= 0 ; i -- ) { if ( level [ i ] > level [ 2 * i + 1 ] ) return false ; if ( 2 * i + 2 < n ) { if ( level [ i ] > level [ 2 * i + 2 ] ) return false ; } } return true ; } public static void main ( String [ ] args ) throws IOException { int [ ] level = new int [ ] { 10 , 15 , 14 , 25 , 30 } ; if ( isMinHeap ( level ) ) System . out . println ( " True " ) ; else System . out . println ( " False " ) ; } }


"Given number of matches played , find number of teams in tournament | Java implementation of the approach ; Function to return the number of teams ; To store both roots of the equation ; sqrt ( b ^ 2 - 4 ac ) ; First root ( - b + sqrt ( b ^ 2 - 4 ac ) ) / 2 a ; Second root ( - b - sqrt ( b ^ 2 - 4 ac ) ) / 2 a ; Return the positive root ; Driver code"
How can the above be solved in Java?

import java . io . * ; class GFG { static int number_of_teams ( int M ) { int N1 , N2 , sqr ; sqr = ( int ) Math . sqrt ( 1 + ( 8 * M ) ) ; N1 = ( 1 + sqr ) / 2 ; N2 = ( 1 - sqr ) / 2 ; if ( N1 > 0 ) return N1 ; return N2 ; } public static void main ( String [ ] args ) { int M = 45 ; System . out . println ( number_of_teams ( M ) ) ; } }


"Given two arrays count all pairs whose sum is an odd number | Java program to implement the above approach ; Function that returns the number of pairs ; Count of odd and even numbers ; Traverse in the first array and count the number of odd and evene numbers in them ; Traverse in the second array and count the number of odd and evene numbers in them ; Count the number of pairs ; Return the number of pairs ; Driver code"
How can the above be solved in Java?

class GFG { static int count_pairs ( int a [ ] , int b [ ] , int n , int m ) { int odd1 = 0 , even1 = 0 ; int odd2 = 0 , even2 = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( a [ i ] % 2 == 1 ) { odd1 ++ ; } else { even1 ++ ; } } for ( int i = 0 ; i < m ; i ++ ) { if ( b [ i ] % 2 == 1 ) { odd2 ++ ; } else { even2 ++ ; } } int pairs = Math . min ( odd1 , even2 ) + Math . min ( odd2 , even1 ) ; return pairs ; } public static void main ( String [ ] args ) { int a [ ] = { 9 , 14 , 6 , 2 , 11 } ; int b [ ] = { 8 , 4 , 7 , 20 } ; int n = a . length ; int m = b . length ; System . out . println ( count_pairs ( a , b , n , m ) ) ; } }


"Given two binary strings perform operation until B > 0 and print the result | Java implementation of the approach ; Function to return the required result ; Reverse the strings ; Count the number of set bits in b ; To store the powers of 2 ; power [ i ] = pow ( 2 , i ) % mod ; To store the final answer ; Add power [ i ] to the ans after multiplying it with the number of set bits in b ; Divide by 2 means right shift b >> 1 if b has 1 at right most side than number of set bits will get decreased ; If no more set bits in b i . e . b = 0 ; Return the required answer ;  ; Driver code"
How can the above be solved in Java?

class GFG { static int mod = ( int ) ( 1e9 + 7 ) ; static int BitOperations ( String a , int n , String b , int m ) { char [ ] ch1 = a . toCharArray ( ) ; reverse ( ch1 ) ; a = new String ( ch1 ) ; char [ ] ch2 = b . toCharArray ( ) ; reverse ( ch2 ) ; b = new String ( ch2 ) ; int c = 0 ; for ( int i = 0 ; i < m ; i ++ ) if ( b . charAt ( i ) == '1' ) c ++ ; int [ ] power = new int [ n ] ; power [ 0 ] = 1 ; for ( int i = 1 ; i < n ; i ++ ) power [ i ] = ( power [ i - 1 ] * 2 ) % mod ; int ans = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( a . charAt ( i ) == '1' ) { ans += c * power [ i ] ; if ( ans >= mod ) ans %= mod ; } if ( b . charAt ( i ) == '1' ) c -- ; if ( c == 0 ) break ; } return ans ; } static void reverse ( char a [ ] ) { int i , k , n = a . length ; char t ; for ( i = 0 ; i < n / 2 ; i ++ ) { t = a [ i ] ; a [ i ] = a [ n - i - 1 ] ; a [ n - i - 1 ] = t ; } } public static void main ( String [ ] args ) { String a = "1001" , b = "10101" ; int n = a . length ( ) , m = b . length ( ) ; System . out . println ( BitOperations ( a , n , b , m ) ) ; } }


"Given two numbers a and b find all x such that a % x = b | Java program to find x such that a % x is equal to b . ; if a is less than b then no solution ; if a is equal to b then every number greater than a will be the solution so its infinity ; count variable store the number of values possible ; checking for both divisor and quotient whether they divide ( a - b ) completely and greater than b . ; Here y is added twice in the last iteration so 1 y should be decremented to get correct solution ; Driver code"
How can the above be solved in Java?

import java . io . * ; class GFG { static void modularEquation ( int a , int b ) { if ( a < b ) { System . out . println ( " No ▁ solution ▁ possible ▁ " ) ; return ; } if ( a == b ) { System . out . println ( " Infinite ▁ Solution ▁ possible ▁ " ) ; return ; } int count = 0 ; int n = a - b ; int y = ( int ) Math . sqrt ( a - b ) ; for ( int i = 1 ; i <= y ; ++ i ) { if ( n % i == 0 ) { if ( n / i > b ) count ++ ; if ( i > b ) count ++ ; } } if ( y * y == n && y > b ) count -- ; System . out . println ( count ) ; } public static void main ( String [ ] args ) { int a = 21 , b = 5 ; modularEquation ( a , b ) ; } }


"Given two numbers as strings , find if one is a power of other | Java program to check if one number is power of other ; Multiply the numbers . It multiplies each digit of second string to each digit of first and stores the result . ; If the digit exceeds 9 , add the cumulative carry to previous digit . ; if all zeroes , return "0" . ; Remove starting zeroes . ; Removes Extra zeroes from front of a string . ; Make sure there are no leading zeroes in the string . ; Making sure that s1 is smaller . If it is greater , we recur we reversed parameters . ; Driver Code"
How can the above be solved in Java?

import java . util . * ; class new_file { static boolean isGreaterThanEqual ( String s1 , String s2 ) { if ( s1 . length ( ) > s2 . length ( ) ) return true ; if ( s1 . compareTo ( s2 ) == 0 ) return true ; return false ; } static String multiply ( String s1 , String s2 ) { int n = s1 . length ( ) ; int m = s2 . length ( ) ; int [ ] result = new int [ n + m ] ; for ( int i = n - 1 ; i >= 0 ; i -- ) for ( int j = m - 1 ; j >= 0 ; j -- ) result [ i + j + 1 ] += ( s1 . charAt ( i ) - '0' ) * ( s2 . charAt ( j ) - '0' ) ; int size = result . length ; for ( int i = size - 1 ; i > 0 ; i -- ) { if ( result [ i ] >= 10 ) { result [ i - 1 ] += result [ i ] / 10 ; result [ i ] = result [ i ] % 10 ; } } int i = 0 ; while ( i < size && result [ i ] == 0 ) i ++ ; if ( i == size ) return "0" ; String temp = " " ; while ( i < size ) { temp += Integer . toString ( result [ i ] ) ; i ++ ; } return temp ; } static String removeLeadingZeores ( String s ) { int n = s . length ( ) ; int i = 0 ; while ( i < n && s . charAt ( i ) == '0' ) i ++ ; if ( i == n ) return "0" ; String temp = " " ; while ( i < n ) { temp += s . charAt ( i ) ; i ++ ; } return temp ; } static boolean isPower ( String s1 , String s2 ) { s1 = removeLeadingZeores ( s1 ) ; s2 = removeLeadingZeores ( s2 ) ; if ( s1 == "0" s2 == "0" ) return false ; if ( s1 == "1" && s2 == "1" ) return true ; if ( s1 == "1" s2 == "1" ) return true ; if ( s1 . length ( ) > s2 . length ( ) ) return isPower ( s2 , s1 ) ; String temp = new String ( s1 ) ; while ( ! isGreaterThanEqual ( s1 , s2 ) ) s1 = multiply ( s1 , temp ) ; if ( s1 . compareTo ( s2 ) == 0 ) return true ; return false ; } public static void main ( String [ ] args ) { String s1 = "374747" , s2 = "52627712618930723" ; if ( isPower ( s1 , s2 ) ) System . out . println ( " Yes " ) ; else System . out . println ( " No " ) ; s1 = "4099" ; s2 = "2" ; if ( isPower ( s1 , s2 ) ) System . out . println ( " Yes " ) ; else System . out . println ( " No " ) ; } }


"Given two strings , find if first string is a subsequence of second | Recursive Java program to check if a string is subsequence of another string ; Returns true if str1 [ ] is a subsequence of str2 [ ] m is length of str1 and n is length of str2 ; Base Cases ; If last characters of two strings are matching ; If last characters are not matching ; Driver program"
How can the above be solved in Java?

import java . io . * ; class SubSequence { static boolean isSubSequence ( String str1 , String str2 , int m , int n ) { if ( m == 0 ) return true ; if ( n == 0 ) return false ; if ( str1 . charAt ( m - 1 ) == str2 . charAt ( n - 1 ) ) return isSubSequence ( str1 , str2 , m - 1 , n - 1 ) ; return isSubSequence ( str1 , str2 , m , n - 1 ) ; } public static void main ( String [ ] args ) { String str1 = " gksrek " ; String str2 = " geeksforgeeks " ; int m = str1 . length ( ) ; int n = str2 . length ( ) ; boolean res = isSubSequence ( str1 , str2 , m , n ) ; if ( res ) System . out . println ( " Yes " ) ; else System . out . println ( " No " ) ; } }


"Given two strings check which string makes a palindrome first | Java program to check which string makes palindrome first . ; returns winner of two strings ; Count frequencies of characters in both given strings ; Check if there is a character that appears more than once in A and does not appear in B ; Driver Code"
How can the above be solved in Java?

public class First_Palin { static final int MAX_CHAR = 26 ; static char stringPalindrome ( String A , String B ) { int [ ] countA = new int [ MAX_CHAR ] ; int [ ] countB = new int [ MAX_CHAR ] ; int l1 = A . length ( ) ; int l2 = B . length ( ) ; for ( int i = 0 ; i < l1 ; i ++ ) countA [ A . charAt ( i ) - ' a ' ] ++ ; for ( int i = 0 ; i < l2 ; i ++ ) countB [ B . charAt ( i ) - ' a ' ] ++ ; for ( int i = 0 ; i < 26 ; i ++ ) if ( ( countA [ i ] > 1 && countB [ i ] == 0 ) ) return ' A ' ; return ' B ' ; } public static void main ( String args [ ] ) { String a = " abcdea " ; String b = " bcdesg " ; System . out . println ( stringPalindrome ( a , b ) ) ; } }


"Given two unsorted arrays , find all pairs whose sum is x | JAVA Code for Given two unsorted arrays , find all pairs whose sum is x ; Function to find all pairs in both arrays whose sum is equal to given value x ; Insert all elements of first array in a hash ; Subtract sum from second array elements one by one and check it 's present in array first  or not ; Driver program to test above function"
How can the above be solved in Java?

import java . util . * ; class GFG { public static void findPairs ( int arr1 [ ] , int arr2 [ ] , int n , int m , int x ) { HashMap < Integer , Integer > s = new HashMap < Integer , Integer > ( ) ; for ( int i = 0 ; i < n ; i ++ ) s . put ( arr1 [ i ] , 0 ) ; for ( int j = 0 ; j < m ; j ++ ) if ( s . containsKey ( x - arr2 [ j ] ) ) System . out . println ( x - arr2 [ j ] + " ▁ " + arr2 [ j ] ) ; } public static void main ( String [ ] args ) { int arr1 [ ] = { 1 , 0 , - 4 , 7 , 6 , 4 } ; int arr2 [ ] = { 0 , 2 , 4 , - 3 , 2 , 1 } ; int x = 8 ; findPairs ( arr1 , arr2 , arr1 . length , arr2 . length , x ) ; } }


"Given two unsorted arrays , find all pairs whose sum is x | Java program to find all pairs in both arrays whose sum is equal to given value x ; Function to print all pairs in both arrays whose sum is equal to given value x ; Driver code"
How can the above be solved in Java?

import java . io . * ; class GFG { static void findPairs ( int arr1 [ ] , int arr2 [ ] , int n , int m , int x ) { for ( int i = 0 ; i < n ; i ++ ) for ( int j = 0 ; j < m ; j ++ ) if ( arr1 [ i ] + arr2 [ j ] == x ) System . out . println ( arr1 [ i ] + " ▁ " + arr2 [ j ] ) ; } public static void main ( String [ ] args ) { int arr1 [ ] = { 1 , 2 , 3 , 7 , 5 , 4 } ; int arr2 [ ] = { 0 , 7 , 4 , 3 , 2 , 1 } ; int x = 8 ; findPairs ( arr1 , arr2 , arr1 . length , arr2 . length , x ) ; } }


"Gnome Sort | Java Program to implement Gnome Sort ; A function to sort the algorithm using gnome sort ; Driver program to test above functions ."
How can the above be solved in Java?

import java . util . Arrays ; public class GFG { static void gnomeSort ( int arr [ ] , int n ) { int index = 0 ; while ( index < n ) { if ( index == 0 ) index ++ ; if ( arr [ index ] >= arr [ index - 1 ] ) index ++ ; else { int temp = 0 ; temp = arr [ index ] ; arr [ index ] = arr [ index - 1 ] ; arr [ index - 1 ] = temp ; index -- ; } } return ; } public static void main ( String [ ] args ) { int arr [ ] = { 34 , 2 , 10 , - 9 } ; gnomeSort ( arr , arr . length ) ; System . out . print ( " Sorted ▁ sequence ▁ after ▁ applying ▁ Gnome ▁ sort : ▁ " ) ; System . out . println ( Arrays . toString ( arr ) ) ; } }


"Goldbach 's Weak Conjecture for Odd numbers | Function to check if a number can be represent as as a sum of 3 prime ; Driver code"
How can the above be solved in Java?

class GFG { static void check ( int n ) { if ( n % 2 == 1 && n > 5 ) { System . out . println ( " YES " ) ; } else { System . out . println ( " NO " ) ; } } public static void main ( String [ ] args ) { int a = 3 ; int b = 7 ; check ( a ) ; check ( b ) ; } }


"Golomb sequence | Java Program to find first n terms of Golomb sequence . ; Print the first n term of Golomb Sequence ; base cases ; Finding and printing first n terms of Golomb Sequence . ; Driver code"
How can the above be solved in Java?

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


"Golomb sequence | Java Program to find first n terms of Golomb sequence . ; Return the nth element of Golomb sequence ; base case ; Recursive Step ; Print the first n term of Golomb Sequence ; Finding first n terms of Golomb Sequence . ; Driver Code"
How can the above be solved in Java?

import java . util . * ; class GFG { public static int findGolomb ( int n ) { if ( n == 1 ) return 1 ; return 1 + findGolomb ( n - findGolomb ( findGolomb ( n - 1 ) ) ) ; } public static void printGolomb ( int n ) { for ( int i = 1 ; i <= n ; i ++ ) System . out . print ( findGolomb ( i ) + " ▁ " ) ; } public static void main ( String [ ] args ) { int n = 9 ; printGolomb ( n ) ; } }


"Gould 's Sequence | JAVA program to generate Gould 's Sequence ; 32768 = 2 ^ 15 ; Array to store Sequence up to 2 ^ 16 = 65536 ; Utility function to pre - compute odd numbers in ith row of Pascals 's triangle ; First term of the Sequence is 1 ; Initialize i to 1 ; Initialize p to 1 ( i . e 2 ^ i ) in each iteration i will be pth power of 2 ; loop to generate gould 's Sequence ; i is pth power of 2 traverse the array from j = 0 to i i . e ( 2 ^ p ) ; double the value of arr [ j ] and store to arr [ i + j ] ; update i to next power of 2 ; increment p ; Function to print gould 's Sequence ; loop to generate gould 's Sequence up to n ; Driver code ; Get n ; Function call"
How can the above be solved in Java?

class GFG { static final int MAX = 32768 ; static int [ ] arr = new int [ 2 * MAX ] ; static void gouldSequence ( ) { arr [ 0 ] = 1 ; int i = 1 ; int p = 1 ; while ( i <= MAX ) { int j = 0 ; while ( j < i ) { arr [ i + j ] = 2 * arr [ j ] ; j ++ ; } i = ( 1 << p ) ; p ++ ; } } static void printSequence ( int n ) { for ( int i = 0 ; i < n ; i ++ ) { System . out . print ( arr [ i ] + " ▁ " ) ; } } public static void main ( String [ ] args ) { gouldSequence ( ) ; int n = 16 ; printSequence ( n ) ; } }


"Gould 's Sequence | JAVA program to generate Gould 's Sequence ; Function to generate gould 's Sequence ; loop to generate each row of pascal 's Triangle up to nth row ; Loop to generate each element of ith row ; if c is odd increment count ; print count of odd elements ; Driver code ; Get n ; Function call"
How can the above be solved in Java?

class GFG { static void gouldSequence ( int n ) { for ( int row_num = 1 ; row_num <= n ; row_num ++ ) { int count = 1 ; int c = 1 ; for ( int i = 1 ; i <= row_num ; i ++ ) { c = c * ( row_num - i ) / i ; if ( c % 2 == 1 ) count ++ ; } System . out . print ( count + " ▁ " ) ; } } public static void main ( String [ ] args ) { int n = 16 ; gouldSequence ( n ) ; } }


"Gould 's Sequence | JAVA program to generate Gould 's Sequence ; Utility function to count odd numbers in ith row of Pascals 's triangle ; Initialize count as zero ; Return 2 ^ count ; Function to generate gould 's Sequence ; loop to generate gould 's Sequence up to n ; Driver code ; Get n ; Function call"
How can the above be solved in Java?

class GFG { static int countOddNumber ( int row_num ) { int count = 0 ; while ( row_num > 0 ) { count += row_num & 1 ; row_num >>= 1 ; } return ( 1 << count ) ; } static void gouldSequence ( int n ) { for ( int row_num = 0 ; row_num < n ; row_num ++ ) { System . out . print ( countOddNumber ( row_num ) + " ▁ " ) ; } } public static void main ( String [ ] args ) { int n = 16 ; gouldSequence ( n ) ; } }


"Graph and its representations | Java code to demonstrate Graph representation using ArrayList in Java ; A utility function to add an edge in an undirected graph ; A utility function to print the adjacency list representation of graph ; Driver Code ; Creating a graph with 5 vertices ; Adding edges one by one"
How can the above be solved in Java?

import java . util . * ; class Graph { static void addEdge ( ArrayList < ArrayList < Integer > > adj , int u , int v ) { adj . get ( u ) . add ( v ) ; adj . get ( v ) . add ( u ) ; } static void printGraph ( ArrayList < ArrayList < Integer > > adj ) { for ( int i = 0 ; i < adj . size ( ) ; i ++ ) { System . out . println ( " Adjacency list of vertex " + i); System . out . print ( " head " ) ; for ( int j = 0 ; j < adj . get ( i ) . size ( ) ; j ++ ) { System . out . print ( " ▁ - > ▁ " + adj . get ( i ) . get ( j ) ) ; } System . out . println ( ) ; } } public static void main ( String [ ] args ) { int V = 5 ; ArrayList < ArrayList < Integer > > adj = new ArrayList < ArrayList < Integer > > ( V ) ; for ( int i = 0 ; i < V ; i ++ ) adj . add ( new ArrayList < Integer > ( ) ) ; addEdge ( adj , 0 , 1 ) ; addEdge ( adj , 0 , 4 ) ; addEdge ( adj , 1 , 2 ) ; addEdge ( adj , 1 , 3 ) ; addEdge ( adj , 1 , 4 ) ; addEdge ( adj , 2 , 3 ) ; addEdge ( adj , 3 , 4 ) ; printGraph ( adj ) ; } }


"Graph representations using set and hash | A Java program to demonstrate adjacency list using HashMap and TreeSet representation of graphs using sets ; TreeSet is used to get clear understand of graph . ; Adds an edge to an undirected graph ; Add an edge from src to dest into the set ; Since graph is undirected , add an edge from dest to src into the set ; A utility function to print the graph ; Searches for a given edge in the graph ; Driver code ; Create the graph given in the above figure ; Print the adjacency list representation of the above graph ; Search the given edge in the graph"
How can the above be solved in Java?

import java . util . * ; class Graph { HashMap < Integer , TreeSet < Integer > > graph ; static int v ; public Graph ( ) { graph = new HashMap < > ( ) ; for ( int i = 0 ; i < v ; i ++ ) { graph . put ( i , new TreeSet < > ( ) ) ; } } public void addEdge ( int src , int dest ) { graph . get ( src ) . add ( dest ) ; graph . get ( dest ) . add ( src ) ; } public void printGraph ( ) { for ( int i = 0 ; i < v ; i ++ ) { System . out . println ( " Adjacency ▁ list ▁ of ▁ vertex ▁ " + i ) ; Iterator set = graph . get ( i ) . iterator ( ) ; while ( set . hasNext ( ) ) System . out . print ( set . next ( ) + " ▁ " ) ; System . out . println ( ) ; System . out . println ( ) ; } } public void searchEdge ( int src , int dest ) { Iterator set = graph . get ( src ) . iterator ( ) ; if ( graph . get ( src ) . contains ( dest ) ) System . out . println ( " Edge ▁ from ▁ " + src + " ▁ to ▁ " + dest + " ▁ found " ) ; else System . out . println ( " Edge ▁ from ▁ " + src + " ▁ to ▁ " + dest + " ▁ not ▁ found " ) ; System . out . println ( ) ; } public static void main ( String [ ] args ) { v = 5 ; Graph graph = new Graph ( ) ; graph . addEdge ( 0 , 1 ) ; graph . addEdge ( 0 , 4 ) ; graph . addEdge ( 1 , 2 ) ; graph . addEdge ( 1 , 3 ) ; graph . addEdge ( 1 , 4 ) ; graph . addEdge ( 2 , 3 ) ; graph . addEdge ( 3 , 4 ) ; graph . printGraph ( ) ; graph . searchEdge ( 2 , 1 ) ; graph . searchEdge ( 0 , 3 ) ; } }


"Gray to Binary and Binary to Gray conversion | Java Program for above approach ; Driver code"
How can the above be solved in Java?

public class Main { public static int greyConverter ( int n ) { return n ^ ( n >> 1 ) ; } public static void main ( String [ ] args ) { int n = 3 ; System . out . println ( greyConverter ( n ) ) ; n = 9 ; System . out . println ( greyConverter ( n ) ) ; } }


"Gray to Binary and Binary to Gray conversion | Java program for Binary To Gray and Gray to Binary conversion ; Helper function to xor two characters ; Helper function to flip the bit ; function to convert binary string to gray string ; MSB of gray code is same as binary code ; Compute remaining bits , next bit is computed by doing XOR of previous and current in Binary ; Concatenate XOR of previous bit with current bit ; function to convert gray code string to binary string ; MSB of binary code is same as gray code ; Compute remaining bits ; If current bit is 0 , concatenate previous bit ; Else , concatenate invert of previous bit ; Driver program to test above functions"
How can the above be solved in Java?

import java . io . * ; class code_conversion { char xor_c ( char a , char b ) { return ( a == b ) ? '0' : '1' ; } char flip ( char c ) { return ( c == '0' ) ? '1' : '0' ; } String binarytoGray ( String binary ) { String gray = " " ; gray += binary . charAt ( 0 ) ; for ( int i = 1 ; i < binary . length ( ) ; i ++ ) { gray += xor_c ( binary . charAt ( i - 1 ) , binary . charAt ( i ) ) ; } return gray ; } String graytoBinary ( String gray ) { String binary = " " ; binary += gray . charAt ( 0 ) ; for ( int i = 1 ; i < gray . length ( ) ; i ++ ) { if ( gray . charAt ( i ) == '0' ) binary += binary . charAt ( i - 1 ) ; else binary += flip ( binary . charAt ( i - 1 ) ) ; } return binary ; } public static void main ( String args [ ] ) throws IOException { code_conversion ob = new code_conversion ( ) ; String binary = "01001" ; System . out . println ( " Gray ▁ code ▁ of ▁ " + binary + " ▁ is ▁ " + ob . binarytoGray ( binary ) ) ; String gray = "01101" ; System . out . println ( " Binary ▁ code ▁ of ▁ " + gray + " ▁ is ▁ " + ob . graytoBinary ( gray ) ) ; } }


"Greatest Integer Function | Java program to illustrate greatest integer Function ; Function to calculate the GIF value of a number ; GIF is the floor of a number ; Driver code"
How can the above be solved in Java?

class GFG { static int GIF ( double n ) { return ( int ) Math . floor ( n ) ; } public static void main ( String [ ] args ) { double n = 2.3 ; System . out . println ( GIF ( n ) ) ; } }


"Greatest contiguous sub | Java implementation of the approach ; Function that returns the sub - array ; Data - structure to store all the sub - arrays of size K ; Iterate to find all the sub - arrays ; Store the sub - array elements in the array ; Push the vector in the container ; Sort the vector of elements ; The last sub - array in the sorted order will be the answer ; Driver code ; Get the sub - array"
How can the above be solved in Java?

import java . io . * ; import java . util . * ; class GFG { static ArrayList < Integer > findSubarray ( int a [ ] , int k , int n ) { ArrayList < ArrayList < Integer > > vec = new ArrayList < ArrayList < Integer > > ( ) ; for ( int i = 0 ; i < n - k + 1 ; i ++ ) { ArrayList < Integer > temp = new ArrayList < Integer > ( ) ; for ( int j = i ; j < i + k ; j ++ ) { temp . add ( a [ j ] ) ; } vec . add ( temp ) ; } Collections . sort ( vec , new Comparator < ArrayList < Integer > > ( ) { @ Override public int compare ( ArrayList < Integer > o1 , ArrayList < Integer > o2 ) { return o1 . get ( 0 ) . compareTo ( o2 . get ( 0 ) ) ; } } ) ; return vec . get ( vec . size ( ) - 1 ) ; } public static void main ( String [ ] args ) { int a [ ] = { 1 , 4 , 3 , 2 , 5 } ; int k = 4 ; int n = a . length ; ArrayList < Integer > ans = findSubarray ( a , k , n ) ; for ( int it : ans ) { System . out . print ( it + " ▁ " ) ; } } }


"Greatest divisor which divides all natural number in range [ L , R ] | Java implementation of the approach ; Function to return the greatest divisor that divides all the natural numbers in the range [ l , r ] ; Driver Code"
How can the above be solved in Java?

class GFG { static int find_greatest_divisor ( int l , int r ) { if ( l == r ) { return l ; } return 1 ; } public static void main ( String [ ] args ) { int l = 2 , r = 12 ; System . out . println ( find_greatest_divisor ( l , r ) ) ; } }


"Greatest number that can be formed from a pair in a given Array | Java implementation to find the greatest number from the given pairs of the array ; Function to find the greatest number formed from the pairs ; First append Y at the end of X ; Then append X at the end of Y ; Now see which of the two formed numbers is greater than other ; Function to find pairs from array ; Iterate through all pairs ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { static String getNumber ( int a , int b ) { String X = Integer . toString ( a ) ; String Y = Integer . toString ( b ) ; String XY = X + Y ; String YX = Y + X ; return XY . compareTo ( YX ) > 0 ? XY : YX ; } static void printMaxPair ( int arr [ ] , int n ) { int largest = Integer . MIN_VALUE ; for ( int i = 0 ; i < n ; i ++ ) for ( int j = i + 1 ; j < n ; j ++ ) { int number = Integer . parseInt ( getNumber ( arr [ i ] , arr [ j ] ) ) ; largest = Math . max ( largest , number ) ; } System . out . println ( largest ) ; } public static void main ( String [ ] args ) { int a [ ] = { 23 , 14 , 16 , 25 , 3 , 9 } ; int n = a . length ; printMaxPair ( a , n ) ; } }


"Greatest odd factor of an even number | Java program for the above approach ; Function to print greatest odd factor ; Initialize i with 1 ; Iterate till i <= pow_2 ; Find the pow ( 2 , i ) ; If factor is odd , then print the number and break ; Driver code ; Given Number ; Function Call"
How can the above be solved in Java?

class GFG { public static int greatestOddFactor ( int n ) { int pow_2 = ( int ) ( Math . log ( n ) ) ; int i = 1 ; while ( i <= pow_2 ) { int fac_2 = ( 2 * i ) ; if ( n % fac_2 == 0 ) { if ( ( n / fac_2 ) % 2 == 1 ) { return ( n / fac_2 ) ; } } i += 1 ; } return 0 ; } public static void main ( String [ ] args ) { int N = 8642 ; System . out . println ( greatestOddFactor ( N ) ) ; } }


"Greedy Algorithm to find Minimum number of Coins | Java program to find minimum number of denominations ; All denominations of Indian Currency ; Initialize result ; Traverse through all denomination ; Find denominations ; Print result ; Driver code"
How can the above be solved in Java?

import java . util . Vector ; class GFG { static int deno [ ] = { 1 , 2 , 5 , 10 , 20 , 50 , 100 , 500 , 1000 } ; static int n = deno . length ; static void findMin ( int V ) { Vector < Integer > ans = new Vector < > ( ) ; for ( int i = n - 1 ; i >= 0 ; i -- ) { while ( V >= deno [ i ] ) { V -= deno [ i ] ; ans . add ( deno [ i ] ) ; } } for ( int i = 0 ; i < ans . size ( ) ; i ++ ) { System . out . print ( " ▁ " + ans . elementAt ( i ) ) ; } } public static void main ( String [ ] args ) { int n = 93 ; System . out . print ( " Following ▁ is ▁ minimal ▁ number ▁ " + " of ▁ change ▁ for ▁ " + n + " : ▁ " ) ; findMin ( n ) ; } }


"Group all co | Java implementation to group mutually coprime numbers into one group with minimum group possible ; Function to group the mutually co - prime numbers into one group ; Loop for the numbers less than the 4 ; Integers 1 , 2 and 3 can be grouped into one group ; Consecutive even and odd numbers ; Driver Code ; Function Call"
How can the above be solved in Java?

class GFG { static void mutually_coprime ( int n ) { if ( n <= 3 ) { for ( int j = 1 ; j < n + 1 ; j ++ ) System . out . print ( j + " ▁ " ) ; System . out . println ( ) ; } else { System . out . println ( "1 ▁ 2 ▁ 3" ) ; for ( int j = 4 ; j < n ; j += 2 ) { System . out . println ( j + " ▁ " + ( j + 1 ) ) ; if ( n % 2 == 0 ) System . out . println ( n ) ; } } } public static void main ( String [ ] args ) { int n = 9 ; mutually_coprime ( n ) ; } }


"Group all occurrences of characters according to first appearance | Java program to print all occurrences of every character together . ; Since only lower case characters are there ; Method to print the string ; Initialize counts of all characters as 0 ; Count occurrences of all characters in string ; Starts traversing the string ; Print the character till its count in hash array ; Make this character 's count value as 0. ; Driver method"
How can the above be solved in Java?

class Test { static final int MAX_CHAR = 26 ; static void printGrouped ( String str ) { int n = str . length ( ) ; int count [ ] = new int [ MAX_CHAR ] ; for ( int i = 0 ; i < n ; i ++ ) count [ str . charAt ( i ) - ' a ' ] ++ ; for ( int i = 0 ; i < n ; i ++ ) { while ( count [ str . charAt ( i ) - ' a ' ] != 0 ) { System . out . print ( str . charAt ( i ) ) ; count [ str . charAt ( i ) - ' a ' ] -- ; } count [ str . charAt ( i ) - ' a ' ] = 0 ; } } public static void main ( String args [ ] ) { String str = new String ( " geeksforgeeks " ) ; printGrouped ( str ) ; } }


"Group consecutive characters of same type in a string | Java implementation of the approach ; Function to return the modified String ; Store original String ; Remove all white spaces ; To store the resultant String ; Traverse the String ; Group upper case characters ; Group numeric characters ; Group arithmetic operators ; Return the resultant String ; Driver code"
How can the above be solved in Java?

class GFG { static String groupCharacters ( char [ ] s , int len ) { String temp = " " ; for ( int i = 0 ; i < len ; i ++ ) if ( s [ i ] != ' ▁ ' ) temp = temp + s [ i ] ; len = temp . length ( ) ; String ans = " " ; int i = 0 ; while ( i < len ) { if ( temp . charAt ( i ) >= ( ' A ' ) && temp . charAt ( i ) <= ( ' Z ' ) ) { while ( i < len && temp . charAt ( i ) >= ( ' A ' ) && temp . charAt ( i ) <= ( ' Z ' ) ) { ans = ans + temp . charAt ( i ) ; i ++ ; } ans = ans + " ▁ " ; } else if ( temp . charAt ( i ) >= ( '0' ) && temp . charAt ( i ) <= ( '9' ) ) { while ( i < len && temp . charAt ( i ) >= ( '0' ) && temp . charAt ( i ) <= ( '9' ) ) { ans = ans + temp . charAt ( i ) ; i ++ ; } ans = ans + " ▁ " ; } else { while ( i < len && temp . charAt ( i ) >= ( ' * ' ) && temp . charAt ( i ) <= ( ' / ' ) ) { ans = ans + temp . charAt ( i ) ; i ++ ; } ans = ans + " ▁ " ; } } return ans ; } public static void main ( String [ ] args ) { String s = "34FTG234 + ▁ + - ▁ * " ; int len = s . length ( ) ; System . out . print ( groupCharacters ( s . toCharArray ( ) , len ) ) ; } }


"Group multiple occurrence of array elements ordered by first occurrence | A simple Java program to group multiple occurrences of individual array elements ; A simple method to group all occurrences of individual elements ; Initialize all elements as not visited ; Traverse all elements ; Check if this is first occurrence ; If yes , print it and all subsequent occurrences ; Driver code"
How can the above be solved in Java?

class GFG { static void groupElements ( int arr [ ] , int n ) { boolean visited [ ] = new boolean [ n ] ; for ( int i = 0 ; i < n ; i ++ ) { visited [ i ] = false ; } for ( int i = 0 ; i < n ; i ++ ) { if ( ! visited [ i ] ) { System . out . print ( arr [ i ] + " ▁ " ) ; for ( int j = i + 1 ; j < n ; j ++ ) { if ( arr [ i ] == arr [ j ] ) { System . out . print ( arr [ i ] + " ▁ " ) ; visited [ j ] = true ; } } } } } public static void main ( String [ ] args ) { int arr [ ] = { 4 , 6 , 9 , 2 , 3 , 4 , 9 , 6 , 10 , 4 } ; int n = arr . length ; groupElements ( arr , n ) ; } }


"Group multiple occurrence of array elements ordered by first occurrence | Java program to group multiple occurrences of individual array elements ; A hashing based method to group all occurrences of individual elements ; Creates an empty hashmap ; Traverse the array elements , and store count for every element in HashMap ; Check if element is already in HashMap ; Increment count of element element in HashMap ; Traverse array again ; Check if this is first occurrence ; If yes , then print the element ' count ' times ; And remove the element from HashMap . ; Driver method to test above method"
How can the above be solved in Java?

import java . util . HashMap ; class Main { static void orderedGroup ( int arr [ ] ) { HashMap < Integer , Integer > hM = new HashMap < Integer , Integer > ( ) ; for ( int i = 0 ; i < arr . length ; i ++ ) { Integer prevCount = hM . get ( arr [ i ] ) ; if ( prevCount == null ) prevCount = 0 ; hM . put ( arr [ i ] , prevCount + 1 ) ; } for ( int i = 0 ; i < arr . length ; i ++ ) { Integer count = hM . get ( arr [ i ] ) ; if ( count != null ) { for ( int j = 0 ; j < count ; j ++ ) System . out . print ( arr [ i ] + " ▁ " ) ; hM . remove ( arr [ i ] ) ; } } } public static void main ( String [ ] args ) { int arr [ ] = { 10 , 5 , 3 , 10 , 10 , 4 , 1 , 3 } ; orderedGroup ( arr ) ; } }


"Group words with same set of characters | Java program to print all words that have the same unique character set ; Generates a key from given string . The key contains all unique characters of given string in sorted order consisting of only distinct elements . ; store all unique characters of current word in key ; Print all words together with same character sets . ; Stores indexes of all words that have same set of unique characters . unordered_map < string , vector < int > > Hash ; ; Traverse all words ; if the key is already in the map then get its corresponding value and update the list and put it in the map ; if key is not present in the map then create a new list and add both key and the list ; print all words that have the same unique character set ; Driver program to test above function"
How can the above be solved in Java?

import java . util . ArrayList ; import java . util . Arrays ; import java . util . HashMap ; import java . util . Map . Entry ; public class GFG { static final int MAX_CHAR = 26 ; static String getKey ( String str ) { boolean [ ] visited = new boolean [ MAX_CHAR ] ; Arrays . fill ( visited , false ) ; for ( int j = 0 ; j < str . length ( ) ; j ++ ) visited [ str . charAt ( j ) - ' a ' ] = true ; String key = " " ; for ( int j = 0 ; j < MAX_CHAR ; j ++ ) if ( visited [ j ] ) key = key + ( char ) ( ' a ' + j ) ; return key ; } static void wordsWithSameCharSet ( String words [ ] , int n ) { HashMap < String , ArrayList < Integer > > Hash = new HashMap < > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { String key = getKey ( words [ i ] ) ; if ( Hash . containsKey ( key ) ) { ArrayList < Integer > get_al = Hash . get ( key ) ; get_al . add ( i ) ; Hash . put ( key , get_al ) ; } else { ArrayList < Integer > new_al = new ArrayList < > ( ) ; new_al . add ( i ) ; Hash . put ( key , new_al ) ; } } for ( Entry < String , ArrayList < Integer > > it : Hash . entrySet ( ) ) { ArrayList < Integer > get = it . getValue ( ) ; for ( Integer v : get ) System . out . print ( words [ v ] + " , ▁ " ) ; System . out . println ( ) ; } } public static void main ( String args [ ] ) { String words [ ] = { " may " , " student " , " students " , " dog " , " studentssess " , " god " , " cat " , " act " , " tab " , " bat " , " flow " , " wolf " , " lambs " , " amy " , " yam " , " balms " , " looped " , " poodle " } ; int n = words . length ; wordsWithSameCharSet ( words , n ) ; } }


"Grouping Countries | Java program to count no of distinct countries from a given group of people ; Answer is valid if adjacent sitting num people give same answer ; someone gives different answer ; check next person ; one valid country group has been found ; driver code"
How can the above be solved in Java?

 class Country { public static void countCountries ( int ans [ ] , int N ) { int total_countries = 0 , i = 0 ; boolean invalid = false ; while ( i < N ) { int curr_size = ans [ i ] ; int num = ans [ i ] ; while ( num > 0 ) { if ( ans [ i ] != curr_size ) { System . out . print ( "Invalid Answer
" ); return ; } else num -- ; i ++ ; } total_countries ++ ; } System . out . print ( " There ▁ are ▁ " + total_countries + " distinct companies in the group.
" ); } public static void main ( String [ ] args ) { int ans [ ] = { 1 , 1 , 2 , 2 , 4 , 4 , 4 , 4 } ; int n = 8 ; countCountries ( ans , n ) ; } }


"Growable array based stack | Java Program to implement growable array based stack using tight strategy ; constant amount at which stack is increased ; top of the stack ; length of stack ; function to create new stack ; allocate memory for new stack ; copying the content of old stack ; re - sizing the length ; function to push new element ; if stack is full , create new one ; insert element at top of the stack ; function to pop an element ; function to display ; if top is - 1 , that means stack is empty ; Driver Code ; creating initial stack ; pushing element to top of stack ; pushing more element when stack is full ; pushing more element so that stack can grow"
How can the above be solved in Java?

class GFG { static final int BOUND = 4 ; static int top = - 1 ; static int length = 0 ; static int [ ] create_new ( int [ ] a ) { int [ ] new_a = new int [ length + BOUND ] ; for ( int i = 0 ; i < length ; i ++ ) new_a [ i ] = a [ i ] ; length += BOUND ; return new_a ; } static int [ ] push ( int [ ] a , int element ) { if ( top == length - 1 ) a = create_new ( a ) ; a [ ++ top ] = element ; return a ; } static void pop ( int [ ] a ) { top -- ; } static void display ( int [ ] a ) { if ( top == - 1 ) System . out . println ( " Stack ▁ is ▁ Empty " ) ; else { System . out . print ( " Stack : ▁ " ) ; for ( int i = 0 ; i <= top ; i ++ ) System . out . print ( a [ i ] + " ▁ " ) ; System . out . println ( ) ; } } public static void main ( String args [ ] ) { int [ ] a = create_new ( new int [ length + BOUND ] ) ; a = push ( a , 1 ) ; a = push ( a , 2 ) ; a = push ( a , 3 ) ; a = push ( a , 4 ) ; display ( a ) ; a = push ( a , 5 ) ; a = push ( a , 6 ) ; display ( a ) ; a = push ( a , 7 ) ; a = push ( a , 8 ) ; display ( a ) ; a = push ( a , 9 ) ; display ( a ) ; } }