"Count the number of ordered sets not containing consecutive numbers | Java program to count the number of ordered sets not containing consecutive numbers ; Function to calculate the count of ordered set for a given size ; Base cases ; Function returns the count of all ordered sets ; Prestore the factorial value ; Iterate all ordered set sizes and find the count for each one maximum ordered set size will be smaller than N as all elements are distinct and non consecutive ; Multiply ny size ! for all the arrangements because sets are ordered ; Add to total answer ; Driver code"
How can the above be solved in Java?

class GFG { static int CountSets ( int x , int pos ) { if ( x <= 0 ) { if ( pos == 0 ) return 1 ; else return 0 ; } if ( pos == 0 ) return 1 ; int answer = CountSets ( x - 1 , pos ) + CountSets ( x - 2 , pos - 1 ) ; return answer ; } static int CountOrderedSets ( int n ) { int [ ] factorial = new int [ 10000 ] ; factorial [ 0 ] = 1 ; for ( int i = 1 ; i < 10000 ; i ++ ) factorial [ i ] = factorial [ i - 1 ] * i ; int answer = 0 ; for ( int i = 1 ; i <= n ; i ++ ) { int sets = CountSets ( n , i ) * factorial [ i ] ; answer = answer + sets ; } return answer ; } public static void main ( String [ ] args ) { int N = 3 ; System . out . print ( CountOrderedSets ( N ) ) ; } }


"Count the number of pop operations on stack to get each element of the array | Java program to implement above approach ; Function to find the count ; Hashmap to store all the elements which are popped once . ; Check if the number is present in the hashmap Or in other words been popped out from the stack before . ; Keep popping the elements while top is not equal to num ; Pop the top ie . equal to num ; Print the number of elements popped . ; Driver code"
How can the above be solved in Java?

import java . util . HashMap ; import java . util . Stack ; class GFG { public static void countEle ( Stack < Integer > s , int [ ] a , int N ) { HashMap < Integer , Boolean > mp = new HashMap < > ( ) ; for ( int i = 0 ; i < N ; ++ i ) { int num = a [ i ] ; if ( mp . containsKey ( num ) ) System . out . print ( "0 ▁ " ) ; else { int cnt = 0 ; while ( s . peek ( ) != num ) { mp . put ( s . peek ( ) , true ) ; s . pop ( ) ; cnt ++ ; } s . pop ( ) ; cnt ++ ; System . out . print ( cnt + " ▁ " ) ; } } } public static void main ( String [ ] args ) { int N = 5 ; Stack < Integer > s = new Stack < > ( ) ; s . add ( 1 ) ; s . add ( 2 ) ; s . add ( 3 ) ; s . add ( 4 ) ; s . add ( 6 ) ; int [ ] a = { 6 , 3 , 4 , 1 , 2 } ; countEle ( s , a , N ) ; } }


"Count the number of possible triangles | Java code to count the number of possible triangles using brute force approach ; Function to count all possible triangles with arr [ ] elements ; Count of triangles ; The three loops select three different values from array ; The innermost loop checks for the triangle property ; Sum of two sides is greater than the third ; Driver code"
How can the above be solved in Java?

import java . io . * ; import java . util . * ; class GFG { static int findNumberOfTriangles ( int arr [ ] , int n ) { int count = 0 ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = i + 1 ; j < n ; j ++ ) { for ( int k = j + 1 ; k < n ; k ++ ) if ( arr [ i ] + arr [ j ] > arr [ k ] && arr [ i ] + arr [ k ] > arr [ j ] && arr [ k ] + arr [ j ] > arr [ i ] ) count ++ ; } } return count ; } public static void main ( String [ ] args ) { int arr [ ] = { 10 , 21 , 22 , 100 , 101 , 200 , 300 } ; int size = arr . length ; System . out . println ( " Total ▁ number ▁ of ▁ triangles ▁ possible ▁ is ▁ " + findNumberOfTriangles ( arr , size ) ) ; } }


"Count the number of possible triangles | Java implementation of the above approach ; CountTriangles function ; If it is possible with a [ l ] , a [ r ] and a [ i ] then it is also possible with a [ l + 1 ] . . a [ r - 1 ] , a [ r ] and a [ i ] ; checking for more possible solutions ; if not possible check for higher values of arr [ l ] ; Driver Code"
How can the above be solved in Java?

import java . util . * ; class GFG { static void CountTriangles ( int [ ] A ) { int n = A . length ; Arrays . sort ( A ) ; int count = 0 ; for ( int i = n - 1 ; i >= 1 ; i -- ) { int l = 0 , r = i - 1 ; while ( l < r ) { if ( A [ l ] + A [ r ] > A [ i ] ) { count += r - l ; r -- ; } else { l ++ ; } } } System . out . print ( " No ▁ of ▁ possible ▁ solutions : ▁ " + count ) ; } public static void main ( String [ ] args ) { int [ ] A = { 4 , 3 , 5 , 7 , 6 } ; CountTriangles ( A ) ; } }


"Count the number of possible triangles | Java program to count number of triangles that can be formed from given array ; Function to count all possible triangles with arr [ ] elements ; Sort the array elements in non - decreasing order ; Initialize count of triangles ; Fix the first element . We need to run till n - 3 as the other two elements are selected from arr [ i + 1. . . n - 1 ] ; Initialize index of the rightmost third element ; Fix the second element ; Find the rightmost element which is smaller than the sum of two fixed elements The important thing to note here is , we use the previous value of k . If value of arr [ i ] + arr [ j - 1 ] was greater than arr [ k ] , then arr [ i ] + arr [ j ] must be greater than k , because the array is sorted . ; Total number of possible triangles that can be formed with the two fixed elements is k - j - 1. The two fixed elements are arr [ i ] and arr [ j ] . All elements between arr [ j + 1 ] to arr [ k - 1 ] can form a triangle with arr [ i ] and arr [ j ] . One is subtracted from k because k is incremented one extra in above while loop . k will always be greater than j . If j becomes equal to k , then above loop will increment k , because arr [ k ] + arr [ i ] is always / greater than arr [ k ] ; Driver code"
How can the above be solved in Java?

import java . io . * ; import java . util . * ; class CountTriangles { static int findNumberOfTriangles ( int arr [ ] ) { int n = arr . length ; Arrays . sort ( arr ) ; int count = 0 ; for ( int i = 0 ; i < n - 2 ; ++ i ) { int k = i + 2 ; for ( int j = i + 1 ; j < n ; ++ j ) { while ( k < n && arr [ i ] + arr [ j ] > arr [ k ] ) ++ k ; if ( k > j ) count += k - j - 1 ; } } return count ; } public static void main ( String [ ] args ) { int arr [ ] = { 10 , 21 , 22 , 100 , 101 , 200 , 300 } ; System . out . println ( " Total ▁ number ▁ of ▁ triangles ▁ is ▁ " + findNumberOfTriangles ( arr ) ) ; } }


"Count the number of rhombi possible inside a rectangle of given size | Java implementation of the approach ; Function to return the count of rhombi possible ; All possible diagonal lengths ; Update rhombi possible with the current diagonal lengths ; Return the total count of rhombi possible ; Driver code"
How can the above be solved in Java?

import java . io . * ; class GFG { static int countRhombi ( int h , int w ) { int ct = 0 ; for ( int i = 2 ; i <= h ; i += 2 ) for ( int j = 2 ; j <= w ; j += 2 ) ct += ( h - i + 1 ) * ( w - j + 1 ) ; return ct ; } public static void main ( String [ ] args ) { int h = 2 , w = 2 ; System . out . println ( countRhombi ( h , w ) ) ; } }


"Count the number of special permutations | Java program to count the number of required permutations ; Function to return the number of ways to choose r objects out of n objects ; Function to return the number of derangements of n ; Function to return the required number of permutations ; Ways to choose i indices from n indices ; Dearangements of ( n - i ) indices System . out . println ( ans ) ; ; Driver Code to test above functions"
How can the above be solved in Java?

public class GFG { static int nCr ( int n , int r ) { int ans = 1 ; if ( r > n - r ) r = n - r ; for ( int i = 0 ; i < r ; i ++ ) { ans *= ( n - i ) ; ans /= ( i + 1 ) ; } return ans ; } static int countDerangements ( int n ) { int der [ ] = new int [ n + 3 ] ; der [ 0 ] = 1 ; der [ 1 ] = 0 ; der [ 2 ] = 1 ; for ( int i = 3 ; i <= n ; i ++ ) der [ i ] = ( i - 1 ) * ( der [ i - 1 ] + der [ i - 2 ] ) ; return der [ n ] ; } static int countPermutations ( int n , int k ) { int ans = 0 ; for ( int i = n - k ; i <= n ; i ++ ) { int ways = nCr ( n , i ) ; ans += ( ways * countDerangements ( n - i ) ) ; } return ans ; } public static void main ( String [ ] args ) { int n = 5 , k = 3 ; System . out . println ( countPermutations ( n , k ) ) ; } }


"Count the number of subsequences of length k having equal LCM and HCF | Java implementation for above approach ; Returns factorial of n ; Returns nCr for the given values of r and n ; Map to store the frequencies of each elements ; Loop to store the frequencies of elements in the map ; Using nCR formula to calculate the number of subsequences of a given length ; Driver Code ; Function calling"
How can the above be solved in Java?

import java . util . * ; class GFG { static long fact ( int n ) { long res = 1 ; for ( int i = 2 ; i <= n ; i ++ ) res = res * i ; return res ; } static long nCr ( int n , int r ) { return fact ( n ) / ( 1 * fact ( r ) * fact ( n - r ) ) ; } static long number_of_subsequences ( int arr [ ] , int k , int n ) { long s = 0 ; HashMap < Integer , Integer > mp = new HashMap < Integer , Integer > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( mp . containsKey ( arr [ i ] ) ) { mp . put ( arr [ i ] , mp . get ( arr [ i ] ) + 1 ) ; } else { mp . put ( arr [ i ] , 1 ) ; } } for ( Map . Entry < Integer , Integer > j : mp . entrySet ( ) ) { s = s + 1 * nCr ( j . getValue ( ) , k ) ; } return s ; } static public void main ( String [ ] arg ) { int arr [ ] = { 1 , 1 , 1 , 1 , 2 , 2 , 2 } ; int k = 2 ; int n = arr . length ; System . out . println ( number_of_subsequences ( arr , k , n ) ) ; } }


"Count the number of times a Bulb switches its state | Java implementation of the above approach ; Function to find the number of times a bulb switches its state ; Count of 1 s ; Traverse the array ; Update count of 1 s ; Update the status of bulb ; Traverse the array Q [ ] ; Stores previous state of the bulb ; Toggle the switch and update count of 1 s ; If the bulb switches state ; Return count ; Driver Code ; Input ; Queries ; Function call to find number of times the bulb toggles"
How can the above be solved in Java?

import java . util . * ; public class Main { static int solve ( int [ ] A , int n , int Q [ ] , int q ) { int one = 0 ; for ( int i = 0 ; i < n ; i ++ ) if ( A [ i ] == 1 ) one ++ ; int glows = 0 , count = 0 ; if ( one >= ( int ) Math . ceil ( n / 2 ) ) glows = 1 ; for ( int i = 0 ; i < q ; i ++ ) { int prev = glows ; if ( A [ Q [ i ] - 1 ] == 1 ) one -- ; if ( A [ Q [ i ] - 1 ] == 0 ) one ++ ; A [ Q [ i ] - 1 ] ^= 1 ; if ( one >= ( int ) Math . ceil ( n / 2.0 ) ) { glows = 1 ; } else { glows = 0 ; } if ( prev != glows ) count ++ ; } return count ; } public static void main ( String args [ ] ) { int n = 3 ; int arr [ ] = { 1 , 1 , 0 } ; int q = 3 ; int Q [ ] = { 3 , 2 , 1 } ; System . out . println ( solve ( arr , n , Q , q ) ) ; } }


"Count the number of times graph crosses X | Java implementation to count the number of times the graph crosses the x - axis . ; Function to to count the number of times the graph crosses the x - axis . ; Iterate over the steps array ; Update the previous level and current level by value given in the steps array ; Condition to check that the graph crosses the origin . ; Driver Code"
How can the above be solved in Java?

class GFG { static int times ( int [ ] steps , int n ) { int current_level = 0 ; int previous_level = 0 ; int count = 0 ; for ( int i = 0 ; i < n ; i ++ ) { previous_level = current_level ; current_level = current_level + steps [ i ] ; if ( ( previous_level < 0 && current_level >= 0 ) || ( previous_level > 0 && current_level <= 0 ) ) { count ++ ; } } return count ; } public static void main ( String [ ] args ) { int steps [ ] = { 1 , - 1 , 0 , 0 , 1 , 1 , - 3 , 2 } ; int n = steps . length ; System . out . println ( times ( steps , n ) ) ; } }


"Count the number of unordered triplets with elements in increasing order and product less than or equal to integer X | Java implementation to count the number of unordered triplets such that the numbers are in increasing order and the product of them is less than or equal to integer X ; Function to count the number of triplets ; Iterate through all the triplets ; Rearrange the numbers in ascending order ; Check if the necessary conditions satisfy ; Increment count ; Return the answer ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { static int countTriplets ( int a [ ] , int n , int x ) { int answer = 0 ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = i + 1 ; j < n ; j ++ ) { for ( int k = j + 1 ; k < n ; k ++ ) { Vector < Integer > temp = new Vector < > ( ) ; temp . add ( a [ i ] ) ; temp . add ( a [ j ] ) ; temp . add ( a [ k ] ) ; Collections . sort ( temp ) ; if ( temp . get ( 0 ) < temp . get ( 1 ) && temp . get ( 1 ) < temp . get ( 2 ) && temp . get ( 0 ) * temp . get ( 1 ) * temp . get ( 2 ) <= x ) answer ++ ; } } } return answer ; } public static void main ( String [ ] args ) { int A [ ] = { 3 , 2 , 5 , 7 } ; int N = A . length ; int X = 42 ; System . out . println ( countTriplets ( A , N , X ) ) ; } }


"Count the number of vowels occurring in all the substrings of given string | Java implementation of the above approach ; Returns the total sum of occurrences of all vowels ; No . of occurrences of 0 th character in all the substrings ; No . of occurrences of ith character in all the substrings ; Check if ith character is a vowel ; Return the total sum of occurrences of vowels ; Driver Code"
How can the above be solved in Java?

import java . io . * ; import java . util . * ; public class Gfg { static int vowel_calc ( String s ) { int n = s . length ( ) ; int arr [ ] = new int [ n ] ; for ( int i = 0 ; i < n ; i ++ ) { if ( i == 0 ) arr [ i ] = n ; else arr [ i ] = ( n - i ) + arr [ i - 1 ] - i ; } int sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) { char ch = s . charAt ( i ) ; if ( ch == ' a ' ch == ' e ' ch == ' i ' ch == ' o ' ch == ' u ' ) sum += arr [ i ] ; } return sum ; } public static void main ( String args [ ] ) { String s = " daceh " ; System . out . println ( vowel_calc ( s ) ) ; } }


"Count the number of ways to divide N in k groups incrementally | Java implementation to count the number of ways to divide N in groups such that each group has K number of elements ; DP Table ; Function to count the number of ways to divide the number N in groups such that each group has K number of elements ; 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 in groups ; Initialize DP Table as - 1 ; Driver Code"
How can the above be solved in Java?

import java . util . * ; class GFG { static int [ ] [ ] [ ] dp = new int [ 500 ] [ 500 ] [ 500 ] ; static int calculate ( int pos , int prev , int left , int k ) { if ( pos == k ) { if ( left == 0 ) return 1 ; else return 0 ; } if ( left == 0 ) return 0 ; if ( dp [ pos ] [ prev ] [ left ] != - 1 ) return dp [ pos ] [ prev ] [ left ] ; int answer = 0 ; for ( int i = prev ; i <= left ; i ++ ) { answer += calculate ( pos + 1 , i , left - i , k ) ; } return dp [ pos ] [ prev ] [ left ] = answer ; } static int countWaystoDivide ( int n , int k ) { for ( int i = 0 ; i < 500 ; i ++ ) { for ( int j = 0 ; j < 500 ; j ++ ) { for ( int l = 0 ; l < 500 ; l ++ ) dp [ i ] [ j ] [ l ] = - 1 ; } } return calculate ( 0 , 1 , n , k ) ; } public static void main ( String [ ] args ) { int N = 8 ; int K = 4 ; System . out . print ( countWaystoDivide ( N , K ) ) ; } }


"Count the number of ways to divide N in k groups incrementally | Java implementation to count the number of ways to divide N in groups such that each group has K number of elements ; Function to count the number of ways to divide the number N in groups such that each group has K number of elements ; 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?

import java . util . * ; class GFG { static int calculate ( int pos , int prev , int left , int k ) { if ( pos == k ) { if ( left == 0 ) return 1 ; else return 0 ; } if ( left == 0 ) return 0 ; int answer = 0 ; for ( int i = prev ; i <= left ; i ++ ) { answer += calculate ( pos + 1 , i , left - i , k ) ; } return answer ; } static int countWaystoDivide ( int n , int k ) { return calculate ( 0 , 1 , n , k ) ; } public static void main ( String [ ] args ) { int N = 8 ; int K = 4 ; System . out . print ( countWaystoDivide ( N , K ) ) ; } }


"Count the number of ways to fill K boxes with N distinct items | Java program to calculate the above formula ; To store the factorials of all numbers ; Function to calculate factorial of all numbers ; Calculate x to the power y in O ( log n ) time ; Function to find inverse mod of a number x ; Calculate ( n C r ) ; Loop to compute the formula evaluated ; Add even power terms ; Subtract odd power terms ; Choose the k boxes which were used ; Driver Code"
How can the above be solved in Java?

 import java . util . * ; class GFG { static long mod = 1000000007 ; static long factorial [ ] = new long [ 100005 ] ; static void StoreFactorials ( int n ) { factorial [ 0 ] = 1 ; for ( int i = 1 ; i <= n ; i ++ ) { factorial [ i ] = ( i * factorial [ i - 1 ] ) % mod ; } } static long Power ( long x , long y ) { long ans = 1 ; while ( y > 0 ) { if ( y % 2 == 1 ) { ans = ( ans * x ) % mod ; } x = ( x * x ) % mod ; y /= 2 ; } return ans ; } static long invmod ( long x ) { return Power ( x , mod - 2 ) ; } static long nCr ( int n , int r ) { return ( factorial [ n ] * invmod ( ( factorial [ r ] * factorial [ n - r ] ) % mod ) ) % mod ; } static long CountWays ( int n , int k ) { StoreFactorials ( n ) ; long ans = 0 ; for ( int i = k ; i >= 0 ; i -- ) { if ( i % 2 == k % 2 ) { ans = ( ans + ( Power ( i , n ) * nCr ( k , i ) ) % mod ) % mod ; } else { ans = ( ans + mod - ( Power ( i , n ) * nCr ( k , i ) ) % mod ) % mod ; } } ans = ( ans * nCr ( n , k ) ) % mod ; return ans ; } public static void main ( String [ ] args ) { int N = 5 ; int K = 5 ; System . out . print ( CountWays ( N , K ) + "
"); } }


"Count the number of ways to give ranks for N students such that same ranks are possible | Java program to calculate the number of ways to give ranks for N students such that same ranks are possible ; Initializing a table in order to store the bell triangle ; Function to calculate the K - th bell number ; If we have already calculated the bell numbers until the required N ; Base case ; First Bell Number ; If the value of the bell triangle has already been calculated ; Fill the defined dp table ; Function to return the number of ways to give ranks for N students such that same ranks are possible ; Resizing the dp table for the given value of n ; Variables to store the answer and the factorial value ; Iterating till N ; Simultaneously calculate the k ! ; Computing the K - th bell number and multiplying it with K ! ; Driver code"
How can the above be solved in Java?

 import java . util . * ; class GFG { static int mod = ( int ) ( 1e9 + 7 ) ; static int [ ] [ ] dp ; static int f ( int n , int k ) { if ( n < k ) return 0 ; if ( n == k ) return 1 ; if ( k == 1 ) return 1 ; if ( dp [ n ] [ k ] != - 1 ) return dp [ n ] [ k ] ; return dp [ n ] [ k ] = ( ( k * f ( n - 1 , k ) ) % mod + ( f ( n - 1 , k - 1 ) ) % mod ) % mod ; } static long operation ( int n ) { dp = new int [ n + 1 ] [ n + 1 ] ; for ( int i = 0 ; i < n + 1 ; i ++ ) { for ( int j = 0 ; j < n + 1 ; j ++ ) { dp [ i ] [ j ] = - 1 ; } } long ans = 0 , fac = 1 ; for ( int k = 1 ; k <= n ; k ++ ) { fac *= k ; ans = ( ans + ( fac * f ( n , k ) ) % mod ) % mod ; } return ans ; } public static void main ( String [ ] args ) { int n = 5 ; System . out . print ( operation ( n ) + "
"); } }


"Count the number of ways to tile the floor of size n x m using 1 x m size tiles | Java implementation to count number of ways to tile a floor of size n x m using 1 x m tiles ; function to count the total number of ways ; table to store values of subproblems ; Fill the table upto value n ; recurrence relation ; base cases ; i = = m ; required number of ways ; Driver program"
How can the above be solved in Java?

import java . io . * ; class GFG { static int countWays ( int n , int m ) { int count [ ] = new int [ n + 1 ] ; count [ 0 ] = 0 ; int i ; for ( i = 1 ; i <= n ; i ++ ) { if ( i > m ) count [ i ] = count [ i - 1 ] + count [ i - m ] ; else if ( i < m i == 1 ) count [ i ] = 1 ; else count [ i ] = 2 ; } return count [ n ] ; } public static void main ( String [ ] args ) { int n = 7 ; int m = 4 ; System . out . println ( " Number ▁ of ▁ ways ▁ = ▁ " + countWays ( n , m ) ) ; } }


"Count the number of ways to traverse a Matrix | A simple recursive solution to count number of ways to reach mat [ m - 1 ] [ n - 1 ] from mat [ 0 ] [ 0 ] in a matrix mat [ ] [ ] ; Returns The number of way from top - left to mat [ m - 1 ] [ n - 1 ] ; Driver code"
How can the above be solved in Java?

class GFG { static int countPaths ( int m , int n ) { int [ ] [ ] dp = new int [ m + 1 ] [ n + 1 ] ; for ( int i = 1 ; i <= m ; i ++ ) { for ( int j = 1 ; j <= n ; j ++ ) { if ( i == 1 j == 1 ) dp [ i ] [ j ] = 1 ; else dp [ i ] [ j ] = dp [ i - 1 ] [ j ] + dp [ i ] [ j - 1 ] ; } } return dp [ m ] [ n ] ; } public static void main ( String [ ] args ) { int n = 5 ; int m = 5 ; System . out . println ( countPaths ( n , m ) ) ; } }


"Count the number of ways to traverse a Matrix | Java Program for above approach ; Find factorial ; Find number of ways to reach mat [ m - 1 ] [ n - 1 ] from mat [ 0 ] [ 0 ] in a matrix mat [ ] [ ] ] ; Driver Code ; Function Call"
How can the above be solved in Java?

import java . io . * ; class GFG { static int factorial ( int n ) { int res = 1 , i ; for ( i = 2 ; i <= n ; i ++ ) res *= i ; return res ; } static int countWays ( int m , int n ) { m = m - 1 ; n = n - 1 ; return factorial ( m + n ) / ( factorial ( m ) * factorial ( n ) ) ; } public static void main ( String [ ] args ) { int m = 5 ; int n = 5 ; int result = countWays ( m , n ) ; System . out . println ( result ) ; } }


"Count the number of ways to traverse a Matrix | Java program using recursive solution to count number of ways to reach mat [ m - 1 ] [ n - 1 ] from mat [ 0 ] [ 0 ] in a matrix mat [ ] [ ] ; Returns The number of way from top - left to mat [ m - 1 ] [ n - 1 ] ; Return 1 if it is the first row or first column ; Recursively find the no of way to reach the last cell . ; Driver Code"
How can the above be solved in Java?

import java . lang . * ; import java . util . * ; class GFG { public int countPaths ( int m , int n ) { if ( m == 1 n == 1 ) return 1 ; return countPaths ( m - 1 , n ) + countPaths ( m , n - 1 ) ; } public static void main ( String args [ ] ) { GFG g = new GFG ( ) ; int n = 5 , m = 5 ; System . out . println ( g . countPaths ( n , m ) ) ; } }


"Count the number of words having sum of ASCII values less than and greater than k | Java implementation of the above approach ; Function to count the words ; Sum of ascii values ; Number of words having sum of ascii less than k ; If character is a space ; else Add the ascii value to sum ; Handling the Last word separately ; Driver code"
How can the above be solved in Java?

class GFG { static void CountWords ( String str , int k ) { int sum = 0 ; int NumberOfWords = 0 ; int counter = 0 ; int len = str . length ( ) ; for ( int i = 0 ; i < len ; ++ i ) { if ( str . charAt ( i ) == ' ▁ ' ) { if ( sum < k ) { counter ++ ; } sum = 0 ; NumberOfWords ++ ; } { sum += str . charAt ( i ) ; } } NumberOfWords ++ ; if ( sum < k ) { counter ++ ; } System . out . println ( " Number ▁ of ▁ words ▁ having ▁ sum ▁ " + " of ▁ ASCII ▁ values ▁ less ▁ than ▁ k ▁ = ▁ " + counter ) ; System . out . println ( " Number ▁ of ▁ words ▁ having ▁ sum ▁ of ▁ " + " ASCII ▁ values ▁ greater ▁ than ▁ or ▁ equal ▁ to ▁ k ▁ = ▁ " + ( NumberOfWords - counter ) ) ; } public static void main ( String [ ] args ) { String str = " Learn ▁ how ▁ to ▁ code " ; int k = 400 ; CountWords ( str , k ) ; } }


"Count the numbers < N which have equal number of divisors as K | Java implementation of the approach ; Function to return the count of the divisors of a number ; Count the number of 2 s that divide n ; n must be odd at this point . So we can skip one element ; While i divides n ; This condition is to handle the case when n is a prime number > 2 ; Count the total elements that have divisors exactly equal to as that of k 's ; Exclude k from the result if it is smaller than n . ; Driver code"
How can the above be solved in Java?

public class GFG { static int countDivisors ( int n ) { int x = 0 , ans = 1 ; while ( n % 2 == 0 ) { x ++ ; n = n / 2 ; } ans = ans * ( x + 1 ) ; for ( int i = 3 ; i <= Math . sqrt ( n ) ; i = i + 2 ) { x = 0 ; while ( n % i == 0 ) { x ++ ; n = n / i ; } ans = ans * ( x + 1 ) ; } if ( n > 2 ) ans = ans * 2 ; return ans ; } static int getTotalCount ( int n , int k ) { int k_count = countDivisors ( k ) ; int count = 0 ; for ( int i = 1 ; i < n ; i ++ ) if ( k_count == countDivisors ( i ) ) count ++ ; if ( k < n ) count = count - 1 ; return count ; } public static void main ( String [ ] args ) { int n = 500 , k = 6 ; System . out . println ( getTotalCount ( n , k ) ) ; } }


"Count the numbers with N digits and whose suffix is divisible by K | Java implementation to Count the numbers with N digits and whose suffix is divisible by K ; Suffix of length pos with remainder rem and Z representing whether the suffix has a non zero digit until now ; Base case ; If count of digits is less than n ; Placing all possible digits in remaining positions ; If remainder non zero and suffix has n digits ; If the subproblem is already solved ; Placing all digits at MSB of suffix and increasing it 's length by 1 ; Non zero digit is placed ; Store and return the solution to this subproblem ; Function to Count the numbers with N digits and whose suffix is divisible by K ; Since we need powers of 10 for counting , it 's better to  pre store them along with their  modulo with 1e9 + 7 for counting ; Since at each recursive step we increase the suffix length by 1 by placing digits at its leftmost position , we need powers of 10 modded with k , in order to fpos the new remainder efficiently ; Initialising dp table values - 1 represents subproblem hasn 't  been solved yet ; Driver Code"
How can the above be solved in Java?

import java . util . * ; import java . util . Arrays ; class GFG { static int mod = 1000000007 ; static int dp [ ] [ ] [ ] = new int [ 1005 ] [ 105 ] [ 2 ] ; static int powers [ ] = new int [ 1005 ] ; static int powersModk [ ] = new int [ 1005 ] ; static int calculate ( int pos , int rem , int z , int k , int n ) { if ( rem == 0 && z != 0 ) { if ( pos != n ) return ( powers [ n - pos - 1 ] * 9 ) % mod ; else return 1 ; } if ( pos == n ) return 0 ; if ( dp [ pos ] [ rem ] [ z ] != - 1 ) return dp [ pos ] [ rem ] [ z ] ; int count = 0 ; for ( int i = 0 ; i < 10 ; i ++ ) { if ( i == 0 ) count = ( count + ( calculate ( pos + 1 , ( rem + ( i * powersModk [ pos ] ) % k ) % k , z , k , n ) ) ) % mod ; else count = ( count + ( calculate ( pos + 1 , ( rem + ( i * powersModk [ pos ] ) % k ) % k , 1 , k , n ) ) ) % mod ; } return dp [ pos ] [ rem ] [ z ] = count ; } static int countNumbers ( int n , int k ) { int st = 1 ; int i ; for ( i = 0 ; i <= n ; i ++ ) { powers [ i ] = st ; st *= 10 ; st %= mod ; } st = 1 ; for ( i = 0 ; i <= n ; i ++ ) { powersModk [ i ] = st ; st *= 10 ; st %= mod ; } for ( int [ ] [ ] row : dp ) { for ( int [ ] innerRow : row ) { Arrays . fill ( innerRow , - 1 ) ; } } ; return calculate ( 0 , 0 , 0 , k , n ) ; } public static void main ( String [ ] args ) { int N = 2 ; int K = 2 ; System . out . print ( countNumbers ( N , K ) ) ; } }


"Count the occurrence of Nth term in first N terms of Van Eck 's sequence | Java program to count the occurrence of nth term in first n terms of Van Eck 's sequence ; Utility function to compute Van Eck 's sequence ; Initialize sequence array ; Loop to generate sequence ; Check if sequence [ i ] has occured previously or is new to sequence ; If occurrence found then the next term will be how far back this last term occured previously ; Utility function to count the occurrence of nth term in first n terms of the sequence ; Get nth term of the sequence ; Count the occurrence of nth term in first n terms of the sequence ; Return count ; Driver code ; Pre - compute Van Eck 's sequence ; Print count of the occurrence of nth term in first n terms of the sequence ; Print count of the occurrence of nth term in first n terms of the sequence"
How can the above be solved in Java?

class GFG { static int MAX = 100000 ; static int sequence [ ] = new int [ MAX + 1 ] ; static void vanEckSequence ( ) { for ( int i = 0 ; i < MAX ; i ++ ) { sequence [ i ] = 0 ; } for ( int i = 0 ; i < MAX ; i ++ ) { for ( int j = i - 1 ; j >= 0 ; j -- ) { if ( sequence [ j ] == sequence [ i ] ) { sequence [ i + 1 ] = i - j ; break ; } } } } static int getCount ( int n ) { int nthTerm = sequence [ n - 1 ] ; int count = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( sequence [ i ] == nthTerm ) count ++ ; } return count ; } public static void main ( String [ ] args ) { vanEckSequence ( ) ; int n = 5 ; System . out . println ( getCount ( n ) ) ; n = 11 ; System . out . println ( getCount ( n ) ) ; } }


"Count the occurrence of Nth term in first N terms of Van Eck 's sequence | Java program to count the occurrence of nth term in first n terms of Van Eck 's sequence ; Utility function to compute Van Eck 's sequence ; Initialize sequence array ; Loop to generate sequence ; Check if sequence [ i ] has occured previously or is new to sequence ; If occurrence found then the next term will be how far back this last term occured previously ; Utility function to count the occurrence of nth term in first n terms of the sequence ; Initialize count as 1 ; Increment count if ( i + 1 ) th term is non - zero ; Previous occurrence of sequence [ i ] will be it ( i - sequence [ i + 1 ] ) th position ; Return the count of occurrence ; Driver code ; Pre - compute Van Eck 's sequence ; Print count of the occurrence of nth term in first n terms of the sequence ; Print count of the occurrence of nth term in first n terms of the sequence"
How can the above be solved in Java?

class GFG { static int MAX = 100000 ; static int sequence [ ] = new int [ MAX + 1 ] ; static void vanEckSequence ( ) { for ( int i = 0 ; i < MAX ; i ++ ) { sequence [ i ] = 0 ; } for ( int i = 0 ; i < MAX ; i ++ ) { for ( int j = i - 1 ; j >= 0 ; j -- ) { if ( sequence [ j ] == sequence [ i ] ) { sequence [ i + 1 ] = i - j ; break ; } } } } static int getCount ( int n ) { int count = 1 ; int i = n - 1 ; while ( sequence [ i + 1 ] != 0 ) { count ++ ; i = i - sequence [ i + 1 ] ; } return count ; } public static void main ( String [ ] args ) { vanEckSequence ( ) ; int n = 5 ; System . out . println ( getCount ( n ) ) ; n = 11 ; System . out . println ( getCount ( n ) ) ; } }


"Count the occurrence of digit K in a given number N using Recursion | Java implementation to count the occurrence of a digit in number using Recursion ; Function to count the digit K in the given number N ; Extracting least significant digit ; Driver Code"
How can the above be solved in Java?

import java . util . * ; class GFG { static double countdigits ( int n , int k ) { if ( n == 0 ) return 0 ; int digit = n % 10 ; if ( digit == k ) return 1 + countdigits ( n / 10 , k ) ; return countdigits ( n / 10 , k ) ; } public static void main ( String [ ] args ) { int n = 1000 ; int k = 0 ; System . out . println ( countdigits ( n , k ) ) ; } }


"Count the pairs in an array such that the difference between them and their indices is equal | Java implementation of the approach ; Function to return the count of all valid pairs ; To store the frequencies of ( arr [ i ] - i ) ; To store the required count ; If cnt is the number of elements whose difference with their index is same then ( ( cnt * ( cnt - 1 ) ) / 2 ) such pairs are possible ; Driver code"
How can the above be solved in Java?

import java . util . HashMap ; class GFG { static int countPairs ( int arr [ ] , int n ) { HashMap < Integer , Integer > map = new HashMap < Integer , Integer > ( ) ; for ( int i = 0 ; i < n ; i ++ ) map . put ( arr [ i ] - i , 0 ) ; for ( int i = 0 ; i < n ; i ++ ) map . put ( arr [ i ] - i , map . get ( arr [ i ] - i ) + 1 ) ; int res = 0 ; for ( int x : map . values ( ) ) { int cnt = x ; res += ( ( cnt * ( cnt - 1 ) ) / 2 ) ; } return res ; } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 5 , 6 , 7 , 9 } ; int n = arr . length ; System . out . println ( countPairs ( arr , n ) ) ; } }


"Count the pairs of vowels in the given string | Java implementation of the approach ; Function that return true if character ch is a vowel ; Function to return the count of adjacent vowel pairs in the given string ; If current character and the character after it are both vowels ; Driver code"
How can the above be solved in Java?

class GFG { static boolean isVowel ( char ch ) { switch ( ch ) { case ' a ' : case ' e ' : case ' i ' : case ' o ' : case ' u ' : return true ; default : return false ; } } static int vowelPairs ( String s , int n ) { int cnt = 0 ; for ( int i = 0 ; i < n - 1 ; i ++ ) { if ( isVowel ( s . charAt ( i ) ) && isVowel ( s . charAt ( i + 1 ) ) ) cnt ++ ; } return cnt ; } public static void main ( String args [ ] ) { String s = " abaebio " ; int n = s . length ( ) ; System . out . print ( vowelPairs ( s , n ) ) ; } }


"Count the total number of squares that can be visited by Bishop in one move | Java implementation of above approach ; Function to return the count of total positions the Bishop can visit in a single move ; Count top left squares ; Count bottom right squares ; Count top right squares ; Count bottom left squares ; Return total count ; Driver code ; Bishop 's Position"
How can the above be solved in Java?

class GFG { static int countSquares ( int row , int column ) { int topLeft = Math . min ( row , column ) - 1 ; int bottomRight = 8 - Math . max ( row , column ) ; int topRight = Math . min ( row , 9 - column ) - 1 ; int bottomLeft = 8 - Math . max ( row , 9 - column ) ; return ( topLeft + topRight + bottomRight + bottomLeft ) ; } public static void main ( String [ ] args ) { int row = 4 , column = 4 ; System . out . println ( countSquares ( row , column ) ) ; } }


"Count the total number of triangles after Nth operation |  ; Method to return the total no . of Triangles ; For every subtriangle formed there are possibilities of generating ( curr * 3 ) + 2 ; Changing the curr value to Tri_count ; driver code"
How can the above be solved in Java?

class Gfg { public static int CountTriangles ( int n ) { int curr = 1 ; int Tri_count = 0 ; for ( int i = 1 ; i <= n ; i ++ ) { Tri_count = ( curr * 3 ) + 2 ; curr = Tri_count ; } return Tri_count ; } public static void main ( String [ ] args ) { int n = 10 ; System . out . println ( CountTriangles ( n ) ) ; } }


"Count three | Java program to implement the above approach ; Function to count three - digit numbers having difference x with its reverse ; If x is not multiple of 99 ; No solution exists ; Generate all possible pairs of digits [ 1 , 9 ] ; If any pair is obtained with difference x / 99 ; Increase count ; Return the count ; Driver Code"
How can the above be solved in Java?

import java . io . * ; import java . util . Arrays ; class GFG { static int Count_Number ( int x ) { int ans = 0 ; if ( x % 99 != 0 ) { ans = - 1 ; } else { int diff = x / 99 ; for ( int i = 1 ; i < 10 ; i ++ ) { for ( int j = 1 ; j < 10 ; j ++ ) { if ( ( i - j ) == diff ) { ans += 10 ; } } } } return ans ; } public static void main ( String [ ] args ) { int x = 792 ; System . out . println ( Count_Number ( x ) ) ; } }


"Count tiles of dimensions 2 * 1 that can be placed in an M * N rectangular board that satisfies the given conditions | Java Program to implement the above approach ; Function to count tiles of dimensions 2 x 1 that can be placed in a grid of dimensions M * N as per given conditions ; Number of tiles required ; Driver Code"
How can the above be solved in Java?

import java . io . * ; class GFG { static int numberOfTiles ( int n , int m ) { if ( n % 2 == 1 ) { return - 1 ; } return ( m * n ) / 2 ; } public static void main ( String [ ] args ) { int n = 2 , m = 4 ; System . out . println ( numberOfTiles ( n , m ) ) ; } }


"Count total bits in a number | Function to get no of bits in binary representation of positive integer ; Driver program"
How can the above be solved in Java?

class GFG { static int countBits ( int n ) { int count = 0 ; while ( n != 0 ) { count ++ ; n >>= 1 ; } return count ; } public static void main ( String [ ] arg ) { int i = 65 ; System . out . print ( countBits ( i ) ) ; } }


"Count total bits in a number | Java program to find total bit in given number ; log function in base 2 take only integer part ; Driver code"
How can the above be solved in Java?

import java . io . * ; class GFG { static int countBits ( int number ) { return ( int ) ( Math . log ( number ) / Math . log ( 2 ) + 1 ) ; } public static void main ( String [ ] args ) { int num = 65 ; System . out . println ( countBits ( num ) ) ; } }


"Count total divisors of A or B in a given range | Java program to count total divisors of ' a ' or ' b ' in a given range ; Utility method to find LCM of two numbers ; method to calculate all divisors in given range ; Find LCM of a and b ; Find common divisor by using LCM ; Driver method"
How can the above be solved in Java?

import java . math . BigInteger ; class Test { static int FindLCM ( int a , int b ) { return ( a * b ) / new BigInteger ( a + " " ) . gcd ( new BigInteger ( b + " " ) ) . intValue ( ) ; } static int rangeDivisor ( int m , int n , int a , int b ) { int lcm = FindLCM ( a , b ) ; int a_divisor = n / a - ( m - 1 ) / a ; int b_divisor = n / b - ( m - 1 ) / b ; int common_divisor = n / lcm - ( m - 1 ) / lcm ; int ans = a_divisor + b_divisor - common_divisor ; return ans ; } public static void main ( String args [ ] ) { int m = 3 , n = 11 , a = 2 , b = 3 ; System . out . println ( rangeDivisor ( m , n , a , b ) ) ; m = 11 ; n = 1000000 ; a = 6 ; b = 35 ; System . out . println ( rangeDivisor ( m , n , a , b ) ) ; } }


"Count total number of N digit numbers such that the difference between sum of even and odd digits is 1 | A memoization based recursive program to count numbers with difference between odd and even digit sums as 1 ; A lookup table used for memoization . ; Memoization based recursive function to count numbers with even and odd digit sum difference as 1. This function considers leading zero as a digit ; Base Case ; If current subproblem is already computed ; Initialize result ; If current digit is odd , then add it to odd sum and recur ; else Add to even sum and recur ; Store current result in lookup table and return the same ; This is mainly a wrapper over countRec . It explicitly handles leading digit and calls countRec ( ) for remaining digits . ; Initialize number digits considered so far ; Initialize all entries of lookup table ; Initialize final answer ; Initialize even and odd sums ; Explicitly handle first digit and call recursive function countRec for remaining digits . Note that the first digit is considered as even digit . ; Driver program"
How can the above be solved in Java?

class GFG { static int [ ] [ ] [ ] [ ] lookup = new int [ 50 ] [ 1000 ] [ 1000 ] [ 2 ] ; static int countRec ( int digits , int esum , int osum , int isOdd , int n ) { if ( digits == n ) return ( esum - osum == 1 ) ? 1 : 0 ; if ( lookup [ digits ] [ esum ] [ osum ] [ isOdd ] != - 1 ) return lookup [ digits ] [ esum ] [ osum ] [ isOdd ] ; int ans = 0 ; if ( isOdd == 1 ) for ( int i = 0 ; i <= 9 ; i ++ ) ans += countRec ( digits + 1 , esum , osum + i , 0 , n ) ; for ( int i = 0 ; i <= 9 ; i ++ ) ans += countRec ( digits + 1 , esum + i , osum , 1 , n ) ; return lookup [ digits ] [ esum ] [ osum ] [ isOdd ] = ans ; } static int finalCount ( int n ) { int digits = 0 ; for ( int i = 0 ; i < 50 ; i ++ ) for ( int j = 0 ; j < 1000 ; j ++ ) for ( int k = 0 ; k < 1000 ; k ++ ) for ( int l = 0 ; l < 2 ; l ++ ) lookup [ i ] [ j ] [ k ] [ l ] = - 1 ; int ans = 0 ; int esum = 0 , osum = 0 ; for ( int i = 1 ; i <= 9 ; i ++ ) ans += countRec ( digits + 1 , esum + i , osum , 1 , n ) ; return ans ; } public static void main ( String [ ] args ) { int n = 3 ; System . out . println ( " Count ▁ of ▁ " + n + " ▁ digit ▁ numbers ▁ is ▁ " + finalCount ( n ) ) ; } }


"Count total number of digits from 1 to n | Java program to count total number of digits we have to write from 1 to n ; number_of_digits store total digits we have to write ; In the loop we are decreasing 0 , 9 , 99 ... from n till ( n - i + 1 ) is greater than 0 and sum them to number_of_digits to get the required sum ; Driver Method"
How can the above be solved in Java?

public class GFG { static int totalDigits ( int n ) { int number_of_digits = 0 ; for ( int i = 1 ; i <= n ; i *= 10 ) number_of_digits += ( n - i + 1 ) ; return number_of_digits ; } public static void main ( String [ ] args ) { int n = 13 ; System . out . println ( totalDigits ( n ) ) ; } }


"Count total number of even sum sequences | Java implementation of the above approach ; Iterative function to calculate ( x ^ y ) % p in O ( log y ) ; Initialize result ; Update x if it is greater than or equal to p ; If y is odd then multiply x with the result ; y must be even now y = y >> 1 ; y = y / 2 ; Function to return n ^ ( - 1 ) mod p ; Function to return ( 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 count of odd numbers from 1 to n ; Function to return the count of even numbers from 1 to n ; Function to return the count of the required sequences ; Take i even and n - i odd numbers ; Number of odd numbers must be even ; Total ways of placing n - i odd numbers in the sequence of n numbers ; Add this number to the final answer ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { static final int M = 1000000007 ; static long power ( long x , int y , int p ) { long res = 1 ; x = x % p ; while ( y > 0 ) { if ( ( y & 1 ) == 1 ) res = ( res * x ) % p ; x = ( x * x ) % p ; } return res ; } static long modInverse ( long n , int p ) { return power ( n , p - 2 , p ) ; } static long nCrModPFermat ( long n , int r , int p ) { if ( r == 0 ) return 1 ; long fac [ ] = new long [ ( int ) n + 1 ] ; fac [ 0 ] = 1 ; int i ; for ( i = 1 ; i <= n ; i ++ ) fac [ i ] = fac [ i - 1 ] * i % p ; return ( fac [ ( int ) n ] * modInverse ( fac [ r ] , p ) % p * modInverse ( fac [ ( int ) n - r ] , p ) % p ) % p ; } static long countOdd ( long n ) { long x = n / 2 ; if ( n % 2 == 1 ) x ++ ; return x ; } static long counteEven ( long n ) { long x = n / 2 ; return x ; } static long CountEvenSumSequences ( long n ) { long count = 0 ; for ( int i = 0 ; i <= n ; i ++ ) { int even = i , odd = ( int ) n - i ; if ( odd % 2 == 1 ) continue ; long tot = ( power ( countOdd ( n ) , odd , M ) * nCrModPFermat ( n , odd , M ) ) % M ; tot = ( tot * power ( counteEven ( n ) , i , M ) ) % M ; count += tot ; count %= M ; } return count ; } public static void main ( String [ ] args ) { long n = 5 ; System . out . println ( CountEvenSumSequences ( n ) ) ; } }


"Count total set bits in all numbers from 1 to n |  ; ans store sum of set bits from 0 to n ; while n greater than equal to 2 ^ i ; This k will get flipped after 2 ^ i iterations ; change is iterator from 2 ^ i to 1 ; This will loop from 0 to n for every bit position ; When change = 1 flip the bit ; again set change to 2 ^ i ; increment the position ; Driver program"
How can the above be solved in Java?

public class GFG { static int countSetBits ( int n ) { int i = 0 ; int ans = 0 ; while ( ( 1 << i ) <= n ) { boolean k = false ; int change = 1 << i ; for ( int j = 0 ; j <= n ; j ++ ) { if ( k == true ) ans += 1 ; else ans += 0 ; if ( change == 1 ) { k = ! k ; change = 1 << i ; } else { change -- ; } } i ++ ; } return ans ; } public static void main ( String [ ] args ) { int n = 17 ; System . out . println ( countSetBits ( n ) ) ; } }


"Count total set bits in all numbers from 1 to n | A simple program to count set bits in all numbers from 1 to n . ; Returns count of set bits present in all numbers from 1 to n ; initialize the result ; A utility function to count set bits in a number x ; Driver program"
How can the above be solved in Java?

class GFG { static int countSetBits ( int n ) { int bitCount = 0 ; for ( int i = 1 ; i <= n ; i ++ ) bitCount += countSetBitsUtil ( i ) ; return bitCount ; } static int countSetBitsUtil ( int x ) { if ( x <= 0 ) return 0 ; return ( x % 2 == 0 ? 0 : 1 ) + countSetBitsUtil ( x / 2 ) ; } public static void main ( String [ ] args ) { int n = 4 ; System . out . print ( " Total ▁ set ▁ bit ▁ count ▁ is ▁ " ) ; System . out . print ( countSetBits ( n ) ) ; } }


"Count total set bits in all numbers from 1 to n | Java A O ( Logn ) complexity program to count set bits in all numbers from 1 to n ; Returns position of leftmost set bit . The rightmost position is considered as 0 ; Given the position of previous leftmost set bit in n ( or an upper bound onleftmost position ) returns the new position of leftmost set bit in n ; The main recursive function used by countSetBits ( ) Returns count of set bits present in all numbers from 1 to n ; Get the position of leftmost set bit in n . This will be used as an upper bound for next set bit function ; Use the position ; Base Case : if n is 0 , then set bit count is 0 ; get position of next leftmost set bit ; If n is of the form 2 ^ x - 1 , i . e . , if n is like 1 , 3 , 7 , 15 , 31 , . . etc , then we are done . Since positions are considered starting from 0 , 1 is added to m ; update n for next recursive call ; Driver code"
How can the above be solved in Java?

import java . io . * ; class GFG { static int getLeftmostBit ( int n ) { int m = 0 ; while ( n > 1 ) { n = n >> 1 ; m ++ ; } return m ; } static int getNextLeftmostBit ( int n , int m ) { int temp = 1 << m ; while ( n < temp ) { temp = temp >> 1 ; m -- ; } return m ; } static int countSetBits ( int n ) { int m = getLeftmostBit ( n ) ; return countSetBits ( n , m ) ; } static int countSetBits ( int n , int m ) { if ( n == 0 ) return 0 ; m = getNextLeftmostBit ( n , m ) ; if ( n == ( ( int ) 1 << ( m + 1 ) ) - 1 ) return ( int ) ( m + 1 ) * ( 1 << m ) ; n = n - ( 1 << m ) ; return ( n + 1 ) + countSetBits ( n ) + m * ( 1 << ( m - 1 ) ) ; } public static void main ( String [ ] args ) { int n = 17 ; System . out . println ( " Total ▁ set ▁ bit ▁ count ▁ is ▁ " + countSetBits ( n ) ) ; } }


"Count total set bits in all numbers from 1 to n | Set 2 | Java implementation of the approach ; Function to return the sum of the count of set bits in the integers from 1 to n ; Ignore 0 as all the bits are unset ; To store the powers of 2 ; To store the result , it is initialized with n / 2 because the count of set least significant bits in the integers from 1 to n is n / 2 ; Loop for every bit required to represent n ; Total count of pairs of 0 s and 1 s ; totalPairs / 2 gives the complete count of the pairs of 1 s Multiplying it with the current power of 2 will give the count of 1 s in the current bit ; If the count of pairs was odd then add the remaining 1 s which could not be groupped together ; Next power of 2 ; Return the result ; Driver code"
How can the above be solved in Java?

class GFG { static int countSetBits ( int n ) { n ++ ; int powerOf2 = 2 ; int cnt = n / 2 ; while ( powerOf2 <= n ) { int totalPairs = n / powerOf2 ; cnt += ( totalPairs / 2 ) * powerOf2 ; cnt += ( totalPairs % 2 == 1 ) ? ( n % powerOf2 ) : 0 ; powerOf2 <<= 1 ; } return cnt ; } public static void main ( String [ ] args ) { int n = 14 ; System . out . println ( countSetBits ( n ) ) ; } }


"Count total set bits in all numbers from 1 to n |"
How can the above be solved in Java?

static int getSetBitsFromOneToN ( int N ) { int two = 2 , ans = 0 ; int n = N ; while ( n != 0 ) { ans += ( N / two ) * ( two >> 1 ) ; if ( ( N & ( two - 1 ) ) > ( two >> 1 ) - 1 ) ans += ( N & ( two - 1 ) ) - ( two >> 1 ) + 1 ; two <<= 1 ; n >>= 1 ; } return ans ; }


"Count total set bits in all numbers from range L to R | Java program for the above approach ; Function that counts the set bits from 0 to N ; To store sum of set bits from 0 - N ; Until n >= to 2 ^ i ; This k will get flipped after 2 ^ i iterations ; Change is iterator from 2 ^ i to 1 ; This will loop from 0 to n for every bit position ; When change = 1 flip the bit ; Again set change to 2 ^ i ; Increment the position ; Function that counts the set bit in the range ( L , R ) ; Return the count ; Driver Code ; Given L and R ; Function Call"
How can the above be solved in Java?

 import java . util . * ; class GFG { static int countSetBit ( int n ) { int i = 0 ; int ans = 0 ; while ( ( 1 << i ) <= n ) { boolean k = true ; int change = 1 << i ; for ( int j = 0 ; j <= n ; j ++ ) { ans += k == true ? 0 : 1 ; if ( change == 1 ) { k = ! k ; change = 1 << i ; } else { change -- ; } } i ++ ; } return ans ; } static int countSetBits ( int L , int R ) { return Math . abs ( countSetBit ( R ) - countSetBit ( L - 1 ) ) ; } public static void main ( String [ ] args ) { int L = 3 , R = 5 ; System . out . print ( " Total ▁ set ▁ bit ▁ count ▁ is ▁ " + countSetBits ( L , R ) + "
"); } }


"Count total set bits in all numbers from range L to R | Java program for the above approach ; Function to count set bit in [ L , R ] ; Variable for count set bit in range ; Count set bit for all number in range ; Use inbuilt function ; Driver Code ; Given range L and R ; Function Call"
How can the above be solved in Java?

class GFG { static int countSetBits ( int L , int R ) { int count = 0 ; for ( int i = L ; i <= R ; i ++ ) { count += Integer . bitCount ( i ) ; } return count ; } public static void main ( String [ ] args ) { int L = 3 , R = 5 ; System . out . print ( " Total ▁ set ▁ bit ▁ count ▁ is ▁ " + countSetBits ( L , R ) ) ; } }


"Count total set bits in all numbers from range L to R | Java program for the above approach ; Function to count set bit in range ; Count variable ; Find the set bit in Nth number ; If last bit is set ; Left sift by one bit ; Return count ; Driver Code ; Given Range L and R ; Function Call"
How can the above be solved in Java?

class GFG { static int countSetBits ( int L , int R ) { int count = 0 ; for ( int i = L ; i <= R ; i ++ ) { int n = i ; while ( n > 0 ) { count += ( n & 1 ) ; n = n >> 1 ; } } return count ; } public static void main ( String [ ] args ) { int L = 3 , R = 5 ; System . out . print ( " Total ▁ set ▁ Bit ▁ count ▁ is ▁ " + countSetBits ( L , R ) ) ; } }


"Count total set bits in all numbers from range L to R | Java program for the above approach ; Function to count set bits in x ; Base Case ; Recursive Call ; Function that returns count of set bits present in all numbers from 1 to N ; Initialize the result ; Return the setbit count ; Driver Code ; Given L and R ; Function Call"
How can the above be solved in Java?

class GFG { static int countSetBitsUtil ( int x ) { if ( x <= 0 ) return 0 ; return ( ( x % 2 == 0 ? 0 : 1 ) + countSetBitsUtil ( x / 2 ) ) ; } static int countSetBits ( int L , int R ) { int bitCount = 0 ; for ( int i = L ; i <= R ; i ++ ) { bitCount += countSetBitsUtil ( i ) ; } return bitCount ; } public static void main ( String [ ] args ) { int L = 3 , R = 5 ; System . out . printf ( " Total ▁ set ▁ bit ▁ count ▁ is ▁ % d " , countSetBits ( L , R ) ) ; } }


"Count total set bits in all numbers from range L to R | Java program for the above approach ; Returns position of leftmost set bit The rightmost position is taken as 0 ; Function that gives the position of previous leftmost set bit in n ; Function that returns count of set bits present in all numbers from 1 to n ; Get the position of leftmost set bit in n ; Use the position ; Function to count the set bits between the two numbers N and M ; Base Case ; Get position of next leftmost set bit ; If n is of the form 2 ^ x - 1 ; Update n for next recursive call ; Function that counts the set bits between L and R ; Driver Code ; Given L and R ; Function Call"
How can the above be solved in Java?

import java . util . * ; class GFG { static int getLeftmostBit ( int n ) { int m = 0 ; while ( n > 1 ) { n = n >> 1 ; m ++ ; } return m ; } static int getNextLeftmostBit ( int n , int m ) { int temp = 1 << m ; while ( n < temp ) { temp = temp >> 1 ; m -- ; } return m ; } static int countSetBit ( int n ) { int m = getLeftmostBit ( n ) ; return _countSetBit ( n , m ) ; } static int _countSetBit ( int n , int m ) { if ( n == 0 ) return 0 ; m = getNextLeftmostBit ( n , m ) ; if ( n == ( ( int ) 1 << ( m + 1 ) ) - 1 ) return ( int ) ( m + 1 ) * ( 1 << m ) ; n = n - ( 1 << m ) ; return ( ( n + 1 ) + countSetBit ( n ) + m * ( 1 << ( m - 1 ) ) ) ; } static int countSetBits ( int L , int R ) { return Math . abs ( countSetBit ( R ) - countSetBit ( L - 1 ) ) ; } public static void main ( String [ ] args ) { int L = 3 , R = 5 ; System . out . print ( " Total ▁ set ▁ bit ▁ count ▁ is ▁ " + countSetBits ( L , R ) ) ; } }


"Count total unset bits in all the numbers from 1 to N | Java implementation of the approach ; Function to return the count of unset bits in the binary representation of all the numbers from 1 to n ; To store the count of unset bits ; For every integer from the range [ 1 , n ] ; A copy of the current integer ; Count of unset bits in the current integer ; If current bit is unset ; Driver code"
How can the above be solved in Java?

class GFG { static int countUnsetBits ( int n ) { int cnt = 0 ; for ( int i = 1 ; i <= n ; i ++ ) { int temp = i ; while ( temp > 0 ) { if ( temp % 2 == 0 ) { cnt = cnt + 1 ; } temp = temp / 2 ; } } return cnt ; } public static void main ( String [ ] args ) { int n = 5 ; System . out . println ( countUnsetBits ( n ) ) ; } }


"Count total ways to reach destination from source in an undirected Graph | Java program to count total number of ways to reach destination in a graph ; Utility Function to count total ways ; Base condition When reach to the destination ; Make vertex visited ; Recursive function , for count ways ; Backtracking Make vertex unvisited ; Return total ways ; Function to count total ways to reach destination ; Loop to make all vertex unvisited , Initially ; Make source visited ; Print total ways"
How can the above be solved in Java?

class GFG { static int countWays ( int mtrx [ ] [ ] , int vrtx , int i , int dest , boolean visited [ ] ) { if ( i == dest ) { return 1 ; } int total = 0 ; for ( int j = 0 ; j < vrtx ; j ++ ) { if ( mtrx [ i ] [ j ] == 1 && ! visited [ j ] ) { visited [ j ] = true ; total += countWays ( mtrx , vrtx , j , dest , visited ) ; visited [ j ] = false ; } } return total ; } static int totalWays ( int mtrx [ ] [ ] , int vrtx , int src , int dest ) { boolean [ ] visited = new boolean [ vrtx ] ; for ( int i = 0 ; i < vrtx ; i ++ ) { visited [ i ] = false ; } visited [ src ] = true ; return countWays ( mtrx , vrtx , src , dest , visited ) ; } public static void main ( String [ ] args ) { int vrtx = 11 ; int mtrx [ ] [ ] = { { 0 , 1 , 0 , 0 , 0 , 0 , 1 , 0 , 0 , 0 , 0 } , { 1 , 0 , 1 , 1 , 0 , 0 , 0 , 0 , 0 , 0 , 0 } , { 0 , 1 , 0 , 1 , 0 , 0 , 0 , 0 , 0 , 0 , 0 } , { 0 , 1 , 1 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 } , { 0 , 0 , 0 , 0 , 0 , 1 , 0 , 0 , 0 , 1 , 0 } , { 0 , 0 , 0 , 0 , 1 , 0 , 1 , 0 , 0 , 1 , 0 } , { 1 , 0 , 0 , 0 , 0 , 1 , 0 , 1 , 0 , 0 , 0 } , { 0 , 0 , 0 , 0 , 0 , 0 , 1 , 0 , 1 , 0 , 0 } , { 0 , 0 , 0 , 0 , 0 , 0 , 0 , 1 , 0 , 1 , 0 } , { 0 , 0 , 0 , 0 , 1 , 1 , 0 , 0 , 1 , 0 , 0 } , { 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 1 , 0 } } ; int src = 3 ; int dest = 9 ; System . out . print ( totalWays ( mtrx , vrtx , src - 1 , dest - 1 ) ) ; } }


"Count trailing zeroes in factorial of a number | Java program to count trailing 0 s in n ! ; Function to return trailing 0 s in factorial of n ; Initialize result ; Keep dividing n by powers of 5 and update count ; Driver Code"
How can the above be solved in Java?

import java . io . * ; class GFG { static int findTrailingZeros ( int n ) { int count = 0 ; for ( int i = 5 ; n / i >= 1 ; i *= 5 ) count += n / i ; return count ; } public static void main ( String [ ] args ) { int n = 100 ; System . out . println ( " Count ▁ of ▁ trailing ▁ 0s ▁ in ▁ " + n + " ! ▁ is ▁ " + findTrailingZeros ( n ) ) ; } }


"Count trailing zeroes present in binary representation of a given number using XOR | Java implementation of the above approach ; Function to print count of trailing zeroes present in binary representation of N ; Stores XOR of N and ( N - 1 ) ; Return count of set bits in res ; Driver Code ; Function call to print the count of trailing zeroes in the binary representation of N"
How can the above be solved in Java?

import java . io . * ; class GFG { public static int countTrailingZeroes ( int N ) { int res = N ^ ( N - 1 ) ; return ( int ) ( Math . log ( temp ) / Math . log ( 2 ) ) ; } public static void main ( String [ ] args ) { int N = 12 ; System . out . println ( countTrailingZeroes ( N ) ) ; } }


"Count triangles required to form a House of Cards of height N | Java implementation of the above approach ; Function to find number of triangles ; Driver Code ; Function call"
How can the above be solved in Java?

import java . lang . * ; class GFG { public static int noOfTriangles ( int n ) { return ( n * ( n + 2 ) * ( 2 * n + 1 ) / 8 ) ; } public static void main ( String args [ ] ) { int n = 3 ; System . out . print ( noOfTriangles ( n ) ) ; } }


"Count triplet of indices ( i , j , k ) such that XOR of elements between [ i , j ) equals [ j , k ] | Java program to count the Number of triplets in array having subarray XOR equal ; Function return the count of triplets having subarray XOR equal ; XOR value till i ; Count and ways array as defined above ; Using the formula stated ; Increase the frequency of x ; Add i + 1 to ways [ x ] for upcoming indices ; Driver code"
How can the above be solved in Java?

import java . io . * ; import java . util . Arrays ; import java . util . ArrayList ; import java . lang . * ; import java . util . Collections ; class GFG { static int CountOfTriplets ( int a [ ] , int n ) { int answer = 0 ; int x = 0 ; int count [ ] = new int [ 100005 ] ; int ways [ ] = new int [ 100005 ] ; for ( int i = 0 ; i < n ; i ++ ) { x ^= a [ i ] ; answer += count [ x ] * i - ways [ x ] ; count [ x ] ++ ; ways [ x ] += ( i + 1 ) ; } return answer ; } public static void main ( String [ ] args ) { int Arr [ ] = { 3 , 6 , 12 , 8 , 6 , 2 , 1 , 5 } ; int N = Arr . length ; System . out . print ( CountOfTriplets ( Arr , N ) ) ; } }


"Count triplet pairs ( A , B , C ) of points in 2 | Java implementation of the approach ; Function to return the count of possible triplets ; Insert all the points in a set ; If the mid point exists in the set ; Return the count of valid triplets ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { static class pair { int first , second ; public pair ( int first , int second ) { this . first = first ; this . second = second ; } } static int countTriplets ( int n , Vector < pair > points ) { Set < pair > pts = new HashSet < pair > ( ) ; int ct = 0 ; for ( int i = 0 ; i < n ; i ++ ) pts . add ( points . get ( i ) ) ; for ( int i = 0 ; i < n ; i ++ ) for ( int j = i + 1 ; j < n ; j ++ ) { int x = points . get ( i ) . first + points . get ( j ) . first ; int y = points . get ( i ) . second + points . get ( j ) . second ; if ( x % 2 == 0 && y % 2 == 0 ) if ( ! pts . contains ( new pair ( x / 2 , y / 2 ) ) ) ct ++ ; } return ct ; } public static void main ( String args [ ] ) { Vector < pair > points = new Vector < > ( ) ; points . add ( new pair ( 1 , 1 ) ) ; points . add ( new pair ( 2 , 2 ) ) ; points . add ( new pair ( 3 , 3 ) ) ; int n = points . size ( ) ; System . out . println ( countTriplets ( n , points ) ) ; } }


"Count triplets ( a , b , c ) such that a + b , b + c and a + c are all divisible by K | Java implementation of the approach ; Function returns the count of the triplets ; iterate for all triples pairs ( i , j , l ) ; if the condition is satisfied ; Driver code"
How can the above be solved in Java?

class GFG { static long count_triples ( int n , int k ) { int i = 0 , j = 0 , l = 0 ; int count = 0 ; for ( i = 1 ; i <= n ; i ++ ) { for ( j = 1 ; j <= n ; j ++ ) { for ( l = 1 ; l <= n ; l ++ ) { if ( ( i + j ) % k == 0 && ( i + l ) % k == 0 && ( j + l ) % k == 0 ) count ++ ; } } } return count ; } public static void main ( String [ ] args ) { int n = 3 ; int k = 2 ; long ans = count_triples ( n , k ) ; System . out . println ( ans ) ; } }


"Count triplets ( a , b , c ) such that a + b , b + c and a + c are all divisible by K | Set 2 | Java program for the above approach ; Function to count the number of triplets from the range [ 1 , N - 1 ] having sum of all pairs divisible by K ; If K is even ; Otherwise ; Driver Code"
How can the above be solved in Java?

import java . io . * ; import java . lang . * ; import java . util . * ; class GFG { static int countTriplets ( int N , int K ) { if ( K % 2 == 0 ) { int x = N / K ; int y = ( N + ( K / 2 ) ) / K ; return x * x * x + y * y * y ; } else { int x = N / K ; return x * x * x ; } } public static void main ( String [ ] args ) { int N = 2 , K = 2 ; System . out . print ( countTriplets ( N , K ) ) ; } }


"Count triplets from a sorted array having difference between adjacent elements equal to D | Java program for the above approach ; Function to count the number of triplets having difference between adjacent elements equal to D ; Stores the frequency of array elements ; Stores the count of resultant triplets ; Traverse the array ; Check if arr [ i ] - D and arr [ i ] - 2 * D exists in the Hashmap or not ; Update the value of ans ; Increase the frequency of the current element ; Return the resultant count ; Driver Code"
How can the above be solved in Java?

import java . util . * ; class GFG { static int countTriplets ( int D , int [ ] arr ) { HashMap < Integer , Integer > freq = new HashMap < Integer , Integer > ( ) ; int ans = 0 ; for ( int i = 0 ; i < arr . length ; i ++ ) { if ( freq . containsKey ( arr [ i ] - D ) && freq . containsKey ( arr [ i ] - 2 * D ) ) { ans += freq . get ( arr [ i ] - D ) * freq . get ( arr [ i ] - 2 * D ) ; } if ( freq . containsKey ( arr [ i ] ) ) { freq . put ( arr [ i ] , freq . get ( arr [ i ] ) + 1 ) ; } else { freq . put ( arr [ i ] , 1 ) ; } } return ans ; } public static void main ( String [ ] args ) { int [ ] arr = { 1 , 2 , 4 , 5 , 7 , 8 , 10 } ; int D = 1 ; System . out . print ( countTriplets ( D , arr ) ) ; } }


"Count triplets from an array which can form quadratic equations with real roots | Java program for the above approach ; Function to count the number of triplets ( a , b , c ) such that the equation ax ^ 2 + bx + c = 0 has real roots ; Sort the array in ascending order ; Stores count of triplets ( a , b , c ) such that ax ^ 2 + bx + c = 0 has real roots ; Base case ; Traverse the given array ; If values of a and c are equal to b ; Increment a ; Decrement c ; Condition for having real roots for a quadratic equation ; If b lies in between a and c ; Update count ; Update count ; Increment a ; Decrement c ; For each pair two values are possible of a and c ; Driver Code ; Function Call"
How can the above be solved in Java?

import java . util . * ; class GFG { static int getCount ( int arr [ ] , int N ) { Arrays . sort ( arr ) ; int count = 0 ; if ( N < 3 ) return 0 ; for ( int b = 0 ; b < N ; b ++ ) { int a = 0 , c = N - 1 ; int d = arr [ b ] * arr [ b ] / 4 ; while ( a < c ) { if ( a == b ) { a ++ ; continue ; } if ( c == b ) { c -- ; continue ; } if ( arr [ a ] * arr <= d ) { if ( a < b && b < c ) { count += c - a - 1 ; } else { count += c - a ; } a ++ ; } else { c -- ; } } } return count * 2 ; } public static void main ( String [ ] args ) { int arr [ ] = { 3 , 6 , 10 , 13 , 21 } ; int N = arr . length ; System . out . print ( getCount ( arr , N ) ) ; } }


"Count triplets from an array which can form quadratic equations with real roots | Java program for the above approach ; Function to find count of triplets ( a , b , c ) such that the equations ax ^ 2 + bx + c = 0 has real roots ; Stores count of triplets ( a , b , c ) such that ax ^ 2 + bx + c = 0 has real roots ; Base case ; Generate all possible triplets ( a , b , c ) ; If the coefficient of X ^ 2 and X are equal ; If coefficient of X ^ 2 or x are equal to the constant ; Condition for having real roots ; Driver Code ; Function Call"
How can the above be solved in Java?

import java . util . * ; class GFG { static int getCount ( int arr [ ] , int N ) { int count = 0 ; if ( N < 3 ) return 0 ; for ( int b = 0 ; b < N ; b ++ ) { for ( int a = 0 ; a < N ; a ++ ) { if ( a == b ) continue ; for ( int c = 0 ; c < N ; c ++ ) { if ( c == a c == b ) continue ; int d = arr [ b ] * arr [ b ] / 4 ; if ( arr [ a ] * arr <= d ) count ++ ; } } } return count ; } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 2 , 3 , 4 , 5 } ; int N = arr . length ; System . out . print ( getCount ( arr , N ) ) ; } }


"Count triplets in a sorted doubly linked list whose product is equal to a given value x | Java implementation to count triplets in a sorted doubly linked list whose product is equal to a given value ' x ' ; Structure of node of doubly linked list ; Function to count triplets in a sorted doubly linked list whose product is equal to a given value ' x ' ; Unordered_map ' um ' implemented as hash table ; Insert the < node data , node pointer > tuple in ' um ' ; Generate all possible pairs ; p_product = product of elements in the current pair ; If ' x / p _ product ' is present in ' um ' and either of the two nodes are not equal to the ' um [ x / p _ product ] ' node ; Increment count ; Required count of triplets division by 3 as each triplet is counted 3 times ; A utility function to insert a new node at the beginning of doubly linked list ; Allocate node ; Put in the data ; Driver code ; Start with an empty doubly linked list ; Insert values in sorted order"
How can the above be solved in Java?

import java . io . * ; import java . util . * ; class Node { int data ; Node next , prev ; } class GFG { static int countTriplets ( Node head , int x ) { Node ptr , ptr1 , ptr2 ; int count = 0 ; Map < Integer , Node > um = new HashMap < Integer , Node > ( ) ; for ( ptr = head ; ptr != null ; ptr = ptr . next ) { um . put ( ptr . data , ptr ) ; } for ( ptr1 = head ; ptr1 != null ; ptr1 = ptr1 . next ) { for ( ptr2 = ptr1 . next ; ptr2 != null ; ptr2 = ptr2 . next ) { int p_product = ( ptr1 . data * ptr2 . data ) ; if ( um . containsKey ( x / p_product ) && um . get ( x / p_product ) != ptr1 && um . get ( x / p_product ) != ptr2 ) { count ++ ; } } } return ( count / 3 ) ; } static Node insert ( Node head , int data ) { Node temp = new Node ( ) ; temp . data = data ; temp . next = temp . prev = null ; if ( head == null ) { head = temp ; } else { temp . next = head ; head . prev = temp ; head = temp ; } return head ; } public static void main ( String [ ] args ) { Node head = null ; head = insert ( head , 9 ) ; head = insert ( head , 8 ) ; head = insert ( head , 6 ) ; head = insert ( head , 5 ) ; head = insert ( head , 4 ) ; head = insert ( head , 2 ) ; head = insert ( head , 1 ) ; int x = 8 ; System . out . println ( " Count ▁ = ▁ " + countTriplets ( head , x ) ) ; } }


"Count triplets in a sorted doubly linked list whose product is equal to a given value x | Java implementation to count triplets in a sorted doubly linked list whose product is equal to a given value ' x ' ; structure of node of doubly linked list ; function to count pairs whose product equal to given ' value ' ; The loop terminates when either of two pointers become null , or they cross each other ( second . next == first ) , or they become same ( first == second ) ; pair found ; increment count ; move first in forward direction ; move second in backward direction ; if product is greater than ' value ' move second in backward direction ; else move first in forward direction ; required count of pairs ; function to count triplets in a sorted doubly linked list whose product is equal to a given value ' x ' ; if list is empty ; get pointer to the last node of the doubly linked list ; traversing the doubly linked list ; for each current node ; count pairs with product ( x / current . data ) in the range first to last and add it to the ' count ' of triplets ; required count of triplets ; A utility function to insert a new node at the beginning of doubly linked list ; allocate node ; put in the data ; Driver code ; start with an empty doubly linked list ; insert values in sorted order"
How can the above be solved in Java?

import java . util . * ; class GFG { static class Node { int data ; Node next , prev ; } ; static int countPairs ( Node first , Node second , int value ) { int count = 0 ; while ( first != null && second != null && first != second && second . next != first ) { if ( ( first . data * second . data ) == value ) { count ++ ; first = first . next ; second = second . prev ; } else if ( ( first . data * second . data ) > value ) second = second . prev ; else first = first . next ; } return count ; } static int countTriplets ( Node head , int x ) { if ( head == null ) return 0 ; Node current , first , last ; int count = 0 ; last = head ; while ( last . next != null ) last = last . next ; for ( current = head ; current != null ; current = current . next ) { first = current . next ; count += countPairs ( first , last , x / current . data ) ; } return count ; } static Node insert ( Node head , int data ) { Node temp = new Node ( ) ; temp . data = data ; temp . next = temp . prev = null ; if ( ( head ) == null ) ( head ) = temp ; else { temp . next = head ; ( head ) . prev = temp ; ( head ) = temp ; } return head ; } public static void main ( String args [ ] ) { Node head = null ; head = insert ( head , 9 ) ; head = insert ( head , 8 ) ; head = insert ( head , 6 ) ; head = insert ( head , 5 ) ; head = insert ( head , 4 ) ; head = insert ( head , 2 ) ; head = insert ( head , 1 ) ; int x = 8 ; System . out . println ( " Count ▁ = ▁ " + countTriplets ( head , x ) ) ; } }


"Count triplets in a sorted doubly linked list whose product is equal to a given value x | Java implementation to count triplets in a sorted doubly linked list whose sum is equal to a given value ' x ' ; Represents node of a doubly linked list ; function to count triplets in a sorted doubly linked list whose sum is equal to a given value ' x ' ; generate all possible triplets ; if elements in the current triplet sum up to ' x ' ; increment count ; required count of triplets ; A utility function to insert a new node at the beginning of doubly linked list ; allocate node ; Driver code ; start with an empty doubly linked list ; insert values in sorted order"
How can the above be solved in Java?

import java . util . * ; class Node { public int data ; public Node prev , next ; public Node ( int val ) { data = val ; prev = null ; next = null ; } } class GFG { static int countTriplets ( Node head , int x ) { Node ptr1 , ptr2 , ptr3 ; int count = 0 ; for ( ptr1 = head ; ptr1 != null ; ptr1 = ptr1 . next ) for ( ptr2 = ptr1 . next ; ptr2 != null ; ptr2 = ptr2 . next ) for ( ptr3 = ptr2 . next ; ptr3 != null ; ptr3 = ptr3 . next ) if ( ( ptr1 . data * ptr2 . data * ptr3 . data ) == x ) count ++ ; return count ; } static Node insert ( Node head , int val ) { Node temp = new Node ( val ) ; if ( head == null ) head = temp ; else { temp . next = head ; head . prev = temp ; head = temp ; } return head ; } public static void main ( String [ ] args ) { Node head = null ; head = insert ( head , 9 ) ; head = insert ( head , 8 ) ; head = insert ( head , 6 ) ; head = insert ( head , 5 ) ; head = insert ( head , 4 ) ; head = insert ( head , 2 ) ; head = insert ( head , 1 ) ; int x = 8 ; System . out . println ( " count ▁ = ▁ " + countTriplets ( head , x ) ) ; } }


"Count triplets in a sorted doubly linked list whose sum is equal to a given value x | Java implementation to count triplets in a sorted doubly linked list whose sum is equal to a given value ' x ' ; structure of node of doubly linked list ; function to count pairs whose sum equal to given ' value ' ; The loop terminates when either of two pointers become null , or they cross each other ( second . next == first ) , or they become same ( first == second ) ; pair found ; increment count ; move first in forward direction ; move second in backward direction ; if sum is greater than ' value ' move second in backward direction ; else move first in forward direction ; required count of pairs ; function to count triplets in a sorted doubly linked list whose sum is equal to a given value ' x ' ; if list is empty ; get pointer to the last node of the doubly linked list ; traversing the doubly linked list ; for each current node ; count pairs with sum ( x - current . data ) in the range first to last and add it to the ' count ' of triplets ; required count of triplets ; A utility function to insert a new node at the beginning of doubly linked list ; allocate node ; put in the data ; Driver program to test above ; start with an empty doubly linked list ; insert values in sorted order"
How can the above be solved in Java?

import java . util . * ; class GFG { static class Node { int data ; Node next , prev ; } ; static int countPairs ( Node first , Node second , int value ) { int count = 0 ; while ( first != null && second != null && first != second && second . next != first ) { if ( ( first . data + second . data ) == value ) { count ++ ; first = first . next ; second = second . prev ; } else if ( ( first . data + second . data ) > value ) second = second . prev ; else first = first . next ; } return count ; } static int countTriplets ( Node head , int x ) { if ( head == null ) return 0 ; Node current , first , last ; int count = 0 ; last = head ; while ( last . next != null ) last = last . next ; for ( current = head ; current != null ; current = current . next ) { first = current . next ; count += countPairs ( first , last , x - current . data ) ; } return count ; } static Node insert ( Node head , int data ) { Node temp = new Node ( ) ; temp . data = data ; temp . next = temp . prev = null ; if ( ( head ) == null ) ( head ) = temp ; else { temp . next = head ; ( head ) . prev = temp ; ( head ) = temp ; } return head ; } public static void main ( String [ ] args ) { Node head = null ; head = insert ( head , 9 ) ; head = insert ( head , 8 ) ; head = insert ( head , 6 ) ; head = insert ( head , 5 ) ; head = insert ( head , 4 ) ; head = insert ( head , 2 ) ; head = insert ( head , 1 ) ; int x = 17 ; System . out . print ( " Count ▁ = ▁ " + countTriplets ( head , x ) ) ; } }


"Count triplets such that product of two numbers added with third number is N | Java program for the above approach ; Function to find the divisors of the number ( N - i ) ; Stores the resultant count of divisors of ( N - i ) ; Iterate over range [ 1 , sqrt ( N ) ] ; Return the total divisors ; Function to find the number of triplets such that A * B - C = N ; Loop to fix the value of C ; Adding the number of divisors in count ; Return count of triplets ; Driver Code"
How can the above be solved in Java?

import java . io . * ; class GFG { static int countDivisors ( int n ) { int divisors = 0 ; int i ; for ( i = 1 ; i * i < n ; i ++ ) { if ( n % i == 0 ) { divisors ++ ; } } if ( i - ( n / i ) == 1 ) { i -- ; } for ( ; i >= 1 ; i -- ) { if ( n % i == 0 ) { divisors ++ ; } } return divisors ; } static int possibleTriplets ( int N ) { int count = 0 ; for ( int i = 1 ; i < N ; i ++ ) { count += countDivisors ( N - i ) ; } return count ; } public static void main ( String [ ] args ) { int N = 10 ; System . out . println ( possibleTriplets ( N ) ) ; } }


"Count triplets with sum smaller than a given value | A Simple Java program to count triplets with sum smaller than a given value ; Initialize result ; Fix the first element as A [ i ] ; Fix the second element as A [ j ] ; Now look for the third number ; Driver method to test the above function"
How can the above be solved in Java?

class Test { static int arr [ ] = new int [ ] { 5 , 1 , 3 , 4 , 7 } ; static int countTriplets ( int n , int sum ) { int ans = 0 ; for ( int i = 0 ; i < n - 2 ; i ++ ) { for ( int j = i + 1 ; j < n - 1 ; j ++ ) { for ( int k = j + 1 ; k < n ; k ++ ) if ( arr [ i ] + arr [ j ] + arr [ k ] < sum ) ans ++ ; } } return ans ; } public static void main ( String [ ] args ) { int sum = 12 ; System . out . println ( countTriplets ( arr . length , sum ) ) ; } }


"Count triplets with sum smaller than a given value | A Simple Java program to count triplets with sum smaller than a given value ; Sort input array ; Initialize result ; Every iteration of loop counts triplet with first element as arr [ i ] . ; Initialize other two elements as corner elements of subarray arr [ j + 1. . k ] ; Use Meet in the Middle concept ; If sum of current triplet is more or equal , move right corner to look for smaller values ; Else move left corner ; This is important . For current i and j , there can be total k - j third elements . ; Driver method to test the above function"
How can the above be solved in Java?

import java . util . Arrays ; class Test { static int arr [ ] = new int [ ] { 5 , 1 , 3 , 4 , 7 } ; static int countTriplets ( int n , int sum ) { Arrays . sort ( arr ) ; int ans = 0 ; for ( int i = 0 ; i < n - 2 ; i ++ ) { int j = i + 1 , k = n - 1 ; while ( j < k ) { if ( arr [ i ] + arr [ j ] + arr [ k ] >= sum ) k -- ; else { ans += ( k - j ) ; j ++ ; } } } return ans ; } public static void main ( String [ ] args ) { int sum = 12 ; System . out . println ( countTriplets ( arr . length , sum ) ) ; } }


"Count twin prime pairs in an Array | Java program to count Twin Prime pairs in array ; A utility function to check if the number n is prime or not ; Base Cases ; Check to skip middle five numbers in below loop ; If n is divisible by i and i + 2 then it is not prime ; A utility function that check if n1 and n2 are Twin Primes or not ; Function to find Twin Prime pairs from the given array ; Iterate through all pairs ; Increment count if twin prime pair ; Driver 's code ; Function call to find Twin Primes pair"
How can the above be solved in Java?

import java . util . * ; class GFG { static boolean isPrime ( int n ) { if ( n <= 1 ) return false ; if ( n <= 3 ) return true ; if ( n % 2 == 0 n % 3 == 0 ) return false ; for ( int i = 5 ; i * i <= n ; i += 6 ) { if ( n % i == 0 || n % ( i + 2 ) == 0 ) { return false ; } } return true ; } static boolean twinPrime ( int n1 , int n2 ) { return ( isPrime ( n1 ) && isPrime ( n2 ) && Math . abs ( n1 - n2 ) == 2 ) ; } static int countTwinPairs ( int arr [ ] , int n ) { int count = 0 ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = i + 1 ; j < n ; j ++ ) { if ( twinPrime ( arr [ i ] , arr [ j ] ) ) { count ++ ; } } } return count ; } public static void main ( String [ ] args ) { int arr [ ] = { 2 , 3 , 5 , 11 } ; int n = arr . length ; System . out . print ( countTwinPairs ( arr , n ) ) ; } }


"Count unique numbers that can be generated from N by adding one and removing trailing zeros | Java implementation of the approach ; Function to count the unique numbers ; If the number has already been visited ; Insert the number to the set ; First step ; Second step remove trailing zeros ; Recur again for the new number ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { static void count_unique ( HashSet < Integer > s , int n ) { if ( s . contains ( n ) ) return ; s . add ( n ) ; n += 1 ; while ( n % 10 == 0 ) { n = n / 10 ; } count_unique ( s , n ) ; } public static void main ( String [ ] args ) { int n = 10 ; HashSet < Integer > s = new HashSet < > ( ) ; count_unique ( s , n ) ; System . out . println ( s . size ( ) ) ; } }


"Count unique paths is a matrix whose product of elements contains odd number of divisors | Java program for the above approach ; Function to calculate and store all the paths product in vector ; Base Case ; If reaches the bottom right corner and product is a perfect square ; Find square root ; If square root is an integer ; Move towards down in the matrix ; Move towards right in the matrix ; Driver Code ; Given matrix mat [ ] [ ] ; Function call"
How can the above be solved in Java?

import java . io . * ; import java . util . * ; import java . lang . * ; class GFG { static int countPaths = 0 ; static void CountUniquePaths ( int [ ] [ ] a , int i , int j , int m , int n , int ans ) { if ( i >= m j >= n ) return ; if ( i == m - 1 && j == n - 1 ) { double sr = Math . sqrt ( ans * a [ i ] [ j ] ) ; if ( ( sr - Math . floor ( sr ) ) == 0 ) countPaths ++ ; } CountUniquePaths ( a , i + 1 , j , m , n , ans * a [ i ] [ j ] ) ; CountUniquePaths ( a , i , j + 1 , m , n , ans * a [ i ] [ j ] ) ; } public static void main ( String [ ] args ) { int M = 3 , N = 2 ; int [ ] [ ] mat = { { 1 , 1 } , { 3 , 1 } , { 3 , 1 } } ; CountUniquePaths ( mat , 0 , 0 , M , N , 1 ) ; System . out . println ( countPaths ) ; } }


"Count unique paths is a matrix whose product of elements contains odd number of divisors | Java program for the above approach ; Stores the results ; Count of unique product paths ; Function to check whether number is perfect square or not ; If square root is an integer ; Function to calculate and store all the paths product in vector ; Store the value a [ 0 ] [ 0 ] ; Initialize first row of dp ; Find prefix product ; Initialize first column of dp ; Find the prefix product ; Iterate over range ( 1 , 1 ) to ( N , M ) ; Copy dp [ i - 1 ] [ j ] in top [ ] ; Copy dp [ i ] [ j - 1 ] into left [ ] ; Compute the values of current state and store it in curr [ ] ; Find the product of a [ i ] [ j ] with elements at top [ ] ; Find the product of a [ i ] [ j ] with elements at left [ ] ; Update the current state ; Traverse dp [ m - 1 ] [ n - 1 ] ; Check if perfect square ; Driver code ; Given matrix mat [ ] [ ] ; Function Call ; Print the final count"
How can the above be solved in Java?

import java . util . * ; class GFG { static ArrayList < ArrayList < ArrayList < Integer > > > dp ; static int countPaths = 0 ; static boolean isPerfectSquare ( int n ) { double sr = Math . sqrt ( n ) ; return ( ( sr - Math . floor ( sr ) ) == 0 ) ; } static void countUniquePaths ( int a [ ] [ ] , int m , int n , int ans ) { dp . get ( 0 ) . get ( 0 ) . add ( a [ 0 ] [ 0 ] ) ; for ( int i = 1 ; i < m ; i ++ ) { a [ i ] [ 0 ] *= a [ i - 1 ] [ 0 ] ; dp . get ( i ) . get ( 0 ) . add ( a [ i ] [ 0 ] ) ; } for ( int i = 1 ; i < n ; i ++ ) { a [ 0 ] [ i ] *= a [ 0 ] [ i - 1 ] ; dp . get ( 0 ) . get ( i ) . add ( a [ 0 ] [ i ] ) ; } for ( int i = 1 ; i < m ; i ++ ) { for ( int j = 1 ; j < n ; j ++ ) { ArrayList < Integer > top = dp . get ( i - 1 ) . get ( j ) ; ArrayList < Integer > left = dp . get ( i ) . get ( j - 1 ) ; ArrayList < Integer > curr = new ArrayList < > ( ) ; for ( int k = 0 ; k < top . size ( ) ; k ++ ) { curr . add ( top . get ( k ) * a [ i ] [ j ] ) ; } for ( int k = 0 ; k < left . size ( ) ; k ++ ) { curr . add ( left . get ( k ) * a [ i ] [ j ] ) ; } dp . get ( i ) . set ( j , curr ) ; } } for ( Integer i : dp . get ( m - 1 ) . get ( n - 1 ) ) { if ( isPerfectSquare ( i ) ) { countPaths ++ ; } } } public static void main ( String [ ] args ) { int M = 3 , N = 4 ; int mat [ ] [ ] = { { 1 , 2 , 3 , 1 } , { 3 , 1 , 2 , 4 } , { 2 , 3 , 1 , 1 } } ; dp = new ArrayList < > ( ) ; for ( int i = 0 ; i < 105 ; i ++ ) { dp . add ( new ArrayList < > ( ) ) ; for ( int j = 0 ; j < 105 ; j ++ ) dp . get ( i ) . add ( new ArrayList < Integer > ( ) ) ; } countUniquePaths ( mat , M , N , 1 ) ; System . out . println ( countPaths ) ; } }


"Count unique paths with given sum in an N | Java program for the above approach ; Function for counting total no of paths possible with the sum is equal to X ; If the path of the sum from the root to current node is stored in sum ; If already computed ; Count different no of paths using all possible ways ; Return total no of paths ; Driver Code ; Stores the number of ways to obtains sums 0 to X ; Function call"
How can the above be solved in Java?

import java . io . * ; import java . util . * ; class GFG { static int mod = ( int ) 1e9 + 7 ; static int findTotalPath ( int X , int n , ArrayList < Integer > dp ) { if ( X == 0 ) { return 1 ; } int ans = 0 ; if ( dp . get ( X ) != - 1 ) { return dp . get ( X ) ; } for ( int i = 1 ; i <= Math . min ( X , n ) ; ++ i ) { ans += findTotalPath ( X - i , n , dp ) % mod ; ans %= mod ; } dp . set ( X , ans ) ; return ans ; } public static void main ( String [ ] args ) { int n = 3 , X = 2 ; ArrayList < Integer > dp = new ArrayList < Integer > ( Collections . nCopies ( X + 1 , - 1 ) ) ; System . out . print ( findTotalPath ( X , n , dp ) ) ; } }


"Count unique stairs that can be reached by moving given number of steps forward or backward | Java program for the above approach ; Function to count the number of unique stairs visited ; Checks whether the current stair is visited or not ; Store the possible moves from the current position ; Initialize a queue ; / Push the starting position ; Mark the starting position S as visited ; Iterate until queue is not empty ; Store the current stair number ; Pop it from the queue ; Check for all possible moves from the current stair ; Store the new stair number ; If it is valid and unvisited ; Push it into queue ; Mark the stair as visited ; Store the result ; Count the all visited stairs ; Print the result ; Driver Code"
How can the above be solved in Java?

import java . util . LinkedList ; import java . util . Queue ; class GFG { static void countStairs ( int n , int x , int a , int b ) { int [ ] vis = new int [ n + 1 ] ; int [ ] moves = { + a , - a , + b , - b } ; Queue < Integer > q = new LinkedList < Integer > ( ) ; q . add ( x ) ; vis [ x ] = 1 ; while ( ! q . isEmpty ( ) ) { int currentStair = q . peek ( ) ; q . remove ( ) ; for ( int j = 0 ; j < 4 ; j ++ ) { int newStair = currentStair + moves [ j ] ; if ( newStair > 0 && newStair <= n && vis [ newStair ] == 0 ) { q . add ( newStair ) ; vis [ newStair ] = 1 ; } } } int cnt = 0 ; for ( int i = 1 ; i <= n ; i ++ ) if ( vis [ i ] == 1 ) cnt ++ ; System . out . print ( cnt ) ; } public static void main ( String args [ ] ) { int N = 10 , S = 2 , A = 5 , B = 7 ; countStairs ( N , S , A , B ) ; } }


"Count unique substrings of a string S present in a wraparound string | Java program for the above approach ; Function to find the count of non - empty substrings of p present in s ; Stores the required answer ; Stores the length of substring present in p ; Stores the current length of substring that is present in string s starting from each character of p ; Iterate over the characters of the string ; Check if the current character can be added with previous substring to form the required substring ; Increment current length ; To avoid repetition ; Update arr [ cur ] ; Print the answer ; Driver Code ; Function call to find the count of non - empty substrings of p present in s"
How can the above be solved in Java?

import java . util . * ; class GFG { static void findSubstringInWraproundString ( String p ) { int ans = 0 ; int curLen = 0 ; int arr [ ] = new int [ 26 ] ; for ( int i = 0 ; i < p . length ( ) ; i ++ ) { int curr = p . charAt ( i ) - ' a ' ; if ( i > 0 && ( p . charAt ( i - 1 ) != ( ( curr + 26 - 1 ) % 26 + ' a ' ) ) ) { curLen = 0 ; } curLen ++ ; if ( curLen > arr [ curr ] ) { ans += ( curLen - arr [ curr ] ) ; arr [ curr ] = curLen ; } } System . out . println ( ans ) ; } public static void main ( String args [ ] ) { String p = " zab " ; findSubstringInWraproundString ( p ) ; } }


"Count unordered pairs ( i , j ) such that product of a [ i ] and a [ j ] is power of two | Java program to Count unordered pairs ( i , j ) in array such that product of a [ i ] and a [ j ] can be expressed as power of two ; Function to check if x is power of 2 ; First x in the below expression is for the case when x is 0 ; Function to Count unordered pairs ; is a number can be expressed as power of two ; count total number of unordered pairs ; Driver code"
How can the above be solved in Java?

import java . io . * ; class GFG { static boolean isPowerOfTwo ( int x ) { return ( x > 0 && ( ! ( ( x & ( x - 1 ) ) > 0 ) ) ) ; } static void Count_pairs ( int a [ ] , int n ) { int count = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( isPowerOfTwo ( a [ i ] ) ) count ++ ; } int ans = ( count * ( count - 1 ) ) / 2 ; System . out . println ( ans ) ; } public static void main ( String [ ] args ) { int a [ ] = { 2 , 5 , 8 , 16 , 128 } ; int n = a . length ; Count_pairs ( a , n ) ; } }


"Count unordered pairs of equal elements for all subarrays | Java program for the above approach ; Function to count all pairs ( i , j ) such that arr [ i ] equals arr [ j ] in all possible subarrays of the array ; Stores the size of the array ; Stores the positions of all the distinct elements ; Append index corresponding to arr [ i ] in the map ; Traverse the map M ; Traverse the array ; Update the value of ans ; Update the value of the sum ; Print the value of ans ; Driver Code"
How can the above be solved in Java?

import java . io . * ; import java . util . * ; import java . util . List ; import com . google . common . collect . * ; class GFG { static void countPairs ( int [ ] arr ) { int N = arr . length ; int ans = 0 ; ListMultimap < Integer , Integer > M = ArrayListMultimap . create ( ) ; for ( int i = 0 ; i < arr . length ; i ++ ) { M . put ( arr [ i ] , i ) ; } for ( var it : M . keySet ( ) ) { List < Integer > v = M . get ( it ) ; int sum = 0 ; for ( int j : v ) { ans += sum * ( N - j ) ; sum += j + 1 ; } } System . out . println ( ans ) ; } public static void main ( String [ ] args ) { int [ ] arr = { 1 , 2 , 1 , 1 } ; countPairs ( arr ) ; } }


"Count unset bits in a range | Java implementation to count unset bits in the given range ; Function to get no of set bits in the binary representation of ' n ' ; function to count unset bits in the given range ; calculating a number ' num ' having ' r ' number of bits and bits in the range l to r are the only set bits ; returns number of unset bits in the range ' l ' to ' r ' in ' n ' ; Driver code"
How can the above be solved in Java?

class GFG { static int countSetBits ( int n ) { int count = 0 ; while ( n > 0 ) { n &= ( n - 1 ) ; count ++ ; } return count ; } static int countUnsetBitsInGivenRange ( int n , int l , int r ) { int num = ( ( 1 << r ) - 1 ) ^ ( ( 1 << ( l - 1 ) ) - 1 ) ; return ( r - l + 1 ) - countSetBits ( n & num ) ; } public static void main ( String [ ] args ) { int n = 80 ; int l = 1 , r = 4 ; System . out . print ( countUnsetBitsInGivenRange ( n , l , r ) ) ; } }


"Count unset bits of a number | An optimized Java program to count unset bits in an integer . ; This makes sure two bits ( From MSB and including MSB ) are set ; This makes sure 4 bits ( From MSB and including MSB ) are set ; Count set bits in toggled number ; Driver code"
How can the above be solved in Java?

class GFG { static int countUnsetBits ( int n ) { int x = n ; n |= n >> 1 ; n |= n >> 2 ; n |= n >> 4 ; n |= n >> 8 ; n |= n >> 16 ; return Integer . bitCount ( x ^ n ) ; } public static void main ( String [ ] args ) { int n = 17 ; System . out . println ( countUnsetBits ( n ) ) ; } }


"Count valid pairs in the array satisfying given conditions | Java implementation of the approach ; Function to return total valid pairs ; Initialize count of all the elements ; frequency count of all the elements ; Add total valid pairs ; Exclude pairs made with a single element i . e . ( x , x ) ; Driver Code ; Function call to print required answer"
How can the above be solved in Java?

class GFG { static int ValidPairs ( int arr [ ] , int n ) { int [ ] count = new int [ 121 ] ; for ( int i = 0 ; i < n ; i ++ ) count [ arr [ i ] ] += 1 ; int ans = 0 ; for ( int i = 0 ; i < n ; i ++ ) for ( int j = 0 ; j < n ; j ++ ) { if ( arr [ i ] < arr [ j ] ) continue ; if ( Math . abs ( arr [ i ] - arr [ j ] ) % 2 == 1 ) continue ; ans += count [ arr [ i ] ] * count [ arr [ j ] ] ; if ( arr [ i ] == arr [ j ] ) ans -= count [ arr [ i ] ] ; } return ans ; } public static void main ( String [ ] args ) { int arr [ ] = { 16 , 17 , 18 } ; int n = arr . length ; System . out . println ( ValidPairs ( arr , n ) ) ; } }


"Count ways to build street under given constraints | Java program of above approach ; Program to count ways ; Iterate from 2 to n ; Driver code ; Count Ways"
How can the above be solved in Java?

import java . io . * ; class GFG { static int countways ( int n ) { int [ ] A = new int [ n + 1 ] ; A [ 0 ] = 1 ; A [ 1 ] = 3 ; A [ 2 ] = 7 ; for ( int i = 2 ; i <= n ; i ++ ) { A [ i ] = 2 * A [ i - 1 ] + A [ i - 2 ] ; } return A [ n ] ; } public static void main ( String [ ] args ) { int n = 5 ; System . out . println ( countways ( 5 ) ) ; } }


"Count ways to build street under given constraints | Java program to count ways to build street under given constraints ; function to count ways of building a street of n rows ; base case ; ways of building houses in both the spots of ith row ; ways of building an office in one of the two spots of ith row ; total ways for n rows ; driver program for checking above function"
How can the above be solved in Java?

public class GFG { static long countWays ( int n ) { long dp [ ] [ ] = new long [ 2 ] [ n + 1 ] ; dp [ 0 ] [ 1 ] = 1 ; dp [ 1 ] [ 1 ] = 2 ; for ( int i = 2 ; i <= n ; i ++ ) { dp [ 0 ] [ i ] = dp [ 0 ] [ i - 1 ] + dp [ 1 ] [ i - 1 ] ; dp [ 1 ] [ i ] = dp [ 0 ] [ i - 1 ] * 2 + dp [ 1 ] [ i - 1 ] ; } return dp [ 0 ] [ n ] + dp [ 1 ] [ n ] ; } public static void main ( String [ ] args ) { int n = 5 ; System . out . print ( " Total ▁ no ▁ of ▁ ways ▁ with ▁ n ▁ = ▁ " + n + " ▁ are : ▁ " + countWays ( n ) ) ; } }


"Count ways to distribute exactly one coin to each worker | Java program for the above approach ; Function to find number of way to distribute coins giving exactly one coin to each person ; Sort the given arrays ; Start from bigger salary ; Increment the amount ; Reduce amount of valid coins by one each time ; Return the result ; Driver code ; Given two arrays ; Function Call"
How can the above be solved in Java?

import java . util . * ; class GFG { static int MOD = 1000000007 ; static int solve ( Vector < Integer > values , Vector < Integer > salary ) { int ret = 1 ; int amt = 0 ; Collections . sort ( values ) ; Collections . sort ( salary ) ; while ( salary . size ( ) > 0 ) { while ( values . size ( ) > 0 && values . get ( values . size ( ) - 1 ) >= salary . get ( salary . size ( ) - 1 ) ) { amt ++ ; values . remove ( values . size ( ) - 1 ) ; } if ( amt == 0 ) return 0 ; ret *= amt -- ; ret %= MOD ; salary . remove ( salary . size ( ) - 1 ) ; } return ret ; } public static void main ( String [ ] args ) { Vector < Integer > values = new Vector < Integer > ( ) ; values . add ( 1 ) ; values . add ( 2 ) ; Vector < Integer > salary = new Vector < Integer > ( ) ; salary . add ( 2 ) ; System . out . print ( solve ( values , salary ) ) ; } }


"Count ways to distribute m items among n people | Java code for calculating number of ways to distribute m mangoes amongst n people where all mangoes and people are identical ; function used to generate binomial coefficient time complexity O ( m ) ; helper function for generating no of ways to distribute m mangoes amongst n people ; not enough mangoes to be distributed ; ways -> ( n + m - 1 ) C ( n - 1 ) ; Driver function ; m represents number of mangoes n represents number of people"
How can the above be solved in Java?

import java . util . * ; class GFG { public static int binomial_coefficient ( int n , int m ) { int res = 1 ; if ( m > n - m ) m = n - m ; for ( int i = 0 ; i < m ; ++ i ) { res *= ( n - i ) ; res /= ( i + 1 ) ; } return res ; } public static int calculate_ways ( int m , int n ) { if ( m < n ) { return 0 ; } int ways = binomial_coefficient ( n + m - 1 , n - 1 ) ; return ways ; } public static void main ( String [ ] args ) { int m = 7 , n = 5 ; int result = calculate_ways ( m , n ) ; System . out . println ( Integer . toString ( result ) ) ; System . exit ( 0 ) ; } }


"Count ways to divide C in two parts and add to A and B to make A strictly greater than B | Java implementation of the above approach ; Function to count the number of ways to divide C into two parts and add to A and B such that A is strictly greater than B ; Minimum value added to A to satisfy the given relation ; Number of different values of A , i . e . , number of ways to divide C ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { static int countWays ( int A , int B , int C ) { int minAddA = Math . max ( 0 , ( C + B - A + 2 ) / 2 ) ; int count_ways = Math . max ( C - minAddA + 1 , 0 ) ; return count_ways ; } public static void main ( String args [ ] ) { int A = 3 , B = 5 , C = 5 ; System . out . println ( countWays ( A , B , C ) ) ; } }


"Count ways to divide circle using N non | Java code to count ways to divide circle using N non - intersecting chords . ; n = no of points required ; dp array containing the sum ; returning the required number ; Driver function"
How can the above be solved in Java?

import java . io . * ; class GFG { static int chordCnt ( int A ) { int n = 2 * A ; int [ ] dpArray = new int [ n + 1 ] ; dpArray [ 0 ] = 1 ; dpArray [ 2 ] = 1 ; for ( int i = 4 ; i <= n ; i += 2 ) { for ( int j = 0 ; j < i - 1 ; j += 2 ) { dpArray [ i ] += ( dpArray [ j ] * dpArray [ i - 2 - j ] ) ; } } return dpArray [ n ] ; } public static void main ( String [ ] args ) { int N ; N = 2 ; System . out . println ( chordCnt ( N ) ) ; N = 1 ; System . out . println ( chordCnt ( N ) ) ; N = 4 ; System . out . println ( chordCnt ( N ) ) ; } }