"Permutation Coefficient | A O ( n ) solution that uses table fact [ ] to calculate the Permutation Coefficient ; Returns value of Permutation Coefficient P ( n , k ) ; base case ; Calculate value factorials up to n ; P ( n , k ) = n ! / ( n - k ) ! ; Driver Code"
Solution in Java:

import java . io . * ; public class GFG { static int permutationCoeff ( int n , int k ) { int [ ] fact = new int [ n + 1 ] ; fact [ 0 ] = 1 ; for ( int i = 1 ; i <= n ; i ++ ) fact [ i ] = i * fact [ i - 1 ] ; return fact [ n ] / fact [ n - k ] ; } static public void main ( String [ ] args ) { int n = 10 , k = 2 ; System . out . println ( " Value ▁ of " + " ▁ P ( ▁ " + n + " , ▁ " + k + " ) ▁ is ▁ " + permutationCoeff ( n , k ) ) ; } }


"Permutation Coefficient | A O ( n ) time and O ( 1 ) extra space solution to calculate the Permutation Coefficient ; Compute n ! and ( n - k ) ! ; Driver Code"
Solution in Java:

import java . io . * ; class GFG { static int PermutationCoeff ( int n , int k ) { int Fn = 1 , Fk = 1 ; for ( int i = 1 ; i <= n ; i ++ ) { Fn *= i ; if ( i == n - k ) Fk = Fn ; } int coeff = Fn / Fk ; return coeff ; } public static void main ( String args [ ] ) { int n = 10 , k = 2 ; System . out . println ( " Value ▁ of ▁ P ( ▁ " + n + " , " + k + " ) ▁ is ▁ " + PermutationCoeff ( n , k ) ) ; } }


"Permutation Coefficient | Java code for Dynamic Programming based solution that uses table P [ ] [ ] to calculate the Permutation Coefficient ; Returns value of Permutation Coefficient P ( n , k ) ; Calculate value of Permutation Coefficient in bottom up manner ; Base Cases ; Calculate value using previosly stored values ; This step is important as P ( i , j ) = 0 for j > i ; Driver Code"
Solution in Java:

import java . io . * ; import java . math . * ; class GFG { static int permutationCoeff ( int n , int k ) { int P [ ] [ ] = new int [ n + 2 ] [ k + 2 ] ; for ( int i = 0 ; i <= n ; i ++ ) { for ( int j = 0 ; j <= Math . min ( i , k ) ; j ++ ) { if ( j == 0 ) P [ i ] [ j ] = 1 ; else P [ i ] [ j ] = P [ i - 1 ] [ j ] + ( j * P [ i - 1 ] [ j - 1 ] ) ; P [ i ] [ j + 1 ] = 0 ; } } return P [ n ] [ k ] ; } public static void main ( String args [ ] ) { int n = 10 , k = 2 ; System . out . println ( " Value ▁ of ▁ P ( ▁ " + n + " , " + k + " ) " + " ▁ is ▁ " + permutationCoeff ( n , k ) ) ; } }


"Permutation of first N natural numbers having given array as the prefix maximum array | Java program for the above approach ; Function to check if the maximum prefix array of ans [ ] is equal to array arr [ ] ; Initialize a variable , Max ; Traverse the array , ans [ ] ; Store the maximum value upto index i ; If it is not equal to a [ i ] , then return false ; Otherwise return false ; Function to find the permutation of the array whose prefix maximum array is same as the given array a [ ] ; Stores the required permutation ; Stores the index of first occurrence of elements ; Traverse the array a [ ] ; If a [ i ] is not present in um , then store it in um ; Update the ans [ i ] to a [ i ] ; Stores the unvisited numbers ; Fill the array , v [ ] ; Store the index ; Traverse the array , ans [ ] ; Fill v [ j ] at places where ans [ i ] is 0 ; Check if the current permutation maximum prefix array is same as the given array a [ ] ; If true , the print the permutation ; Otherwise , print - 1 ; Driver Code ; Function Call"
Solution in Java:

import java . io . * ; import java . lang . * ; import java . util . * ; class GFG { static boolean checkPermutation ( int ans [ ] , int a [ ] , int n ) { int Max = Integer . MIN_VALUE ; for ( int i = 0 ; i < n ; i ++ ) { Max = Math . max ( Max , ans [ i ] ) ; if ( Max != a [ i ] ) return false ; } return true ; } static void findPermutation ( int a [ ] , int n ) { int ans [ ] = new int [ n ] ; HashMap < Integer , Integer > um = new HashMap < > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( ! um . containsKey ( a [ i ] ) ) { ans [ i ] = a [ i ] ; um . put ( a [ i ] , i ) ; } } ArrayList < Integer > v = new ArrayList < > ( ) ; int j = 0 ; for ( int i = 1 ; i <= n ; i ++ ) { if ( ! um . containsKey ( i ) ) { v . add ( i ) ; } } for ( int i = 0 ; i < n ; i ++ ) { if ( ans [ i ] == 0 ) { ans [ i ] = v . get ( j ) ; j ++ ; } } if ( checkPermutation ( ans , a , n ) ) { for ( int i = 0 ; i < n ; i ++ ) { System . out . print ( ans [ i ] + " ▁ " ) ; } } else System . out . println ( " - 1" ) ; } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 3 , 4 , 5 , 5 } ; int N = arr . length ; findPermutation ( arr , N ) ; } }


"Polygon with maximum sides that can be inscribed in an N | Java program for the above approach ; Function to find the maximum sided polygon that can be inscribed ; Base Case ; Return n / 2 if n is even Otherwise , return - 1 ; Driver Code ; Given N ; Function Call"
Solution in Java:

import java . util . * ; class GFG { static int MaximumSides ( int n ) { if ( n < 4 ) return - 1 ; return n % 2 == 0 ? n / 2 : - 1 ; } public static void main ( String [ ] args ) { int N = 8 ; System . out . print ( MaximumSides ( N ) ) ; } }


"Primality Test | Set 5 ( Using Lucas | Java program to check for primality using Lucas - Lehmer series . ; Function to check whether ( 2 ^ p - 1 ) is prime or not . ; generate the number ; First number of the series ; Generate the rest ( p - 2 ) terms of the series . ; now if the ( p - 1 ) th term is 0 return true else false . ; Driver Program ; Check whether 2 ^ p - 1 is prime or not ."
Solution in Java:

class GFG { static boolean isPrime ( int p ) { double checkNumber = Math . pow ( 2 , p ) - 1 ; double nextval = 4 % checkNumber ; for ( int i = 1 ; i < p - 1 ; i ++ ) nextval = ( nextval * nextval - 2 ) % checkNumber ; return ( nextval == 0 ) ; } public static void main ( String [ ] args ) { int p = 7 ; double checkNumber = Math . pow ( 2 , p ) - 1 ; if ( isPrime ( p ) ) System . out . println ( ( int ) checkNumber + " ▁ is ▁ Prime . " ) ; else System . out . println ( ( int ) checkNumber + " ▁ is ▁ not ▁ Prime . " ) ; } }


"Primality Test | Set 5 ( Using Lucas | Java program to find out Lucas - Lehmer series . ; Function to find out first n terms ( considering 4 as 0 th term ) of Lucas - Lehmer series . ; the 0 th term of the series is 4. ; create an array to store the terms . ; compute each term and add it to the array . ; print out the terms one by one . ; Driver Code"
Solution in Java:

import java . util . * ; class GFG { static void LucasLehmer ( int n ) { long current_val = 4 ; ArrayList < Long > series = new ArrayList < > ( ) ; series . add ( current_val ) ; for ( int i = 0 ; i < n ; i ++ ) { current_val = current_val * current_val - 2 ; series . add ( current_val ) ; } for ( int i = 0 ; i <= n ; i ++ ) { System . out . println ( " Term ▁ " + i + " : ▁ " + series . get ( i ) ) ; } } public static void main ( String [ ] args ) { int n = 5 ; LucasLehmer ( n ) ; } }


"Print all paths of the Binary Tree with maximum element in each path greater than or equal to K | Java program to print paths with maximum element in the path greater than K ; A Binary Tree node ; A utility function to create a new node ; A recursive function to print the paths whose maximum element is greater than or equal to K . ; If the current node value is greater than or equal to k , then all the subtrees following that node will get printed , flag = 1 indicates to print the required path ; If the leaf node is encountered , then the path is printed if the size of the path vector is greater than 0 ; Append the node to the path vector ; Recur left and right subtrees ; Backtracking to return the vector and print the path if the flag is 1 ; Function to initialize the variables and call the utility function to print the paths with maximum values greater than or equal to K ; Initialize flag ; ans is used to check empty condition ; Call function that print path ; If the path doesn 't exist ; Driver code ; Constructing the following tree : 10 / \ 5 8 / \ / \ 29 2 1 98 / \ 20 50"
Solution in Java:

import java . util . * ; class GFG { static class Node { int data ; Node left , right ; } ; static int ans ; static Node newNode ( int data ) { Node newNode = new Node ( ) ; newNode . data = data ; newNode . left = newNode . right = null ; return ( newNode ) ; } static void findPathUtil ( Node root , int k , Vector < Integer > path , int flag ) { if ( root == null ) return ; if ( root . data >= k ) flag = 1 ; if ( root . left == null && root . right == null ) { if ( flag == 1 ) { ans = 1 ; System . out . print ( " ( " ) ; for ( int i = 0 ; i < path . size ( ) ; i ++ ) { System . out . print ( path . get ( i ) + " , ▁ " ) ; } System . out . print ( root . data + " ) , ▁ " ) ; } return ; } path . add ( root . data ) ; findPathUtil ( root . left , k , path , flag ) ; findPathUtil ( root . right , k , path , flag ) ; path . remove ( path . size ( ) - 1 ) ; } static void findPath ( Node root , int k ) { int flag = 0 ; ans = 0 ; Vector < Integer > v = new Vector < Integer > ( ) ; findPathUtil ( root , k , v , flag ) ; if ( ans == 0 ) System . out . print ( " - 1" ) ; } public static void main ( String [ ] args ) { int K = 25 ; Node root = newNode ( 10 ) ; root . left = newNode ( 5 ) ; root . right = newNode ( 8 ) ; root . left . left = newNode ( 29 ) ; root . left . right = newNode ( 2 ) ; root . right . right = newNode ( 98 ) ; root . right . left = newNode ( 1 ) ; root . right . right . right = newNode ( 50 ) ; root . left . left . left = newNode ( 20 ) ; findPath ( root , K ) ; } }


"Print all possible combinations of r elements in a given array of size n | Java program to print all combination of size r in an array of size n ; The main function that prints all combinations of size r in arr [ ] of size n . This function mainly uses combinationUtil ( ) ; A temporary array to store all combination one by one ; Print all combination using temprary array ' data [ ] ' ; arr [ ] -- -> Input Array data [ ] -- -> Temporary array to store current combination start & end -- -> Staring and Ending indexes in arr [ ] index -- -> Current index in data [ ] r -- -> Size of a combination to be printed ; Current combination is ready to be printed , print it ; When no more elements are there to put in data [ ] ; current is included , put next at next location ; current is excluded , replace it with next ( Note that i + 1 is passed , but index is not changed ) ; Driver function to check for above function"
Solution in Java:

import java . io . * ; class Combination { static void printCombination ( int arr [ ] , int n , int r ) { int data [ ] = new int [ r ] ; combinationUtil ( arr , n , r , 0 , data , 0 ) ; } static void combinationUtil ( int arr [ ] , int n , int r , int index , int data [ ] , int i ) { if ( index == r ) { for ( int j = 0 ; j < r ; j ++ ) System . out . print ( data [ j ] + " ▁ " ) ; System . out . println ( " " ) ; return ; } if ( i >= n ) return ; data [ index ] = arr [ i ] ; combinationUtil ( arr , n , r , index + 1 , data , i + 1 ) ; combinationUtil ( arr , n , r , index , data , i + 1 ) ; } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 2 , 3 , 4 , 5 } ; int r = 3 ; int n = arr . length ; printCombination ( arr , n , r ) ; } }


"Print all possible combinations of r elements in a given array of size n | Java program to print all combination of size r in an array of size n ; The main function that prints all combinations of size r in arr [ ] of size n . This function mainly uses combinationUtil ( ) ; A temporary array to store all combination one by one ; Print all combination using temprary array ' data [ ] ' ; arr [ ] -- -> Input Array data [ ] -- -> Temporary array to store current combination start & end -- -> Staring and Ending indexes in arr [ ] index -- -> Current index in data [ ] r -- -> Size of a combination to be printed ; Current combination is ready to be printed , print it ; replace index with all possible elements . The condition " end - i + 1 ▁ > = ▁ r - index " makes sure that including one element at index will make a combination with remaining elements at remaining positions ; Driver function to check for above function"
Solution in Java:

import java . io . * ; class Combination { static void printCombination ( int arr [ ] , int n , int r ) { int data [ ] = new int [ r ] ; combinationUtil ( arr , data , 0 , n - 1 , 0 , r ) ; } static void combinationUtil ( int arr [ ] , int data [ ] , int start , int end , int index , int r ) { if ( index == r ) { for ( int j = 0 ; j < r ; j ++ ) System . out . print ( data [ j ] + " ▁ " ) ; System . out . println ( " " ) ; return ; } for ( int i = start ; i <= end && end - i + 1 >= r - index ; i ++ ) { data [ index ] = arr [ i ] ; combinationUtil ( arr , data , i + 1 , end , index + 1 , r ) ; } } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 2 , 3 , 4 , 5 } ; int r = 3 ; int n = arr . length ; printCombination ( arr , n , r ) ; } }


"Print all strings from given array that can be typed using keys from a single row of a QWERTY keyboard | Java program to implement the above approach ; Function to print all strings that can be typed using keys of a single row in a QWERTY Keyboard ; Stores row number of all possible character of the strings ; Traverse the array ; If current string is not an empty string ; Sets true / false if a string can be typed using keys of a single row or not ; Stores row number of the first character of current string ; Stores length of word ; Traverse current string ; If current character can 't be  typed using keys of rowNum only ; Update flag ; If current string can be typed using keys from rowNum only ; Print the string ; Driver Code"
Solution in Java:

import java . io . * ; import java . util . * ; class GFG { static void findWordsSameRow ( List < String > arr ) { Map < Character , Integer > mp = new HashMap < Character , Integer > ( ) ; mp . put ( ' q ' , 1 ) ; mp . put ( ' w ' , 1 ) ; mp . put ( ' e ' , 1 ) ; mp . put ( ' r ' , 1 ) ; mp . put ( ' t ' , 1 ) ; mp . put ( ' y ' , 1 ) ; mp . put ( ' u ' , 1 ) ; mp . put ( ' i ' , 1 ) ; mp . put ( ' o ' , 1 ) ; mp . put ( ' p ' , 1 ) ; mp . put ( ' a ' , 2 ) ; mp . put ( ' s ' , 2 ) ; mp . put ( ' d ' , 2 ) ; mp . put ( ' f ' , 2 ) ; mp . put ( ' g ' , 2 ) ; mp . put ( ' h ' , 2 ) ; mp . put ( ' j ' , 2 ) ; mp . put ( ' k ' , 2 ) ; mp . put ( ' l ' , 2 ) ; mp . put ( ' z ' , 3 ) ; mp . put ( ' x ' , 3 ) ; mp . put ( ' c ' , 3 ) ; mp . put ( ' v ' , 3 ) ; mp . put ( ' b ' , 3 ) ; mp . put ( ' n ' , 3 ) ; mp . put ( ' m ' , 3 ) ; for ( String word : arr ) { if ( word . length ( ) != 0 ) { boolean flag = true ; int rowNum = mp . get ( Character . toLowerCase ( word . charAt ( 0 ) ) ) ; int M = word . length ( ) ; for ( int i = 1 ; i < M ; i ++ ) { if ( mp . get ( Character . toLowerCase ( word . charAt ( i ) ) ) != rowNum ) { flag = false ; break ; } } if ( flag ) { System . out . print ( word + " ▁ " ) ; } } } } public static void main ( String [ ] args ) { List < String > words = Arrays . asList ( " Yeti " , " Had " , " GFG " , " comment " ) ; findWordsSameRow ( words ) ; } }


"Print characters and their frequencies in order of occurrence | Java implementation to print the character and its frequency in order of its occurrence ; function to print the character and its frequency in order of its occurrence ; size of the string ' str ' ; ' freq [ ] ' implemented as hash table ; accumulate frequency of each character in ' str ' ; traverse ' str ' from left to right ; if frequency of character str . charAt ( i ) is not equal to 0 ; print the character along with its frequency ; update frequency of str . charAt ( i ) to 0 so that the same character is not printed again ; Driver program to test above"
Solution in Java:

public class Char_frequency { static final int SIZE = 26 ; static void printCharWithFreq ( String str ) { int n = str . length ( ) ; int [ ] freq = new int [ SIZE ] ; for ( int i = 0 ; i < n ; i ++ ) freq [ str . charAt ( i ) - ' a ' ] ++ ; for ( int i = 0 ; i < n ; i ++ ) { if ( freq [ str . charAt ( i ) - ' a ' ] != 0 ) { System . out . print ( str . charAt ( i ) ) ; System . out . print ( freq [ str . charAt ( i ) - ' a ' ] + " ▁ " ) ; freq [ str . charAt ( i ) - ' a ' ] = 0 ; } } } public static void main ( String args [ ] ) { String str = " geeksforgeeks " ; printCharWithFreq ( str ) ; } }


"Print characters and their frequencies in order of occurrence | Java implementation to print the characters and frequencies in order of its occurrence ; Store all characters and their frequencies in dictionary ; Print characters and their frequencies in same order of their appearance ; Print only if this character is not printed before ; Driver code"
Solution in Java:

import java . util . * ; class Gfg { public static void prCharWithFreq ( String s ) { Map < Character , Integer > d = new HashMap < Character , Integer > ( ) ; for ( int i = 0 ; i < s . length ( ) ; i ++ ) { if ( d . containsKey ( s . charAt ( i ) ) ) { d . put ( s . charAt ( i ) , d . get ( s . charAt ( i ) ) + 1 ) ; } else { d . put ( s . charAt ( i ) , 1 ) ; } } for ( int i = 0 ; i < s . length ( ) ; i ++ ) { if ( d . get ( s . charAt ( i ) ) != 0 ) { System . out . print ( s . charAt ( i ) ) ; System . out . print ( d . get ( s . charAt ( i ) ) + " ▁ " ) ; d . put ( s . charAt ( i ) , 0 ) ; } } } public static void main ( String [ ] args ) { String S = " geeksforgeeks " ; prCharWithFreq ( S ) ; } }


"Print characters having even frequencies in order of occurrence | Java implementation of the approach ; Function to print the even frequency characters in the order of their occurrence ; To store the frequency of each of the character of the string ; Update the frequency of each character ; Traverse str character by character ; If frequency of current character is even ; Driver code"
Solution in Java:

import java . util . * ; class GFG { static int SIZE = 26 ; static void printChar ( String str , int n ) { int [ ] freq = new int [ SIZE ] ; for ( int i = 0 ; i < n ; i ++ ) freq [ str . charAt ( i ) - ' a ' ] ++ ; for ( int i = 0 ; i < n ; i ++ ) { if ( freq [ str . charAt ( i ) - ' a ' ] % 2 == 0 ) { System . out . print ( str . charAt ( i ) ) ; } } } public static void main ( String [ ] args ) { String str = " geeksforgeeks " ; int n = str . length ( ) ; printChar ( str , n ) ; } }


"Print characters having odd frequencies in order of occurrence | Java implementation of the approach ; Function to print the odd frequency characters in the order of their occurrence ; To store the frequency of each of the character of the string ; Update the frequency of each character ; Traverse str character by character ; If frequency of current character is odd ; Driver code"
Solution in Java:

class GFG { public static void printChar ( String str , int n ) { int [ ] freq = new int [ 26 ] ; for ( int i = 0 ; i < n ; i ++ ) freq [ str . charAt ( i ) - ' a ' ] ++ ; for ( int i = 0 ; i < n ; i ++ ) { if ( freq [ str . charAt ( i ) - ' a ' ] % 2 == 1 ) { System . out . print ( str . charAt ( i ) ) ; } } } public static void main ( String [ ] args ) { String str = " geeksforgeeks " ; int n = str . length ( ) ; printChar ( str , n ) ; } }


"Print characters having prime frequencies in order of occurrence | Java code for the above approach ; Function to check primes ; Counting the frequency of all character using Counter function ; Traversing string ; Driver code ; Passing string to checkString function"
Solution in Java:

import java . io . * ; import java . util . * ; class GFG { static boolean prime ( int n ) { if ( n <= 1 ) return false ; int max_div = ( int ) Math . floor ( Math . sqrt ( n ) ) ; for ( int i = 2 ; i < 1 + max_div ; i ++ ) { if ( n % i == 0 ) return false ; } return true ; } static void checkString ( String s ) { Map < Character , Integer > freq = new HashMap < Character , Integer > ( ) ; for ( int i = 0 ; i < s . length ( ) ; i ++ ) { if ( ! freq . containsKey ( s . charAt ( i ) ) ) freq . put ( s . charAt ( i ) , 0 ) ; freq . put ( s . charAt ( i ) , freq . get ( s . charAt ( i ) ) + 1 ) ; } for ( int i = 0 ; i < s . length ( ) ; i ++ ) { if ( prime ( freq . get ( s . charAt ( i ) ) ) ) System . out . print ( s . charAt ( i ) ) ; } } public static void main ( String [ ] args ) { String s = " geeksforgeeks " ; checkString ( s ) ; } }


"Print characters having prime frequencies in order of occurrence | Java implementation of the approach ; Function to create Sieve to check primes ; false here indicates that it is not prime ; If prime [ p ] is not changed , then it is a prime ; Update all multiples of p , set them to non - prime ; Function to print the prime frequency characters in the order of their occurrence ; Function to create Sieve to check primes ; To store the frequency of each of the character of the string ; Initialize all elements of freq [ ] to 0 ; Update the frequency of each character ; Traverse str character by character ; If frequency of current character is prime ; Driver code"
Solution in Java:

class GFG { static int SIZE = 26 ; static void SieveOfEratosthenes ( boolean [ ] prime , int p_size ) { prime [ 0 ] = false ; prime [ 1 ] = false ; for ( int p = 2 ; p * p <= p_size ; p ++ ) { if ( prime [ p ] ) { for ( int i = p * 2 ; i < p_size ; i += p ) prime [ i ] = false ; } } } static void printChar ( String str , int n ) { boolean [ ] prime = new boolean [ n + 1 ] ; for ( int i = 0 ; i < n + 1 ; i ++ ) prime [ i ] = true ; SieveOfEratosthenes ( prime , str . length ( ) + 1 ) ; int [ ] freq = new int [ SIZE ] ; for ( int i = 0 ; i < SIZE ; i ++ ) freq [ i ] = 0 ; for ( int i = 0 ; i < n ; i ++ ) freq [ str . charAt ( i ) - ' a ' ] ++ ; for ( int i = 0 ; i < n ; i ++ ) { if ( prime [ freq [ str . charAt ( i ) - ' a ' ] ] ) { System . out . print ( str . charAt ( i ) ) ; } } } public static void main ( String [ ] args ) { String str = " geeksforgeeks " ; int n = str . length ( ) ; printChar ( str , n ) ; } }


"Print indices of array elements whose removal makes the sum of odd and even | Java program to implement the above approach ; Function to find indices of array elements whose removal makes the sum of odd and even indexed array elements equal ; Stores size of array ; Store prefix sum of odd index array elements ; Store prefix sum of even index array elements ; Update even [ 0 ] ; Traverse the given array ; Update odd [ i ] ; Update even [ i ] ; If the current index is an even number ; Update even [ i ] ; If the current index is an odd number ; Update odd [ i ] ; Check if at least one index found or not that satisfies the condition ; Store odd indices sum by removing 0 - th index ; Store even indices sum by removing 0 - th index ; If p and q are equal ; Traverse the array arr [ ] ; If i is an even number ; Update p by removing the i - th element ; Update q by removing the i - th element ; Update q by removing the i - th element ; Update p by removing the i - th element ; If odd index values sum is equal to even index values sum ; Set the find variable ; Print the current index ; If no index found ; Print not possible ; Driver Code"
Solution in Java:

import java . util . * ; class GFG { static void removeIndicesToMakeSumEqual ( int [ ] arr ) { int N = arr . length ; int [ ] odd = new int [ N ] ; int [ ] even = new int [ N ] ; even [ 0 ] = arr [ 0 ] ; for ( int i = 1 ; i < N ; i ++ ) { odd [ i ] = odd [ i - 1 ] ; even [ i ] = even [ i - 1 ] ; if ( i % 2 == 0 ) { even [ i ] += arr [ i ] ; } else { odd [ i ] += arr [ i ] ; } } boolean find = false ; int p = odd [ N - 1 ] ; int q = even [ N - 1 ] - arr [ 0 ] ; if ( p == q ) { System . out . print ( "0 ▁ " ) ; find = true ; } for ( int i = 1 ; i < N ; i ++ ) { if ( i % 2 == 0 ) { p = even [ N - 1 ] - even [ i - 1 ] - arr [ i ] + odd [ i - 1 ] ; q = odd [ N - 1 ] - odd [ i - 1 ] + even [ i - 1 ] ; } else { q = odd [ N - 1 ] - odd [ i - 1 ] - arr [ i ] + even [ i - 1 ] ; p = even [ N - 1 ] - even [ i - 1 ] + odd [ i - 1 ] ; } if ( p == q ) { find = true ; System . out . print ( i + " ▁ " ) ; } } if ( ! find ) { System . out . print ( - 1 ) ; } } public static void main ( String [ ] args ) { int [ ] arr = { 4 , 1 , 6 , 2 } ; removeIndicesToMakeSumEqual ( arr ) ; } }


"Print path from root to all nodes in a Complete Binary Tree | Java program to print path from root to all nodes in a complete binary tree . ; Function to print path of all the nodes nth node represent as given node kth node represents as left and right node ; base condition if kth node value is greater then nth node then its means kth node is not valid so we not store it into the res simply we just return ; Storing node into res ; Print the path from root to node ; store left path of a tree So for left we will go node ( kThNode * 2 ) ; right path of a tree and for right we will go node ( kThNode * 2 + 1 ) ; Function to print path from root to all of the nodes ; res is for store the path from root to particulate node ; Print path from root to all node . third argument 1 because of we have to consider root node is 1 ; Driver Code ; Given Node ; Print path from root to all node ."
Solution in Java:

 import java . util . * ; class GFG { static void printPath ( Vector < Integer > res , int nThNode , int kThNode ) { if ( kThNode > nThNode ) return ; res . add ( kThNode ) ; for ( int i = 0 ; i < res . size ( ) ; i ++ ) System . out . print ( res . get ( i ) + " ▁ " ) ; System . out . print ( "
"); printPath ( res , nThNode , kThNode * 2 ) ; printPath ( res , nThNode , kThNode * 2 + 1 ) ; res . remove ( res . size ( ) - 1 ) ; } static void printPathToCoverAllNodeUtil ( int nThNode ) { Vector < Integer > res = new Vector < Integer > ( ) ; printPath ( res , nThNode , 1 ) ; } public static void main ( String args [ ] ) { int nThNode = 7 ; printPathToCoverAllNodeUtil ( nThNode ) ; } }


"Print reverse string after removing vowels | Java Program for removing characters from reversed string where vowels are present in original string ; Function for replacing the string ; initialize a string of length n ; Traverse through all characters of string ; assign the value to string r from last index of string s ; if s [ i ] is a consonant then print r [ i ] ; Driver function"
Solution in Java:

class GFG { static void replaceOriginal ( String s , int n ) { char r [ ] = new char [ n ] ; for ( int i = 0 ; i < n ; i ++ ) { r [ i ] = s . charAt ( n - 1 - i ) ; if ( s . charAt ( i ) != ' a ' && s . charAt ( i ) != ' e ' && s . charAt ( i ) != ' i ' && s . charAt ( i ) != ' o ' && s . charAt ( i ) != ' u ' ) { System . out . print ( r [ i ] ) ; } } System . out . println ( " " ) ; } public static void main ( String [ ] args ) { String s = " geeksforgeeks " ; int n = s . length ( ) ; replaceOriginal ( s , n ) ; } }


"Print sorted distinct elements of array | Java program to print sorted distinct elements . ; Create a set using array elements ; Print contents of the set . ; Driver code"
Solution in Java:

import java . io . * ; import java . util . * ; public class GFG { static void printRepeating ( Integer [ ] arr , int size ) { SortedSet < Integer > s = new TreeSet < > ( ) ; Collections . addAll ( s , arr ) ; System . out . print ( s ) ; } public static void main ( String args [ ] ) { Integer [ ] arr = { 1 , 3 , 2 , 2 , 1 } ; int n = arr . length ; printRepeating ( arr , n ) ; } }


"Probability of A winning the match when individual probabilities of hitting the target given | Java implementation of the approach ; Function to return the probability of A winning ; p and q store the values of fractions a / b and c / d ; To store the winning probability of A ; Driver code"
Solution in Java:

class GFG { static double getProbability ( int a , int b , int c , int d ) { double p = ( double ) a / ( double ) b ; double q = ( double ) c / ( double ) d ; double ans = p * ( 1 / ( 1 - ( 1 - q ) * ( 1 - p ) ) ) ; return ans ; } public static void main ( String [ ] args ) { int a = 1 , b = 2 , c = 10 , d = 11 ; System . out . printf ( " % .5f " , getProbability ( a , b , c , d ) ) ; } }


"Probability of Euler 's Totient Function in a range [L, R] to be divisible by M | Java Program to implement the above approach ; Seieve of Erotosthenes to compute all primes ; If prime ; Mark all its multiples as non - prime ; Function to find the probability of Euler 's Totient Function in a given range ; Initializing two arrays with values from L to R for Euler 's totient ; Indexing from 0 ; If the current number is prime ; Checking if i is prime factor of numbers in range L to R ; Update all the numbers which has prime factor i ; If number in range has a prime factor > Math . sqrt ( number ) ; Count those which are divisible by M ; Return the result ; Driver Code"
Solution in Java:

import java . util . * ; class GFG { static final int size = 1000001 ; static void seiveOfEratosthenes ( int [ ] prime ) { prime [ 0 ] = 1 ; prime [ 1 ] = 0 ; for ( int i = 2 ; i * i < 1000001 ; i ++ ) { if ( prime [ i ] == 0 ) { for ( int j = i * i ; j < 1000001 ; j += i ) { prime [ j ] = 1 ; } } } } static float probabiltyEuler ( int [ ] prime , int L , int R , int M ) { int [ ] arr = new int [ size ] ; int [ ] eulerTotient = new int [ size ] ; int count = 0 ; for ( int i = L ; i <= R ; i ++ ) { eulerTotient [ i - L ] = i ; arr [ i - L ] = i ; } for ( int i = 2 ; i < 1000001 ; i ++ ) { if ( prime [ i ] == 0 ) { for ( int j = ( L / i ) * i ; j <= R ; j += i ) { if ( j - L >= 0 ) { eulerTotient [ j - L ] = eulerTotient [ j - L ] / i * ( i - 1 ) ; while ( arr [ j - L ] % i == 0 ) { arr [ j - L ] /= i ; } } } } } for ( int i = L ; i <= R ; i ++ ) { if ( arr [ i - L ] > 1 ) { eulerTotient [ i - L ] = ( eulerTotient [ i - L ] / arr [ i - L ] ) * ( arr [ i - L ] - 1 ) ; } } for ( int i = L ; i <= R ; i ++ ) { if ( ( eulerTotient [ i - L ] % M ) == 0 ) { count ++ ; } } return ( float ) ( 1.0 * count / ( R + 1 - L ) ) ; } public static void main ( String [ ] args ) { int [ ] prime = new int [ size ] ; seiveOfEratosthenes ( prime ) ; int L = 1 , R = 7 , M = 3 ; System . out . print ( probabiltyEuler ( prime , L , R , M ) ) ; } }


"Probability of rain on N + 1 th day | Java code to find the probability of rain on n + 1 - th day when previous day 's data is given ; Function to find the probability ; count 1 ; find probability ; Driver Code"
Solution in Java:

import java . io . * ; import java . util . * ; class GFG { static float rainDayProbability ( int a [ ] , int n ) { float count = 0 , m ; for ( int i = 0 ; i < n ; i ++ ) { if ( a [ i ] == 1 ) count ++ ; } m = count / n ; return m ; } public static void main ( String args [ ] ) { int a [ ] = { 1 , 0 , 1 , 0 , 1 , 1 , 1 , 1 } ; int n = a . length ; System . out . print ( rainDayProbability ( a , n ) ) ; } }


"Probability that a random pair chosen from an array ( a [ i ] , a [ j ] ) has the maximum sum | Java implementation of the approach ; Function to return the probability of getting the maximum pair sum when a random pair is chosen from the given array ; Initialize the maximum sum , its count and the count of total pairs ; For every single pair ; Get the sum of the current pair ; If the sum is equal to the current maximum sum so far ; Increment its count ; If the sum is greater than the current maximum ; Update the current maximum and re - initialize the count to 1 ; Find the required probability ; Driver code"
Solution in Java:

import java . util . * ; class GFG { static float findProb ( int arr [ ] , int n ) { long maxSum = Integer . MIN_VALUE , maxCount = 0 , totalPairs = 0 ; for ( int i = 0 ; i < n - 1 ; i ++ ) { for ( int j = i + 1 ; j < n ; j ++ ) { int sum = arr [ i ] + arr [ j ] ; if ( sum == maxSum ) { maxCount ++ ; } else if ( sum > maxSum ) { maxSum = sum ; maxCount = 1 ; } totalPairs ++ ; } } float prob = ( float ) maxCount / ( float ) totalPairs ; return prob ; } public static void main ( String args [ ] ) { int arr [ ] = { 1 , 1 , 1 , 2 , 2 , 2 } ; int n = arr . length ; System . out . println ( findProb ( arr , n ) ) ; } }


"Probability that the sum of all numbers obtained on throwing a dice N times lies between two given integers | Java program for above approach ; Function to calculate probability that the sum of numbers on N throws of dice lies between A and B ; Base case ; Add the probability for all the numbers between a and b ; Driver Code ; Print the answer"
Solution in Java:

import java . util . * ; class GFG { static float [ ] [ ] dp = new float [ 105 ] [ 605 ] ; static float find ( int N , int a , int b ) { float probability = 0.0f ; for ( int i = 1 ; i <= 6 ; i ++ ) dp [ 1 ] [ i ] = ( float ) ( 1.0 / 6 ) ; for ( int i = 2 ; i <= N ; i ++ ) { for ( int j = i ; j <= 6 * i ; j ++ ) { for ( int k = 1 ; k <= 6 && k <= j ; k ++ ) { dp [ i ] [ j ] = dp [ i ] [ j ] + dp [ i - 1 ] [ j - k ] / 6 ; } } } for ( int sum = a ; sum <= b ; sum ++ ) probability = probability + dp [ N ] [ sum ] ; return probability ; } public static void main ( String [ ] args ) { int N = 4 , a = 13 , b = 17 ; float probability = find ( N , a , b ) ; System . out . printf ( " % .6f " , probability ) ; } }


"Probability that the sum of all numbers obtained on throwing a dice N times lies between two given integers | Java program for above approach ; Function to calculate the probability for the given sum to be equal to sum in N throws of dice ; Base cases ; Driver Code ; Calculate probability of all sums from a to b ; Print the answer"
Solution in Java:

class GFG { static float [ ] [ ] dp = new float [ 105 ] [ 605 ] ; static float find ( int N , int sum ) { if ( N < 0 sum < 0 ) return 0 ; if ( dp [ N ] [ sum ] > 0 ) return dp [ N ] [ sum ] ; if ( sum > 6 * N sum < N ) return 0 ; if ( N == 1 ) { if ( sum >= 1 && sum <= 6 ) return ( float ) ( 1.0 / 6 ) ; else return 0 ; } for ( int i = 1 ; i <= 6 ; i ++ ) dp [ N ] [ sum ] = dp [ N ] [ sum ] + find ( N - 1 , sum - i ) / 6 ; return dp [ N ] [ sum ] ; } public static void main ( String [ ] args ) { int N = 4 , a = 13 , b = 17 ; float probability = 0.0f ; for ( int sum = a ; sum <= b ; sum ++ ) probability = probability + find ( N , sum ) ; System . out . printf ( " % .6f " , probability ) ; } }


"Probability that the sum of all numbers obtained on throwing a dice N times lies between two given integers | Java program for the above approach ; Function to calculate the probability for the given sum to be equal to sum in N throws of dice ; Base cases ; Driver code ; Print the answer"
Solution in Java:

import java . util . * ; class GFG { static double find ( int N , int sum ) { if ( sum > 6 * N sum < N ) return 0 ; if ( N == 1 ) { if ( sum >= 1 && sum <= 6 ) return 1.0 / 6 ; else return 0 ; } double s = 0 ; for ( int i = 1 ; i <= 6 ; i ++ ) s = s + find ( N - 1 , sum - i ) / 6 ; return s ; } public static void main ( String [ ] args ) { int N = 4 , a = 13 , b = 17 ; double probability = 0.0 ; for ( int sum = a ; sum <= b ; sum ++ ) probability = probability + find ( N , sum ) ; System . out . format ( " % .6f " , probability ) ; } }


"Product of all sorted subsets of size K using elements whose index divide K completely | Java implementation of the above approach ; Iterative Function to calculate ( x ^ y ) % p in O ( log y ) ; If y is odd , multiply x with result ; y must be even now ; Iterative Function to calculate ( nCr ) % p and save in f [ n ] [ r ] ; If j > i then C ( i , j ) = 0 ; If iis equal to j then C ( i , j ) = 1 ; Function calculate the Final answer ; Initialize ans ; x is count of occurence of arr [ i ] in different set such that index of arr [ i ] in those sets divides K completely . ; Finding the count of arr [ i ] by placing it at index which divides K completely ; By Fermat 's theorem ; Driver code"
Solution in Java:

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


"Program for Goldbachâ €™ s Conjecture ( Two Primes with given Sum ) | Java program to implement Goldbach 's conjecture ; Array to store all prime less than and equal to 10 ^ 6 ; Utility function for Sieve of Sundaram ; In general Sieve of Sundaram , produces primes smaller than ( 2 * x + 2 ) for a number given number x . Since we want primes smaller than MAX , we reduce MAX to half This array is used to separate numbers of the form i + j + 2 * i * j from others where 1 <= i <= j ; Main logic of Sundaram . Mark all numbers which do not generate prime number by doing 2 * i + 1 ; Since 2 is a prime number ; Print other primes . Remaining primes are of the form 2 * i + 1 such that marked [ i ] is false . ; Function to perform Goldbach 's conjecture ; Return if number is not even or less than 3 ; Check only upto half of number ; find difference by subtracting current prime from n ; Search if the difference is also a prime number ; Express as a sum of primes ; Driver code ; Finding all prime numbers before limit ; Express number as a sum of two primes"
Solution in Java:

import java . util . * ; class GFG { static int MAX = 10000 ; static ArrayList < Integer > primes = new ArrayList < Integer > ( ) ; static void sieveSundaram ( ) { boolean [ ] marked = new boolean [ MAX / 2 + 100 ] ; for ( int i = 1 ; i <= ( Math . sqrt ( MAX ) - 1 ) / 2 ; i ++ ) for ( int j = ( i * ( i + 1 ) ) << 1 ; j <= MAX / 2 ; j = j + 2 * i + 1 ) marked [ j ] = true ; primes . add ( 2 ) ; for ( int i = 1 ; i <= MAX / 2 ; i ++ ) if ( marked [ i ] == false ) primes . add ( 2 * i + 1 ) ; } static void findPrimes ( int n ) { if ( n <= 2 n % 2 != 0 ) { System . out . println ( " Invalid ▁ Input ▁ " ) ; return ; } for ( int i = 0 ; primes . get ( i ) <= n / 2 ; i ++ ) { int diff = n - primes . get ( i ) ; if ( primes . contains ( diff ) ) { System . out . println ( primes . get ( i ) + " ▁ + ▁ " + diff + " ▁ = ▁ " + n ) ; return ; } } } public static void main ( String [ ] args ) { sieveSundaram ( ) ; findPrimes ( 4 ) ; findPrimes ( 38 ) ; findPrimes ( 100 ) ; } }


"Program for addition of two matrices | Java program for addition of two matrices ; This function adds A [ ] [ ] and B [ ] [ ] , and stores the result in C [ ] [ ] ; Driver code"
Solution in Java:


"Program for factorial of a number | Java program to find factorial of given number ; method to find factorial of given number ; Driver method"
Solution in Java:

class Test { static int factorial ( int n ) { if ( n == 0 ) return 1 ; return n * factorial ( n - 1 ) ; } public static void main ( String [ ] args ) { int num = 5 ; System . out . println ( " Factorial ▁ of ▁ " + num + " ▁ is ▁ " + factorial ( 5 ) ) ; } }


"Program for factorial of a number | Java program to find factorial of given number ; single line to find factorial ; Driver Code"
Solution in Java:

class Factorial { int factorial ( int n ) { return ( n == 1 n == 0 ) ? 1 : n * factorial ( n - 1 ) ; } public static void main ( String args [ ] ) { Factorial obj = new Factorial ( ) ; int num = 5 ; System . out . println ( " Factorial ▁ of ▁ " + num + " ▁ is ▁ " + obj . factorial ( num ) ) ; } }


"Program for subtraction of matrices | Java program for subtraction of matrices ; This function subtracts B [ ] [ ] from A [ ] [ ] , and stores the result in C [ ] [ ] ; Driver code"
Solution in Java:

 class GFG { static final int N = 4 ; static void subtract ( int A [ ] [ ] , int B [ ] [ ] , int C [ ] [ ] ) { int i , j ; for ( i = 0 ; i < N ; i ++ ) for ( j = 0 ; j < N ; j ++ ) C [ i ] [ j ] = A [ i ] [ j ] - B [ i ] [ j ] ; } public static void main ( String [ ] args ) { int A [ ] [ ] = { { 1 , 1 , 1 , 1 } , { 2 , 2 , 2 , 2 } , { 3 , 3 , 3 , 3 } , { 4 , 4 , 4 , 4 } } ; int B [ ] [ ] = { { 1 , 1 , 1 , 1 } , { 2 , 2 , 2 , 2 } , { 3 , 3 , 3 , 3 } , { 4 , 4 , 4 , 4 } } ; int C [ ] [ ] = new int [ N ] [ N ] ; int i , j ; subtract ( A , B , C ) ; System . out . print ( "Result matrix is
"); for ( i = 0 ; i < N ; i ++ ) { for ( j = 0 ; j < N ; j ++ ) System . out . print ( C [ i ] [ j ] + " ▁ " ) ; System . out . print ( "
"); } } }


"Program to convert Centimeters to Pixels | Java program to convert centimeter to pixels ; Function to convert centimeters to pixels ; Driver Code"
Solution in Java:

import java . io . * ; class GFG { static double Conversion ( double centi ) { double pixels = ( 96 * centi ) / 2.54 ; System . out . println ( pixels ) ; return 0 ; } public static void main ( String args [ ] ) { int centi = 15 ; Conversion ( centi ) ; } }


"Program to duplicate Vowels in String | Java program for printing string with duplicate vowels ; Function to check for the Vowel ; Function to get the resultant string with vowels duplicated ; Another string to store the resultant string ; Loop to check for each character ; Driver Code ; Print the original string ; Print the resultant string"
Solution in Java:

import java . util . * ; class GFG { static boolean isVowel ( char ch ) { ch = Character . toUpperCase ( ch ) ; return ( ch == ' A ' ch == ' E ' ch == ' I ' ch == ' O ' ch == ' U ' ) ; } static String duplicateVowels ( String str ) { int t = str . length ( ) ; String res = " " ; for ( int i = 0 ; i < t ; i ++ ) { if ( isVowel ( str . charAt ( i ) ) ) res += str . charAt ( i ) ; res += str . charAt ( i ) ; } return res ; } public static void main ( String [ ] args ) { String str = " helloworld " ; System . out . println ( " Original ▁ String : ▁ " + str ) ; String res = duplicateVowels ( str ) ; System . out . println ( " String ▁ with ▁ Vowels ▁ duplicated : ▁ " + res ) ; } }


"Program to find the number of men initially | Java implementation of the approach ; Function to return the number of men initially ; Driver code"
Solution in Java:

import java . util . * ; class GFG { static int numberOfMen ( int D , int m , int d ) { int Men = ( m * ( D - d ) ) / d ; return Men ; } public static void main ( String args [ ] ) { int D = 5 , m = 4 , d = 4 ; System . out . println ( numberOfMen ( D , m , d ) ) ; } }


"Program to find the sum of a Series 1 + 1 / 2 ^ 2 + 1 / 3 ^ 3 + â €¦ . . + 1 / n ^ n | Java program to calculate the following series ; Function to calculate the following series ; Driver Code"
Solution in Java:

import java . io . * ; class Maths { static double Series ( int n ) { int i ; double sums = 0.0 , ser ; for ( i = 1 ; i <= n ; ++ i ) { ser = 1 / Math . pow ( i , i ) ; sums += ser ; } return sums ; } public static void main ( String [ ] args ) { int n = 3 ; double res = Series ( n ) ; res = Math . round ( res * 100000.0 ) / 100000.0 ; System . out . println ( res ) ; } }


"Program to find value of 1 ^ k + 2 ^ k + 3 ^ k + ... + n ^ k | Java Program to find the value 1 ^ K + 2 ^ K + 3 ^ K + . . + N ^ K ; Function to find value of 1 ^ K + 2 ^ K + 3 ^ K + . . + N ^ K ; Initialise sum to 0 ; Find the value of pow ( i , 4 ) and then add it to the sum ; Return the sum ; Drivers Code ; Function call to find the sum"
Solution in Java:

class GFG { static int findSum ( int N , int k ) { int sum = 0 ; for ( int i = 1 ; i <= N ; i ++ ) { sum += ( int ) Math . pow ( i , k ) ; } return sum ; } public static void main ( String [ ] args ) { int N = 8 , k = 4 ; System . out . println ( findSum ( N , k ) ) ; } }


"Program to find whether a given number is power of 2 | Java program for the above approach ; Function which checks whether a number is a power of 2 ; base cases '1' is the only odd number which is a power of 2 ( 2 ^ 0 ) ; all other odd numbers are not powers of 2 ; recursive function call ; Driver Code ; True ; False"
Solution in Java:

 import java . util . * ; class GFG { static boolean powerOf2 ( int n ) { if ( n == 1 ) return true ; else if ( n % 2 != 0 n == 0 ) return false ; return powerOf2 ( n / 2 ) ; } public static void main ( String [ ] args ) { int n = 64 ; int m = 12 ; if ( powerOf2 ( n ) == true ) System . out . print ( " True " + "
"); else System . out . print ( " False " + "
"); if ( powerOf2 ( m ) == true ) System . out . print ( " True " + "
"); else System . out . print ( " False " + "
"); } }


"Program to find whether a given number is power of 2 | Java program of the above approach ; Function to check if x is power of 2 ; Driver code"
Solution in Java:

import java . io . * ; class GFG { static boolean isPowerofTwo ( int n ) { if ( n == 0 ) return false ; if ( ( n & ( ~ ( n - 1 ) ) ) == n ) return true ; return false ; } public static void main ( String [ ] args ) { if ( isPowerofTwo ( 30 ) == true ) System . out . println ( " Yes " ) ; else System . out . println ( " No " ) ; if ( isPowerofTwo ( 128 ) == true ) System . out . println ( " Yes " ) ; else System . out . println ( " No " ) ; } }


"Program to find whether a given number is power of 2 | Java program to efficiently check for power for 2 ; Method to check if x is power of 2 ; First x in the below expression is for the case when x is 0 ; Driver method"
Solution in Java:

class Test { static boolean isPowerOfTwo ( int x ) { return x != 0 && ( ( x & ( x - 1 ) ) == 0 ) ; } public static void main ( String [ ] args ) { System . out . println ( isPowerOfTwo ( 31 ) ? " Yes " : " No " ) ; System . out . println ( isPowerOfTwo ( 64 ) ? " Yes " : " No " ) ; } }


"Program to print ' N ' alphabet using the number pattern from 1 to n | Java implementation of the approach ; Function to print the desired Alphabet N Pattern ; Declaring the values of Right , Left and Diagonal values ; Main Loop for the rows ; For the left Values ; Spaces for the diagonals ; Condition for the diagonals ; Spaces for the Right Values ; For the right values ; Driver Code ; Size of the Pattern ; Calling the function to print the desired Pattern"
Solution in Java:

import java . util . * ; class solution { static void Alphabet_N_Pattern ( int N ) { int index , side_index , size ; int Right = 1 , Left = 1 , Diagonal = 2 ; for ( index = 0 ; index < N ; index ++ ) { System . out . print ( Left ++ ) ; for ( side_index = 0 ; side_index < 2 * ( index ) ; side_index ++ ) System . out . print ( " ▁ " ) ; if ( index != 0 && index != N - 1 ) System . out . print ( Diagonal ++ ) ; else System . out . print ( " ▁ " ) ; for ( side_index = 0 ; side_index < 2 * ( N - index - 1 ) ; side_index ++ ) System . out . print ( " ▁ " ) ; System . out . print ( Right ++ ) ; System . out . println ( ) ; } } public static void main ( String args [ ] ) { int Size = 6 ; Alphabet_N_Pattern ( Size ) ; } }


"Program to print modified Binary triangle pattern | Java implementation to print the modified binary triangle pattern ; Function to print the modified binary pattern ; Loop to traverse the rows ; Loop to traverse the numbers in each row ; Check if j is 1 or i In either case print 1 ; Else print 0 ; Change the cursor to next line after each row ; Driver Code ; Function call"
Solution in Java:

import java . io . * ; class GFG { static void modifiedBinaryPattern ( int n ) { for ( int i = 1 ; i <= n ; i ++ ) { for ( int j = 1 ; j <= i ; j ++ ) { if ( j == 1 j == i ) System . out . print ( 1 ) ; else System . out . print ( 0 ) ; } System . out . println ( ) ; } } public static void main ( String [ ] args ) { int n = 7 ; modifiedBinaryPattern ( n ) ; } }


"Program to print prime numbers from 1 to N . | Java program to display first N Prime numbers ; Function to print first N prime numbers ; Declare the variables ; Print display message ; Traverse each number from 1 to N with the help of for loop ; Skip 0 and 1 as they are neither prime nor composite ; flag variable to tell if i is prime or not ; flag = 1 means i is prime and flag = 0 means i is not prime ; Driver code"
Solution in Java:

class GFG { static void print_primes_till_N ( int N ) { int i , j , flag ; System . out . println ( " Prime ▁ numbers ▁ between ▁ 1 ▁ and ▁ " + N + " ▁ are : " ) ; for ( i = 1 ; i <= N ; i ++ ) { if ( i == 1 i == 0 ) continue ; flag = 1 ; for ( j = 2 ; j <= i / 2 ; ++ j ) { if ( i % j == 0 ) { flag = 0 ; break ; } } if ( flag == 1 ) System . out . print ( i + " ▁ " ) ; } } public static void main ( String [ ] args ) { int N = 100 ; print_primes_till_N ( N ) ; } }


"Queries on count of points lie inside a circle | JAVA Code for Queries on count of points lie inside a circle ; Computing the x ^ 2 + y ^ 2 for each given points and sorting them . ; Return count of points lie inside or on circumference of circle using binary search on p [ 0. . n - 1 ] ; Driver program to test above function ; Compute distances of all points and keep the distances sorted so that query can work in O ( logn ) using Binary Search . ; Print number of points in a circle of radius 3. ; Print number of points in a circle of radius 32."
Solution in Java:

import java . util . * ; class GFG { public static void preprocess ( int p [ ] , int x [ ] , int y [ ] , int n ) { for ( int i = 0 ; i < n ; i ++ ) p [ i ] = x [ i ] * x [ i ] + y [ i ] * y [ i ] ; Arrays . sort ( p ) ; } public static int query ( int p [ ] , int n , int rad ) { int start = 0 , end = n - 1 ; while ( ( end - start ) > 1 ) { int mid = ( start + end ) / 2 ; double tp = Math . sqrt ( p [ mid ] ) ; if ( tp > ( rad * 1.0 ) ) end = mid - 1 ; else start = mid ; } double tp1 = Math . sqrt ( p [ start ] ) ; double tp2 = Math . sqrt ( p [ end ] ) ; if ( tp1 > ( rad * 1.0 ) ) return 0 ; else if ( tp2 <= ( rad * 1.0 ) ) return end + 1 ; else return start + 1 ; } public static void main ( String [ ] args ) { int x [ ] = { 1 , 2 , 3 , - 1 , 4 } ; int y [ ] = { 1 , 2 , 3 , - 1 , 4 } ; int n = x . length ; int p [ ] = new int [ n ] ; preprocess ( p , x , y , n ) ; System . out . println ( query ( p , n , 3 ) ) ; System . out . println ( query ( p , n , 32 ) ) ; } }


"Queries to check if count of increasing and decreasing subarrays is same in given range | Java program for the above approach ; Function to check if given range have equal number of increasing as well as decreasing subarrays ; Traverse each query ; For 0 - based indexing ; Condition for same count of increasing & decreasing subarray ; Driver Code"
Solution in Java:

import java . io . * ; import java . util . * ; class GFG { static void checkCount ( int A [ ] , int Q [ ] [ ] , int q ) { for ( int i = 0 ; i < q ; i ++ ) { int L = Q [ i ] [ 0 ] ; int R = Q [ i ] [ 1 ] ; L -- ; R -- ; if ( ( A [ L ] < A [ L + 1 ] ) != ( A [ R - 1 ] < A [ R ] ) ) { System . out . println ( " Yes " ) ; } else { System . out . println ( " No " ) ; } } } public static void main ( String [ ] args ) { int arr [ ] = { 11 , 13 , 12 , 14 } ; int Q [ ] [ ] = { { 1 , 4 } , { 2 , 4 } } ; int q = Q . length ; checkCount ( arr , Q , q ) ; } }


"Queries to count groups of N students possible having sum of ratings within given range | Java program for the above approach ; Function to count number of ways to get given sum groups ; Initialise dp array ; Mark all 1 st row values as 1 since the mat [ 0 ] [ i ] is all possible sums in first row ; Fix the ith row ; Fix the sum ; Iterate through all values of ith row ; If sum can be obtained ; Find the prefix sum of last row ; Traverse each query ; No of ways to form groups ; Driver Code ; Given N batches and K students ; Given ratings ; Given Queries ; Function Call"
Solution in Java:

import java . util . * ; public class Main { public static void numWays ( int [ ] [ ] ratings , int queries [ ] [ ] , int n , int k ) { int dp [ ] [ ] = new int [ n ] [ 10000 + 2 ] ; for ( int i = 0 ; i < k ; i ++ ) dp [ 0 ] [ ratings [ 0 ] [ i ] ] += 1 ; for ( int i = 1 ; i < n ; i ++ ) { for ( int sum = 0 ; sum <= 10000 ; sum ++ ) { for ( int j = 0 ; j < k ; j ++ ) { if ( sum >= ratings [ i ] [ j ] ) dp [ i ] [ sum ] += dp [ i - 1 ] [ sum - ratings [ i ] [ j ] ] ; } } } for ( int sum = 1 ; sum <= 10000 ; sum ++ ) { dp [ n - 1 ] [ sum ] += dp [ n - 1 ] [ sum - 1 ] ; } for ( int q = 0 ; q < queries . length ; q ++ ) { int a = queries [ q ] [ 0 ] ; int b = queries [ q ] [ 1 ] ; System . out . print ( dp [ n - 1 ] [ b ] - dp [ n - 1 ] [ a - 1 ] + " ▁ " ) ; } } public static void main ( String args [ ] ) { int N = 2 , K = 3 ; int ratings [ ] [ ] = { { 1 , 2 , 3 } , { 4 , 5 , 6 } } ; int queries [ ] [ ] = { { 6 , 6 } , { 1 , 6 } } ; numWays ( ratings , queries , N , K ) ; } }


"Queries to evaluate the given equation in a range [ L , R ] | Java Program to implement the above approach ; Function to obtain the middle index of the range ; Recursive function to get the sum of values in the given range from the array . The following are parameters for this function . st . Pointer to segment tree node . Index of current node in the segment tree ss & se . Starting and ending indexes of the segment represented by current node , i . e . , st [ node ] l & r . Starting and ending indexes of range query ; If the segment of this node lies completely within the given range ; Return maximum in the segment ; If the segment of this node lies outside the given range ; If segment of this node lies partially in the given range ; Function to return the maximum in the range from [ l , r ] ; Check for erroneous input values ; Function to conSegment Tree for the subarray [ ss . . se ] ; For a single element ; Otherwise ; Recur for left subtree ; Recur for right subtree ; Function to conSegment Tree from the given array ; Height of Segment Tree ; Maximum size of Segment Tree ; Allocate memory ; Fill the allocated memory ; Return the constructed Segment Tree ; Driver Code ; Build the Segment Tree from the given array"
Solution in Java:

import java . util . * ; class GFG { static int getMid ( int s , int e ) { return s + ( e - s ) / 2 ; } static int MaxUtil ( int [ ] st , int ss , int se , int l , int r , int node ) { if ( l <= ss && r >= se ) return st [ node ] ; if ( se < l ss > r ) return - 1 ; int mid = getMid ( ss , se ) ; return Math . max ( MaxUtil ( st , ss , mid , l , r , 2 * node + 1 ) , MaxUtil ( st , mid + 1 , se , l , r , 2 * node + 2 ) ) ; } static int getMax ( int [ ] st , int n , int l , int r ) { if ( l < 0 r > n - 1 l > r ) { System . out . printf ( " Invalid ▁ Input " ) ; return - 1 ; } return MaxUtil ( st , 0 , n - 1 , l , r , 0 ) ; } static int constructSTUtil ( int arr [ ] , int ss , int se , int [ ] st , int si ) { if ( ss == se ) { st [ si ] = arr [ ss ] ; return arr [ ss ] ; } int mid = getMid ( ss , se ) ; st [ si ] = Math . max ( constructSTUtil ( arr , ss , mid , st , si * 2 + 1 ) , constructSTUtil ( arr , mid + 1 , se , st , si * 2 + 2 ) ) ; return st [ si ] ; } static int [ ] constructST ( int arr [ ] , int n ) { int x = ( int ) ( Math . ceil ( Math . log ( n ) ) ) ; int max_size = 2 * ( int ) Math . pow ( 2 , x ) - 1 ; int [ ] st = new int [ max_size ] ; constructSTUtil ( arr , 0 , n - 1 , st , 0 ) ; return st ; } public static void main ( String [ ] args ) { int arr [ ] = { 5 , 2 , 3 , 0 } ; int n = arr . length ; int [ ] st = constructST ( arr , n ) ; int [ ] [ ] Q = { { 1 , 3 } , { 0 , 2 } } ; for ( int i = 0 ; i < Q . length ; i ++ ) { int max = getMax ( st , n , Q [ i ] [ 0 ] , Q [ i ] [ 1 ] ) ; int ok = 0 ; for ( int j = 30 ; j >= 0 ; j -- ) { if ( ( max & ( 1 << j ) ) != 0 ) ok = 1 ; if ( ok <= 0 ) continue ; max |= ( 1 << j ) ; } System . out . print ( max + " ▁ " ) ; } } }


"Queries to print the character that occurs the maximum number of times in a given range | Java program to find the sum of the addition of all possible subsets . ; Function that answers all the queries ; Length of the string ; Number of queries ; Prefix array ; Iterate for all the characters ; Increase the count of the character ; Presum array for all 26 characters ; Update the prefix array ; Answer every query ; Range ; Iterate for all characters ; Times the lowercase character j occurs till r - th index ; Subtract the times it occurred till ( l - 1 ) th index ; Max times it occurs ; Print the answer ; Driver Code"
Solution in Java:

class GFG { static void solveQueries ( String str , int [ ] [ ] query ) { int len = str . length ( ) ; int Q = query . length ; int [ ] [ ] pre = new int [ len ] [ 26 ] ; for ( int i = 0 ; i < len ; i ++ ) { pre [ i ] [ str . charAt ( i ) - ' a ' ] ++ ; if ( i > 0 ) { for ( int j = 0 ; j < 26 ; j ++ ) pre [ i ] [ j ] += pre [ i - 1 ] [ j ] ; } } for ( int i = 0 ; i < Q ; i ++ ) { int l = query [ i ] [ 0 ] ; int r = query [ i ] [ 1 ] ; int maxi = 0 ; char c = ' a ' ; for ( int j = 0 ; j < 26 ; j ++ ) { int times = pre [ r ] [ j ] ; if ( l > 0 ) times -= pre [ l - 1 ] [ j ] ; if ( times > maxi ) { maxi = times ; c = ( char ) ( ' a ' + j ) ; } } System . out . println ( " Query " + ( i + 1 ) + " : ▁ " + c ) ; } } public static void main ( String [ ] args ) { String str = " striver " ; int [ ] [ ] query = { { 0 , 1 } , { 1 , 6 } , { 5 , 6 } } ; solveQueries ( str , query ) ; } }


"Range LCM Queries | LCM of given range queries using Segment Tree ; allocate space for tree ; declaring the array globally ; Function to return gcd of a and b ; utility function to find lcm ; Function to build the segment tree Node starts beginning index of current subtree . start and end are indexes in arr [ ] which is global ; If there is only one element in current subarray ; build left and right segments ; build the parent ; Function to make queries for array range ) l , r ) . Node is index of root of current segment in segment tree ( Note that indexes in segment tree begin with 1 for simplicity ) . start and end are indexes of subarray covered by root of current segment . ; Completely outside the segment , returning 1 will not affect the lcm ; ; completely inside the segment ; partially inside ; Driver code ; initialize the array ; build the segment tree ; Now we can answer each query efficiently Print LCM of ( 2 , 5 ) ; Print LCM of ( 5 , 10 ) ; Print LCM of ( 0 , 10 )"
Solution in Java:

class GFG { static final int MAX = 1000 ; static int tree [ ] = new int [ 4 * MAX ] ; static int arr [ ] = new int [ MAX ] ; static int gcd ( int a , int b ) { if ( a == 0 ) { return b ; } return gcd ( b % a , a ) ; } static int lcm ( int a , int b ) { return a * b / gcd ( a , b ) ; } static void build ( int node , int start , int end ) { if ( start == end ) { tree [ node ] = arr [ start ] ; return ; } int mid = ( start + end ) / 2 ; build ( 2 * node , start , mid ) ; build ( 2 * node + 1 , mid + 1 , end ) ; int left_lcm = tree [ 2 * node ] ; int right_lcm = tree [ 2 * node + 1 ] ; tree [ node ] = lcm ( left_lcm , right_lcm ) ; } static int query ( int node , int start , int end , int l , int r ) { if ( end < l start > r ) { return 1 ; } if ( l <= start && r >= end ) { return tree [ node ] ; } int mid = ( start + end ) / 2 ; int left_lcm = query ( 2 * node , start , mid , l , r ) ; int right_lcm = query ( 2 * node + 1 , mid + 1 , end , l , r ) ; return lcm ( left_lcm , right_lcm ) ; } public static void main ( String [ ] args ) { arr [ 0 ] = 5 ; arr [ 1 ] = 7 ; arr [ 2 ] = 5 ; arr [ 3 ] = 2 ; arr [ 4 ] = 10 ; arr [ 5 ] = 12 ; arr [ 6 ] = 11 ; arr [ 7 ] = 17 ; arr [ 8 ] = 14 ; arr [ 9 ] = 1 ; arr [ 10 ] = 44 ; build ( 1 , 0 , 10 ) ; System . out . println ( query ( 1 , 0 , 10 , 2 , 5 ) ) ; System . out . println ( query ( 1 , 0 , 10 , 5 , 10 ) ) ; System . out . println ( query ( 1 , 0 , 10 , 0 , 10 ) ) ; } }


"Rare Numbers | Java implementation to check if N is a Rare number ; Iterative function to reverse digits of num ; Function to check if N is perfect square ; Find floating point value of square root of x . ; If square root is an integer ; Function to check if N is an Rare number ; Find reverse of N ; Number should be non - palindromic ; Driver code"
Solution in Java:

class GFG { static int reversDigits ( int num ) { int rev_num = 0 ; while ( num > 0 ) { rev_num = rev_num * 10 + num % 10 ; num = num / 10 ; } return rev_num ; } static boolean isPerfectSquare ( double x ) { double sr = Math . sqrt ( x ) ; return ( ( sr - Math . floor ( sr ) ) == 0 ) ; } static boolean isRare ( int N ) { int reverseN = reversDigits ( N ) ; if ( reverseN == N ) return false ; return isPerfectSquare ( N + reverseN ) && isPerfectSquare ( N - reverseN ) ; } public static void main ( String [ ] args ) { int n = 65 ; if ( isRare ( n ) ) { System . out . println ( " Yes " ) ; } else { System . out . println ( " No " ) ; } } }


"Rearrange an array to minimize sum of product of consecutive pair elements | Java program to sort an array such that sum of product of alternate element is minimum . ; create evenArr [ ] and oddArr [ ] ; sort main array in ascending order ; Put elements in oddArr [ ] and evenArr [ ] as per desired value . ; sort evenArr [ ] in descending order ; merge both sub - array and calculate minimum sum of product of alternate elements ; Driver program"
Solution in Java:

import java . util . Arrays ; import java . util . Collections ; import java . util . Comparator ; import java . util . Vector ; class GFG { static int minSum ( int arr [ ] , int n ) { Vector < Integer > evenArr = new Vector < > ( ) ; Vector < Integer > oddArr = new Vector < > ( ) ; Arrays . sort ( arr ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( i < n / 2 ) { oddArr . add ( arr [ i ] ) ; } else { evenArr . add ( arr [ i ] ) ; } } Comparator comparator = Collections . reverseOrder ( ) ; Collections . sort ( evenArr , comparator ) ; int i = 0 , sum = 0 ; for ( int j = 0 ; j < evenArr . size ( ) ; j ++ ) { arr [ i ++ ] = evenArr . get ( j ) ; arr [ i ++ ] = oddArr . get ( j ) ; sum += evenArr . get ( j ) * oddArr . get ( j ) ; } return sum ; } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 5 , 8 , 9 , 6 , 7 , 3 , 4 , 2 , 0 } ; int n = arr . length ; System . out . println ( " Minimum ▁ required ▁ sum ▁ = ▁ " + minSum ( arr , n ) ) ; System . out . println ( " Sorted ▁ array ▁ in ▁ required ▁ format ▁ : ▁ " ) ; for ( int i = 0 ; i < n ; i ++ ) { System . out . print ( arr [ i ] + " ▁ " ) ; } } }


"Rearrange array to maximize sum of GCD of array elements with their respective indices | Java program to implement the above approach ; Function to find the maximum sum of GCD ( arr [ i ] , i ) by rearranging the array ; Sort the array in ascending order ; Stores maximum sum of GCD ( arr [ i ] , i ) by rearranging the array elements ; Generate all possible permutations of the array ; Stores sum of GCD ( arr [ i ] , i ) ; Traverse the array ; Update sum ; Update res ; Driver Code"
Solution in Java:

import java . util . * ; class GFG { static int findMaxValByRearrArr ( int arr [ ] , int N ) { Arrays . sort ( arr ) ; int res = 0 ; do { int sum = 0 ; for ( int i = 0 ; i < N ; i ++ ) { sum += __gcd ( i + 1 , arr [ i ] ) ; } res = Math . max ( res , sum ) ; } while ( next_permutation ( arr ) ) ; return res ; } static int __gcd ( int a , int b ) { return b == 0 ? a : __gcd ( b , a % b ) ; } static boolean next_permutation ( int [ ] p ) { for ( int a = p . length - 2 ; a >= 0 ; -- a ) if ( p [ a ] < p [ a + 1 ] ) for ( int b = p . length - 1 ; ; -- b ) if ( p [ b ] > p [ a ] ) { int t = p [ a ] ; p [ a ] = p [ b ] ; p [ b ] = t ; for ( ++ a , b = p . length - 1 ; a < b ; ++ a , -- b ) { t = p [ a ] ; p [ a ] = p [ b ] ; p [ b ] = t ; } return true ; } return false ; } public static void main ( String [ ] args ) { int arr [ ] = { 3 , 2 , 1 } ; int N = arr . length ; System . out . print ( findMaxValByRearrArr ( arr , N ) ) ; } }


"Rearrange array to maximize sum of GCD of array elements with their respective indices | Java program to implement the above approach ; Function to find the maximum sum of GCD ( arr [ i ] , i ) by rearranging the array ; Stores maximum sum of GCD ( arr [ i ] , i ) by rearranging the array elements ; Update res ; Driver Code"
Solution in Java:

import java . util . * ; class GFG { static int findMaxValByRearrArr ( int arr [ ] , int N ) { int res = 0 ; res = ( N * ( N + 1 ) ) / 2 ; return res ; } public static void main ( String [ ] args ) { int arr [ ] = { 3 , 2 , 1 } ; int N = arr . length ; System . out . print ( findMaxValByRearrArr ( arr , N ) ) ; } }


"Reduce a given number to form a key by the given operations | Java program of the above approach ; Function to find the key of the given number ; Convert the integer to String ; Iterate the num - string to get the result ; Check if digit is even or odd ; Iterate until odd sum is obtained by adding consecutive digits ; Check if sum becomes odd ; Add the result in ans ; Assign the digit index to num string ; If the number is odd ; Iterate until odd sum is obtained by adding consecutive digits ; Check if sum becomes even ; Add the result in ans ; assign the digit index to main numstring ; Check if all digits are visited or not ; Driver Code"
Solution in Java:

import java . io . * ; import java . util . * ; import java . lang . * ; public class Main { static int key ( int N ) { String num = " " + N ; int ans = 0 ; int j = 0 ; for ( j = 0 ; j < num . length ( ) ; j ++ ) { if ( ( num . charAt ( j ) - 48 ) % 2 == 0 ) { int add = 0 ; int i ; for ( i = j ; j < num . length ( ) ; j ++ ) { add += num . charAt ( j ) - 48 ; if ( add % 2 == 1 ) break ; } if ( add == 0 ) { ans *= 10 ; } else { int digit = ( int ) Math . floor ( Math . log10 ( add ) + 1 ) ; ans *= ( Math . pow ( 10 , digit ) ) ; ans += add ; } i = j ; } else { int add = 0 ; int i ; for ( i = j ; j < num . length ( ) ; j ++ ) { add += num . charAt ( j ) - 48 ; if ( add % 2 == 0 ) { break ; } } if ( add == 0 ) { ans *= 10 ; } else { int digit = ( int ) Math . floor ( Math . log10 ( add ) + 1 ) ; ans *= ( Math . pow ( 10 , digit ) ) ; ans += add ; } i = j ; } } if ( j + 1 >= num . length ( ) ) { return ans ; } else { return ans += num . charAt ( num . length ( ) - 1 ) - 48 ; } } public static void main ( String [ ] args ) { int N = 1667848271 ; System . out . print ( key ( N ) ) ; } }


"Reduce given three Numbers by decrementing in Pairs | Java program for the above approach ; Function to find the minimum number operations ; Insert the three numbers in array ; Sort the array ; Case 2 ; Case 1 ; Driver Code ; Given A , B , C ; Function call"
Solution in Java:

import java . util . * ; class GFG { public static int solution ( int A , int B , int C ) { int arr [ ] = new int [ 3 ] ; arr [ 0 ] = A ; arr [ 1 ] = B ; arr [ 2 ] = C ; Arrays . sort ( arr ) ; if ( arr [ 2 ] < arr [ 0 ] + arr [ 1 ] ) return ( ( arr [ 0 ] + arr [ 1 ] + arr [ 2 ] ) / 2 ) ; else return ( arr [ 0 ] + arr [ 1 ] ) ; } public static void main ( String [ ] args ) { int A = 8 , B = 1 , C = 5 ; System . out . println ( solution ( A , B , C ) ) ; } }


"Reduce string by removing outermost parenthesis from each primitive substring | Java program to implement the above approach ; Function to remove the outermost parentheses of every primitive substring from the given string ; Stores the resultant string ; Stores the count of opened parentheses ; Traverse the string ; If opening parenthesis is encountered and their count exceeds 0 ; Include the character ; If closing parenthesis is encountered and their count is less than count of opening parentheses ; Include the character ; Return the resultant string ; Driver Code"
Solution in Java:

import java . io . * ; class GFG { static String removeOuterParentheses ( String S ) { String res = " " ; int count = 0 ; for ( int c = 0 ; c < S . length ( ) ; c ++ ) { if ( S . charAt ( c ) == ' ( ' && count ++ > 0 ) res += S . charAt ( c ) ; if ( S . charAt ( c ) == ' ) ' && count -- > 1 ) res += S . charAt ( c ) ; } return res ; } public static void main ( String [ ] args ) { String S = " ( ( ) ( ) ) ( ( ) ) ( ) " ; System . out . print ( removeOuterParentheses ( S ) ) ; } }


"Reduce the array to a single element with the given operation | Java implementation of the approach ; Function to return the final element ; Driver code"
Solution in Java:

class OddPosition { public static long getFinalElement ( long n ) { long finalNum ; for ( finalNum = 2 ; finalNum * 2 <= n ; finalNum *= 2 ) ; return finalNum ; } public static void main ( String [ ] args ) { int N = 12 ; System . out . println ( getFinalElement ( N ) ) ; } }


"Remove all characters other than alphabets from string | Java program to remove all the characters other then alphabets ; function to remove characters and print new string ; Finding the character whose ASCII value fall under this range ; erase function to erase the character ; Driver code"
Solution in Java:

class GFG { static void removeSpecialCharacter ( String s ) { for ( int i = 0 ; i < s . length ( ) ; i ++ ) { if ( s . charAt ( i ) < ' A ' || s . charAt ( i ) > ' Z ' && s . charAt ( i ) < ' a ' || s . charAt ( i ) > ' z ' ) { s = s . substring ( 0 , i ) + s . substring ( i + 1 ) ; i -- ; } } System . out . print ( s ) ; } public static void main ( String [ ] args ) { String s = " $ Gee * k ; s . . fo , ▁ r ' Ge ^ eks ? " ; removeSpecialCharacter ( s ) ; } }


"Remove all characters other than alphabets from string | Java program to remove all the characters other then alphabets ; function to remove characters and print new string ; Store only valid characters ; driver code"
Solution in Java:

class GFG { static void removeSpecialCharacter ( String str ) { char [ ] s = str . toCharArray ( ) ; int j = 0 ; for ( int i = 0 ; i < s . length ; i ++ ) { if ( ( s [ i ] >= ' A ' && s [ i ] <= ' Z ' ) || ( s [ i ] >= ' a ' && s [ i ] <= ' z ' ) ) { s [ j ] = s [ i ] ; j ++ ; } } System . out . println ( String . valueOf ( s ) . substring ( 0 , j ) ) ; } public static void main ( String [ ] args ) { String s = " $ Gee * k ; s . . fo , ▁ r ' Ge ^ eks ? " ; removeSpecialCharacter ( s ) ; } }


"Remove minimum number of characters so that two strings become anagram | Java program to find minimum number of characters to be removed to make two strings anagram . ; function to calculate minimum numbers of characters to be removed to make two strings anagram ; make hash array for both string and calculate frequency of each character ; count frequency of each character in first string ; count frequency of each character in second string ; traverse count arrays to find number of characters to be removed ; Driver program to run the case"
Solution in Java:

import java . util . * ; class GFG { static int remAnagram ( String str1 , String str2 ) { int count1 [ ] = new int [ 26 ] ; int count2 [ ] = new int [ 26 ] ; for ( int i = 0 ; i < str1 . length ( ) ; i ++ ) count1 [ str1 . charAt ( i ) - ' a ' ] ++ ; for ( int i = 0 ; i < str2 . length ( ) ; i ++ ) count2 [ str2 . charAt ( i ) - ' a ' ] ++ ; int result = 0 ; for ( int i = 0 ; i < 26 ; i ++ ) result += Math . abs ( count1 [ i ] - count2 [ i ] ) ; return result ; } public static void main ( String [ ] args ) { String str1 = " bcadeh " , str2 = " hea " ; System . out . println ( remAnagram ( str1 , str2 ) ) ; } }


"Remove minimum numbers from the array to get minimum OR value | Java implementation of the approach ; Function to return the minimum deletions to get minimum OR ; To store the minimum element ; Find the minimum element from the array ; To store the frequency of the minimum element ; Find the frequency of the minimum element ; Return the final answer ; Driver code"
Solution in Java:

class GFG { static int findMinDel ( int [ ] arr , int n ) { int min_num = Integer . MAX_VALUE ; for ( int i = 0 ; i < n ; i ++ ) min_num = Math . min ( arr [ i ] , min_num ) ; int cnt = 0 ; for ( int i = 0 ; i < n ; i ++ ) if ( arr [ i ] == min_num ) cnt ++ ; return n - cnt ; } public static void main ( String [ ] args ) { int arr [ ] = { 3 , 3 , 2 } ; int n = arr . length ; System . out . print ( findMinDel ( arr , n ) ) ; } }


"Replace ' ? ' to convert given string to a binary string with maximum count of '0' and "10" | Java program to implement the above approach ; Function to maximize count of 0 and 10 by replacing character ' ? ' to '0' or '1' ; Traverse the given String ; If current character is ' ? ' ; Replace str [ i ] to '0' ; Driver Code ; Given String"
Solution in Java:

class GFG { static void findMaxOccurence ( char [ ] str , int N ) { for ( int i = 0 ; i < N ; i ++ ) { if ( str [ i ] == ' ? ' ) { str [ i ] = '0' ; } } System . out . print ( str ) ; } public static void main ( String [ ] args ) { String str = "10?0?11" ; int N = str . length ( ) ; findMaxOccurence ( str . toCharArray ( ) , N ) ; } }


"Replace every character of string by character whose ASCII value is K times more than it | Java program to move every character K times ahead in a given string ; Function to move string character ; changed string ; iterate for every characters ; ASCII value ; store the duplicate ; if k - th ahead character exceed ' z ' ; print the new string ; Driver Code ; function call"
Solution in Java:

class GFG { static void encode ( String s , int k ) { String newS = " " ; for ( int i = 0 ; i < s . length ( ) ; ++ i ) { int val = s . charAt ( i ) ; int dup = k ; if ( val + k > 122 ) { k -= ( 122 - val ) ; k = k % 26 ; newS += ( char ) ( 96 + k ) ; } else { newS += ( char ) ( val + k ) ; } k = dup ; } System . out . println ( newS ) ; } public static void main ( String [ ] args ) { String str = " abc " ; int k = 28 ; encode ( str , k ) ; } }


"Replace every matrix element with maximum of GCD of row or column | Java program to replace each each element with maximum of GCD of row or column . ; returning the greatest common divisor of two number ; Finding GCD of each row and column and replacing with each element with maximum of GCD of row or column . ; Calculating GCD of each row and each column in O ( mn ) and store in arrays . ; Replacing matrix element ; Driver program"
Solution in Java:

import java . io . * ; class GFG { static int R = 3 ; static int C = 4 ; static int gcd ( int a , int b ) { if ( b == 0 ) return a ; return gcd ( b , a % b ) ; } static void replacematrix ( int [ ] [ ] mat , int n , int m ) { int [ ] rgcd = new int [ R ] ; int [ ] cgcd = new int [ C ] ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = 0 ; j < m ; j ++ ) { rgcd [ i ] = gcd ( rgcd [ i ] , mat [ i ] [ j ] ) ; cgcd [ j ] = gcd ( cgcd [ j ] , mat [ i ] [ j ] ) ; } } for ( int i = 0 ; i < n ; i ++ ) for ( int j = 0 ; j < m ; j ++ ) mat [ i ] [ j ] = Math . max ( rgcd [ i ] , cgcd [ j ] ) ; } static public void main ( String [ ] args ) { int [ ] [ ] m = { { 1 , 2 , 3 , 3 } , { 4 , 5 , 6 , 6 } , { 7 , 8 , 9 , 9 } , } ; replacematrix ( m , R , C ) ; for ( int i = 0 ; i < R ; i ++ ) { for ( int j = 0 ; j < C ; j ++ ) System . out . print ( m [ i ] [ j ] + " ▁ " ) ; System . out . println ( ) ; } } }


"Reverse actual bits of the given number | Java implementation to reverse bits of a number ; function to reverse bits of a number ; traversing bits of ' n ' from the right ; bitwise left shift ' rev ' by 1 ; if current bit is '1' ; bitwise right shift ' n ' by 1 ; required number ; Driver code"
Solution in Java:

class GFG { public static int reverseBits ( int n ) { int rev = 0 ; while ( n > 0 ) { rev <<= 1 ; if ( ( int ) ( n & 1 ) == 1 ) rev ^= 1 ; n >>= 1 ; } return rev ; } public static void main ( String [ ] args ) { int n = 11 ; System . out . println ( reverseBits ( n ) ) ; } }


"Reverse words in a given string | Java code to reverse a string ; Reverse the string ; Check if number of words is even ; Find the middle word ; Starting from the middle start swapping words at jth position and l - 1 - j position ; Check if number of words is odd ; Find the middle word ; Starting from the middle start swapping the words at jth position and l - 1 - j position ; Return the reversed sentence ; Driver Code"
Solution in Java:

class GFG { public static String [ ] RevString ( String [ ] s , int l ) { if ( l % 2 == 0 ) { int j = l / 2 ; while ( j <= l - 1 ) { String temp ; temp = s [ l - j - 1 ] ; s [ l - j - 1 ] = s [ j ] ; s [ j ] = temp ; j += 1 ; } } else { int j = ( l / 2 ) + 1 ; while ( j <= l - 1 ) { String temp ; temp = s [ l - j - 1 ] ; s [ l - j - 1 ] = s [ j ] ; s [ j ] = temp ; j += 1 ; } } return s ; } public static void main ( String [ ] args ) { String s = " getting ▁ good ▁ at ▁ coding ▁ " + " needs ▁ a ▁ lot ▁ of ▁ practice " ; String [ ] words = s . split ( " \\ s " ) ; words = RevString ( words , words . length ) ; s = String . join ( " ▁ " , words ) ; System . out . println ( s ) ; } }


"Reverse words in a given string | Java program to reverse a string s = input ( )"
Solution in Java:

public class ReverseWords { public static void main ( String [ ] args ) { String s [ ] = " i ▁ like ▁ this ▁ program ▁ very ▁ much " . split ( " ▁ " ) ; String ans = " " ; for ( int i = s . length - 1 ; i >= 0 ; i -- ) { ans += s [ i ] + " ▁ " ; } System . out . println ( " Reversed ▁ String : " ) ; System . out . println ( ans . substring ( 0 , ans . length ( ) - 1 ) ) ; } }


"Rotate all Matrix elements except the diagonal K times by 90 degrees in clockwise direction | Java program for the above approach ; Function to print the matrix ; Iterate over the rows ; Iterate over the columns ; Print the value ; Function to perform the swapping of matrix elements in clockwise manner ; Stores the last row ; Stores the last column ; Perform the swaps ; Function to rotate non - diagonal elements of the matrix K times in clockwise direction ; Update K to K % 4 ; Iterate until K is positive ; Iterate each up to N / 2 - th row ; Iterate each column from i to N - i - 1 ; Check if the element at i , j is not a diagonal element ; Perform the swapping ; Print the matrix ; Driver Code"
Solution in Java:

import java . io . * ; import java . lang . * ; import java . util . * ; public class GFG { static void print ( int mat [ ] [ ] ) { for ( int i = 0 ; i < mat . length ; i ++ ) { for ( int j = 0 ; j < mat [ 0 ] . length ; j ++ ) System . out . print ( mat [ i ] [ j ] + " ▁ " ) ; System . out . println ( ) ; } } static void performSwap ( int mat [ ] [ ] , int i , int j ) { int N = mat . length ; int ei = N - 1 - i ; int ej = N - 1 - j ; int temp = mat [ i ] [ j ] ; mat [ i ] [ j ] = mat [ ej ] [ i ] ; mat [ ej ] [ i ] = mat [ ei ] [ ej ] ; mat [ ei ] [ ej ] = mat [ j ] [ ei ] ; mat [ j ] [ ei ] = temp ; } static void rotate ( int mat [ ] [ ] , int N , int K ) { K = K % 4 ; while ( K -- > 0 ) { for ( int i = 0 ; i < N / 2 ; i ++ ) { for ( int j = i ; j < N - i - 1 ; j ++ ) { if ( i != j && ( i + j ) != N - 1 ) { performSwap ( mat , i , j ) ; } } } } print ( mat ) ; } public static void main ( String [ ] args ) { int K = 5 ; int mat [ ] [ ] = { { 1 , 2 , 3 , 4 } , { 6 , 7 , 8 , 9 } , { 11 , 12 , 13 , 14 } , { 16 , 17 , 18 , 19 } , } ; int N = mat . length ; rotate ( mat , N , K ) ; } }


"Search an element in a sorted and rotated array with duplicates | Java implementation of the approach ; Function to return the index of the key in arr [ l . . h ] if the key is present otherwise return - 1 ; The tricky case , just update left and right ; If arr [ l ... mid ] is sorted ; As this subarray is sorted , we can quickly check if key lies in any of the halves ; If key does not lie in the first half subarray then divide the other half into two subarrays such that we can quickly check if key lies in the other half ; If arr [ l . . mid ] first subarray is not sorted then arr [ mid ... h ] must be sorted subarray ; Driver code"
Solution in Java:

class GFG { static int search ( int arr [ ] , int l , int h , int key ) { if ( l > h ) return - 1 ; int mid = ( l + h ) / 2 ; if ( arr [ mid ] == key ) return mid ; if ( ( arr [ l ] == arr [ mid ] ) && ( arr [ h ] == arr [ mid ] ) ) { l ++ ; h -- ; return search ( arr , l , h , key ) ; } else if ( arr [ l ] <= arr [ mid ] ) { if ( key >= arr [ l ] && key <= arr [ mid ] ) return search ( arr , l , mid - 1 , key ) ; else return search ( arr , mid + 1 , h , key ) ; } else if ( key >= arr [ mid ] && key <= arr [ h ] ) return search ( arr , mid + 1 , h , key ) ; return search ( arr , l , mid - 1 , key ) ; } public static void main ( String [ ] args ) { int arr [ ] = { 3 , 3 , 1 , 2 , 3 , 3 } ; int n = arr . length ; int key = 3 ; System . out . println ( search ( arr , 0 , n - 1 , key ) ) ; } }


"Search an element in a sorted and rotated array | Java program to search an element in sorted and rotated array using single pass of Binary Search ; Returns index of key in arr [ l . . h ] if key is present , otherwise returns - 1 ; If arr [ l ... mid ] first subarray is sorted ; As this subarray is sorted , we can quickly check if key lies in half or other half ; If key not lies in first half subarray , Divide other half into two subarrays , such that we can quickly check if key lies in other half ; If arr [ l . . mid ] first subarray is not sorted , then arr [ mid ... h ] must be sorted subarry ; main function"
Solution in Java:

class Main { static int search ( int arr [ ] , int l , int h , int key ) { if ( l > h ) return - 1 ; int mid = ( l + h ) / 2 ; if ( arr [ mid ] == key ) return mid ; if ( arr [ l ] <= arr [ mid ] ) { if ( key >= arr [ l ] && key <= arr [ mid ] ) return search ( arr , l , mid - 1 , key ) ; return search ( arr , mid + 1 , h , key ) ; } if ( key >= arr [ mid ] && key <= arr [ h ] ) return search ( arr , mid + 1 , h , key ) ; return search ( arr , l , mid - 1 , key ) ; } public static void main ( String args [ ] ) { int arr [ ] = { 4 , 5 , 6 , 7 , 8 , 9 , 1 , 2 , 3 } ; int n = arr . length ; int key = 6 ; int i = search ( arr , 0 , n - 1 , key ) ; if ( i != - 1 ) System . out . println ( " Index : ▁ " + i ) ; else System . out . println ( " Key ▁ not ▁ found " ) ; } }


"Segregate 0 s and 1 s in an array |  ; Function to put all 0 s on left and all 1 s on right ; Initialize left and right indexes ; Increment left index while we see 0 at left ; Decrement right index while we see 1 at right ; If left is smaller than right then there is a 1 at left and a 0 at right . Exchange arr [ left ] and arr [ right ] ; Driver Program to test above functions"
Solution in Java:

class Segregate { void segregate0and1 ( int arr [ ] , int size ) { int left = 0 , right = size - 1 ; while ( left < right ) { while ( arr [ left ] == 0 && left < right ) left ++ ; while ( arr [ right ] == 1 && left < right ) right -- ; if ( left < right ) { arr [ left ] = 0 ; arr [ right ] = 1 ; left ++ ; right -- ; } } } public static void main ( String [ ] args ) { Segregate seg = new Segregate ( ) ; int arr [ ] = new int [ ] { 0 , 1 , 0 , 1 , 1 , 1 } ; int i , arr_size = arr . length ; seg . segregate0and1 ( arr , arr_size ) ; System . out . print ( " Array ▁ after ▁ segregation ▁ is ▁ " ) ; for ( i = 0 ; i < 6 ; i ++ ) System . out . print ( arr [ i ] + " ▁ " ) ; } }


"Segregate 0 s and 1 s in an array | Java code to Segregate 0 s and 1 s in an array ; function to segregate 0 s and 1 s ; counts the no of zeros in arr ; loop fills the arr with 0 until count ; loop fills remaining arr space with 1 ; function to print segregated array ; driver function"
Solution in Java:

class GFG { static void segregate0and1 ( int arr [ ] , int n ) { int count = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( arr [ i ] == 0 ) count ++ ; } for ( int i = 0 ; i < count ; i ++ ) arr [ i ] = 0 ; for ( int i = count ; i < n ; i ++ ) arr [ i ] = 1 ; } static void print ( int arr [ ] , int n ) { System . out . print ( " Array ▁ after ▁ segregation ▁ is ▁ " ) ; for ( int i = 0 ; i < n ; i ++ ) System . out . print ( arr [ i ] + " ▁ " ) ; } public static void main ( String [ ] args ) { int arr [ ] = new int [ ] { 0 , 1 , 0 , 1 , 1 , 1 } ; int n = arr . length ; segregate0and1 ( arr , n ) ; print ( arr , n ) ; } }


"Segregate 0 s and 1 s in an array | Java code to segregate 0 and 1 ; * Method for segregation 0 and 1 given input array ; Driver program"
Solution in Java:

import java . util . * ; class GFG { static void segregate0and1 ( int arr [ ] ) { int type0 = 0 ; int type1 = arr . length - 1 ; while ( type0 < type1 ) { if ( arr [ type0 ] == 1 ) { arr [ type1 ] = arr [ type1 ] + arr [ type0 ] ; arr [ type0 ] = arr [ type1 ] - arr [ type0 ] ; arr [ type1 ] = arr [ type1 ] - arr [ type0 ] ; type1 -- ; } else { type0 ++ ; } } } public static void main ( String [ ] args ) { int [ ] array = { 0 , 1 , 0 , 1 , 1 , 1 } ; segregate0and1 ( array ) ; for ( int a : array ) { System . out . print ( a + " ▁ " ) ; } } }


"Segregate Prime and Non | Java program for the above approach ; Function to generate prime numbers using Sieve of Eratosthenes ; If prime [ p ] is unchanged , then it is a prime ; Update all multiples of p ; Function to segregate the primes and non - primes ; Generate all primes till 10 ^ ; Initialize left and right ; Traverse the array ; Increment left while array element at left is prime ; Decrement right while array element at right is non - prime ; If left < right , then swap arr [ left ] and arr [ right ] ; Swap arr [ left ] and arr [ right ] ; Print segregated array ; Driver code ; Function Call"
Solution in Java:

import java . util . * ; class GFG { public static void SieveOfEratosthenes ( boolean [ ] prime , int n ) { for ( int p = 2 ; p * p <= n ; p ++ ) { if ( prime [ p ] == true ) { for ( int i = p * p ; i <= n ; i += p ) prime [ i ] = false ; } } } public static void segregatePrimeNonPrime ( boolean [ ] prime , int arr [ ] , int N ) { SieveOfEratosthenes ( prime , 10000000 ) ; int left = 0 , right = N - 1 ; while ( left < right ) { while ( prime [ arr [ left ] ] ) left ++ ; while ( ! prime [ arr [ right ] ] ) right -- ; if ( left < right ) { int temp = arr [ left ] ; arr [ left ] = arr [ right ] ; arr [ right ] = temp ; left ++ ; right -- ; } } for ( int i = 0 ; i < N ; i ++ ) System . out . printf ( arr [ i ] + " ▁ " ) ; } public static void main ( String [ ] args ) { boolean [ ] prime = new boolean [ 10000001 ] ; Arrays . fill ( prime , true ) ; int arr [ ] = { 2 , 3 , 4 , 6 , 7 , 8 , 9 , 10 } ; int N = arr . length ; segregatePrimeNonPrime ( prime , arr , N ) ; } }


"Sentinel Linear Search | Java implementation of the approach ; Function to search x in the given array ; Last element of the array ; Element to be searched is placed at the last index ; Put the last element back ; Driver code"
Solution in Java:

class GFG { static void sentinelSearch ( int arr [ ] , int n , int key ) { int last = arr [ n - 1 ] ; arr [ n - 1 ] = key ; int i = 0 ; while ( arr [ i ] != key ) i ++ ; arr [ n - 1 ] = last ; if ( ( i < n - 1 ) || ( arr [ n - 1 ] == key ) ) System . out . println ( key + " ▁ is ▁ present ▁ at ▁ index ▁ " + i ) ; else System . out . println ( " Element ▁ Not ▁ found " ) ; } public static void main ( String [ ] args ) { int arr [ ] = { 10 , 20 , 180 , 30 , 60 , 50 , 110 , 100 , 70 } ; int n = arr . length ; int key = 180 ; sentinelSearch ( arr , n , key ) ; } }


"Smallest N digit number divisible by all possible prime digits | Java implementation of the above approach ; Function to find the minimum number of n digits divisible by all prime digits ; Driver code"
Solution in Java:

class GFG { static void minNum ( int n ) { if ( n < 3 ) System . out . println ( - 1 ) ; else System . out . println ( 210 * ( ( int ) ( Math . pow ( 10 , n - 1 ) / 210 ) + 1 ) ) ; } public static void main ( String [ ] args ) { int n = 5 ; minNum ( n ) ; } }


"Smallest character in a string having minimum sum of distances between consecutive repetitions | Java program for the above approach ; Function to find the character repeats with minimum distance ; Stores the first and last index ; Initialize with - 1 ; Get the values of last and first occurence ; Update the first index ; Update the last index ; Initialize min ; Get the minimum ; Values must not be same ; Update the minimum distance ; return ans ; Driver Code ; Function Call"
Solution in Java:

import java . util . * ; class GFG { static char minDistChar ( char [ ] s ) { int n = s . length ; int [ ] first = new int [ 26 ] ; int [ ] last = new int [ 26 ] ; for ( int i = 0 ; i < 26 ; i ++ ) { first [ i ] = - 1 ; last [ i ] = - 1 ; } for ( int i = 0 ; i < n ; i ++ ) { if ( first [ s [ i ] - ' a ' ] == - 1 ) { first [ s [ i ] - ' a ' ] = i ; } last [ s [ i ] - ' a ' ] = i ; } int min = Integer . MAX_VALUE ; char ans = '1' ; for ( int i = 0 ; i < 26 ; i ++ ) { if ( last [ i ] == first [ i ] ) continue ; if ( min > last [ i ] - first [ i ] ) { min = last [ i ] - first [ i ] ; ans = ( char ) ( i + ' a ' ) ; } } return ans ; } public static void main ( String [ ] args ) { String str = " geeksforgeeks " ; System . out . print ( minDistChar ( str . toCharArray ( ) ) ) ; } }


"Smallest number exceeding N whose Kth bit is set | Java program for the above approach ; Function to find the number greater than n whose Kth bit is set ; Iterate from N + 1 ; Check if Kth bit is set or not ; Increment M for next number ; Return the minimum value ; Driver Code ; Given N and K ; Function Call"
Solution in Java:

import java . util . * ; class GFG { static int find_next ( int n , int k ) { int M = n + 1 ; while ( true ) { if ( ( M & ( 1L << k ) ) > 0 ) break ; M ++ ; } return M ; } public static void main ( String [ ] args ) { int N = 15 , K = 2 ; System . out . print ( find_next ( N , K ) ) ; } }


"Smallest number exceeding N whose Kth bit is set | Java program for the above approach ; Function to find the number greater than n whose Kth bit is set ; Stores the resultant number ; If Kth bit is not set ; cur will be the sum of all powers of 2 < k ; If the current bit is set ; Add Kth power of 2 to n and subtract the all powers of 2 less than K that are set ; If the kth bit is set ; First unset bit position ; sum of bits that are set ; Add Kth power of 2 to n and subtract the all powers of 2 less than K that are set ; If Kth bit became unset then set it again ; Return the resultant number ; Driver Code ; Print ans"
Solution in Java:

import java . util . * ; class GFG { static int find_next ( int n , int k ) { int ans = 0 ; if ( ( n & ( 1L << k ) ) == 0 ) { int cur = 0 ; for ( int i = 0 ; i < k ; i ++ ) { if ( ( n & ( 1L << i ) ) > 0 ) cur += 1L << i ; } ans = ( int ) ( n - cur + ( 1L << k ) ) ; } else { int first_unset_bit = - 1 , cur = 0 ; for ( int i = 0 ; i < 64 ; i ++ ) { if ( ( n & ( 1L << i ) ) == 0 ) { first_unset_bit = i ; break ; } else cur += ( 1L << i ) ; } ans = ( int ) ( n - cur + ( 1L << first_unset_bit ) ) ; if ( ( ans & ( 1L << k ) ) == 0 ) ans += ( 1L << k ) ; } return ans ; } public static void main ( String [ ] args ) { int N = 15 , K = 2 ; System . out . print ( find_next ( N , K ) ) ; } }


"Smallest number greater than Y with sum of digits equal to X | Java program for the above approach ; Function to return the minimum String of length d having the sum of digits s ; Return a String of length d ; Greedily put 9 's in the end ; Put remaining sum ; Function to find the smallest number greater than Y whose sum of digits is X ; Convert number y to String ; Maintain prefix sum of digits ; Iterate over Y from the back where k is current length of suffix ; Stores current digit ; Increase current digit ; Sum upto current prefix ; Return answer if remaining sum can be obtained in suffix ; Find suffix of length k having sum of digits x - r ; Append current character ; Return the result ; Driver code ; Given number and sum ; Function call"
Solution in Java:

import java . util . * ; @ SuppressWarnings ( " unchecked " ) class GFG { static String helper ( int d , int s ) { StringBuilder ans = new StringBuilder ( ) ; for ( int i = 0 ; i < d ; i ++ ) { ans . append ( "0" ) ; } for ( int i = d - 1 ; i >= 0 ; i -- ) { if ( s >= 9 ) { ans . setCharAt ( i , '9' ) ; s -= 9 ; } else { char c = ( char ) ( s + ( int ) '0' ) ; ans . setCharAt ( i , c ) ; s = 0 ; } } return ans . toString ( ) ; } static String findMin ( int x , int Y ) { String y = Integer . toString ( Y ) ; int n = y . length ( ) ; ArrayList p = new ArrayList ( ) ; for ( int i = 0 ; i < n ; i ++ ) { p . add ( 0 ) ; } for ( int i = 0 ; i < n ; i ++ ) { p . add ( i , ( int ) ( ( int ) y . charAt ( i ) - ( int ) '0' ) ) ; if ( i > 0 ) { p . add ( i , ( int ) p . get ( i ) + ( int ) p . get ( i - 1 ) ) ; } } for ( int i = n - 1 , k = 0 ; ; i -- , k ++ ) { int d = 0 ; if ( i >= 0 ) { d = ( int ) y . charAt ( i ) - ( int ) '0' ; } for ( int j = d + 1 ; j <= 9 ; j ++ ) { int r = j ; if ( i > 0 ) { r += ( int ) p . get ( i - 1 ) ; } if ( x - r >= 0 && x - r <= 9 * k ) { String suf = helper ( k , x - r ) ; String pre = " " ; if ( i > 0 ) pre = y . substring ( 0 , i ) ; char cur = ( char ) ( j + ( int ) '0' ) ; pre += cur ; return pre + suf ; } } } } public static void main ( String [ ] arg ) { int x = 18 ; int y = 99 ; System . out . print ( findMin ( x , y ) ) ; } }


"Smallest power of 2 greater than or equal to n | Java program to find smallest power of 2 greater than or equal to n ; Driver Code"
Solution in Java:

import java . io . * ; class GFG { static int nextPowerOf2 ( int n ) { int p = 1 ; if ( n > 0 && ( n & ( n - 1 ) ) == 0 ) return n ; while ( p < n ) p <<= 1 ; return p ; } public static void main ( String args [ ] ) { int n = 5 ; System . out . println ( nextPowerOf2 ( n ) ) ; } }


"Smallest power of 2 greater than or equal to n | Java program to find smallest power of 2 greater than or equal to n ; Finds next power of two for n . If n itself is a power of two then returns n ; Driver Code"
Solution in Java:

import java . io . * ; class GFG { static int nextPowerOf2 ( int n ) { n -- ; n |= n >> 1 ; n |= n >> 2 ; n |= n >> 4 ; n |= n >> 8 ; n |= n >> 16 ; n ++ ; return n ; } public static void main ( String args [ ] ) { int n = 5 ; System . out . println ( nextPowerOf2 ( n ) ) ; } }


"Smallest power of 2 greater than or equal to n | Java program to find smallest power of 2 greater than or equal to n ; First n in the below condition is for the case where n is 0 ; Driver Code"
Solution in Java:

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


"Smallest power of 2 which is greater than or equal to sum of array elements | Java implementation of the above approach ; Function to find the nearest power of 2 ; The number ; If already a power of 2 ; Find the next power of 2 ; Function to find the memory used ; Sum of array ; Traverse and find the sum of array ; Function call to find the nearest power of 2 ; Driver Code"
Solution in Java:

class GFG { static int nextPowerOf2 ( int n ) { int p = 1 ; if ( n != 0 && ( ( n & ( n - 1 ) ) == 0 ) ) return n ; while ( p < n ) p <<= 1 ; return p ; } static int memoryUsed ( int arr [ ] , int n ) { int sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) sum += arr [ i ] ; int nearest = nextPowerOf2 ( sum ) ; return nearest ; } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 2 , 3 , 2 } ; int n = arr . length ; System . out . println ( memoryUsed ( arr , n ) ) ; } }


"Smallest power of 4 greater than or equal to N | Java implementation of above approach ; Function to return the smallest power of 4 greater than or equal to n ; If n is itself is a power of 4 then return n ; Driver code"
Solution in Java:

import java . util . * ; import java . lang . Math ; import java . io . * ; class GFG { static int nextPowerOfFour ( int n ) { int x = ( int ) Math . floor ( Math . sqrt ( Math . sqrt ( n ) ) ) ; if ( Math . pow ( x , 4 ) == n ) return n ; else { x = x + 1 ; return ( int ) Math . pow ( x , 4 ) ; } } public static void main ( String [ ] args ) throws java . lang . Exception { int n = 122 ; System . out . println ( nextPowerOfFour ( n ) ) ; } }


"Smallest subset with sum greater than all other elements | Java code to find minimum number of elements such that their sum is greater than sum of remaining elements of the array . ; Function to find minimum elements needed ; Calculating HALF of array sum ; Sort the array in ascending order and start traversing array from the ascending sort in descending order . ; Current sum greater than sum ; Driver Code"
Solution in Java:

import java . io . * ; import java . util . * ; class GFG { static int minElements ( int arr [ ] , int n ) { int halfSum = 0 ; for ( int i = 0 ; i < n ; i ++ ) halfSum = halfSum + arr [ i ] ; halfSum = halfSum / 2 ; Arrays . sort ( arr ) ; int res = 0 , curr_sum = 0 ; for ( int i = n - 1 ; i >= 0 ; i -- ) { curr_sum += arr [ i ] ; res ++ ; if ( curr_sum > halfSum ) return res ; } return res ; } public static void main ( String [ ] args ) { int arr [ ] = { 3 , 1 , 7 , 1 } ; int n = arr . length ; System . out . println ( minElements ( arr , n ) ) ; } }


"Sophie Germain Prime | Java program to print all sophie german  prime number till n . ; function to detect prime number here we have used sieve method https : www . geeksforgeeks . org / sieve - of - eratosthenes / to detect prime number ; If prime [ p ] is not changed , then it is a prime ; Update all multiples of p ; We have made array till 2 * n + 1 so that we can check prime number till that and conclude about sophie german prime . ; checking every i whether it is sophie german prime or not . ; Driver code"
Solution in Java:

import java . io . * ; import java . util . * ; class GFG { static void sieve ( int n , boolean prime [ ] ) { for ( int p = 2 ; p * p <= n ; p ++ ) { if ( prime [ p ] == true ) { for ( int i = p * 2 ; i < n ; i += p ) prime [ i ] = false ; } } } static void printSophieGermanNumber ( int n ) { boolean prime [ ] = new boolean [ 2 * n + 1 ] ; Arrays . fill ( prime , true ) ; sieve ( 2 * n + 1 , prime ) ; for ( int i = 2 ; i < n ; ++ i ) { if ( prime [ i ] && prime [ 2 * i + 1 ] ) System . out . print ( i + " ▁ " ) ; } } public static void main ( String args [ ] ) { int n = 25 ; printSophieGermanNumber ( n ) ; } }


"Sort Linked List containing values from 1 to N | Java program to sort linked list containing values from 1 to N ; Link list node ; Function to sort linked list ; Function to add a node at the beginning of Linked List ; allocate node ; put in the data ; link the old list off the new node ; move the head to point to the new node ; This function prints contents of linked list starting from the given node ; Driver Code ; The constructed linked list is : 3 -> 5 -> 4 -> 6 -> 1 -> 2"
Solution in Java:

import java . util . * ; class GFG { static class Node { int data ; Node next ; } ; static Node start ; static void sortList ( Node head ) { int startVal = 1 ; while ( head != null ) { head . data = startVal ; startVal ++ ; head = head . next ; } } static void push ( Node head_ref , int new_data ) { Node new_node = new Node ( ) ; new_node . data = new_data ; new_node . next = head_ref ; head_ref = new_node ; start = head_ref ; } static void printList ( Node node ) { while ( node != null ) { System . out . print ( node . data + " ▁ " ) ; node = node . next ; } } public static void main ( String [ ] args ) { start = null ; push ( start , 2 ) ; push ( start , 1 ) ; push ( start , 6 ) ; push ( start , 4 ) ; push ( start , 5 ) ; push ( start , 3 ) ; sortList ( start ) ; printList ( start ) ; } }