"Number of turns to reach from one node to other in binary tree | A Java Program to count number of turns in a Binary Tree . ; A Binary Tree Node ; Constructor ; Utility function to find the LCA of two given values n1 and n2 . ; Base case ; If either n1 or n2 matches with root 's key, report the presence by  returning root (Note that if a key  is ancestor of other, then the  ancestor key becomes LCA ; Look for keys in left and right subtrees ; If both of the above calls return Non - NULL , then one key is present in once subtree and other is present in other , So this node is the LCA ; Otherwise check if left subtree or right subtree is LCA ; function count number of turn need to reach given node from it 's LCA we have two way to ; if found the key value in tree ; Case 1 : ; Case 2 : ; Function to find nodes common to given two nodes ; there is no path between these two node ; case 1 : ; count number of turns needs to reached the second node from LCA ; count number of turns needs to reached the first node from LCA ; case 2 : ; count number of turns needs to reached the second node from LCA ; count number of turns needs to reached the first node from LCA1 ; Driver program to test above functions ; Let us create binary tree given in the above example"
How can the above be solved in Java?

public class Turns_to_reach_another_node { static int Count ; static class Node { Node left , right ; int key ; Node ( int key ) { this . key = key ; left = null ; right = null ; } } static Node findLCA ( Node root , int n1 , int n2 ) { if ( root == null ) return null ; if ( root . key == n1 root . key == n2 ) return root ; Node left_lca = findLCA ( root . left , n1 , n2 ) ; Node right_lca = findLCA ( root . right , n1 , n2 ) ; if ( left_lca != null && right_lca != null ) return root ; return ( left_lca != null ) ? left_lca : right_lca ; } static boolean CountTurn ( Node root , int key , boolean turn ) { if ( root == null ) return false ; if ( root . key == key ) return true ; if ( turn == true ) { if ( CountTurn ( root . left , key , turn ) ) return true ; if ( CountTurn ( root . right , key , ! turn ) ) { Count += 1 ; return true ; } } else { if ( CountTurn ( root . right , key , turn ) ) return true ; if ( CountTurn ( root . left , key , ! turn ) ) { Count += 1 ; return true ; } } return false ; } static int NumberOfTurn ( Node root , int first , int second ) { Node LCA = findLCA ( root , first , second ) ; if ( LCA == null ) return - 1 ; Count = 0 ; if ( LCA . key != first && LCA . key != second ) { if ( CountTurn ( LCA . right , second , false ) || CountTurn ( LCA . left , second , true ) ) ; if ( CountTurn ( LCA . left , first , true ) || CountTurn ( LCA . right , first , false ) ) ; return Count + 1 ; } if ( LCA . key == first ) { CountTurn ( LCA . right , second , false ) ; CountTurn ( LCA . left , second , true ) ; return Count ; } else { CountTurn ( LCA . right , first , false ) ; CountTurn ( LCA . left , first , true ) ; return Count ; } } public static void main ( String [ ] args ) { Node root = new Node ( 1 ) ; root . left = new Node ( 2 ) ; root . right = new Node ( 3 ) ; root . left . left = new Node ( 4 ) ; root . left . right = new Node ( 5 ) ; root . right . left = new Node ( 6 ) ; root . right . right = new Node ( 7 ) ; root . left . left . left = new Node ( 8 ) ; root . right . left . left...


"Number of unique rectangles formed using N unit squares | Java program to count rotationally equivalent rectangles with n unit squares ; height >= length is maintained ; driver code"
How can the above be solved in Java?

class GFG { static int countRect ( int n ) { int ans = 0 ; for ( int length = 1 ; length <= Math . sqrt ( n ) ; ++ length ) for ( int height = length ; height * length <= n ; ++ height ) ans ++ ; return ans ; } public static void main ( String [ ] args ) { int n = 5 ; System . out . print ( countRect ( n ) ) ; } }


"Number of unique triplets whose XOR is zero | Java program to count the number of unique triplets whose XOR is 0 ; function to count the number of unique triplets whose xor is 0 ; To store values that are present ; stores the count of unique triplets ; traverse for all i , j pairs such that j > i ; xor of a [ i ] and a [ j ] ; if xr of two numbers is present , then increase the count ; returns answer ; Driver code"
How can the above be solved in Java?

import java . io . * ; import java . util . * ; class GFG { static int countTriplets ( int [ ] a , int n ) { ArrayList < Integer > s = new ArrayList < Integer > ( ) ; for ( int i = 0 ; i < n ; i ++ ) s . add ( a [ i ] ) ; int count = 0 ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = i + 1 ; j < n ; j ++ ) { int xr = a [ i ] ^ a [ j ] ; if ( s . contains ( xr ) && xr != a [ i ] && xr != a [ j ] ) count ++ ; } } return count / 3 ; } public static void main ( String srgs [ ] ) { int [ ] a = { 1 , 3 , 5 , 10 , 14 , 15 } ; int n = a . length ; System . out . print ( countTriplets ( a , n ) ) ; } }


"Number of unmarked integers in a special sieve | Java Program to determine the number of unmarked integers in a special sieve ; Driver Code"
How can the above be solved in Java?

import java . io . * ; class GFG { static int countUnmarked ( int N ) { if ( N % 2 == 0 ) return N / 2 ; else return N / 2 + 1 ; } public static void main ( String [ ] args ) { int N = 4 ; System . out . println ( " Number ▁ of ▁ unmarked ▁ " + " elements : ▁ " + countUnmarked ( N ) ) ; } }


"Number of valid indices in the permutation of first N natural numbers | Java implementation of the approach ; Function to return the number of i 's  such that Pi <= Pj for all 1 <= j <= i  in the permutation of first N natural numbers ; To store the count of such indices ; Store the mini value ; For all the elements ; Return the required answer ; Driver code"
How can the above be solved in Java?

class GFG { static int INT_MAX = Integer . MAX_VALUE ; static int min_index ( int p [ ] , int n ) { int ans = 0 ; int mini = INT_MAX ; for ( int i = 0 ; i < n ; i ++ ) { if ( p [ i ] <= mini ) mini = p [ i ] ; if ( mini == p [ i ] ) ans ++ ; } return ans ; } public static void main ( String [ ] args ) { int P [ ] = { 4 , 2 , 5 , 1 , 3 } ; int n = P . length ; System . out . println ( min_index ( P , n ) ) ; } }


"Number of visible boxes after putting one inside another | Java program to count number of visible boxes . ; return the minimum number of visible boxes ; New Queue of integers . ; sorting the array ; traversing the array ; checking if current element is greater than or equal to twice of front element ; Pushing each element of array ; Driver code"
How can the above be solved in Java?

import java . util . LinkedList ; import java . util . Queue ; import java . util . Arrays ; public class GFG { static int minimumBox ( int [ ] arr , int n ) { Queue < Integer > q = new LinkedList < > ( ) ; Arrays . sort ( arr ) ; q . add ( arr [ 0 ] ) ; for ( int i = 1 ; i < n ; i ++ ) { int now = q . element ( ) ; if ( arr [ i ] >= 2 * now ) q . remove ( ) ; q . add ( arr [ i ] ) ; } return q . size ( ) ; } public static void main ( String args [ ] ) { int [ ] arr = { 4 , 1 , 2 , 8 } ; int n = arr . length ; System . out . println ( minimumBox ( arr , n ) ) ; } }


"Number of ways N can be divided into four parts to construct a rectangle | Java implementation of the approach ; Function to return the required number of ways ; Driver code"
How can the above be solved in Java?

class GFG { static int cntWays ( int n ) { if ( n % 2 == 1 ) { return 0 ; } else { return ( n - 2 ) / 4 ; } } public static void main ( String [ ] args ) { int n = 18 ; System . out . println ( cntWays ( n ) ) ; } }


"Number of ways a convex polygon of n + 2 sides can split into triangles by connecting vertices | Java program to find the nth catalan number ; Returns value of Binomial Coefficient C ( n , k ) ; Since C ( n , k ) = C ( n , n - k ) ; Calculate value of [ n * ( n - 1 ) * -- - * ( n - k + 1 ) ] / [ k * ( k - 1 ) * -- - * 1 ] ; A Binomial coefficient based function to find nth catalan number in O ( n ) time ; Calculate value of 2 nCn ; return 2 nCn / ( n + 1 ) ; Driver code"
How can the above be solved in Java?

class GFG { static long binomialCoeff ( int n , int k ) { long res = 1 ; if ( k > n - k ) k = n - k ; for ( int i = 0 ; i < k ; ++ i ) { res *= ( n - i ) ; res /= ( i + 1 ) ; } return res ; } static long catalan ( int n ) { long c = binomialCoeff ( 2 * n , n ) ; return c / ( n + 1 ) ; } public static void main ( String [ ] args ) { int n = 3 ; System . out . println ( catalan ( n ) ) ; } }


"Number of ways in which N can be represented as the sum of two positive integers | Java implementation of the approach ; Function to return the number of distinct ways to represent n as the sum of two integers ; Driver code"
How can the above be solved in Java?

class GFG { static int ways ( int n ) { return n / 2 ; } public static void main ( String args [ ] ) { int n = 2 ; System . out . println ( ways ( n ) ) ; } }


"Number of ways in which an item returns back to its initial position in N swaps in array of size K | Java program to find the number of ways in which an item returns back to its initial position in N swaps in an array of size K ; Function to calculate ( x ^ y ) % p in O ( log y ) ; Initialize result ; Update x if it is more than or equal to p ; If y is odd , multiply x with result ; y must be even now y = y / 2 ; Function to return the number of ways ; Base case ; Recursive case F ( n ) = ( k - 1 ) ^ ( n - 1 ) - F ( n - 1 ) . ; Driver code ; Function calling"
How can the above be solved in Java?

class GFG { static int mod = 1000000007 ; public static int power ( int x , int y ) { int p = mod ; int res = 1 ; x = x % p ; while ( y > 0 ) { if ( ( y & 1 ) != 0 ) res = ( res * x ) % p ; y = y >> 1 ; x = ( x * x ) % p ; } return res ; } public static int solve ( int n , int k ) { if ( n == 1 ) return 0 ; return ( power ( ( k - 1 ) , n - 1 ) % mod - solve ( n - 1 , k ) + mod ) % mod ; } public static void main ( String [ ] args ) { int n = 4 , k = 5 ; System . out . println ( solve ( n , k ) ) ; } }


"Number of ways in which the substring in range [ L , R ] can be formed using characters out of the range | Java implementation of the approach ; Function to return the number of ways to form the sub - string ; Initialize a hash - table with 0 ; Iterate in the string and count the frequency of characters that do not lie in the range L and R ; Out of range characters ; Stores the final number of ways ; Iterate for the sub - string in the range L and R ; If exists then multiply the number of ways and decrement the frequency ; If does not exist the sub - string cannot be formed ; Return the answer ; Driver code"
How can the above be solved in Java?

class GfG { static int calculateWays ( String s , int n , int l , int r ) { int freq [ ] = new int [ 26 ] ; for ( int i = 0 ; i < n ; i ++ ) { if ( i < l i > r ) freq [ s . charAt ( i ) - ' a ' ] ++ ; } int ways = 1 ; for ( int i = l ; i <= r ; i ++ ) { if ( freq [ s . charAt ( i ) - ' a ' ] != 0 ) { ways = ways * freq [ s . charAt ( i ) - ' a ' ] ; freq [ s . charAt ( i ) - ' a ' ] -- ; } else { ways = 0 ; break ; } } return ways ; } public static void main ( String [ ] args ) { String s = " cabcaab " ; int n = s . length ( ) ; int l = 1 , r = 3 ; System . out . println ( calculateWays ( s , n , l , r ) ) ; } }


"Number of ways of choosing K equal substrings of any length for every query | Java implementation of the approach ; Function to generate all the sub - strings ; Length of the string ; Generate all sub - strings ; Count the occurrence of every sub - string ; Compute the Binomial Coefficient ; Calculate value of Binomial Coefficient in bottom up manner ; Base Cases ; Calculate value using previously stored values ; Function to return the result for a query ; Iterate for every unique sub - string ; Count the combinations ; Driver code ; Get all the sub - strings Store the occurrence of all the sub - strings ; Pre - computation ; Queries ; Perform queries"
How can the above be solved in Java?

import java . util . HashMap ; class GFG { static int maxlen = 100 ; public static void generateSubStrings ( String s , HashMap < String , Integer > mpp ) { int l = s . length ( ) ; for ( int i = 0 ; i < l ; i ++ ) { String temp = " " ; for ( int j = i ; j < l ; j ++ ) { temp += s . charAt ( j ) ; if ( mpp . containsKey ( temp ) ) { int x = mpp . get ( temp ) ; mpp . put ( temp , ++ x ) ; } else mpp . put ( temp , 1 ) ; } } } public static void binomialCoeff ( int [ ] [ ] C ) { int i , j ; for ( i = 1 ; i < 100 ; i ++ ) { for ( j = 0 ; j < 100 ; j ++ ) { if ( j == 0 j == i ) C [ i ] [ j ] = 1 ; else C [ i ] [ j ] = C [ i - 1 ] [ j - 1 ] + C [ i - 1 ] [ j ] ; } } } public static int answerQuery ( HashMap < String , Integer > mpp , int [ ] [ ] C , int k ) { int ans = 0 ; for ( HashMap . Entry < String , Integer > entry : mpp . entrySet ( ) ) { if ( entry . getValue ( ) >= k ) ans += C [ entry . getValue ( ) ] [ k ] ; } return ans ; } public static void main ( String [ ] args ) { String s = " aabaab " ; HashMap < String , Integer > mpp = new HashMap < > ( ) ; generateSubStrings ( s , mpp ) ; int [ ] [ ] C = new int [ maxlen ] [ maxlen ] ; binomialCoeff ( C ) ; int [ ] queries = { 2 , 3 , 4 } ; int q = queries . length ; for ( int i = 0 ; i < q ; i ++ ) System . out . println ( answerQuery ( mpp , C , queries [ i ] ) ) ; } }


"Number of ways of distributing N identical objects in R distinct groups with no groups empty | Java implementation of the above approach ; Function to return the value of ncr effectively ; Initialize the answer ; Divide simultaneously by i to avoid overflow ; Function to return the number of ways to distribute N identical objects in R distinct objects ; Driver code"
How can the above be solved in Java?

import java . io . * ; class GFG { static int ncr ( int n , int r ) { int ans = 1 ; for ( int i = 1 ; i <= r ; i += 1 ) { ans *= ( n - r + i ) ; ans /= i ; } return ans ; } static int NoOfDistributions ( int N , int R ) { return ncr ( N - 1 , R - 1 ) ; } public static void main ( String [ ] args ) { int N = 4 ; int R = 3 ; System . out . println ( NoOfDistributions ( N , R ) ) ; } }


"Number of ways of distributing N identical objects in R distinct groups | Java implementation of the above approach ; Function to return the value of ncr effectively ; Initialize the answer ; Divide simultaneously by i to avoid overflow ; Function to return the number of ways to distribute N identical objects in R distinct objects ; Driver code ; Function call"
How can the above be solved in Java?

import java . util . * ; class GFG { static int ncr ( int n , int r ) { int ans = 1 ; for ( int i = 1 ; i <= r ; i += 1 ) { ans *= ( n - r + i ) ; ans /= i ; } return ans ; } static int NoOfDistributions ( int N , int R ) { return ncr ( N + R - 1 , R - 1 ) ; } public static void main ( String [ ] args ) { int N = 4 , R = 3 ; System . out . println ( NoOfDistributions ( N , R ) ) ; } }


"Number of ways of scoring R runs in B balls with at most W wickets | Java implementation of the approach ; Function to return the number of ways to score R runs in B balls with at most W wickets ; If the wickets lost are more ; If runs scored are more ; If condition is met ; If no run got scored ; Already visited state ; If scored 0 run ; If scored 1 run ; If scored 2 runs ; If scored 3 runs ; If scored 4 runs ; If scored 6 runs ; If scored no run and lost a wicket ; Memoize and return ; Driver code"
How can the above be solved in Java?

class GFG { static int mod = 1000000007 ; static int RUNMAX = 300 ; static int BALLMAX = 50 ; static int WICKETMAX = 10 ; static int CountWays ( int r , int b , int l , int R , int B , int W , int [ ] [ ] [ ] dp ) { if ( l > W ) return 0 ; if ( r > R ) return 0 ; if ( b == B && r == R ) return 1 ; if ( b == B ) return 0 ; if ( dp [ r ] [ b ] [ l ] != - 1 ) return dp [ r ] [ b ] [ l ] ; int ans = 0 ; ans += CountWays ( r , b + 1 , l , R , B , W , dp ) ; ans = ans % mod ; ans += CountWays ( r + 1 , b + 1 , l , R , B , W , dp ) ; ans = ans % mod ; ans += CountWays ( r + 2 , b + 1 , l , R , B , W , dp ) ; ans = ans % mod ; ans += CountWays ( r + 3 , b + 1 , l , R , B , W , dp ) ; ans = ans % mod ; ans += CountWays ( r + 4 , b + 1 , l , R , B , W , dp ) ; ans = ans % mod ; ans += CountWays ( r + 6 , b + 1 , l , R , B , W , dp ) ; ans = ans % mod ; ans += CountWays ( r , b + 1 , l + 1 , R , B , W , dp ) ; ans = ans % mod ; return dp [ r ] [ b ] [ l ] = ans ; } public static void main ( String [ ] args ) { int R = 40 , B = 10 , W = 4 ; int [ ] [ ] [ ] dp = new int [ RUNMAX ] [ BALLMAX ] [ WICKETMAX ] ; for ( int i = 0 ; i < RUNMAX ; i ++ ) for ( int j = 0 ; j < BALLMAX ; j ++ ) for ( int k = 0 ; k < WICKETMAX ; k ++ ) dp [ i ] [ j ] [ k ] = - 1 ; System . out . println ( CountWays ( 0 , 0 , 0 , R , B , W , dp ) ) ; } }


"Number of ways of writing N as a sum of 4 squares | Java implementation of above approach ; Number of ways of writing n as a sum of 4 squares ; sum of odd and even factor ; iterate from 1 to the number ; if i is the factor of n ; if factor is even ; if factor is odd ; n / i is also a factor ; if factor is even ; if factor is odd ; if n is odd ; if n is even ; Driver code"
How can the above be solved in Java?

import java . io . * ; class GFG { static int sum_of_4_squares ( int n ) { int i , odd = 0 , even = 0 ; for ( i = 1 ; i <= Math . sqrt ( n ) ; i ++ ) { if ( n % i == 0 ) { if ( i % 2 == 0 ) even += i ; else odd += i ; if ( ( n / i ) != i ) { if ( ( n / i ) % 2 == 0 ) even += ( n / i ) ; else odd += ( n / i ) ; } } } if ( n % 2 == 1 ) return 8 * ( odd + even ) ; else return 24 * ( odd ) ; } public static void main ( String [ ] args ) { int n = 4 ; System . out . println ( sum_of_4_squares ( n ) ) ; } }


"Number of ways such that only K bars are visible from the left | Java implementation for the above approach ; dp array ; Function to calculate the number of permutations of N , where only K bars are visible from the left . ; If subproblem has already been calculated , return ; Only ascending order is possible ; N is placed at the first position The nest N - 1 are arranged in ( N - 1 ) ! ways ; Recursing ; Driver code ; Input ; Initialize dp array ; Function call"
How can the above be solved in Java?

import java . util . * ; class GFG { static int [ ] [ ] dp = new int [ 1005 ] [ 1005 ] ; static int KvisibleFromLeft ( int N , int K ) { if ( dp [ N ] [ K ] != - 1 ) return dp [ N ] [ K ] ; if ( N == K ) return dp [ N ] [ K ] = 1 ; if ( K == 1 ) { int ans = 1 ; for ( int i = 1 ; i < N ; i ++ ) ans *= i ; return dp [ N ] [ K ] = ans ; } return dp [ N ] [ K ] = KvisibleFromLeft ( N - 1 , K - 1 ) + ( N - 1 ) * KvisibleFromLeft ( N - 1 , K ) ; } public static void main ( String [ ] args ) { int N = 5 , K = 2 ; for ( int i = 0 ; i < 1005 ; i ++ ) { for ( int j = 0 ; j < 1005 ; j ++ ) { dp [ i ] [ j ] = - 1 ; } } System . out . print ( KvisibleFromLeft ( N , K ) ) ; } }


"Number of ways such that only K bars are visible from the left | Java program for the above approach ; Function to calculate the number of permutations of N , where only K bars are visible from the left . ; Only ascending order is possible ; N is placed at the first position The nest N - 1 are arranged in ( N - 1 ) ! ways ; Recursing ; Driver code ; Input ; Function call"
How can the above be solved in Java?

class GFG { static int KvisibleFromLeft ( int N , int K ) { if ( N == K ) return 1 ; if ( K == 1 ) { int ans = 1 ; for ( int i = 1 ; i < N ; i ++ ) ans *= i ; return ans ; } return KvisibleFromLeft ( N - 1 , K - 1 ) + ( N - 1 ) * KvisibleFromLeft ( N - 1 , K ) ; } public static void main ( String [ ] args ) { int N = 5 , K = 2 ; System . out . println ( KvisibleFromLeft ( N , K ) ) ; } }


"Number of ways to arrange 2 * N persons on the two sides of a table with X and Y persons on opposite sides | Java implementation for the above approach ; Function to returns factorial of n ; Function to find nCr ; Function to find the number of ways to arrange 2 * N persons ; Driver code ; Function call"
How can the above be solved in Java?

import java . util . * ; import java . lang . * ; import java . io . * ; class GFG { static int factorial ( int n ) { if ( n <= 1 ) return 1 ; return n * factorial ( n - 1 ) ; } static int nCr ( int n , int r ) { return factorial ( n ) / ( factorial ( n - r ) * factorial ( r ) ) ; } static int NumberOfWays ( int n , int x , int y ) { return nCr ( 2 * n - x - y , n - x ) * factorial ( n ) * factorial ( n ) ; } public static void main ( String [ ] args ) throws java . lang . Exception { int n = 5 , x = 4 , y = 2 ; System . out . println ( NumberOfWays ( n , x , y ) ) ; } }


"Number of ways to arrange K different objects taking N objects at a time | Java implementation of the approach ; Function to return n ! % p ; long res = 1 ; Initialize result ; Iterative Function to calculate ( x ^ y ) % p in O ( log y ) ; x = x % p ; Update x if it is more than or equal to p ; If y is odd , multiply x with result ; y must be even now y = y >> 1 ; y = y / 2 ; Returns n ^ ( - 1 ) mod p ; Returns nCr % p using Fermat 's little theorem. ; Base case ; Fill factorial array so that we can find all factorial of r , n and n - r ; Function to return the number of ways to arrange K different objects taking N objects at a time ; Driver Code ; Function call"
How can the above be solved in Java?

class GFG { static long mod = ( long ) ( 1e9 + 7 ) ; static long factorial ( long n , long p ) { for ( int i = 2 ; i <= n ; i ++ ) res = ( res * i ) % p ; return res ; } static long power ( long x , long y , long p ) { while ( y > 0 ) { if ( ( y & 1 ) == 1 ) res = ( res * x ) % p ; x = ( x * x ) % p ; } return res ; } static long modInverse ( long n , long p ) { return power ( n , p - 2 , p ) ; } static long nCrModP ( long n , long r , long p ) { if ( r == 0 ) return 1 ; long fac [ ] = new long [ ( int ) n + 1 ] ; fac [ 0 ] = 1 ; for ( int i = 1 ; i <= n ; i ++ ) fac [ i ] = fac [ i - 1 ] * i % p ; return ( fac [ ( int ) n ] * modInverse ( fac [ ( int ) r ] , p ) % p * modInverse ( fac [ ( int ) n - ( int ) r ] , p ) % p ) % p ; } static long countArrangements ( long n , long k , long p ) { return ( factorial ( n , p ) * nCrModP ( k , n , p ) ) % p ; } public static void main ( String [ ] args ) { long N = 5 , K = 8 ; System . out . println ( countArrangements ( N , K , mod ) ) ; } }


"Number of ways to arrange N items under given constraints | Java program to find number of ways to arrange items under given constraint ; method returns number of ways with which items can be arranged ; Calculate value of Binomial Coefficient in bottom up manner ; Base Cases ; Calculate value using previously stored values ; declare dp array to store result up to ith colored item ; variable to keep track of count of items considered till now ; loop over all different colors ; populate next value using current value and stated relation ; return value stored at last index ; Driver code"
How can the above be solved in Java?

class GFG { static int waysToArrange ( int N , int K , int [ ] k ) { int [ ] [ ] C = new int [ N + 1 ] [ N + 1 ] ; int i , j ; for ( i = 0 ; i <= N ; i ++ ) { for ( j = 0 ; j <= i ; j ++ ) { if ( j == 0 j == i ) { C [ i ] [ j ] = 1 ; } else { C [ i ] [ j ] = ( C [ i - 1 ] [ j - 1 ] + C [ i - 1 ] [ j ] ) ; } } } int [ ] dp = new int [ K + 1 ] ; int count = 0 ; dp [ 0 ] = 1 ; for ( i = 0 ; i < K ; i ++ ) { dp [ i + 1 ] = ( dp [ i ] * C [ count + k [ i ] - 1 ] [ k [ i ] - 1 ] ) ; count += k [ i ] ; } return dp [ K ] ; } public static void main ( String [ ] args ) { int N = 4 ; int [ ] k = new int [ ] { 2 , 2 } ; int K = k . length ; System . out . println ( waysToArrange ( N , K , k ) ) ; } }


"Number of ways to arrange N numbers which are in a range from 1 to K under given constraints . | Java program to calculate number of ways to arrange N numbers under given constraints . ; Function to print Total number of ways ; If the First number and the last number is same . ; DP approach to find current state with the help of previous state . ; Driver Code ; Function call"
How can the above be solved in Java?

import java . io . * ; import java . util . * ; class GFG { static void NumberOfWays ( int n , int k , int p , int q ) { int [ ] [ ] dp = new int [ n ] [ 2 ] ; if ( p == q ) { dp [ 0 ] [ 0 ] = 1 ; dp [ 0 ] [ 1 ] = 0 ; } else { dp [ 0 ] [ 0 ] = 0 ; dp [ 0 ] [ 1 ] = 1 ; } for ( int i = 1 ; i < n ; i ++ ) { dp [ i ] [ 0 ] = dp [ i - 1 ] [ 1 ] ; dp [ i ] [ 1 ] = ( dp [ i - 1 ] [ 0 ] * ( k - 1 ) ) + ( dp [ i - 1 ] [ 1 ] * ( k - 2 ) ) ; } System . out . println ( dp [ n - 1 ] [ 0 ] ) ; } public static void main ( String args [ ] ) { int N = 5 ; int K = 3 ; int P = 2 ; int Q = 1 ; NumberOfWays ( N , K , P , Q ) ; } }


"Number of ways to choose K intersecting line segments on X | Java program to find Number of ways to choose K intersecting line segments on X - axis ; Function to find ( a ^ b ) % mod in log b ; Till power becomes 0 ; If power is odd ; Multiply base ; Divide power by 1 ; Function to find nCk ; Base case ; Apply formula to find nCk ; Function to find the number of ways ; sort the given lines ; Find the number of total case ; Declare a multiset ; Loop till N ; Check if smallest element is smaller than lines [ i ] ; Erase first element ; Exclude the odd cases ; Modulus operation ; Insert into multiset ; Function to precompute factorial and inverse ; Pre - compute factorial and inverse ; Driver code ; Function to pre - compute factorial and inverse"
How can the above be solved in Java?

import java . util . * ; import java . lang . * ; class GFG { static long mod = 1000000007 ; static int MAXN = 1001 ; static long factorial [ ] = new long [ MAXN ] , inverse [ ] = new long [ MAXN ] ; static long power ( long a , long b ) { long res = 1 ; while ( b > 0 ) { if ( b % 2 == 1 ) { res = ( res * a ) % mod ; } a = ( a * a ) % mod ; b >>= 1 ; } return res ; } static long nCk ( int n , int k ) { if ( k < 0 k > n ) { return 0 ; } long ans = factorial [ n ] ; ans = ( ans * inverse [ n - k ] ) % mod ; ans = ( ans * inverse [ k ] ) % mod ; return ans ; } static void numberOfWays ( ArrayList < int [ ] > lines , int K , int N ) { Collections . sort ( lines , ( a , b ) -> a [ 0 ] - b [ 0 ] ) ; long total_case = nCk ( N , K ) ; PriorityQueue < Integer > m = new PriorityQueue < > ( ) ; for ( int i = 0 ; i < N ; i ++ ) { while ( ! m . isEmpty ( ) && ( m . peek ( ) < lines . get ( i ) [ 0 ] ) ) { m . poll ( ) ; } total_case -= nCk ( m . size ( ) , K - 1 ) ; total_case += mod ; total_case %= mod ; m . add ( lines . get ( i ) [ 1 ] ) ; } System . out . println ( total_case ) ; } static void preCompute ( ) { long fact = 1 ; factorial [ 0 ] = 1 ; inverse [ 0 ] = 1 ; for ( int i = 1 ; i < MAXN ; i ++ ) { fact = ( fact * i ) % mod ; factorial [ i ] = fact ; inverse [ i ] = power ( factorial [ i ] , mod - 2 ) ; } } public static void main ( String [ ] args ) { int N = 3 , K = 2 ; ArrayList < int [ ] > lines = new ArrayList < > ( ) ; preCompute ( ) ; lines . add ( new int [ ] { 1 , 3 } ) ; lines . add ( new int [ ] { 4 , 5 } ) ; lines . add ( new int [ ] { 5 , 7 } ) ; numberOfWays ( lines , K , N ) ; } }


"Number of ways to choose elements from the array such that their average is K | Java implementation of the above approach ; This dp array is used to store our values so that we don 't have to calculate same  values again and again ; Base cases Index can 't be less than 0 ; No element is picked hence average cannot be calculated ; If remainder is non zero , we cannot divide the sum by count i . e . the average will not be an integer ; If we find an average return 1 ; If we have already calculated this function simply return it instead of calculating it again ; If we don 't pick the current element  simple recur for index -1 ; If we pick the current element add it to our current sum and increment count by 1 ; Store the value for the current function ; Function to return the number of ways ; Push - 1 at the beginning to make it 1 - based indexing ; Initialize dp array by - 1 ; Call recursive function waysutil to calculate total ways ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { static int MAX_INDEX = 51 ; static int MAX_SUM = 2505 ; static int [ ] [ ] [ ] dp = new int [ MAX_INDEX ] [ MAX_SUM ] [ MAX_INDEX ] ; static int waysutil ( int index , int sum , int count , Vector < Integer > arr , int K ) { if ( index < 0 ) { return 0 ; } if ( index == 0 ) { if ( count == 0 ) { return 0 ; } int remainder = sum % count ; if ( remainder != 0 ) { return 0 ; } int average = sum / count ; if ( average == K ) { return 1 ; } } if ( dp [ index ] [ sum ] [ count ] != - 1 ) { return dp [ index ] [ sum ] [ count ] ; } int dontpick = waysutil ( index - 1 , sum , count , arr , K ) ; int pick = waysutil ( index - 1 , sum + arr . get ( index ) , count + 1 , arr , K ) ; int total = pick + dontpick ; dp [ index ] [ sum ] [ count ] = total ; return total ; } static int ways ( int N , int K , int [ ] arr ) { Vector < Integer > Arr = new Vector < > ( ) ; Arr . add ( - 1 ) ; for ( int i = 0 ; i < N ; ++ i ) { Arr . add ( arr [ i ] ) ; } for ( int i = 0 ; i < MAX_INDEX ; i ++ ) { for ( int j = 0 ; j < MAX_SUM ; j ++ ) { for ( int l = 0 ; l < MAX_INDEX ; l ++ ) { dp [ i ] [ j ] [ l ] = - 1 ; } } } int answer = waysutil ( N , 0 , 0 , Arr , K ) ; return answer ; } public static void main ( String args [ ] ) { int arr [ ] = { 3 , 6 , 2 , 8 , 7 , 6 , 5 , 9 } ; int N = arr . length ; int K = 5 ; System . out . println ( ways ( N , K , arr ) ) ; } }


"Number of ways to color N | Java program for the above approach ; Function to count the ways to color block ; For storing powers of 2 ; For storing binomial coefficient values ; Calculating binomial coefficient using DP ; Calculating powers of 2 ; Sort the indices to calculate length of each section ; Initialise answer to 1 ; Find the length of each section ; Merge this section ; Return the final count ; Driver Code ; Number of blocks ; Number of colored blocks ; Function call"
How can the above be solved in Java?

import java . util . * ; class GFG { static int mod = 1000000007 ; static int waysToColor ( int arr [ ] , int n , int k ) { int powOf2 [ ] = new int [ 500 ] ; int [ ] [ ] c = new int [ 500 ] [ 500 ] ; for ( int i = 0 ; i <= n ; i ++ ) { c [ i ] [ 0 ] = 1 ; for ( int j = 1 ; j <= i ; j ++ ) { c [ i ] [ j ] = ( c [ i - 1 ] [ j ] + c [ i - 1 ] [ j - 1 ] ) % mod ; } } powOf2 [ 0 ] = powOf2 [ 1 ] = 1 ; for ( int i = 2 ; i <= n ; i ++ ) { powOf2 [ i ] = powOf2 [ i - 1 ] * 2 % mod ; } int rem = n - k ; arr [ k ++ ] = n + 1 ; Arrays . sort ( arr ) ; int answer = 1 ; for ( int i = 0 ; i < k ; i ++ ) { int x = arr [ i ] - ( i - 1 >= 0 ? arr [ i - 1 ] : 0 ) - 1 ; answer *= c [ rem ] [ x ] % mod * ( i != 0 && i != k - 1 ? powOf2 [ x ] : 1 ) % mod ; rem -= x ; } return answer ; } public static void main ( String [ ] args ) { int N = 6 ; int K = 3 ; int arr [ ] = { 1 , 2 , 6 , 0 } ; System . out . print ( waysToColor ( arr , N , K ) ) ; } }


"Number of ways to color N | Java program for the above approach ; Recursive function to count the ways ; Base case ; Initialise answer to 0 ; Color each uncolored block according to the given condition ; If any block is uncolored ; Check if adjacent blocks are colored or not ; Color the block ; recursively iterate for next uncolored block ; Uncolored for the next recursive call ; Return the final count ; Function to count the ways to color block ; Mark which blocks are colored in each recursive step ; Function call to count the ways ; Driver Code ; Number of blocks ; Number of colored blocks ; Function call"
How can the above be solved in Java?

import java . util . * ; class GFG { static int mod = 1000000007 ; static int countWays ( int colored [ ] , int count , int n ) { if ( count == n ) { return 1 ; } int answer = 0 ; for ( int i = 1 ; i < n + 1 ; i ++ ) { if ( colored [ i ] == 0 ) { if ( colored [ i - 1 ] == 1 colored [ i + 1 ] == 1 ) { colored [ i ] = 1 ; answer = ( answer + countWays ( colored , count + 1 , n ) ) % mod ; colored [ i ] = 0 ; } } } return answer ; } static int waysToColor ( int arr [ ] , int n , int k ) { int colored [ ] = new int [ n + 2 ] ; for ( int i = 0 ; i < k ; i ++ ) { colored [ arr [ i ] ] = 1 ; } return countWays ( colored , k , n ) ; } public static void main ( String [ ] args ) { int N = 6 ; int K = 3 ; int arr [ ] = { 1 , 2 , 6 } ; System . out . print ( waysToColor ( arr , N , K ) ) ; } }


"Number of ways to color boundary of each block of M * N table | Java program to count the number of ways to color boundary of each block of M * N table . ; Function to compute all way to fill the boundary of all sides of the unit square ; Count possible ways to fill all upper and left side of the rectangle M * N ; Count possible ways to fill all side of the all squares unit size ; Driver code ; Number of rows ; Number of columns"
How can the above be solved in Java?

import java . util . * ; class GFG { static int CountWays ( int N , int M ) { int count = 1 ; count = ( int ) Math . pow ( 3 , M + N ) ; count *= ( int ) Math . pow ( 2 , M * N ) ; return count ; } public static void main ( String args [ ] ) { int N = 3 ; int M = 2 ; System . out . println ( CountWays ( N , M ) ) ; } }


"Number of ways to convert a character X to a string Y | Java implementation of the approach ; Function to find the modular - inverse ; While power > 1 ; Updating s and a ; Updating power ; Return the final answer ; Function to return the count of ways ; To store the final answer ; To store pre - computed factorials ; Computing factorials ; Loop to find the occurrences of x and update the ans ; Multiplying the answer by ( n - 1 ) ! ; Return the final answer ; Driver code"
How can the above be solved in Java?

class GFG { final static int MOD = 1000000007 ; static long modInv ( long a ) { long p = MOD - 2 ; long s = 1 ; while ( p != 1 ) { if ( p % 2 == 1 ) s = ( s * a ) % MOD ; a = ( a * a ) % MOD ; p /= 2 ; } return ( a * s ) % MOD ; } static long findCnt ( char x , String y ) { long ans = 0 ; long fact [ ] = new long [ y . length ( ) + 1 ] ; for ( int i = 0 ; i < y . length ( ) + 1 ; i ++ ) fact [ i ] = 1 ; for ( int i = 1 ; i <= y . length ( ) ; i ++ ) fact [ i ] = ( fact [ i - 1 ] * i ) % MOD ; for ( int i = 0 ; i < y . length ( ) ; i ++ ) { if ( y . charAt ( i ) == x ) { ans += ( modInv ( fact [ i ] ) * modInv ( fact [ y . length ( ) - i - 1 ] ) ) % MOD ; ans %= MOD ; } } ans *= fact [ ( y . length ( ) - 1 ) ] ; ans %= MOD ; return ans ; } public static void main ( String [ ] args ) { char x = ' a ' ; String y = " xxayy " ; System . out . println ( findCnt ( x , y ) ) ; } }


"Number of ways to cut a stick of length N into in even length at most K units long pieces | Java program for the above approach ; Recursive Function to count the total number of ways ; Base case if no - solution exist ; Condition if a solution exist ; Check if already calculated ; Initialize counter ; Recursive call ; Store the answer ; Return the answer ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { static int solve ( int n , int k , int mod , int dp [ ] ) { if ( n < 0 ) return 0 ; if ( n == 0 ) return 1 ; if ( dp [ n ] != - 1 ) return dp [ n ] ; int cnt = 0 ; for ( int i = 2 ; i <= k ; i += 2 ) { cnt = ( cnt % mod + solve ( n - i , k , mod , dp ) % mod ) % mod ; } dp [ n ] = cnt ; return cnt ; } public static void main ( String [ ] args ) { int mod = ( int ) ( 1e9 + 7 ) ; int n = 4 , k = 2 ; int [ ] dp = new int [ n + 1 ] ; for ( int i = 0 ; i < n + 1 ; i ++ ) dp [ i ] = - 1 ; int ans = solve ( n , k , mod , dp ) ; System . out . println ( ans ) ; } }


"Number of ways to distribute N Paper Set among M students | Java implementation of the approach ; Function to return n ! % 1000000007 ; To store the factorial ; Find the factorial ; Function to return the count of possible ways ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { static int MOD = 1000000007 ; static int factMod ( int n ) { long fact = 1 ; for ( int i = 2 ; i <= n ; i ++ ) { fact *= ( i % MOD ) ; fact %= MOD ; } return ( int ) fact ; } static int countWays ( int n , int m ) { return factMod ( m ) ; } public static void main ( String args [ ] ) { int n = 2 , m = 2 ; System . out . print ( countWays ( n , m ) ) ; } }


"Number of ways to divide an array into K equal sum sub | Java implementation of the approach ; Array to store the states of DP ; Array to check if a state has been solved before ; To store the sum of the array elements ; Function to find the sum of all the array elements ; Function to return the number of ways ; If sum is not divisible by k answer will be zero ; Base case ; To check if a state has been solved before ; Sum of all the numbers from the beginning of the array ; Setting the current state as solved ; Recurrence relation ; Returning solved state ; Driver code ; Function call to find the sum of the array elements ; Print the number of ways"
How can the above be solved in Java?

class GFG { static int max_size = 20 ; static int max_k = 20 ; static int [ ] [ ] dp = new int [ max_size ] [ max_k ] ; static boolean [ ] [ ] v = new boolean [ max_size ] [ max_k ] ; static int sum = 0 ; static void findSum ( int arr [ ] , int n ) { for ( int i = 0 ; i < n ; i ++ ) sum += arr [ i ] ; } static int cntWays ( int arr [ ] , int i , int ck , int k , int n , int curr_sum ) { if ( sum % k != 0 ) return 0 ; if ( i != n && ck == k + 1 ) return 0 ; if ( i == n ) { if ( ck == k + 1 ) return 1 ; else return 0 ; } if ( v [ i ] [ ck ] ) return dp [ i ] [ ck ] ; curr_sum += arr [ i ] ; v [ i ] [ ck ] = true ; dp [ i ] [ ck ] = cntWays ( arr , i + 1 , ck , k , n , curr_sum ) ; if ( curr_sum == ( sum / k ) * ck ) dp [ i ] [ ck ] += cntWays ( arr , i + 1 , ck + 1 , k , n , curr_sum ) ; return dp [ i ] [ ck ] ; } public static void main ( String [ ] args ) { int arr [ ] = { 1 , - 1 , 1 , - 1 , 1 , - 1 } ; int n = arr . length ; int k = 2 ; findSum ( arr , n ) ; System . out . println ( cntWays ( arr , 0 , 1 , k , n , 0 ) ) ; } }


"Number of ways to erase exactly one element in the Binary Array to make XOR zero | Java program to find the number of ways to erase exactly one element from this array to make XOR zero ; Function to find the number of ways ; Calculate the number of 1 ' s ▁ and ▁ 0' s ; Considering the 4 cases ; Driver code"
How can the above be solved in Java?

class GFG { static int no_of_ways ( int a [ ] , int n ) { int count_0 = 0 , count_1 = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( a [ i ] == 0 ) count_0 ++ ; else count_1 ++ ; } if ( count_1 % 2 == 0 ) return count_0 ; else return count_1 ; } public static void main ( String [ ] args ) { int n = 4 ; int a1 [ ] = { 1 , 1 , 0 , 0 } ; System . out . println ( no_of_ways ( a1 , n ) ) ; n = 5 ; int a2 [ ] = { 1 , 1 , 1 , 0 , 0 } ; System . out . println ( no_of_ways ( a2 , n ) ) ; n = 5 ; int a3 [ ] = { 1 , 1 , 0 , 0 , 0 } ; System . out . println ( no_of_ways ( a3 , n ) ) ; n = 6 ; int a4 [ ] = { 1 , 1 , 1 , 0 , 0 , 0 } ; System . out . println ( no_of_ways ( a4 , n ) ) ; } }


"Number of ways to form a heap with n distinct integers | Java program to count max heaps with n distinct keys ; dp [ i ] = number of max heaps for i distinct integers ; nck [ i ] [ j ] = number of ways to choose j elements form i elements , no order ; log2 [ i ] = floor of logarithm of base 2 of i ; to calculate nCk ; calculate l for give value of n ; number of elements that are actually present in last level ( hth level ) ( 2 ^ h - 1 ) ; if more than half - filled ; return ( 1 << h ) - 1 ; ( 2 ^ h ) - 1 ; find maximum number of heaps for n ; function to initialize arrays ; for each power of two find logarithm ; Driver code"
How can the above be solved in Java?

class GFG { static int [ ] dp = new int [ MAXN ] ; static int [ ] [ ] nck = new int [ MAXN ] [ MAXN ] ; static int [ ] log2 = new int [ MAXN ] ; public static int choose ( int n , int k ) { if ( k > n ) { return 0 ; } if ( n <= 1 ) { return 1 ; } if ( k == 0 ) { return 1 ; } if ( nck [ n ] [ k ] != - 1 ) { return nck [ n ] [ k ] ; } int answer = choose ( n - 1 , k - 1 ) + choose ( n - 1 , k ) ; nck [ n ] [ k ] = answer ; return answer ; } public static int getLeft ( int n ) { if ( n == 1 ) { return 0 ; } int h = log2 [ n ] ; int last = n - ( ( 1 << h ) - 1 ) ; if ( last >= ( numh / 2 ) ) { } else { return ( 1 << h ) - 1 - ( ( numh / 2 ) - last ) ; } } public static int numberOfHeaps ( int n ) { if ( n <= 1 ) { return 1 ; } if ( dp [ n ] != - 1 ) { return dp [ n ] ; } int left = getLeft ( n ) ; int ans = ( choose ( n - 1 , left ) * numberOfHeaps ( left ) ) * ( numberOfHeaps ( n - 1 - left ) ) ; dp [ n ] = ans ; return ans ; } public static int solve ( int n ) { for ( int i = 0 ; i <= n ; i ++ ) { dp [ i ] = - 1 ; } for ( int i = 0 ; i <= n ; i ++ ) { for ( int j = 0 ; j <= n ; j ++ ) { nck [ i ] [ j ] = - 1 ; } } int currLog2 = - 1 ; int currPower2 = 1 ; for ( int i = 1 ; i <= n ; i ++ ) { if ( currPower2 == i ) { currLog2 ++ ; currPower2 *= 2 ; } log2 [ i ] = currLog2 ; } return numberOfHeaps ( n ) ; } public static void main ( String [ ] args ) { int n = 10 ; System . out . print ( solve ( n ) ) ; } }


"Number of ways to form a number with maximum Ks in it | Java program for tha above approach ; Function to calculate number of ways a number can be formed that has the maximum number of Ks ; Convert to string ; Calculate length of subarrays that can contribute to the answer ; Count length of subarray where adjacent digits add up to K ; Current subarray can contribute to the answer only if it is odd ; Return the answer ; Driver Code ; Input ; Function call"
How can the above be solved in Java?

import java . util . * ; class GFG { static int noOfWays ( int N , int K ) { String S = String . valueOf ( N ) ; int ans = 1 ; for ( int i = 1 ; i < S . length ( ) ; i ++ ) { int count = 1 ; while ( i < S . length ( ) && ( int ) S . charAt ( i ) - 48 + ( int ) S . charAt ( i - 1 ) - 48 == K ) { count ++ ; i ++ ; } if ( count % 2 == 1 ) ans *= ( count + 1 ) / 2 ; } return ans ; } public static void main ( String [ ] args ) { int N = 1454781 ; int K = 9 ; System . out . print ( noOfWays ( N , K ) ) ; } }


"Number of ways to form an array with distinct adjacent elements | Java program to count the number of ways to form arrays of N numbers such that the first and last numbers are fixed and all consecutive numbers are distinct ; Returns the total ways to form arrays such that every consecutive element is different and each element except the first and last can take values from 1 to M ; define the dp [ ] [ ] array ; if the first element is 1 ; there is only one way to place a 1 at the first index ; the value at first index needs to be 1 , thus there is no way to place a non - one integer ; if the first element was 1 then at index 1 , only non one integer can be placed thus there are M - 1 ways to place a non one integer at index 2 and 0 ways to place a 1 at the 2 nd index ; Else there is one way to place a one at index 2 and if a non one needs to be placed here , there are ( M - 2 ) options , i . e neither the element at this index should be 1 , neither should it be equal to the previous element ; Build the dp array in bottom up manner ; f ( i , one ) = f ( i - 1 , non - one ) ; f ( i , non - one ) = f ( i - 1 , one ) * ( M - 1 ) + f ( i - 1 , non - one ) * ( M - 2 ) ; last element needs to be one , so return dp [ n - 1 ] [ 0 ] ; Driver Code"
How can the above be solved in Java?

import java . io . * ; class GFG { static int totalWays ( int N , int M , int X ) { int dp [ ] [ ] = new int [ N + 1 ] [ 2 ] ; if ( X == 1 ) { dp [ 0 ] [ 0 ] = 1 ; } else { dp [ 0 ] [ 1 ] = 0 ; } if ( X == 1 ) { dp [ 1 ] [ 0 ] = 0 ; dp [ 1 ] [ 1 ] = M - 1 ; } else { dp [ 1 ] [ 0 ] = 1 ; dp [ 1 ] [ 1 ] = ( M - 2 ) ; } for ( int i = 2 ; i < N ; i ++ ) { dp [ i ] [ 0 ] = dp [ i - 1 ] [ 1 ] ; dp [ i ] [ 1 ] = dp [ i - 1 ] [ 0 ] * ( M - 1 ) + dp [ i - 1 ] [ 1 ] * ( M - 2 ) ; } return dp [ N - 1 ] [ 0 ] ; } public static void main ( String [ ] args ) { int N = 4 , M = 3 , X = 2 ; System . out . println ( totalWays ( N , M , X ) ) ; } }


"Number of ways to get a given sum with n number of m | Java function to calculate the number of ways to achieve sum x in n no of throwsVal ; Function to calculate recursively the number of ways to get sum in given throwsVal and [ 1. . m ] values ; Base condition 1 ; Base condition 2 ; If value already calculated dont move into re - computation ; Recursively moving for sum - i in throwsVal - 1 no of throwsVal left ; Inserting present values in dp ; Driver code"
How can the above be solved in Java?

class GFG { static int mod = 1000000007 ; static int [ ] [ ] dp = new int [ 55 ] [ 55 ] ; static int NoofWays ( int face , int throwsVal , int sum ) { if ( sum == 0 && throwsVal == 0 ) { return 1 ; } if ( sum < 0 throwsVal == 0 ) { return 0 ; } if ( dp [ throwsVal ] [ sum ] != - 1 ) { return dp [ throwsVal ] [ sum ] ; } int ans = 0 ; for ( int i = 1 ; i <= face ; i ++ ) { ans += NoofWays ( face , throwsVal - 1 , sum - i ) ; } return dp [ throwsVal ] [ sum ] = ans ; } public static void main ( String [ ] args ) { int faces = 6 , throwsVal = 3 , sum = 12 ; for ( int i = 0 ; i < 55 ; i ++ ) { for ( int j = 0 ; j < 55 ; j ++ ) { dp [ i ] [ j ] = - 1 ; } } System . out . println ( NoofWays ( faces , throwsVal , sum ) ) ; } }


"Number of ways to insert a character to increase the LCS by one | Java Program for Number of ways to insert a character to increase LCS by one ; Return the Number of ways to insert a character to increase the Longest Common Subsequence by one ; Insert all positions of all characters in string B . ; Longest Common Subsequence ; Longest Common Subsequence from reverse ; inserting character between position i and i + 1 ; Driver Code"
How can the above be solved in Java?

import java . util . * ; class GFG { static final int MAX = 256 ; static int numberofways ( String A , String B , int N , int M ) { Vector < Integer > [ ] pos = new Vector [ MAX ] ; for ( int i = 0 ; i < MAX ; i ++ ) pos [ i ] = new Vector < > ( ) ; for ( int i = 0 ; i < M ; i ++ ) pos [ B . charAt ( i ) ] . add ( i + 1 ) ; int [ ] [ ] dpl = new int [ N + 2 ] [ M + 2 ] ; for ( int i = 1 ; i <= N ; i ++ ) { for ( int j = 1 ; j <= M ; j ++ ) { if ( A . charAt ( i - 1 ) == B . charAt ( j - 1 ) ) dpl [ i ] [ j ] = dpl [ i - 1 ] [ j - 1 ] + 1 ; else dpl [ i ] [ j ] = Math . max ( dpl [ i - 1 ] [ j ] , dpl [ i ] [ j - 1 ] ) ; } } int LCS = dpl [ N ] [ M ] ; int [ ] [ ] dpr = new int [ N + 2 ] [ M + 2 ] ; for ( int i = N ; i >= 1 ; i -- ) { for ( int j = M ; j >= 1 ; j -- ) { if ( A . charAt ( i - 1 ) == B . charAt ( j - 1 ) ) dpr [ i ] [ j ] = dpr [ i + 1 ] [ j + 1 ] + 1 ; else dpr [ i ] [ j ] = Math . max ( dpr [ i + 1 ] [ j ] , dpr [ i ] [ j + 1 ] ) ; } } int ans = 0 ; for ( int i = 0 ; i <= N ; i ++ ) { for ( int j = 0 ; j < MAX ; j ++ ) { for ( int x : pos [ j ] ) { if ( dpl [ i ] [ x - 1 ] + dpr [ i + 1 ] [ x + 1 ] == LCS ) { ans ++ ; break ; } } } } return ans ; } public static void main ( String [ ] args ) { String A = " aa " , B = " baaa " ; int N = A . length ( ) , M = B . length ( ) ; System . out . println ( numberofways ( A , B , N , M ) ) ; } }


"Number of ways to make exactly C components in a 2 * N matrix | Java implementation to find the number of ways to make exactly C components in a 2 * N matrix ; row1 and row2 are one when both are same colored ; Function to find the number of ways to make exactly C components in a 2 * N matrix ; if No of components at any stage exceeds the given number then base case ; Condition to check if already visited ; if not visited previously ; At the first column ; color { white , white } or { black , black } ; Color { white , black } or { black , white } ; If previous both rows have same color ; Fill with { same , same } and { white , black } and { black , white } ; Fill with same without increase in component as it has been counted previously ; When previous rows had { white , black } ; When previous rows had { black , white } ; Memoization ; Driver Code ; Initially at first column with 0 components"
How can the above be solved in Java?

class GFG { static int n , k ; static int [ ] [ ] [ ] [ ] dp = new int [ 1024 ] [ 2048 ] [ 2 ] [ 2 ] ; static int Ways ( int col , int comp , int row1 , int row2 ) { if ( comp > k ) return 0 ; if ( col > n ) { if ( comp == k ) return 1 ; else return 0 ; } if ( dp [ col ] [ comp ] [ row1 ] [ row2 ] != - 1 ) return dp [ col ] [ comp ] [ row1 ] [ row2 ] ; else { int ans = 0 ; if ( col == 1 ) { ans = ( ans + Ways ( col + 1 , comp + 1 , 0 , 0 ) + Ways ( col + 1 , comp + 1 , 1 , 1 ) ) ; ans = ( ans + Ways ( col + 1 , comp + 2 , 0 , 1 ) + Ways ( col + 1 , comp + 2 , 1 , 0 ) ) ; } else { if ( ( row1 > 0 && row2 > 0 ) || ( row1 == 0 && row2 == 0 ) ) { ans = ( ( ( ans + Ways ( col + 1 , comp + 1 , 0 , 0 ) ) + Ways ( col + 1 , comp + 1 , 1 , 0 ) ) + Ways ( col + 1 , comp + 1 , 0 , 1 ) ) ; ans = ( ans + Ways ( col + 1 , comp , 1 , 1 ) ) ; } if ( row1 > 0 && row2 == 0 ) { ans = ( ( ( ans + Ways ( col + 1 , comp , 0 , 0 ) ) + Ways ( col + 1 , comp , 1 , 1 ) ) + Ways ( col + 1 , comp , 1 , 0 ) ) ; ans = ( ans + Ways ( col + 1 , comp + 2 , 0 , 1 ) ) ; } if ( row1 == 0 && row2 > 0 ) { ans = ( ( ( ans + Ways ( col + 1 , comp , 0 , 0 ) ) + Ways ( col + 1 , comp , 1 , 1 ) ) + Ways ( col + 1 , comp , 0 , 1 ) ) ; ans = ( ans + Ways ( col + 1 , comp + 2 , 1 , 0 ) ) ; } } return dp [ col ] [ comp ] [ row1 ] [ row2 ] = ans ; } } public static void main ( String [ ] args ) { n = 2 ; k = 1 ; for ( int i = 0 ; i < 1024 ; i ++ ) for ( int j = 0 ; j < 2048 ; j ++ ) for ( int k = 0 ; k < 2 ; k ++ ) for ( int l = 0 ; l < 2 ; l ++ ) dp [ i ] [ j ] [ k ] [ l ] = - 1 ; System . out . print ( Ways ( 1 , 0 , 0 , 0 ) ) ; } }


"Number of ways to obtain each numbers in range [ 1 , b + c ] by adding any two numbers in range [ a , b ] and [ b , c ] | Java program to calculate the number of ways ; 2 is added because sometimes we will decrease the value out of bounds . ; Initialising the array with zeros . ; Printing the array ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { static void CountWays ( int a , int b , int c ) { int x = b + c + 2 ; int arr [ ] = new int [ x ] ; for ( int i = 1 ; i <= b ; i ++ ) { arr [ i + b ] ++ ; arr [ i + c + 1 ] -- ; } for ( int i = 1 ; i < x - 1 ; i ++ ) { arr [ i ] += arr [ i - 1 ] ; System . out . print ( arr [ i ] + " ▁ " ) ; } System . out . println ( ) ; } public static void main ( String [ ] args ) { int a = 1 ; int b = 2 ; int c = 2 ; CountWays ( a , b , c ) ; } }


"Number of ways to obtain each numbers in range [ 1 , b + c ] by adding any two numbers in range [ a , b ] and [ b , c ] | Java program to calculate the number of ways ; Initialising the array with zeros . You can do using memset too . ; Printing the array ; Driver code"
How can the above be solved in Java?

class GFG { public static void CountWays ( int a , int b , int c ) { int x = b + c + 1 ; int [ ] arr = new int [ x ] ; for ( int i = a ; i <= b ; i ++ ) { for ( int j = b ; j <= c ; j ++ ) { arr [ i + j ] ++ ; } } for ( int i = 1 ; i < x ; i ++ ) { System . out . print ( arr [ i ] + " ▁ " ) ; } } public static void main ( String [ ] args ) { int a = 1 ; int b = 2 ; int c = 2 ; CountWays ( a , b , c ) ; } }


"Number of ways to paint K cells in 3 x N grid such that no P continuous columns are left unpainted | Java implementation to find the number of ways to paint K cells of 3 x N grid such that No two adjacent cells are painted ; Visited array to keep track of which columns were painted ; Recursive Function to compute the number of ways to paint the K cells of the 3 x N grid ; Condition to check if total cells painted are K ; Check if any P continuous columns were left unpainted ; Condition to check if no P continuous columns were left unpainted ; return 0 if there are P continuous columns are left unpainted ; Condition to check if No further cells can be painted , so return 0 ; If already calculated the value return the val instead of calculating again ; Previous column was not painted ; Column is painted so , make vis [ col ] = true ; Condition to check if the number of cells to be painted is equal to or more than 2 , then we can paint first and third row ; Condition to check if number of previous continuous columns left unpainted is less than P ; Condition to check if first row was painted in previous column ; Condition to check if second row was painted in previous column ; Condition to check if the number of cells to be painted is equal to or more than 2 , then we can paint first and third row ; Condition to check if third row was painted in previous column ; Condition to check if first and third row were painted in previous column ; Memoize the data and return the computed value ; Function to find the number of ways to paint 3 x N grid ; Set all values of dp to - 1 ; ; Set all values of Visited array to false ; Driver Code"
How can the above be solved in Java?

import java . util . * ; class GFG { static int mod = ( int ) ( 1e9 + 7 ) ; static final int MAX = 301 ; static final int MAXP = 3 ; static final int MAXK = 600 ; static final int MAXPREV = 4 ; static int [ ] [ ] [ ] [ ] dp = new int [ MAX ] [ MAXP + 1 ] [ MAXK ] [ MAXPREV + 1 ] ; static boolean [ ] vis = new boolean [ MAX ] ; static int helper ( int col , int prevCol , int painted , int prev , int N , int P , int K ) { if ( painted >= K ) { int continuousCol = 0 ; int maxContinuousCol = 0 ; for ( int i = 0 ; i < N ; i ++ ) { if ( vis [ i ] == false ) continuousCol ++ ; else { maxContinuousCol = Math . max ( maxContinuousCol , continuousCol ) ; continuousCol = 0 ; } } maxContinuousCol = Math . max ( maxContinuousCol , continuousCol ) ; if ( maxContinuousCol < P ) return 1 ; return 0 ; } if ( col >= N ) return 0 ; if ( dp [ col ] [ prevCol ] [ painted ] [ prev ] != - 1 ) return dp [ col ] [ prevCol ] [ painted ] [ prev ] ; int res = 0 ; if ( prev == 0 ) { vis [ col ] = true ; res += ( helper ( col + 1 , 0 , painted + 1 , 1 , N , P , K ) ) % mod ; res += ( helper ( col + 1 , 0 , painted + 1 , 2 , N , P , K ) ) % mod ; res += ( helper ( col + 1 , 0 , painted + 1 , 3 , N , P , K ) ) % mod ; if ( painted + 2 <= K ) { res += ( helper ( col + 1 , 0 , painted + 2 , 4 , N , P , K ) ) % mod ; } vis [ col ] = false ; if ( prevCol + 1 < P ) { res += ( helper ( col + 1 , prevCol + 1 , painted , 0 , N , P , K ) ) % mod ; } } else if ( prev == 1 ) { vis [ col ] = true ; res += ( helper ( col + 1 , 0 , painted + 1 , 2 , N , P , K ) ) % mod ; res += ( helper ( col + 1 , 0 , painted + 1 , 3 , N , P , K ) ) % mod ; vis [ col ] = false ; if ( prevCol + 1 < P ) { res += ( helper ( col + 1 , prevCol + 1 , painted , 0 , N , P , K ) ) % mod ; } } else if ( prev == 2 ) { vis [ col ] = true ; res += ( helper ( col + 1 , 0 , painted + 1 , 1 , N , P , K ) ) % mod ; res += ( helper ( col + 1 , 0 , painted + 1 , 3 , N , P , K ) ) % mod ; if ( painted + 2 <= K ) { res += ( helper ( col + 1 , 0 , painted + 2 , 4 , N , P , K ) ) % mod ; }...


"Number of ways to partition a string into two balanced subsequences | Java implementation of the above approach ; For maximum length of input string ; Declaring the DP table ; Function to calculate the number of valid assignments ; Return 1 if both subsequences are balanced ; Increment the count if it an opening bracket ; Decrement the count if it a closing bracket ; Driver Code ; Initializing the DP table ; Initial value for c_x and c_y is zero"
How can the above be solved in Java?

class GFG { static int MAX = 10 ; static int [ ] [ ] [ ] F = new int [ MAX ] [ MAX ] [ MAX ] ; static int noOfAssignments ( String s , int n , int i , int c_x , int c_y ) { if ( F [ i ] [ c_x ] [ c_y ] != - 1 ) return F [ i ] [ c_x ] [ c_y ] ; if ( i == n ) { F [ i ] [ c_x ] [ c_y ] = ( c_x == 0 && c_y == 0 ) ? 1 : 0 ; return F [ i ] [ c_x ] [ c_y ] ; } if ( s . charAt ( i ) == ' ( ' ) { F [ i ] [ c_x ] [ c_y ] = noOfAssignments ( s , n , i + 1 , c_x + 1 , c_y ) + noOfAssignments ( s , n , i + 1 , c_x , c_y + 1 ) ; return F [ i ] [ c_x ] [ c_y ] ; } F [ i ] [ c_x ] [ c_y ] = 0 ; if ( c_x != 0 ) F [ i ] [ c_x ] [ c_y ] += noOfAssignments ( s , n , i + 1 , c_x - 1 , c_y ) ; if ( c_y != 0 ) F [ i ] [ c_x ] [ c_y ] += noOfAssignments ( s , n , i + 1 , c_x , c_y - 1 ) ; return F [ i ] [ c_x ] [ c_y ] ; } public static void main ( String [ ] args ) { String s = " ( ( ) ) " ; int n = s . length ( ) ; for ( int i = 0 ; i < MAX ; i ++ ) for ( int j = 0 ; j < MAX ; j ++ ) for ( int k = 0 ; k < MAX ; k ++ ) F [ i ] [ j ] [ k ] = - 1 ; System . out . println ( noOfAssignments ( s , n , 0 , 0 , 0 ) ) ; } }


"Number of ways to partition a string into two balanced subsequences | Java implementation of the approach ; For maximum length of input string ; Declaring the DP table ; Declaring the prefix array ; Function to calculate the number of valid assignments ; Return 1 if X is balanced . ; Increment the count if it an opening bracket ; Decrement the count if it a closing bracket ; Driver code ; Initializing the DP table ; Creating the prefix array ; Initial value for c_x and c_y is zero"
How can the above be solved in Java?

public class GFG { static int MAX = 10 ; static int F [ ] [ ] = new int [ MAX ] [ MAX ] ; static int C [ ] = new int [ MAX ] ; static int noOfAssignments ( String S , int n , int i , int c_x ) { if ( F [ i ] [ c_x ] != - 1 ) { return F [ i ] [ c_x ] ; } if ( i == n ) { if ( c_x == 1 ) { F [ i ] [ c_x ] = 0 ; } else { F [ i ] [ c_x ] = 1 ; } return F [ i ] [ c_x ] ; } int c_y = C [ i ] - c_x ; if ( S . charAt ( i ) == ' ( ' ) { F [ i ] [ c_x ] = noOfAssignments ( S , n , i + 1 , c_x + 1 ) + noOfAssignments ( S , n , i + 1 , c_x ) ; return F [ i ] [ c_x ] ; } F [ i ] [ c_x ] = 0 ; if ( c_x == 1 ) { F [ i ] [ c_x ] += noOfAssignments ( S , n , i + 1 , c_x - 1 ) ; } if ( c_y == 1 ) { F [ i ] [ c_x ] += noOfAssignments ( S , n , i + 1 , c_x ) ; } return F [ i ] [ c_x ] ; } public static void main ( String [ ] args ) { String S = " ( ) " ; int n = S . length ( ) ; for ( int i = 0 ; i < MAX ; i ++ ) { for ( int j = 0 ; j < MAX ; j ++ ) { F [ i ] [ j ] = - 1 ; } } C [ 0 ] = 0 ; for ( int i = 0 ; i < n ; ++ i ) { if ( S . charAt ( i ) == ' ( ' ) { C [ i + 1 ] = C [ i ] + 1 ; } else { C [ i + 1 ] = C [ i ] - 1 ; } } System . out . println ( noOfAssignments ( S , n , 0 , 0 ) ) ; } }


"Number of ways to place two queens on a N * N chess | Java implementation to find the number of ways to place two queens on the N * N chess board ; Function to find number of valid positions for two queens in the N * N chess board ; Driver Code ; Function Call"
How can the above be solved in Java?

 class GFG { static double possiblePositions ( double n ) { double term1 = Math . pow ( n , 4 ) ; double term2 = Math . pow ( n , 3 ) ; double term3 = Math . pow ( n , 2 ) ; double term4 = n / 3 ; double ans = ( Math . ceil ( term1 / 2 ) ) - ( Math . ceil ( 5 * term2 ) / 3 ) + ( Math . ceil ( 3 * term3 ) / 2 ) - term4 ; return ( long ) ans ; } public static void main ( String [ ] args ) { double n ; n = 3 ; double ans = possiblePositions ( n ) ; System . out . print ( ans + "
"); } }


"Number of ways to reach ( M , N ) in a matrix starting from the origin without visiting ( X , Y ) | Java program from the above approach ; Function for computing nCr ; Function to find factorial of a number ; Function for counting the number of ways to reach ( m , n ) without visiting ( x , y ) ; Driver code ; Given Dimensions of Matrix ; Cell not to be visited ; Function Call"
How can the above be solved in Java?

import java . util . * ; class GFG { public static int nCr ( int n , int r ) { return fact ( n ) / ( fact ( r ) * fact ( n - r ) ) ; } public static int fact ( int n ) { int res = 1 ; for ( int i = 2 ; i <= n ; i ++ ) res = res * i ; return res ; } public static int countWays ( int m , int n , int x , int y ) { return nCr ( m + n , m ) - nCr ( x + y , x ) * nCr ( m + n - x - y , m - x ) ; } public static void main ( String [ ] args ) { int m = 5 ; int n = 4 ; int x = 3 ; int y = 2 ; System . out . println ( countWays ( m , n , x , y ) ) ; } }


"Number of ways to reach ( X , Y ) in a matrix starting from the origin | Java implementation of the approach ; To store the factorial and factorial mod inverse of the numbers ; Function to find ( a ^ m1 ) % mod ; Function to find the factorial of all the numbers ; Function to find the factorial modinverse of all the numbers ; Function to return nCr ; Function to return the number of ways to reach ( X , Y ) in a matrix with the given moves starting from the origin ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { static long [ ] factorial = new long [ 1000005 ] ; static long [ ] modinverse = new long [ 1000005 ] ; static long mod = 1000000007 ; static int N = 1000005 ; static long power ( long a , long m1 ) { if ( m1 == 0 ) return 1 ; else if ( m1 == 1 ) return a ; else if ( m1 == 2 ) return ( a * a ) % mod ; else if ( ( m1 & 1 ) != 0 ) return ( a * power ( power ( a , m1 / 2 ) , 2 ) ) % mod ; else return power ( power ( a , m1 / 2 ) , 2 ) % mod ; } static void factorialfun ( ) { factorial [ 0 ] = 1 ; for ( int i = 1 ; i < N ; i ++ ) factorial [ i ] = ( factorial [ i - 1 ] * i ) % mod ; } static void modinversefun ( ) { modinverse [ N - 1 ] = power ( factorial [ N - 1 ] , mod - 2 ) % mod ; for ( int i = N - 2 ; i >= 0 ; i -- ) modinverse [ i ] = ( modinverse [ i + 1 ] * ( i + 1 ) ) % mod ; } static long binomial ( int n , int r ) { if ( r > n ) return 0 ; long a = ( factorial [ n ] * modinverse [ n - r ] ) % mod ; a = ( a * modinverse [ r ] ) % mod ; return a ; } static long ways ( long x , long y ) { factorialfun ( ) ; modinversefun ( ) ; if ( ( 2 * x - y ) % 3 == 0 && ( 2 * y - x ) % 3 == 0 ) { long m = ( 2 * x - y ) / 3 ; long n = ( 2 * y - x ) / 3 ; System . out . println ( n + m + " ▁ " + n ) ; return binomial ( ( int ) ( n + m ) , ( int ) n ) ; } return 0 ; } public static void main ( String [ ] args ) { long x = 3 , y = 3 ; System . out . println ( ways ( x , y ) ) ; } }


"Number of ways to represent a number as sum of k fibonacci numbers | Java implementation of above approach ; to store fibonacci numbers 42 second number in fibonacci series largest possible integer ; Function to generate fibonacci series ; Recursive function to return the number of ways ; base condition ; for recursive function call ; Driver code"
How can the above be solved in Java?

public class AQW { static int fib [ ] = new int [ 43 ] ; static void fibonacci ( ) { fib [ 0 ] = 1 ; fib [ 1 ] = 2 ; for ( int i = 2 ; i < 43 ; i ++ ) fib [ i ] = fib [ i - 1 ] + fib [ i - 2 ] ; } static int rec ( int x , int y , int last ) { if ( y == 0 ) { if ( x == 0 ) return 1 ; return 0 ; } int sum = 0 ; for ( int i = last ; i >= 0 && fib [ i ] * y >= x ; i -- ) { if ( fib [ i ] > x ) continue ; sum += rec ( x - fib [ i ] , y - 1 , i ) ; } return sum ; } public static void main ( String [ ] args ) { fibonacci ( ) ; int n = 13 , k = 3 ; System . out . println ( " Possible ▁ ways ▁ are : ▁ " + rec ( n , k , 42 ) ) ; } }


"Number of ways to select equal sized subarrays from two arrays having atleast K equal pairs of elements | Java implementation to count the number of ways to select equal sized subarrays such that they have atleast K common elements ; 2D prefix sum for submatrix sum query for matrix ; Function to find the prefix sum of the matrix from i and j ; Function to count the number of ways to select equal sized subarrays such that they have atleast K common elements ; Combining the two arrays ; Calculating the 2D prefix sum ; Iterating through all the elements of matrix and considering them to be the bottom right ; Applying binary search over side length ; If sum of this submatrix >= k then new search space will be [ low , mid ] ; Else new search space will be [ mid + 1 , high ] ; Adding the total submatrices ; Driver Code"
How can the above be solved in Java?

class GFG { static int [ ] [ ] prefix_2D = new int [ 2005 ] [ 2005 ] ; static int subMatrixSum ( int i , int j , int len ) { return prefix_2D [ i ] [ j ] - prefix_2D [ i ] [ j - len ] - prefix_2D [ i - len ] [ j ] + prefix_2D [ i - len ] [ j - len ] ; } static int numberOfWays ( int a [ ] , int b [ ] , int n , int m , int k ) { for ( int i = 1 ; i <= n ; i ++ ) { for ( int j = 1 ; j <= m ; j ++ ) { if ( a [ i - 1 ] == b [ j - 1 ] ) prefix_2D [ i ] [ j ] = 1 ; else prefix_2D [ i ] [ j ] = 0 ; } } for ( int i = 1 ; i <= n ; i ++ ) { for ( int j = 1 ; j <= m ; j ++ ) { prefix_2D [ i ] [ j ] += prefix_2D [ i ] [ j - 1 ] ; } } for ( int i = 1 ; i <= n ; i ++ ) { for ( int j = 1 ; j <= m ; j ++ ) { prefix_2D [ i ] [ j ] += prefix_2D [ i - 1 ] [ j ] ; } } int answer = 0 ; for ( int i = 1 ; i <= n ; i ++ ) { for ( int j = 1 ; j <= m ; j ++ ) { int low = 1 ; int high = Math . min ( i , j ) ; while ( low < high ) { int mid = ( low + high ) >> 1 ; if ( subMatrixSum ( i , j , mid ) >= k ) { high = mid ; } else { low = mid + 1 ; } } if ( subMatrixSum ( i , j , low ) >= k ) { answer += ( Math . min ( i , j ) - low + 1 ) ; } } } return answer ; } public static void main ( String [ ] args ) { int N = 2 , M = 3 ; int A [ ] = { 1 , 2 } ; int B [ ] = { 1 , 2 , 3 } ; int K = 1 ; System . out . print ( numberOfWays ( A , B , N , M , K ) ) ; } }


"Number of ways to select exactly K even numbers from given Array | Java program for the above approach ; Function for calculating factorial ; Factorial of n defined as : n ! = n * ( n - 1 ) * ... * 1 ; Function to find the number of ways to select exactly K even numbers from the given array ; Count even numbers ; Check if the current number is even ; Check if the even numbers to be chosen is greater than n . Then , there is no way to pick it . ; The number of ways will be nCk ; Driver Code ; Given array arr [ ] ; Given count of even elements ; Function call"
How can the above be solved in Java?

 class GFG { static int [ ] f = new int [ 12 ] ; static void fact ( ) { f [ 0 ] = f [ 1 ] = 1 ; for ( int i = 2 ; i <= 10 ; i ++ ) f [ i ] = i * 1 * f [ i - 1 ] ; } static void solve ( int arr [ ] , int n , int k ) { fact ( ) ; int even = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( arr [ i ] % 2 == 0 ) even ++ ; } if ( k > even ) System . out . print ( 0 + "
"); else { System . out . print ( f [ even ] / ( f [ k ] * f [ even - k ] ) ) ; } } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 2 , 3 , 4 } ; int n = arr . length ; int k = 1 ; solve ( arr , n , k ) ; } }


"Number of ways to split N as sum of K numbers from the given range | Java implementation to count the number of ways to divide N in K groups such that each group has elements in range [ L , R ] ; DP Table ; Function to count the number of ways to divide the number N in K groups such that each group has number of elements in range [ L , R ] ; Base Case ; If N is divides completely into less than k groups ; If the subproblem has been solved , use the value ; Put all possible values greater equal to prev ; Function to count the number of ways to divide the number N ; Initialize DP Table as - 1 ; Driver Code"
How can the above be solved in Java?

class GFG { static int mod = 1000000007 ; static int [ ] [ ] dp = new int [ 1000 ] [ 1000 ] ; static int calculate ( int pos , int left , int k , int L , int R ) { if ( pos == k ) { if ( left == 0 ) return 1 ; else return 0 ; } if ( left == 0 ) return 0 ; if ( dp [ pos ] [ left ] != - 1 ) return dp [ pos ] [ left ] ; int answer = 0 ; for ( int i = L ; i <= R ; i ++ ) { if ( i > left ) break ; answer = ( answer + calculate ( pos + 1 , left - i , k , L , R ) ) % mod ; } return dp [ pos ] [ left ] = answer ; } static int countWaystoDivide ( int n , int k , int L , int R ) { for ( int i = 0 ; i < 1000 ; i ++ ) { for ( int j = 0 ; j < 1000 ; j ++ ) { dp [ i ] [ j ] = - 1 ; } } return calculate ( 0 , n , k , L , R ) ; } public static void main ( String [ ] args ) { int N = 12 ; int K = 3 ; int L = 1 ; int R = 5 ; System . out . print ( countWaystoDivide ( N , K , L , R ) ) ; } }


"Number of ways to split N as sum of K numbers from the given range | Java implementation to count the number of ways to divide N in K groups such that each group has elements in range [ L , R ] ; Function to count the number of ways to divide the number N in K groups such that each group has number of elements in range [ L , R ] ; Base Case ; If N is divides completely into less than k groups ; Put all possible values greater equal to prev ; Function to count the number of ways to divide the number N ; Driver Code"
How can the above be solved in Java?

class GFG { static int mod = 1000000007 ; static int calculate ( int pos , int left , int k , int L , int R ) { if ( pos == k ) { if ( left == 0 ) return 1 ; else return 0 ; } if ( left == 0 ) return 0 ; int answer = 0 ; for ( int i = L ; i <= R ; i ++ ) { if ( i > left ) break ; answer = ( ( answer + calculate ( pos + 1 , left - i , k , L , R ) ) % mod ) ; } return answer ; } static int countWaystoDivide ( int n , int k , int L , int R ) { return calculate ( 0 , n , k , L , R ) ; } public static void main ( String [ ] args ) { int N = 12 ; int K = 3 ; int L = 1 ; int R = 5 ; System . out . print ( countWaystoDivide ( N , K , L , R ) ) ; } }


"Number of ways to sum up a total of N from limited denominations | Java program for the above approach ; Function to find the number of ways to sum up a total of N from limited denominations ; Store the count of denominations ; Stores the final result ; As one of the denominations is rupee 1 , so we can reduce the computation by checking the equality for N - ( A * 1 ) = N - A ; Increment the count for number of ways ; Driver Code ; Given denominations ; Function call"
How can the above be solved in Java?

import java . util . * ; class GFG { static int calculateWays ( int arr1 [ ] , int arr2 [ ] , int N ) { int A = arr2 [ 0 ] , B = arr2 [ 1 ] ; int C = arr2 [ 2 ] , D = arr2 [ 3 ] ; int ans = 0 ; for ( int b = 0 ; b <= B && b * 5 <= ( N ) ; b ++ ) for ( int c = 0 ; c <= C && b * 5 + c * 10 <= ( N ) ; c ++ ) for ( int d = 0 ; d <= D && b * 5 + c * 10 + d * 20 <= ( N ) ; d ++ ) if ( ( b * 5 ) + ( c * 10 ) + ( d * 20 ) >= ( N - A ) ) ans ++ ; return ans ; } public static void main ( String [ ] args ) { int N = 123 ; int arr1 [ ] = { 1 , 5 , 10 , 20 } ; int arr2 [ ] = { 6 , 4 , 3 , 5 } ; System . out . print ( calculateWays ( arr1 , arr2 , N ) ) ; } }


"Number of ways to sum up a total of N from limited denominations | Java program for the above approach ; Function to find the number of ways to sum up a total of N from limited denominations ; Store the count of denominations ; Stores the final result ; This will give the number of coins for all combinations of coins with value 1 and 5 ; L2 will sum the values of those indices of ways [ ] which is equal to ( N - ( c * 10 + d * 20 ) ) ; Return the final count ; Driver Code ; Given denominations ; Function call"
How can the above be solved in Java?

import java . util . * ; class GFG { static int [ ] ways = new int [ 1010 ] ; static int calculateWays ( int arr1 [ ] , int arr2 [ ] , int N ) { int A = arr2 [ 0 ] , B = arr2 [ 1 ] ; int C = arr2 [ 2 ] , D = arr2 [ 3 ] ; int ans = 0 ; for ( int b = 0 ; b <= B && b * 5 <= N ; b ++ ) { for ( int a = 0 ; a <= A && a * 1 + b * 5 <= N ; a ++ ) { ways [ a + b * 5 ] ++ ; } } for ( int c = 0 ; c <= C && c * 10 <= ( N ) ; c ++ ) { for ( int d = 0 ; d <= D && c * 10 + d * 20 <= ( N ) ; d ++ ) { ans += ways [ N - c * 10 - d * 20 ] ; } } return ans ; } public static void main ( String [ ] args ) { int N = 123 ; int arr1 [ ] = { 1 , 5 , 10 , 20 } ; int arr2 [ ] = { 6 , 4 , 3 , 5 } ; System . out . print ( calculateWays ( arr1 , arr2 , N ) ) ; } }


"Number of ways to swap two bit of s1 so that bitwise OR of s1 and s2 changes | Java program to find no of ways to swap bits of s1 so that bitwise OR of s1 and s2 changes ; Function to find number of ways ; initialise result that store No . of swaps required ; Traverse both strings and check the bits as explained ; calculate result ; Driver code"
How can the above be solved in Java?

import java . io . * ; class GFG { static int countWays ( String s1 , String s2 , int n ) { int a , b , c , d ; a = b = c = d = 0 ; int result = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( s2 . charAt ( i ) == '0' ) { if ( s1 . charAt ( i ) == '0' ) { c ++ ; } else { d ++ ; } } else { if ( s1 . charAt ( i ) == '0' ) { a ++ ; } else { b ++ ; } } } result = a * d + b * c + c * d ; return result ; } public static void main ( String [ ] args ) { int n = 5 ; String s1 = "01011" ; String s2 = "11001" ; System . out . println ( countWays ( s1 , s2 , n ) ) ; } }


"Number of words in a camelcase sequence | Java code to find the count of words in a CamelCase sequence ; Function to find the count of words in a CamelCase sequence ; Driver code"
How can the above be solved in Java?

class solution { static int countWords ( String str ) { int count = 1 ; for ( int i = 1 ; i < str . length ( ) - 1 ; i ++ ) { if ( str . charAt ( i ) >= 65 && str . charAt ( i ) <= 90 ) count ++ ; } return count ; } public static void main ( String args [ ] ) { String str = " geeksForGeeks " ; System . out . print ( countWords ( str ) ) ; } }


"Number of words that can be made using exactly P consonants and Q vowels from the given string | Java implementation of the above approach ; Function to return the value of nCk ; Function to return the factorial of n ; Function that returns true if ch is a vowel ; Function to return the number of words possible ; To store the count of vowels and consonanats in the given string ; If current character is a vowel ; Find the total possible words ; Driver code"
How can the above be solved in Java?

class GFG { static long binomialCoeff ( long n , long k ) { if ( k == 0 k == n ) return 1 ; return binomialCoeff ( n - 1 , k - 1 ) + binomialCoeff ( n - 1 , k ) ; } static long fact ( long n ) { if ( n >= 1 ) return n * fact ( n - 1 ) ; else return 1 ; } static boolean isVowel ( char ch ) { if ( ch == ' a ' ch == ' e ' ch == ' i ' ch == ' o ' ch == ' u ' ) { return true ; } return false ; } static long countWords ( String s , int p , int q ) { long countc = 0 , countv = 0 ; for ( int i = 0 ; i < s . length ( ) ; i ++ ) { if ( isVowel ( s . charAt ( i ) ) ) countv ++ ; else countc ++ ; } long a = binomialCoeff ( countc , p ) ; long b = binomialCoeff ( countv , q ) ; long c = fact ( p + q ) ; long ans = ( a * b ) * c ; return ans ; } public static void main ( String [ ] args ) { String s = " crackathon " ; int p = 4 , q = 3 ; System . out . println ( countWords ( s , p , q ) ) ; } }


"Number which has the maximum number of distinct prime factors in the range M to N | Java program to print the Number which has the maximum number of distinct prime factors of numbers in range m to n ; Function to return the maximum number ; array to store the number of distinct primes ; true if index ' i ' is a prime ; initializing the number of factors to 0 and ; Used in Sieve ; condition works only when ' i ' is prime , hence for factors of all prime number , the prime status is changed to false ; Number is prime ; number of factor of a prime number is 1 ; incrementing factorCount all the factors of i ; and changing prime status to false ; Initialize the max and num ; Gets the maximum number ; Gets the maximum number ; Driver code ; Calling function"
How can the above be solved in Java?

import java . io . * ; class GFG { static int maximumNumberDistinctPrimeRange ( int m , int n ) { long factorCount [ ] = new long [ n + 1 ] ; boolean prime [ ] = new boolean [ n + 1 ] ; for ( int i = 0 ; i <= n ; i ++ ) { factorCount [ i ] = 0 ; prime [ i ] = true ; } for ( int i = 2 ; i <= n ; i ++ ) { if ( prime [ i ] == true ) { factorCount [ i ] = 1 ; for ( int j = i * 2 ; j <= n ; j += i ) { factorCount [ j ] ++ ; prime [ j ] = false ; } } } int max = ( int ) factorCount [ m ] ; int num = m ; for ( int i = m ; i <= n ; i ++ ) { if ( factorCount [ i ] > max ) { max = ( int ) factorCount [ i ] ; num = i ; } } return num ; } public static void main ( String [ ] args ) { int m = 4 , n = 6 ; System . out . println ( maximumNumberDistinctPrimeRange ( m , n ) ) ; } }


"Number which is co | Java program for the above approach ; Function to check whether the given number N is prime or not ; Base Case ; If N has more than one factor , then return false ; Otherwise , return true ; Function to find X which is co - prime with the integers from the range [ L , R ] ; Store the resultant number ; Check for prime integers greater than R ; If the current number is prime , then update coPrime and break out of loop ; Print the resultant number ; Driver Code"
How can the above be solved in Java?

import java . io . * ; import java . lang . * ; import java . util . * ; class GFG { static boolean isPrime ( int N ) { if ( N == 1 ) return false ; for ( int i = 2 ; i * i <= N ; i ++ ) { if ( N % i == 0 ) return false ; } return true ; } static int findCoPrime ( int L , int R ) { int coPrime ; for ( int i = R + 1 ; ; i ++ ) { if ( isPrime ( i ) ) { coPrime = i ; break ; } } return coPrime ; } public static void main ( String [ ] args ) { int L = 16 , R = 17 ; System . out . println ( findCoPrime ( L , R ) ) ; } }


"Number whose XOR sum with given array is a given number k | Java Program to find the number whose XOR sum with given array is equal to a given number k ; This function returns the number to be inserted in the given array ; initialise the answer with k ; XOR of all elements in the array ; Driver Code to test above function"
How can the above be solved in Java?

import java . io . * ; class GFG { static int findEletobeInserted ( int A [ ] , int n , int k ) { int ans = k ; for ( int i = 0 ; i < n ; i ++ ) ans ^= A [ i ] ; return ans ; } public static void main ( String [ ] args ) { int A [ ] = { 1 , 2 , 3 , 4 , 5 } ; int n = A . length ; int k = 10 ; System . out . println ( findEletobeInserted ( A , n , k ) + " ▁ has ▁ to ▁ be ▁ inserted ▁ in ▁ " + " the ▁ given ▁ array ▁ to ▁ make " + " ▁ xor ▁ sum ▁ of ▁ " + k ) ; } }


"Number whose sum of XOR with given array range is maximum | Java program to find smallest integer X such that sum of its XOR with range is maximum . ; Function to make prefix array which counts 1 's of each bit up to that number ; Making a prefix array which sums number of 1 's up to that position ; If j - th bit of a number is set then add one to previously counted 1 's ; Function to find X ; Initially taking maximum value all bits 1 ; Iterating over each bit ; get 1 ' s ▁ at ▁ ith ▁ bit ▁ between ▁ the ▁ range ▁ ▁ L - R ▁ by ▁ subtracting ▁ 1' s till Rth number - 1 's till L-1th number ; If 1 ' s ▁ are ▁ more ▁ than ▁ or ▁ equal ▁ to ▁ 0' s then unset the ith bit from answer ; Set ith bit to 0 by doing Xor with 1 ; Driver program"
How can the above be solved in Java?

import java . lang . Math ; class GFG { private static final int MAX = 2147483647 ; static int [ ] [ ] one = new int [ 100001 ] [ 32 ] ; static void make_prefix ( int A [ ] , int n ) { for ( int j = 0 ; j < 32 ; j ++ ) one [ 0 ] [ j ] = 0 ; for ( int i = 1 ; i <= n ; i ++ ) { int a = A [ i - 1 ] ; for ( int j = 0 ; j < 32 ; j ++ ) { int x = ( int ) Math . pow ( 2 , j ) ; if ( ( a & x ) != 0 ) one [ i ] [ j ] = 1 + one [ i - 1 ] [ j ] ; else one [ i ] [ j ] = one [ i - 1 ] [ j ] ; } } } static int Solve ( int L , int R ) { int l = L , r = R ; int tot_bits = r - l + 1 ; int X = MAX ; for ( int i = 0 ; i < 31 ; i ++ ) { int x = one [ r ] [ i ] - one [ l - 1 ] [ i ] ; if ( x >= tot_bits - x ) { int ith_bit = ( int ) Math . pow ( 2 , i ) ; X = X ^ ith_bit ; } } return X ; } public static void main ( String [ ] args ) { int n = 5 , q = 3 ; int A [ ] = { 210 , 11 , 48 , 22 , 133 } ; int L [ ] = { 1 , 4 , 2 } , R [ ] = { 3 , 14 , 4 } ; make_prefix ( A , n ) ; for ( int j = 0 ; j < q ; j ++ ) System . out . println ( Solve ( L [ j ] , R [ j ] ) ) ; } }


"Number with even sum of digits | Java program to find n - th Good number . ; Function to find kth good number . ; Find the last digit of n . ; If last digit is between 0 to 4 then return 2 * n . ; If last digit is between 5 to 9 then return 2 * n + 1. ; Driver code"
How can the above be solved in Java?

class GFG { static int findKthGoodNo ( int n ) { int lastDig = n % 10 ; if ( lastDig >= 0 && lastDig <= 4 ) return n << 1 ; else return ( n << 1 ) + 1 ; } public static void main ( String [ ] args ) { int n = 10 ; System . out . println ( findKthGoodNo ( n ) ) ; } }


"Number with set bits only between L | Java program to print the integer with all the bits set in range L - R Efficient Approach ; Function to return the integer with all the bits set in range L - R ; Driver Code"
How can the above be solved in Java?

import java . io . * ; class GFG { static int setbitsfromLtoR ( int L , int R ) { return ( 1 << ( R + 1 ) ) - ( 1 << L ) ; } public static void main ( String [ ] args ) { int L = 2 , R = 5 ; System . out . println ( setbitsfromLtoR ( L , R ) ) ; } }


"Number with set bits only between L | Java program to print the integer with all the bits set in range L - R Naive Approach ; Function to return the integer with all the bits set in range L - R ; iterate from L to R and add all powers of 2 ; Driver Code"
How can the above be solved in Java?

import java . io . * ; class GFG { static int getInteger ( int L , int R ) { int number = 0 ; for ( int i = L ; i <= R ; i ++ ) number += Math . pow ( 2 , i ) ; return number ; } public static void main ( String [ ] args ) { int L = 2 , R = 5 ; System . out . println ( getInteger ( L , R ) ) ; } }


"Numbers having Unique ( or Distinct ) digits | Java code for the above approach ; Function to print unique numbers ; Iterate from l to r ; Convert the no . to String ; Convert String to set using stl ; Output if condition satisfies ; Driver Code ; Input of the lower and higher limits ; Function Call"
How can the above be solved in Java?

import java . util . * ; class GFG { static void printUnique ( int l , int r ) { for ( int i = l ; i <= r ; i ++ ) { String s = String . valueOf ( i ) ; HashSet < Integer > uniDigits = new HashSet < Integer > ( ) ; for ( int c : s . toCharArray ( ) ) uniDigits . add ( c ) ; if ( s . length ( ) == uniDigits . size ( ) ) { System . out . print ( i + " ▁ " ) ; } } } public static void main ( String [ ] args ) { int l = 1 , r = 20 ; printUnique ( l , r ) ; } }


"Numbers having Unique ( or Distinct ) digits | Java implementation to find unique digit numbers in a range ; Method to print unique digit numbers in range from l to r . ; Start traversing the numbers ; Find digits and maintain its hash ; if a digit occurs more than 1 time then break ; num will be 0 only when above loop doesn 't get break that means the  number is unique so print it. ; Driver method"
How can the above be solved in Java?

class Test { static void printUnique ( int l , int r ) { for ( int i = l ; i <= r ; i ++ ) { int num = i ; boolean visited [ ] = new boolean [ 10 ] ; while ( num != 0 ) { if ( visited [ num % 10 ] ) break ; visited [ num % 10 ] = true ; num = num / 10 ; } if ( num == 0 ) System . out . print ( i + " ▁ " ) ; } } public static void main ( String args [ ] ) { int l = 1 , r = 20 ; printUnique ( l , r ) ; } }


"Numbers having difference with digit sum more than s | Java Program to find number of integer such that integer - digSum > s ; function for digit sum ; function to calculate count of integer s . t . integer - digSum > s ; if n < s no integer possible ; iterate for s range and then calculate total count of such integer if starting integer is found ; if no integer found return 0 ; Driver program"
How can the above be solved in Java?

import java . io . * ; class GFG { static int digitSum ( long n ) { int digSum = 0 ; while ( n > 0 ) { digSum += n % 10 ; n /= 10 ; } return digSum ; } public static long countInteger ( long n , long s ) { if ( n < s ) return 0 ; for ( long i = s ; i <= Math . min ( n , s + 163 ) ; i ++ ) if ( ( i - digitSum ( i ) ) > s ) return ( n - i + 1 ) ; return 0 ; } public static void main ( String args [ ] ) { long n = 1000 , s = 100 ; System . out . println ( countInteger ( n , s ) ) ; } }


"Numbers less than N that are perfect cubes and the sum of their digits reduced to a single digit is 1 | Java implementation of the approach ; Function that returns true if the eventual digit sum of number nm is 1 ; if reminder will 1 then eventual sum is 1 ; Function to print the required numbers less than n ; If it is the required perfect cube ; Driver code"
How can the above be solved in Java?

class GFG { static boolean isDigitSumOne ( int nm ) { if ( nm % 9 == 1 ) return true ; else return false ; } static void printValidNums ( int n ) { int cbrt_n = ( int ) Math . cbrt ( n ) ; for ( int i = 1 ; i <= cbrt_n ; i ++ ) { int cube = ( int ) Math . pow ( i , 3 ) ; if ( cube >= 1 && cube <= n && isDigitSumOne ( cube ) ) System . out . print ( cube + " ▁ " ) ; } } public static void main ( String args [ ] ) { int n = 1000 ; printValidNums ( n ) ; } }


"Numbers less than N which are product of exactly two distinct prime numbers | Java program to find numbers that are product of exactly two distinct prime numbers ; Function to check whether a number is a PerfectSquare or not ; Function to check if a number is a product of exactly two distinct primes ; Function to find numbers that are product of exactly two distinct prime numbers . ; Vector to store such numbers ; insert in the vector ; Print all numbers till n from the vector ; Driver function"
How can the above be solved in Java?

import java . util . * ; class GFG { static boolean isPerfectSquare ( double x ) { double sr = Math . sqrt ( x ) ; return ( ( sr - Math . floor ( sr ) ) == 0 ) ; } static boolean isProduct ( int num ) { int cnt = 0 ; for ( int i = 2 ; cnt < 2 && i * i <= num ; ++ i ) { while ( num % i == 0 ) { num /= i ; ++ cnt ; } } if ( num > 1 ) ++ cnt ; return cnt == 2 ; } static void findNumbers ( int N ) { Vector < Integer > vec = new Vector < Integer > ( ) ; for ( int i = 1 ; i <= N ; i ++ ) { if ( isProduct ( i ) && ! isPerfectSquare ( i ) ) { vec . add ( i ) ; } } Iterator < Integer > itr = vec . iterator ( ) ; while ( itr . hasNext ( ) ) { System . out . print ( itr . next ( ) + " ▁ " ) ; } } public static void main ( String [ ] args ) { int N = 30 ; findNumbers ( N ) ; } }


"Numbers of Length N having digits A and B and whose sum of digits contain only digits A and B | Java implementation of the approach ; Function that returns true if the num contains a and b digits only ; Modular Exponentiation ; Function to return the modular inverse of x modulo MOD ; Function to return the required count of numbers ; Generating factorials of all numbers ; Generating inverse of factorials modulo MOD of all numbers ; Keeping a as largest number ; Iterate over all possible values of s and if it is a valid S then proceed further ; Check for invalid cases in the equation ; Find answer using combinatorics ; Add this result to final answer ; Driver Code"
How can the above be solved in Java?

class GFG { static int MAX = ( int ) ( 1E5 + 5 ) ; static long MOD = ( long ) ( 1E9 + 7 ) ; static boolean check ( long num , long a , long b ) { while ( num > 0 ) { long rem = num % 10 ; num /= 10 ; if ( rem != a && rem != b ) return false ; } return true ; } static long power ( long x , long y ) { long ans = 1 ; while ( y > 0 ) { if ( ( y & 1 ) > 0 ) ans = ( ans * x ) % MOD ; y >>= 1 ; x = ( x * x ) % MOD ; } return ans % MOD ; } static long modInverse ( long x ) { return power ( x , MOD - 2 ) ; } static long countNumbers ( long n , long a , long b ) { long [ ] fact = new long [ MAX ] ; long [ ] inv = new long [ MAX ] ; long ans = 0 ; fact [ 0 ] = 1 ; for ( int i = 1 ; i < MAX ; i ++ ) { fact [ i ] = ( 1 * fact [ i - 1 ] * i ) ; fact [ i ] %= MOD ; } inv [ MAX - 1 ] = modInverse ( fact [ MAX - 1 ] ) ; for ( int i = MAX - 2 ; i >= 0 ; i -- ) { inv [ i ] = ( inv [ i + 1 ] * ( i + 1 ) ) ; inv [ i ] %= MOD ; } if ( a < b ) { long x = a ; a = b ; b = x ; } for ( long s = n ; s <= 9 * n ; s ++ ) { if ( ! check ( s , a , b ) ) continue ; if ( s < n * b || ( s - n * b ) % ( a - b ) != 0 ) continue ; int numDig = ( int ) ( ( s - n * b ) / ( a - b ) ) ; if ( numDig > n ) continue ; long curr = fact [ ( int ) n ] ; curr = ( curr * inv [ numDig ] ) % MOD ; curr = ( curr * inv [ ( int ) n - numDig ] ) % MOD ; ans = ( ans + curr ) % MOD ; } return ans ; } public static void main ( String [ ] args ) { long n = 3 , a = 1 , b = 3 ; System . out . println ( countNumbers ( n , a , b ) ) ; } }


"Numbers of pairs from an array whose average is also present in the array | Java program for the above approach ; Function to count the number of pairs from the array having sum S ; Stores the total count of pairs whose sum is 2 * S ; Generate all possible pairs and check their sums ; If the sum is S , then increment the count ; Return the total count of pairs ; Function to count of pairs having whose average exists in the array ; Initialize the count ; Use set to remove duplicates ; Add elements in the set ; For every sum , count all possible pairs ; Return the total count ; Driver Code"
How can the above be solved in Java?

import java . io . * ; import java . util . * ; class GFG { public static int getCountPairs ( int arr [ ] , int N , int S ) { int count = 0 ; for ( int i = 0 ; i < arr . length ; i ++ ) { for ( int j = i + 1 ; j < arr . length ; j ++ ) { if ( ( arr [ i ] + arr [ j ] ) == S ) count ++ ; } } return count ; } public static int countPairs ( int arr [ ] , int N ) { int count = 0 ; HashSet < Integer > S = new HashSet < > ( ) ; for ( int i = 0 ; i < N ; i ++ ) S . add ( arr [ i ] ) ; for ( int ele : S ) { int sum = 2 * ele ; count += getCountPairs ( arr , N , sum ) ; } return count ; } public static void main ( String [ ] args ) { int arr [ ] = { 4 , 2 , 5 , 1 , 3 , 5 } ; int N = arr . length ; System . out . print ( countPairs ( arr , N ) ) ; } }


"Numbers of pairs from an array whose average is also present in the array | Java program for the above approach ; Function to count the total count of pairs having sum S ; Store the total count of all elements in map mp ; Initialize value to 0 , if key not found ; Stores the total count of total pairs ; Iterate through each element and increment the count ; If the value ( S - arr [ i ] ) exists in the map hm ; Update the twice count ; Return the half of twice_count ; Function to count of pairs having whose average exists in the array ; Stores the total count of pairs ; Use set to remove duplicates ; Insert all the element in the set S ; For every sum find the getCountPairs ; Return the total count of pairs ; Driver Code"
How can the above be solved in Java?

import java . io . * ; import java . util . * ; class GFG { static int getCountPairs ( int arr [ ] , int N , int S ) { HashMap < Integer , Integer > mp = new HashMap < > ( ) ; for ( int i = 0 ; i < N ; i ++ ) { if ( ! mp . containsKey ( arr [ i ] ) ) mp . put ( arr [ i ] , 0 ) ; mp . put ( arr [ i ] , mp . get ( arr [ i ] ) + 1 ) ; } int twice_count = 0 ; for ( int i = 0 ; i < N ; i ++ ) { if ( mp . get ( S - arr [ i ] ) != null ) { twice_count += mp . get ( S - arr [ i ] ) ; } if ( S - arr [ i ] == arr [ i ] ) twice_count -- ; } return twice_count / 2 ; } public static int countPairs ( int arr [ ] , int N ) { int count = 0 ; HashSet < Integer > S = new HashSet < > ( ) ; for ( int i = 0 ; i < N ; i ++ ) S . add ( arr [ i ] ) ; for ( int ele : S ) { int sum = 2 * ele ; count += getCountPairs ( arr , N , sum ) ; } return count ; } public static void main ( String [ ] args ) { int N = 6 ; int arr [ ] = { 4 , 2 , 5 , 1 , 3 , 5 } ; System . out . println ( countPairs ( arr , N ) ) ; } }


"Numbers that are bitwise AND of at least one non | Java implementation of the approach ; Set to store all possible AND values . ; Starting index of the sub - array . ; Ending index of the sub - array . ; AND value is added to the set . ; The set contains all possible AND values ."
How can the above be solved in Java?

import java . util . HashSet ; class CP { public static void main ( String [ ] args ) { int [ ] A = { 11 , 15 , 7 , 19 } ; int N = A . length ; HashSet < Integer > set = new HashSet < > ( ) ; int i , j , res ; for ( i = 0 ; i < N ; ++ i ) for ( j = i , res = Integer . MAX_VALUE ; j < N ; ++ j ) { res &= A [ j ] ; set . add ( res ) ; } System . out . println ( set ) ; } }


"Numbers that are not divisible by any number in the range [ 2 , 10 ] | Java implementation of the approach ; Function to return the count of numbers from 1 to N which are not divisible by any number in the range [ 2 , 10 ] ; Driver code"
How can the above be solved in Java?

class GFG { static int countNumbers ( int n ) { return n - n / 2 - n / 3 - n / 5 - n / 7 + n / 6 + n / 10 + n / 14 + n / 15 + n / 21 + n / 35 - n / 30 - n / 42 - n / 70 - n / 105 + n / 210 ; } public static void main ( String [ ] args ) { int n = 20 ; System . out . println ( countNumbers ( n ) ) ; } }


"Numbers whose bitwise OR and sum with N are equal | Java program to count numbers whose bitwise OR and sum with N are equal ; Function to find total 0 bit in a number ; Function to find Count of non - negative numbers less than or equal to N , whose bitwise OR and SUM with N are equal . ; count number of zero bit in N ; power of 2 to count ; Driver code"
How can the above be solved in Java?

class GFG { static int CountZeroBit ( int n ) { int count = 0 ; while ( n > 0 ) { if ( ( n & 1 ) != 0 ) count ++ ; n >>= 1 ; } return count ; } static int CountORandSumEqual ( int N ) { int count = CountZeroBit ( N ) ; return ( 1 << count ) ; } public static void main ( String [ ] args ) { int N = 10 ; System . out . print ( CountORandSumEqual ( N ) ) ; } }


"Numbers whose factorials end with n zeros | Binary search based Java program to find numbers with n trailing zeros . ; Function to calculate trailing zeros ; range of numbers ; binary search for first number with n trailing zeros ; Print all numbers after low with n trailing zeros . ; Print result ; Driver code"
How can the above be solved in Java?

import java . io . * ; class GFG { static int trailingZeroes ( int n ) { int cnt = 0 ; while ( n > 0 ) { n /= 5 ; cnt += n ; } return cnt ; } static void binarySearch ( int n ) { int low = 0 ; int high = 1000000 ; while ( low < high ) { int mid = ( low + high ) / 2 ; int count = trailingZeroes ( mid ) ; if ( count < n ) low = mid + 1 ; else high = mid ; } int result [ ] = new int [ 1000 ] ; int k = 0 ; while ( trailingZeroes ( low ) == n ) { result [ k ] = low ; k ++ ; low ++ ; } for ( int i = 0 ; i < k ; i ++ ) System . out . print ( result [ i ] + " ▁ " ) ; } public static void main ( String args [ ] ) { int n = 3 ; binarySearch ( n ) ; } }


"Numbers with a Fibonacci difference between Sum of digits at even and odd positions in a given range | Java program to count the numbers in the range having the difference between the sum of digits at even and odd positions as a Fibonacci Number ; To store all the Fibonacci numbers ; Function to generate Fibonacci numbers upto 100 ; Adding the first two Fibonacci numbers in the set ; Computing the remaining Fibonacci numbers using the first two Fibonacci numbers ; Function to return the count of required numbers from 0 to num ; Base Case ; Check if the difference is equal to any fibonacci number ; If this result is already computed simply return it ; Maximum limit upto which we can place digit . If tight is 1 , means number has already become smaller so we can place any digit , otherwise num [ pos ] ; If the current position is odd add it to currOdd , otherwise to currEven ; Function to convert x into its digit vector and uses count ( ) function to return the required count ; Initialize dp ; Driver Code ; Generate fibonacci numbers"
How can the above be solved in Java?

 import java . util . * ; class GFG { static int M = 18 ; static int a , b ; static int [ ] [ ] [ ] [ ] dp = new int [ M ] [ 90 ] [ 90 ] [ 2 ] ; static HashSet < Integer > fib = new HashSet < Integer > ( ) ; static void fibonacci ( ) { int prev = 0 , curr = 1 ; fib . add ( prev ) ; fib . add ( curr ) ; while ( curr <= 100 ) { int temp = curr + prev ; fib . add ( temp ) ; prev = curr ; curr = temp ; } } static int count ( int pos , int even , int odd , int tight , Vector < Integer > num ) { if ( pos == num . size ( ) ) { if ( num . size ( ) % 2 == 1 ) { odd = odd + even ; even = odd - even ; odd = odd - even ; } int d = even - odd ; if ( fib . contains ( d ) ) return 1 ; return 0 ; } if ( dp [ pos ] [ even ] [ odd ] [ tight ] != - 1 ) return dp [ pos ] [ even ] [ odd ] [ tight ] ; int ans = 0 ; int limit = ( tight == 1 ? 9 : num . get ( pos ) ) ; for ( int d = 0 ; d <= limit ; d ++ ) { int currF = tight , currEven = even ; int currOdd = odd ; if ( d < num . get ( pos ) ) currF = 1 ; if ( pos % 2 == 1 ) currOdd += d ; else currEven += d ; ans += count ( pos + 1 , currEven , currOdd , currF , num ) ; } return dp [ pos ] [ even ] [ odd ] [ tight ] = ans ; } static int solve ( int x ) { Vector < Integer > num = new Vector < Integer > ( ) ; while ( x > 0 ) { num . add ( x % 10 ) ; x /= 10 ; } Collections . reverse ( num ) ; for ( int i = 0 ; i < M ; i ++ ) { for ( int j = 0 ; j < 90 ; j ++ ) { for ( int l = 0 ; l < 90 ; l ++ ) { for ( int k = 0 ; k < 2 ; k ++ ) { dp [ i ] [ j ] [ l ] [ k ] = - 1 ; } } } } return count ( 0 , 0 , 0 , 0 , num ) ; } public static void main ( String [ ] args ) { fibonacci ( ) ; int L = 1 , R = 50 ; System . out . print ( solve ( R ) - solve ( L - 1 ) + "
"); L = 50 ; R = 100 ; System . out . print ( solve ( R ) - solve ( L - 1 ) + "
"); } }


"Numbers with exactly 3 divisors | Java program to print all three - primes smaller than or equal to n using Sieve of Eratosthenes ; Generates all primes upto n and prints their squares ; If prime [ p ] is not changed , then it is a prime ; Update all multiples of p ; print squares of primes upto n ; Driver program"
How can the above be solved in Java?

import java . io . * ; import java . util . * ; class GFG { static void numbersWith3Divisors ( int n ) { boolean [ ] prime = new boolean [ n + 1 ] ; Arrays . fill ( prime , true ) ; prime [ 0 ] = prime [ 1 ] = false ; for ( int p = 2 ; p * p <= n ; p ++ ) { if ( prime [ p ] == true ) { for ( int i = p * 2 ; i <= n ; i += p ) prime [ i ] = false ; } } System . out . println ( " Numbers ▁ with ▁ 3 ▁ divisors ▁ : ▁ " ) ; for ( int i = 0 ; i * i <= n ; i ++ ) if ( prime [ i ] ) System . out . print ( i * i + " ▁ " ) ; } public static void main ( String [ ] args ) { int n = 96 ; numbersWith3Divisors ( n ) ; } }