"Count all numbers up to N having M as the last digit | Java program to implement the above approach ; Function to count the numbers ending with M ; Stores the count of numbers required ; Calculate count upto nearest power of 10 ; Computing the value of x ; Adding the count of numbers ending at M from x to N ; Driver Code ; Function call"
How can the above be solved in Java?

import java . util . * ; class GFG { static int getCount ( int N , int M ) { int total_count = 0 ; total_count += ( N / 10 ) ; int x = ( N / 10 ) * 10 ; if ( ( N - x ) >= M ) { total_count = total_count + 1 ; } return total_count ; } public static void main ( String [ ] args ) { int N = 100 , M = 1 ; System . out . print ( getCount ( N , M ) ) ; } }


"Count all pairs of an array which differ in K bits | Below is Java approach of finding total k bit difference pairs ; Function to calculate K bit different pairs in array ; Get the maximum value among all array elemensts ; Set the count array to 0 , count [ ] stores the total frequency of array elements ; Initialize result ; For 0 bit answer will be total count of same number ; if count [ i ] is 0 , skip the next loop as it will not contribute the answer ; Update answer if k differ bit found ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { static long kBitDifferencePairs ( int arr [ ] , int n , int k ) { int MAX = Arrays . stream ( arr ) . max ( ) . getAsInt ( ) ; long [ ] count = new long [ MAX + 1 ] ; Arrays . fill ( count , 0 ) ; for ( int i = 0 ; i < n ; ++ i ) ++ count [ arr [ i ] ] ; long ans = 0 ; if ( k == 0 ) { for ( int i = 0 ; i <= MAX ; ++ i ) ans += ( count [ i ] * ( count [ i ] - 1 ) ) / 2 ; return ans ; } for ( int i = 0 ; i <= MAX ; ++ i ) { if ( count [ i ] == 0 ) continue ; for ( int j = i + 1 ; j <= MAX ; ++ j ) { if ( Integer . bitCount ( i ^ j ) == k ) ans += count [ i ] * count [ j ] ; } } return ans ; } public static void main ( String [ ] args ) { int k = 2 ; int arr [ ] = { 2 , 4 , 1 , 3 , 1 } ; int n = arr . length ; System . out . println ( " Total ▁ pairs ▁ for ▁ k ▁ = ▁ " + k + " ▁ are ▁ = ▁ " + kBitDifferencePairs ( arr , n , k ) ) ; k = 3 ; System . out . println ( " Total ▁ pairs ▁ for ▁ k ▁ = ▁ " + k + " ▁ are ▁ = ▁ " + kBitDifferencePairs ( arr , n , k ) ) ; } }


"Count all pairs of an array which differ in K bits | Java program to count all pairs with bit difference as k ; Utility function to count total ones in a number ; Function to count pairs of K different bits ; long ans = 0 ; initialize final answer ; Check for K differ bit ; Driver code"
How can the above be solved in Java?

 import java . io . * ; class GFG { static int bitCount ( int n ) { int count = 0 ; while ( n > 0 ) { if ( ( n & 1 ) > 0 ) ++ count ; n >>= 1 ; } return count ; } static long countPairsWithKDiff ( int arr [ ] , int n , int k ) { for ( int i = 0 ; i < n - 1 ; ++ i ) { for ( int j = i + 1 ; j < n ; ++ j ) { int xoredNum = arr [ i ] ^ arr [ j ] ; if ( k == bitCount ( xoredNum ) ) ++ ans ; } } return ans ; } public static void main ( String [ ] args ) { int k = 2 ; int arr [ ] = { 2 , 4 , 1 , 3 , 1 } ; int n = arr . length ; System . out . println ( " Total ▁ pairs ▁ for ▁ k ▁ = ▁ " + k + " ▁ are ▁ " + countPairsWithKDiff ( arr , n , k ) + "
"); } }


"Count all pairs of divisors of a number N whose sum is coprime with N | Java program to count all pairs of divisors such that their sum is coprime with N ; Function to calculate GCD ; Function to count all valid pairs ; Initialize count ; Check if sum of pair and n are coprime ; Return the result ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { public static int gcd ( int a , int b ) { if ( b == 0 ) return a ; return ( gcd ( b , a % b ) ) ; } public static int CountPairs ( int n ) { int cnt = 0 ; for ( int i = 1 ; i * i <= n ; i ++ ) { if ( n % i == 0 ) { int div1 = i ; int div2 = n / i ; int sum = div1 + div2 ; if ( gcd ( sum , n ) == 1 ) cnt += 1 ; } } return cnt ; } public static void main ( String [ ] args ) { int n = 24 ; System . out . println ( CountPairs ( n ) ) ; } }


"Count all pairs with given XOR | Java program to Count all pair with given XOR value x ; Returns count of pairs in arr [ 0. . n - 1 ] with XOR value equals to x . ; create empty map that stores counts of individual elements of array . ; If there exist an element in map m with XOR equals to x ^ arr [ i ] , that means there exist an element such that the XOR of element with arr [ i ] is equal to x , then increment count . ; Increment count of current element ; return total count of pairs with XOR equal to x ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { static int xorPairCount ( int arr [ ] , int n , int x ) { Map < Integer , Integer > m = new HashMap < > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { int curr_xor = x ^ arr [ i ] ; if ( m . containsKey ( curr_xor ) ) result += m . get ( curr_xor ) ; if ( m . containsKey ( arr [ i ] ) ) { m . put ( arr [ i ] , m . get ( arr [ i ] ) + 1 ) ; } else { m . put ( arr [ i ] , 1 ) ; } } return result ; } public static void main ( String [ ] args ) { int arr [ ] = { 2 , 5 , 2 } ; int n = arr . length ; int x = 0 ; System . out . println ( " Count ▁ of ▁ pairs ▁ with ▁ given ▁ XOR ▁ = ▁ " + xorPairCount ( arr , n , x ) ) ; } }


"Count all pairs with given XOR | Java program to Count all pair with given XOR value x ; Returns count of pairs in arr [ 0. . n - 1 ] with XOR value equals to x . ; create empty set that stores the visiting element of array . Refer below post for details of unordered_set https : www . geeksforgeeks . org / unorderd_set - stl - uses / ; If there exist an element in set s with XOR equals to x ^ arr [ i ] , that means there exist an element such that the XOR of element with arr [ i ] is equal to x , then increment count . ; Make element visited ; return total count of pairs with XOR equal to x ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { static int xorPairCount ( int arr [ ] , int n , int x ) { HashSet < Integer > s = new HashSet < Integer > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( s . contains ( x ^ arr [ i ] ) && ( x ^ arr [ i ] ) == ( int ) s . toArray ( ) [ s . size ( ) - 1 ] ) { result ++ ; } s . add ( arr [ i ] ) ; } return result ; } public static void main ( String [ ] args ) { int arr [ ] = { 5 , 4 , 10 , 15 , 7 , 6 } ; int n = arr . length ; int x = 5 ; System . out . print ( " Count ▁ of ▁ pairs ▁ with ▁ given ▁ XOR ▁ = ▁ " + xorPairCount ( arr , n , x ) ) ; } }


"Count all palindrome which is square of a palindrome | Java implementation of the above approach ; check if a number is a palindrome ; Function to return required count of palindromes ; Upper limit ; count odd length palindromes ; if s = '1234' ; then , t = '1234321' ; count even length palindromes ; if s = '1234' ; then , t = '12344321' ; Return count of super - palindromes ; Driver program ; function call to get required answer"
How can the above be solved in Java?

import java . lang . * ; class GFG { public static boolean ispalindrome ( int x ) { int ans = 0 ; int temp = x ; while ( temp > 0 ) { ans = 10 * ans + temp % 10 ; temp = temp / 10 ; } return ans == x ; } public static int SuperPalindromes ( int L , int R ) { int LIMIT = 100000 ; int ans = 0 ; for ( int i = 0 ; i < LIMIT ; i ++ ) { String s = Integer . toString ( i ) ; StringBuilder rs = new StringBuilder ( ) ; rs . append ( s . substring ( 0 , Math . max ( 1 , s . length ( ) - 1 ) ) ) ; String srs = rs . reverse ( ) . toString ( ) ; String p = s + srs ; int p_sq = ( int ) ( Math . pow ( Integer . parseInt ( p ) , 2 ) ) ; if ( p_sq > R ) { break ; } if ( p_sq >= L && ispalindrome ( p_sq ) ) { ans = ans + 1 ; } } for ( int i = 0 ; i < LIMIT ; i ++ ) { String s = Integer . toString ( i ) ; StringBuilder rs = new StringBuilder ( ) ; rs . append ( s ) ; rs = rs . reverse ( ) ; String p = s + rs ; int p_sq = ( int ) ( Math . pow ( Integer . parseInt ( p ) , 2 ) ) ; if ( p_sq > R ) { break ; } if ( p_sq >= L && ispalindrome ( p_sq ) ) { ans = ans + 1 ; } } return ans ; } public static void main ( String [ ] args ) { String L = "4" ; String R = "1000" ; System . out . println ( SuperPalindromes ( Integer . parseInt ( L ) , Integer . parseInt ( R ) ) ) ; } }


"Count all perfect divisors of a number | Java code to count total perfect Divisors ; Utility function to check perfect square number ; Returns count all perfect divisors of n ; Initialize result ; Consider every number that can be a divisor of n ; If i is a divisor ; Driver code"
How can the above be solved in Java?

import java . io . * ; class GFG { static boolean isPerfectSquare ( int n ) { int sq = ( int ) Math . sqrt ( n ) ; return ( n == sq * sq ) ; } static int countPerfectDivisors ( int n ) { int count = 0 ; for ( int i = 1 ; i * i <= n ; ++ i ) { if ( n % i == 0 ) { if ( isPerfectSquare ( i ) ) ++ count ; if ( n / i != i && isPerfectSquare ( n / i ) ) ++ count ; } } return count ; } public static void main ( String [ ] args ) { int n = 16 ; System . out . print ( " Total ▁ perfect ▁ " + " divisors ▁ of ▁ " + n ) ; System . out . println ( " ▁ = ▁ " + countPerfectDivisors ( n ) ) ; n = 12 ; System . out . print ( " Total ▁ perfect ▁ " + " divisors ▁ of ▁ " + n ) ; System . out . println ( " ▁ = ▁ " + countPerfectDivisors ( n ) ) ; } }


"Count all perfect divisors of a number | Java code to count total perfect divisors ; Pre - compute counts of all perfect divisors of all numbers upto MAX . ; Iterate through all the multiples of i * i ; Increment all such multiples by 1 ; Returns count of perfect divisors of n . ; Driver code"
How can the above be solved in Java?

class GFG { static int MAX = 100001 ; static int [ ] perfectDiv = new int [ MAX ] ; static void precomputeCounts ( ) { for ( int i = 1 ; i * i < MAX ; ++ i ) { for ( int j = i * i ; j < MAX ; j += i * i ) ++ perfectDiv [ j ] ; } } static int countPerfectDivisors ( int n ) { return perfectDiv [ n ] ; } public static void main ( String [ ] args ) { precomputeCounts ( ) ; int n = 16 ; System . out . println ( " Total ▁ perfect ▁ divisors ▁ of ▁ " + n + " ▁ = ▁ " + countPerfectDivisors ( n ) ) ; n = 12 ; System . out . println ( " Total ▁ perfect ▁ divisors ▁ of ▁ " + n + " ▁ = ▁ " + countPerfectDivisors ( n ) ) ; } }


"Count all possible N digit numbers that satisfy the given condition | Java implementation of above approach ; Function to return the count of required numbers ; If N is odd then return 0 ; Driver Code"
How can the above be solved in Java?

class GFG { static String getCount ( int N ) { if ( N % 2 == 1 ) return "0" ; String result = "9" ; for ( int i = 1 ; i <= N / 2 - 1 ; i ++ ) result += "0" ; return result ; } public static void main ( String [ ] args ) { int N = 4 ; System . out . println ( getCount ( N ) ) ; } }


"Count all possible N | Java program for the above approach ; Function to find the number of vowel permutations possible ; To avoid the large output value ; Initialize 2D dp array ; Initialize dp [ 1 ] [ i ] as 1 since string of length 1 will consist of only one vowel in the string ; Directed graph using the adjacency matrix ; Iterate over the range [ 1 , N ] ; Traverse the directed graph ; Traversing the list ; Update dp [ i + 1 ] [ u ] ; Stores total count of permutations ; Return count of permutations ; Driver Code"
How can the above be solved in Java?

import java . io . * ; import java . util . * ; class GFG { public static int countVowelPermutation ( int n ) { int MOD = ( int ) ( 1e9 + 7 ) ; long [ ] [ ] dp = new long [ n + 1 ] [ 5 ] ; for ( int i = 0 ; i < 5 ; i ++ ) { dp [ 1 ] [ i ] = 1 ; } int [ ] [ ] relation = new int [ ] [ ] { { 1 } , { 0 , 2 } , { 0 , 1 , 3 , 4 } , { 2 , 4 } , { 0 } } ; for ( int i = 1 ; i < n ; i ++ ) { for ( int u = 0 ; u < 5 ; u ++ ) { dp [ i + 1 ] [ u ] = 0 ; for ( int v : relation [ u ] ) { dp [ i + 1 ] [ u ] += dp [ i ] [ v ] % MOD ; } } } long ans = 0 ; for ( int i = 0 ; i < 5 ; i ++ ) { ans = ( ans + dp [ n ] [ i ] ) % MOD ; } return ( int ) ans ; } public static void main ( String [ ] args ) { int N = 2 ; System . out . println ( countVowelPermutation ( N ) ) ; } }


"Count all possible paths from top left to bottom right of a Matrix without crossing the diagonal | Java Program to implement the above approach ; Function to calculate Binomial Coefficient C ( n , r ) ; C ( n , r ) = C ( n , n - r ) ; [ n * ( n - 1 ) * -- - * ( n - r + 1 ) ] / [ r * ( r - 1 ) * -- -- * 1 ] ; Function to calculate the total possible paths ; Update n to n - 1 as ( N - 1 ) catalan number is the result ; Stores 2 nCn ; Stores Nth Catalan number ; Stores the required answer ; Driver Code"
How can the above be solved in Java?

import java . util . * ; class GFG { static int binCoff ( int n , int r ) { int val = 1 ; int i ; if ( r > ( n - r ) ) { r = ( n - r ) ; } for ( i = 0 ; i < r ; i ++ ) { val *= ( n - i ) ; val /= ( i + 1 ) ; } return val ; } static int findWays ( int n ) { n -- ; int a , b , ans ; a = binCoff ( 2 * n , n ) ; b = a / ( n + 1 ) ; ans = b ; return ans ; } public static void main ( String [ ] args ) { int n = 4 ; System . out . print ( findWays ( n ) ) ; } }


"Count all possible paths from top left to bottom right of a mXn matrix | A Java program to count all possible paths from top left to bottom right ; Returns count of possible paths to reach cell at row number m and column number n from the topmost leftmost cell ( cell at 1 , 1 ) ; Create a 2D table to store results of subproblems ; Count of paths to reach any cell in first column is 1 ; Count of paths to reach any cell in first column is 1 ; Calculate count of paths for other cells in bottom - up manner using the recursive solution ; By uncommenting the last part the code calculates the total possible paths if the diagonal Movements are allowed ; Driver program to test above function"
How can the above be solved in Java?

class GFG { static int numberOfPaths ( int m , int n ) { int count [ ] [ ] = new int [ m ] [ n ] ; for ( int i = 0 ; i < m ; i ++ ) count [ i ] [ 0 ] = 1 ; for ( int j = 0 ; j < n ; j ++ ) count [ 0 ] [ j ] = 1 ; for ( int i = 1 ; i < m ; i ++ ) { for ( int j = 1 ; j < n ; j ++ ) count [ i ] [ j ] = count [ i - 1 ] [ j ] + count [ i ] [ j - 1 ] ; + count [ i - 1 ] [ j - 1 ] ; } return count [ m - 1 ] [ n - 1 ] ; } public static void main ( String args [ ] ) { System . out . println ( numberOfPaths ( 3 , 3 ) ) ; } }


"Count all possible paths from top left to bottom right of a mXn matrix | A Java program to count all possible paths from top left to bottom right ; Returns count of possible paths to reach cell at row number m and column number n from the topmost leftmost cell ( cell at 1 , 1 ) ; If either given row number is first or given column number is first ; If diagonal movements are allowed then the last addition is required . ; Driver Code"
How can the above be solved in Java?

class GFG { static int numberOfPaths ( int m , int n ) { if ( m == 1 n == 1 ) return 1 ; return numberOfPaths ( m - 1 , n ) + numberOfPaths ( m , n - 1 ) ; } public static void main ( String args [ ] ) { System . out . println ( numberOfPaths ( 3 , 3 ) ) ; } }


"Count all possible paths from top left to bottom right of a mXn matrix | Java program to count all possible paths from top left to top bottom using combinatorics ; We have to calculate m + n - 2 C n - 1 here which will be ( m + n - 2 ) ! / ( n - 1 ) ! ( m - 1 ) ! ; Driver code"
How can the above be solved in Java?

class GFG { static int numberOfPaths ( int m , int n ) { int path = 1 ; for ( int i = n ; i < ( m + n - 1 ) ; i ++ ) { path *= i ; path /= ( i - n + 1 ) ; } return path ; } public static void main ( String [ ] args ) { System . out . println ( numberOfPaths ( 3 , 3 ) ) ; } }


"Count all possible paths from top left to bottom right of a mXn matrix | Returns count of possible paths to reach cell at row number m and column number n from the topmost leftmost cell ( cell at 1 , 1 ) ; Create a 1D array to store results of subproblems ; Driver program to test above function"
How can the above be solved in Java?

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


"Count all possible strings that can be generated by placing spaces | Java program to implement the above approach ; Function to count the number of strings that can be generated by placing spaces between pair of adjacent characters ; Count of positions for spaces ; Count of possible strings ; Driver Code"
How can the above be solved in Java?

import java . io . * ; class GFG { static long countNumberOfStrings ( String s ) { int n = s . length ( ) - 1 ; long count = ( long ) ( Math . pow ( 2 , n ) ) ; return count ; } public static void main ( String [ ] args ) { String S = " ABCD " ; System . out . println ( countNumberOfStrings ( S ) ) ; } }


"Count all possible unique sum of series K , K + 1 , K + 2 , K + 3 , K + 4 , ... , K + N | Java program for the above approach ; Function to count the unique sum ; Initialize array fsum [ ] with 0 ; Initialize array rsum [ ] with 0 ; Set fsum [ 0 ] as ar [ 0 ] ; Set rsum [ 0 ] as ar [ n ] ; For each i update fsum [ i ] with ar [ i ] + fsum [ i - 1 ] ; For each i from n - 1 , update rsum [ i ] with ar [ i ] + fsum [ i + 1 ] ; K represent size of subset as explained above ; Using above relation ; Return the result ; Driver Code ; Given a number N ; Function Call"
How can the above be solved in Java?

import java . util . * ; class GFG { static int count_unique_sum ( int n ) { int i ; int ar [ ] = new int [ n + 1 ] ; int fsum [ ] = new int [ n + 1 ] ; int rsum [ ] = new int [ n + 1 ] ; int ans = 1 ; Arrays . fill ( fsum , 0 ) ; Arrays . fill ( rsum , 0 ) ; for ( i = 0 ; i <= n ; i ++ ) { ar [ i ] = i ; } fsum [ 0 ] = ar [ 0 ] ; rsum [ n ] = ar [ n ] ; for ( i = 1 ; i <= n ; i ++ ) { fsum [ i ] = ar [ i ] + fsum [ i - 1 ] ; } for ( i = n - 1 ; i >= 0 ; i -- ) { rsum [ i ] = ar [ i ] + rsum [ i + 1 ] ; } for ( int k = 2 ; k <= n ; k ++ ) { ans += 1 + rsum [ n + 1 - k ] - fsum [ k - 1 ] ; } return ans ; } public static void main ( String [ ] args ) { int N = 4 ; System . out . print ( count_unique_sum ( N ) ) ; } }


"Count all possible values of K less than Y such that GCD ( X , Y ) = GCD ( X + K , Y ) | Java program for the above approach ; Function to find the gcd of a and b ; Function to find the number of Ks ; Find gcd ; Calculating value of totient function for n ; Driver Code ; Given X and Y"
How can the above be solved in Java?

 import java . util . * ; class GFG { static int gcd ( int a , int b ) { if ( b == 0 ) return a ; return gcd ( b , a % b ) ; } static int calculateK ( int x , int y ) { int g = gcd ( x , y ) ; int n = y / g ; int res = n ; for ( int i = 2 ; i * i <= n ; i ++ ) { if ( n % i == 0 ) { res -= ( res / i ) ; while ( n % i == 0 ) n /= i ; } } if ( n != 1 ) res -= ( res / n ) ; return res ; } public static void main ( String [ ] args ) { int x = 3 , y = 15 ; System . out . print ( calculateK ( x , y ) + "
"); } }


"Count all prefixes of the given binary array which are divisible by x | Java implementation of the approach ; Function to return the count of total binary prefix which are divisible by x ; Initialize with zero ; Convert all prefixes to decimal ; If number is divisible by x then increase count ; Driver Code"
How can the above be solved in Java?

class GfG { static int CntDivbyX ( int arr [ ] , int n , int x ) { int number = 0 ; int count = 0 ; for ( int i = 0 ; i < n ; i ++ ) { number = number * 2 + arr [ i ] ; if ( ( number % x == 0 ) ) count += 1 ; } return count ; } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 0 , 1 , 0 , 1 , 1 , 0 } ; int n = arr . length ; int x = 2 ; System . out . println ( CntDivbyX ( arr , n , x ) ) ; } }


"Count all prefixes of the given binary array which are divisible by x | Java implementation of the approach ; Function to return the count of total binary prefix which are divisible by x ; Initialize with zero ; Instead of converting all prefixes to decimal , take reminder with x ; If number is divisible by x then reminder = 0 ; Driver code"
How can the above be solved in Java?

class GFG { public static int CntDivbyX ( int arr [ ] , int n , int x ) { int number = 0 ; int count = 0 ; for ( int i = 0 ; i < n ; i ++ ) { number = ( number * 2 + arr [ i ] ) % x ; if ( number == 0 ) count += 1 ; } return count ; } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 0 , 1 , 0 , 1 , 1 , 0 } ; int n = 7 ; int x = 2 ; System . out . print ( CntDivbyX ( arr , n , x ) ) ; } }


"Count all prime numbers in a given range whose sum of digits is also prime | Java program for the above approach ; Create an array for storing primes ; Create a prefix array that will contain whether sum is prime or not ; Function to find primes in the range and check whether the sum of digits of a prime number is prime or not ; Initialise Prime array arr [ ] ; Since 0 and 1 are not prime numbers we mark them as '0' ; Using Sieve Of Eratosthenes ; if the number is prime ; Mark all the multiples of i starting from square of i with '0' ie . composite ; '0' represents not prime ; Initialise a sum variable as 0 ; Check if the number is prime ; A temporary variable to store the number ; Loop to calculate the sum of digits ; Check if the sum of prime number is prime ; if prime mark 1 ; If not prime mark 0 ; computing prefix array ; Function to count the prime numbers in the range [ L , R ] ; Function Call to find primes ; Print the result ; Driver Code ; Input range ; Function Call"
How can the above be solved in Java?

 class GFG { static int maxN = 1000000 ; static int [ ] arr = new int [ 1000001 ] ; static int [ ] prefix = new int [ 1000001 ] ; static void findPrimes ( ) { for ( int i = 1 ; i <= maxN ; i ++ ) arr [ i ] = 1 ; arr [ 0 ] = 0 ; arr [ 1 ] = 0 ; for ( int i = 2 ; i * i <= maxN ; i ++ ) { if ( arr [ i ] == 1 ) { for ( int j = i * i ; j <= maxN ; j += i ) { arr [ j ] = 0 ; } } } int sum = 0 ; prefix [ 0 ] = 0 ; for ( int i = 1 ; i <= maxN ; i ++ ) { if ( arr [ i ] == 1 ) { int temp = i ; sum = 0 ; while ( temp > 0 ) { int x = temp % 10 ; sum += x ; temp = temp / 10 ; if ( arr [ sum ] == 1 ) { prefix [ i ] = 1 ; } else { prefix [ i ] = 0 ; } } } } for ( int i = 1 ; i <= maxN ; i ++ ) { prefix [ i ] += prefix [ i - 1 ] ; } } static void countNumbersInRange ( int l , int r ) { findPrimes ( ) ; int result = prefix [ r ] - prefix [ l - 1 ] ; System . out . print ( result + "
"); } public static void main ( String [ ] args ) { int l , r ; l = 5 ; r = 20 ; countNumbersInRange ( l , r ) ; } }


"Count all sorted rows in a matrix | Java program to find number of sorted rows ; Function to count all sorted rows in a matrix ; Initialize result ; Start from left side of matrix to count increasing order rows ; Check if there is any pair ofs element that are not in increasing order . ; If the loop didn 't break (All elements of current row were in increasing order) ; Start from right side of matrix to count increasing order rows ( reference to left these are in decreasing order ) ; Check if there is any pair ofs element that are not in decreasing order . ; Note c > 1 condition is required to make sure that a single column row is not counted twice ( Note that a single column row is sorted both in increasing and decreasing order ) ; Driver code"
How can the above be solved in Java?

class GFG { static int MAX = 100 ; static int sortedCount ( int mat [ ] [ ] , int r , int c ) { int result = 0 ; for ( int i = 0 ; i < r ; i ++ ) { int j ; for ( j = 0 ; j < c - 1 ; j ++ ) if ( mat [ i ] [ j + 1 ] <= mat [ i ] [ j ] ) break ; if ( j == c - 1 ) result ++ ; } for ( int i = 0 ; i < r ; i ++ ) { int j ; for ( j = c - 1 ; j > 0 ; j -- ) if ( mat [ i ] [ j - 1 ] <= mat [ i ] [ j ] ) break ; if ( c > 1 && j == 0 ) result ++ ; } return result ; } public static void main ( String arg [ ] ) { int m = 4 , n = 5 ; int mat [ ] [ ] = { { 1 , 2 , 3 , 4 , 5 } , { 4 , 3 , 1 , 2 , 6 } , { 8 , 7 , 6 , 5 , 4 } , { 5 , 7 , 8 , 9 , 10 } } ; System . out . print ( sortedCount ( mat , m , n ) ) ; } }


"Count all square sub | Java program to count total number of k x k sub matrix whose sum is greater than the given number S ; Function to create prefix sum matrix from the given matrix ; Store first value in table ; Initialize first row of matrix ; Initialize first column of matrix ; Initialize rest table with sum ; Utility Function to count the submatrix whose sum is greater than the S ; Loop to iterate over all the possible positions of the given matrix mat [ ] [ ] ; Condition to check , if K x K is first sub matrix ; Condition to check sub - matrix has no margin at top ; Condition when sub matrix has no margin at left ; Condition when submatrix has margin at top and left ; Increment count , If sub matrix sum is greater than S ; Function to count submatrix of size k x k such that sum if greater than or equal to S ; For loop to initialize prefix sum matrix with zero , initially ; Function to create the prefix sum matrix ; Driver Code ; Print total number of sub matrix"
How can the above be solved in Java?

import java . util . * ; class GFG { static final int dim = 5 ; static void createTable ( int mtrx [ ] [ ] , int k , int p , int dp [ ] [ ] ) { dp [ 0 ] [ 0 ] = mtrx [ 0 ] [ 0 ] ; for ( int j = 1 ; j < dim ; j ++ ) { dp [ 0 ] [ j ] = mtrx [ 0 ] [ j ] + dp [ 0 ] [ j - 1 ] ; } for ( int i = 1 ; i < dim ; i ++ ) { dp [ i ] [ 0 ] = mtrx [ i ] [ 0 ] + dp [ i - 1 ] [ 0 ] ; } for ( int i = 1 ; i < dim ; i ++ ) { for ( int j = 1 ; j < dim ; j ++ ) { dp [ i ] [ j ] = mtrx [ i ] [ j ] + dp [ i - 1 ] [ j ] + dp [ i ] [ j - 1 ] - dp [ i - 1 ] [ j - 1 ] ; } } } static int countSubMatrixUtil ( int dp [ ] [ ] , int k , int p ) { int count = 0 ; int subMatSum = 0 ; for ( int i = k - 1 ; i < dim ; i ++ ) { for ( int j = k - 1 ; j < dim ; j ++ ) { if ( i == ( k - 1 ) || j == ( k - 1 ) ) { if ( i == ( k - 1 ) && j == ( k - 1 ) ) { subMatSum = dp [ i ] [ j ] ; } else if ( i == ( k - 1 ) ) { subMatSum = dp [ i ] [ j ] - dp [ i ] [ j - k ] ; } else { subMatSum = dp [ i ] [ j ] - dp [ i - k ] [ j ] ; } } else { subMatSum = dp [ i ] [ j ] - dp [ i - k ] [ j ] - dp [ i ] [ j - k ] + dp [ i - k ] [ j - k ] ; } if ( subMatSum >= p ) { count ++ ; } } } return count ; } static int countSubMatrix ( int mtrx [ ] [ ] , int k , int p ) { int [ ] [ ] dp = new int [ dim ] [ dim ] ; for ( int i = 0 ; i < dim ; i ++ ) { for ( int j = 0 ; j < dim ; j ++ ) { dp [ i ] [ j ] = 0 ; } } createTable ( mtrx , k , p , dp ) ; return countSubMatrixUtil ( dp , k , p ) ; } public static void main ( String [ ] args ) { int mtrx [ ] [ ] = { { 1 , 7 , 1 , 1 , 1 } , { 2 , 2 , 2 , 2 , 2 } , { 3 , 9 , 6 , 7 , 3 } , { 4 , 3 , 2 , 4 , 5 } , { 5 , 1 , 5 , 3 , 1 } } ; int k = 3 ; int p = 35 ; System . out . print ( countSubMatrix ( mtrx , k , p ) ) ; } }


"Count all sub | Java program to find the count of all the sub - Strings with weight of characters atmost K ; Function to find the count of all the subStrings with weight of characters atmost K ; Hashmap to store all subStrings ; Iterate over all subStrings ; Maintain the sum of all characters encountered so far ; Maintain the subString till the current position ; Get the position of the character in String Q ; Add weight to current sum ; Add current character to subString ; If sum of characters is <= K then insert in into the set ; Finding the size of the set ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { static int distinctSubString ( String P , String Q , int K , int N ) { HashSet < String > S = new HashSet < String > ( ) ; for ( int i = 0 ; i < N ; ++ i ) { int sum = 0 ; String s = " " ; for ( int j = i ; j < N ; ++ j ) { int pos = P . charAt ( j ) - ' a ' ; sum += Q . charAt ( pos ) - '0' ; s += P . charAt ( j ) ; if ( sum <= K ) { S . add ( s ) ; } else { break ; } } } return S . size ( ) ; } public static void main ( String [ ] args ) { String P = " abcde " ; String Q = "12345678912345678912345678" ; int K = 5 ; int N = P . length ( ) ; System . out . print ( distinctSubString ( P , Q , K , N ) ) ; } }


"Count all subarrays whose sum can be split as difference of squares of two Integers | Java program to count all the non - contiguous subarrays whose sum can be split as the difference of the squares ; Function to count all the non - contiguous subarrays whose sum can be split as the difference of the squares ; Loop to iterate over all the possible subsequences of the array ; Finding the sum of all the possible subsequences ; Condition to check whether the number can be split as difference of squares ; Driver Code"
How can the above be solved in Java?

import java . io . * ; import java . lang . * ; import java . util . * ; class GFG { static int Solve ( int arr [ ] , int n ) { int temp = 0 , count = 0 ; for ( int i = 0 ; i < n ; i ++ ) { temp = 0 ; for ( int j = i ; j < n ; j ++ ) { temp += arr [ j ] ; if ( ( temp + 2 ) % 4 != 0 ) count ++ ; } } return count ; } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 } ; int N = arr . length ; System . out . println ( Solve ( arr , N ) ) ; } }


"Count all subsequences having product less than K | Java program to find number of subarrays having product less than k . ; Function to count numbers of such subsequences having product less than k . ; number of subsequence using j - 1 terms ; if arr [ j - 1 ] > i it will surely make product greater thus it won 't contribute  then ; number of subsequence using 1 to j - 1 terms and j - th term ; Driver code"
How can the above be solved in Java?

import java . util . * ; class CountSubsequences { public static int productSubSeqCount ( ArrayList < Integer > arr , int k ) { int n = arr . size ( ) ; int dp [ ] [ ] = new int [ k + 1 ] [ n + 1 ] ; for ( int i = 1 ; i <= k ; i ++ ) { for ( int j = 1 ; j <= n ; j ++ ) { dp [ i ] [ j ] = dp [ i ] [ j - 1 ] ; if ( arr . get ( j - 1 ) <= i && arr . get ( j - 1 ) > 0 ) dp [ i ] [ j ] += dp [ i / arr . get ( j - 1 ) ] [ j - 1 ] + 1 ; } } return dp [ k ] [ n ] ; } public static void main ( String args [ ] ) { ArrayList < Integer > A = new ArrayList < Integer > ( ) ; A . add ( 1 ) ; A . add ( 2 ) ; A . add ( 3 ) ; A . add ( 4 ) ; int k = 10 ; System . out . println ( productSubSeqCount ( A , k ) ) ; } }


"Count all substrings having character K | Java implementation of the approach ; Function to return the index of the next occurrence of character ch in str starting from the given index ; Return the index of the first occurrence of ch ; No occurrence found ; Function to return the count of all the substrings of str which contain the character ch at least one ; To store the count of valid substrings ; Index of the first occurrence of ch in str ; No occurrence of ch after index i in str ; Substrings starting at index i and ending at indices j , j + 1 , ... , n - 1 are all valid substring ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { static int nextOccurrence ( String str , int n , int start , char ch ) { for ( int i = start ; i < n ; i ++ ) { if ( str . charAt ( i ) == ch ) return i ; } return - 1 ; } static int countSubStr ( String str , int n , char ch ) { int cnt = 0 ; int j = nextOccurrence ( str , n , 0 , ch ) ; for ( int i = 0 ; i < n ; i ++ ) { while ( j != - 1 && j < i ) { j = nextOccurrence ( str , n , j + 1 , ch ) ; } if ( j == - 1 ) break ; cnt += ( n - j ) ; } return cnt ; } static public void main ( String [ ] arg ) { String str = " geeksforgeeks " ; int n = str . length ( ) ; char ch = ' k ' ; System . out . println ( countSubStr ( str , n , ch ) ) ; } }


"Count all the numbers in a range with smallest factor as K | Java program to find the count of numbers in a range whose smallest factor is K ; Function to check if k is a prime number or not ; Corner case ; Check from 2 to n - 1 ; Function to check if a number is not divisible by any number between 2 and K - 1 ; to check if the num is divisible by any numbers between 2 and k - 1 ; if not divisible by any number between 2 and k - 1 but divisible by k ; Function to find count of numbers in range [ a , b ] with smallest factor as K ; a number can be divisible only by k and not by any number less than k only if k is a prime ; to check if a number has smallest factor as K ; Driver code"
How can the above be solved in Java?

public class GFG { static boolean isPrime ( int k ) { if ( k <= 1 ) return false ; for ( int i = 2 ; i < k ; i ++ ) if ( k % i == 0 ) return false ; return true ; } static int check ( int num , int k ) { int flag = 1 ; for ( int i = 2 ; i < k ; i ++ ) { if ( num % i == 0 ) flag = 0 ; } if ( flag == 1 ) { if ( num % k == 0 ) return 1 ; else return 0 ; } else return 0 ; } static int findCount ( int a , int b , int k ) { int count = 0 ; if ( ! isPrime ( k ) ) return 0 ; else { int ans ; for ( int i = a ; i <= b ; i ++ ) { ans = check ( i , k ) ; if ( ans == 1 ) count ++ ; else continue ; } } return count ; } public static void main ( String args [ ] ) { int a = 2020 , b = 6300 , k = 29 ; System . out . println ( findCount ( a , b , k ) ) ; } }


"Count all the numbers less than 10 ^ 6 whose minimum prime factor is N | Java implementation of above approach ; the sieve of prime number and count of minimum prime factor ; form the prime sieve ; 1 is not a prime number ; form the sieve ; if i is prime ; if i is the least prime factor ; mark the number j as non prime ; count the numbers whose least prime factor is i ; Driver code ; form the sieve ; display ; display"
How can the above be solved in Java?

import java . io . * ; class GFG { static int MAX = 1000000 ; static int sieve_Prime [ ] = new int [ MAX + 4 ] ; static int sieve_count [ ] = new int [ MAX + 4 ] ; static void form_sieve ( ) { sieve_Prime [ 1 ] = 1 ; for ( int i = 2 ; i <= MAX ; i ++ ) { if ( sieve_Prime [ i ] == 0 ) { for ( int j = i * 2 ; j <= MAX ; j += i ) { if ( sieve_Prime [ j ] == 0 ) { sieve_Prime [ j ] = 1 ; sieve_count [ i ] ++ ; } } } } } public static void main ( String [ ] args ) { form_sieve ( ) ; int n = 2 ; System . out . println ( " Count ▁ = ▁ " + ( sieve_count [ n ] + 1 ) ) ; n = 3 ; System . out . println ( " Count ▁ = ▁ " + ( sieve_count [ n ] + 1 ) ) ; } }


"Count all triplets whose sum is equal to a perfect cube | JAVA Code for Count all triplets whose sum is equal to a perfect cube ; Function to calculate all occurrence of a number in a given range ; if i == 0 assign 1 to present state ; else add + 1 to current state with previous state ; Function to calculate triplets whose sum is equal to the perfect cube ; Initialize answer ; count all occurrence of third triplet in range from j + 1 to n ; Driver program to test above function"
How can the above be solved in Java?

import java . util . * ; class GFG { public static int dp [ ] [ ] ; public static void computeDpArray ( int arr [ ] , int n ) { for ( int i = 0 ; i < n ; ++ i ) { for ( int j = 1 ; j <= 15000 ; ++ j ) { if ( i == 0 && j == arr [ i ] ) dp [ i ] [ j ] = 1 ; else if ( i == 0 ) dp [ i ] [ j ] = 0 ; else if ( arr [ i ] == j ) dp [ i ] [ j ] = dp [ i - 1 ] [ j ] + 1 ; else dp [ i ] [ j ] = dp [ i - 1 ] [ j ] ; } } } public static int countTripletSum ( int arr [ ] , int n ) { computeDpArray ( arr , n ) ; int ans = 0 ; for ( int i = 0 ; i < n - 2 ; ++ i ) { for ( int j = i + 1 ; j < n - 1 ; ++ j ) { for ( int k = 1 ; k <= 24 ; ++ k ) { int cube = k * k * k ; int rem = cube - ( arr [ i ] + arr [ j ] ) ; if ( rem > 0 ) ans += dp [ n - 1 ] [ rem ] - dp [ j ] [ rem ] ; } } } return ans ; } public static void main ( String [ ] args ) { int arr [ ] = { 2 , 5 , 1 , 20 , 6 } ; int n = arr . length ; dp = new int [ 1001 ] [ 15001 ] ; System . out . println ( countTripletSum ( arr , n ) ) ; } }


"Count all unique outcomes possible by performing S flips on N coins | Java program for the above approach ; Dimensions of the DP table ; Stores the dp states ; Function to recursively count the number of unique outcomes possible by performing S flips on N coins ; Base Case ; If the count for the current state is not calculated , then calculate it recursively ; Otherwise return the already calculated value ; Driver Code"
How can the above be solved in Java?

import java . util . * ; class GFG { static int size = 100 ; static int [ ] [ ] ans = new int [ size ] [ size ] ; static void initialize ( ) { for ( int i = 0 ; i < size ; i ++ ) { for ( int j = 0 ; j < size ; j ++ ) { ans [ i ] [ j ] = 0 ; } } } static int numberOfUniqueOutcomes ( int n , int s ) { if ( s < n ) ans [ n ] [ s ] = 0 ; else if ( n == 1 n == s ) ans [ n ] [ s ] = 1 ; else if ( ans [ n ] [ s ] == 0 ) { ans [ n ] [ s ] = numberOfUniqueOutcomes ( n - 1 , s - 1 ) + numberOfUniqueOutcomes ( n - 1 , s - 2 ) ; } return ans [ n ] [ s ] ; } public static void main ( String args [ ] ) { initialize ( ) ; int N = 5 , S = 8 ; System . out . println ( numberOfUniqueOutcomes ( N , S ) ) ; } }


"Count all unique outcomes possible by performing S flips on N coins | Java program for the above approach ; Function to recursively count the number of unique outcomes possible S flips are performed on N coins ; Base Cases ; Recursive Calls ; Driver Code"
How can the above be solved in Java?

import java . io . * ; class GFG { static int numberOfUniqueOutcomes ( int N , int S ) { if ( S < N ) return 0 ; if ( N == 1 N == S ) return 1 ; return ( numberOfUniqueOutcomes ( N - 1 , S - 1 ) + numberOfUniqueOutcomes ( N - 1 , S - 2 ) ) ; } public static void main ( String [ ] args ) { int N = 3 , S = 4 ; System . out . println ( numberOfUniqueOutcomes ( N , S ) ) ; } }


"Count alphanumeric palindromes of length N | Java program for the above approach ; Function to calculate ( x ^ y ) mod p ; Initialize result ; Update x if it is more than or equal to p ; If y is odd , multiply x with result ; y must be even now ; Return the final result ; Driver Code ; Given N ; Base Case ; Check whether n is even or odd ; Function Call ; Function Call"
How can the above be solved in Java?

import java . util . * ; class GFG { static int power ( int x , int y , int p ) { int res = 1 ; x = x % p ; if ( x == 0 ) return 0 ; while ( y > 0 ) { if ( ( y & 1 ) == 1 ) res = ( res * x ) % p ; y = y >> 1 ; x = ( x * x ) % p ; } return res ; } public static void main ( String [ ] args ) { int N = 3 ; int flag , k , m = 0 ; if ( ( N == 1 ) || ( N == 2 ) ) System . out . print ( 62 ) ; else m = 1000000000 + 7 ; if ( N % 2 == 0 ) { k = N / 2 ; flag = 1 ; } else { k = ( N - 1 ) / 2 ; flag = 0 ; } if ( flag != 0 ) { int a = power ( 62 , k , m ) ; System . out . print ( a ) ; } else { int a = power ( 62 , ( k + 1 ) , m ) ; System . out . print ( a ) ; } } }


"Count ancestors with smaller value for each node of a Binary Tree | Java program for the above approach ; Function to add an edge between nodes u and v ; Function to perform the DFS Traversal and store parent of each node ; Store the immediate parent ; Traverse the children of the current node ; Recursively call for function dfs for the child node ; Function to count the number of ancestors with values smaller than that of the current node ; Stores the parent of each node ; Perform the DFS Traversal ; Traverse all the nodes ; Store the number of ancestors smaller than node ; Loop until parent [ node ] != - 1 ; If the condition satisfies , increment cnt by 1 ; Print the required result for the current node ; Driver code ; Tree Formation"
How can the above be solved in Java?

import java . io . * ; import java . util . * ; class GFG { static void add_edge ( ArrayList < ArrayList < Integer > > adj , int u , int v ) { adj . get ( u ) . add ( v ) ; adj . get ( v ) . add ( u ) ; } static void dfs ( ArrayList < Integer > parent , ArrayList < ArrayList < Integer > > adj , int u , int par ) { parent . set ( u , par ) ; for ( int child : adj . get ( u ) ) { if ( child != par ) dfs ( parent , adj , child , u ) ; } } static void countSmallerAncestors ( ArrayList < ArrayList < Integer > > adj , int n ) { ArrayList < Integer > parent = new ArrayList < Integer > ( ) ; for ( int i = 0 ; i < ( int ) ( 1e5 ) ; i ++ ) { parent . add ( 0 ) ; } dfs ( parent , adj , 1 , - 1 ) ; for ( int i = 1 ; i <= n ; i ++ ) { int node = i ; int cnt = 0 ; while ( parent . get ( node ) != - 1 ) { if ( parent . get ( node ) < i ) cnt += 1 ; node = parent . get ( node ) ; } System . out . print ( cnt + " ▁ " ) ; } } public static void main ( String [ ] args ) { int N = 6 ; ArrayList < ArrayList < Integer > > adj = new ArrayList < ArrayList < Integer > > ( ) ; for ( int i = 0 ; i < ( int ) ( 1e5 ) ; i ++ ) { adj . add ( new ArrayList < Integer > ( ) ) ; } add_edge ( adj , 1 , 5 ) ; add_edge ( adj , 1 , 4 ) ; add_edge ( adj , 4 , 6 ) ; add_edge ( adj , 5 , 3 ) ; add_edge ( adj , 5 , 2 ) ; countSmallerAncestors ( adj , N ) ; } }


"Count and Print the alphabets having ASCII value in the range [ l , r ] | Java implementation of the above approach ; Function to count the number of characters whose ascii value is in range [ l , r ] ; Initializing the count to 0 ; Increment the count if the value is less ; return the count ; Driver code"
How can the above be solved in Java?

 import java . util . * ; import java . lang . * ; class GFG { static int CountCharacters ( String str , int l , int r ) { int cnt = 0 ; int len = str . length ( ) ; for ( int i = 0 ; i < len ; i ++ ) { if ( l <= str . charAt ( i ) && str . charAt ( i ) <= r ) { cnt ++ ; System . out . print ( str . charAt ( i ) + " ▁ " ) ; } } return cnt ; } public static void main ( String args [ ] ) { String str = " geeksforgeeks " ; int l = 102 , r = 111 ; System . out . print ( " Characters ▁ with ▁ ASCII ▁ values " + " in the range [l, r] are
"); System . out . print ( " and their count is " + CountCharacters ( str , l , r ) ) ; } }


"Count and Print the alphabets having ASCII value not in the range [ l , r ] | Java implementation of the above approach ; Function to count the number of characters whose ascii value not in range [ l , r ] ; Initializing the count to 0 ; using map to print a character only once ; Increment the count if the value is less ; return the count ; Driver code"
How can the above be solved in Java?

import java . util . * ; class Solution { static int CountCharacters ( String str , int l , int r ) { int cnt = 0 ; Map < Character , Integer > m = new HashMap < Character , Integer > ( ) ; int len = str . length ( ) ; for ( int i = 0 ; i < len ; i ++ ) { if ( ! ( l <= str . charAt ( i ) && str . charAt ( i ) <= r ) ) { cnt ++ ; if ( m . get ( str . charAt ( i ) ) != null ) if ( m . get ( str . charAt ( i ) ) != 1 ) { System . out . print ( str . charAt ( i ) + " ▁ " ) ; m . put ( str . charAt ( i ) , m . get ( str . charAt ( i ) ) == null ? 0 : m . get ( str . charAt ( i ) ) + 1 ) ; } } } return cnt ; } public static void main ( String args [ ] ) { String str = " geeksforgeeks " ; int l = 102 , r = 111 ; System . out . println ( "Characters with ASCII values not in the range [l, r]  in the given string are : "); System . out . println ( " and their count is " + CountCharacters(str, l, r)); } }


"Count and Toggle Queries on a Binary Array | Java program to implement toggle and count queries on a binary array . ; segment tree to store count of 1 's within range ; bool type tree to collect the updates for toggling the values of 1 and 0 in given range ; function for collecting updates of toggling node -- > index of current node in segment tree st -- > starting index of current node en -- > ending index of current node us -- > starting index of range update query ue -- > ending index of range update query ; If lazy value is non - zero for current node of segment tree , then there are some pending updates . So we need to make sure that the pending updates are done before making new updates . Because this value may be used by parent after recursive calls ( See last line of this function ) ; Make pending updates using value stored in lazy nodes ; checking if it is not leaf node because if it is leaf node then we cannot go further ; We can postpone updating children we don ' t ▁ need ▁ their ▁ new ▁ values ▁ now . ▁ ▁ Since ▁ we ▁ are ▁ not ▁ yet ▁ updating ▁ children ▁ ▁ of ▁ ' node ', we need to set lazy flags  for the children ; out of range ; Current segment is fully in range ; Add the difference to current node ; same logic for checking leaf node or not ; This is where we store values in lazy nodes , rather than updating the segment tree itelf Since we don 't need these updated values now  we postpone updates by storing values in lazy[] ; If not completely in rang , but overlaps , recur for children , ; And use the result of children calls to update this node ; function to count number of 1 's within given range ; current node is out of range ; If lazy flag is set for current node of segment tree , then there are some pending updates . So we need to make sure that the pending updates are done before processing the sub sum query ; Make pending updates to this node . Note that this node represents sum of elements in arr [ st . . en ] and all these elements must be increased by lazy [ node ] ; checking if..."
How can the above be solved in Java?

class GFG { static final int MAX = 100000 ; static int tree [ ] = new int [ MAX ] ; static boolean lazy [ ] = new boolean [ MAX ] ; static void toggle ( int node , int st , int en , int us , int ue ) { if ( lazy [ node ] ) { lazy [ node ] = false ; tree [ node ] = en - st + 1 - tree [ node ] ; if ( st < en ) { lazy [ node << 1 ] = ! lazy [ node << 1 ] ; lazy [ 1 + ( node << 1 ) ] = ! lazy [ 1 + ( node << 1 ) ] ; } } if ( st > en us > en ue < st ) { return ; } if ( us <= st && en <= ue ) { tree [ node ] = en - st + 1 - tree [ node ] ; if ( st < en ) { lazy [ node << 1 ] = ! lazy [ node << 1 ] ; lazy [ 1 + ( node << 1 ) ] = ! lazy [ 1 + ( node << 1 ) ] ; } return ; } int mid = ( st + en ) / 2 ; toggle ( ( node << 1 ) , st , mid , us , ue ) ; toggle ( ( node << 1 ) + 1 , mid + 1 , en , us , ue ) ; if ( st < en ) { tree [ node ] = tree [ node << 1 ] + tree [ ( node << 1 ) + 1 ] ; } } static int countQuery ( int node , int st , int en , int qs , int qe ) { if ( st > en qs > en qe < st ) { return 0 ; } if ( lazy [ node ] ) { lazy [ node ] = false ; tree [ node ] = en - st + 1 - tree [ node ] ; if ( st < en ) { lazy [ node << 1 ] = ! lazy [ node << 1 ] ; lazy [ ( node << 1 ) + 1 ] = ! lazy [ ( node << 1 ) + 1 ] ; } } if ( qs <= st && en <= qe ) { return tree [ node ] ; } int mid = ( st + en ) / 2 ; return countQuery ( ( node << 1 ) , st , mid , qs , qe ) + countQuery ( ( node << 1 ) + 1 , mid + 1 , en , qs , qe ) ; } public static void main ( String args [ ] ) { int n = 5 ; toggle ( 1 , 0 , n - 1 , 1 , 2 ) ; toggle ( 1 , 0 , n - 1 , 2 , 4 ) ; System . out . println ( countQuery ( 1 , 0 , n - 1 , 2 , 3 ) ) ; toggle ( 1 , 0 , n - 1 , 2 , 4 ) ; System . out . println ( countQuery ( 1 , 0 , n - 1 , 1 , 4 ) ) ; } }


"Count array elements exceeding all previous elements as well as the next array element | Java program for the above approach ; Function to count array elements satisfying the given condition ; If there is only one array element ; Traverse the array ; Update the maximum element encountered so far ; Count the number of array elements strictly greater than all previous and immediately next elements ; Print the count ; Driver Code ; Given array ; Size of the array"
How can the above be solved in Java?

import java . io . * ; class GFG { static void numberOfIntegers ( int [ ] arr , int N ) { int cur_max = 0 , count = 0 ; if ( N == 1 ) { count = 1 ; } else { for ( int i = 0 ; i < N - 1 ; i ++ ) { if ( arr [ i ] > cur_max ) { cur_max = arr [ i ] ; if ( arr [ i ] > arr [ i + 1 ] ) { count ++ ; } } } if ( arr [ N - 1 ] > cur_max ) count ++ ; } System . out . println ( count ) ; } public static void main ( String [ ] args ) { int [ ] arr = new int [ ] { 1 , 2 , 0 , 7 , 2 , 0 , 2 , 0 } ; int N = arr . length ; numberOfIntegers ( arr , N ) ; } }


"Count array elements exceeding sum of preceding K elements | Java program for the above approach ; Function to count array elements exceeding sum of preceding K elements ; Iterate over the array ; Update prefix sum ; Check if arr [ K ] > arr [ 0 ] + . . + arr [ K - 1 ] ; Increment count ; Check if arr [ i ] > arr [ i - K - 1 ] + . . + arr [ i - 1 ] ; Increment count ; Driver Code ; Given array"
How can the above be solved in Java?

class GFG { static int countPrecedingK ( int a [ ] , int n , int K ) { int [ ] prefix = new int [ n ] ; prefix [ 0 ] = a [ 0 ] ; for ( int i = 1 ; i < n ; i ++ ) { prefix [ i ] = prefix [ i - 1 ] + a [ i ] ; } int ctr = 0 ; if ( prefix [ K - 1 ] < a [ K ] ) ctr ++ ; for ( int i = K + 1 ; i < n ; i ++ ) { if ( prefix [ i - 1 ] - prefix [ i - K - 1 ] < a [ i ] ) ctr ++ ; } return ctr ; } public static void main ( String [ ] args ) { int arr [ ] = { 2 , 3 , 8 , 10 , - 2 , 7 , 5 , 5 , 9 , 15 } ; int N = arr . length ; int K = 2 ; System . out . print ( countPrecedingK ( arr , N , K ) ) ; } }


"Count array elements having modular inverse under given prime number P equal to itself | Java program to implement the above approach ; Function to get the count of elements that satisfy the given condition . ; Stores count of elements that satisfy the condition ; Traverse the given array . ; If square of current element is equal to 1 ; Driver Code"
How can the above be solved in Java?

import java . io . * ; class GFG { static int equvInverse ( int [ ] arr , int N , int P ) { int cntElem = 0 ; for ( int i = 0 ; i < N ; i ++ ) { if ( ( arr [ i ] * arr [ i ] ) % P == 1 ) { cntElem ++ ; } } return cntElem ; } public static void main ( String [ ] args ) { int [ ] arr = { 1 , 6 , 4 , 5 } ; int N = arr . length ; int P = 7 ; System . out . println ( equvInverse ( arr , N , P ) ) ; } }


"Count array elements having sum of digits equal to K | Java program for the above approach ; Function to calculate the sum of digits of the number N ; Stores the sum of digits ; Return the sum ; Function to count array elements ; Store the count of array elements having sum of digits K ; Traverse the array ; If sum of digits is equal to K ; Increment the count ; Print the count ; Driver code ; Given array ; Given value of K ; Size of the array ; Function call to count array elements having sum of digits equal to K"
How can the above be solved in Java?

public class GFG { static int sumOfDigits ( int N ) { int sum = 0 ; while ( N != 0 ) { sum += N % 10 ; N /= 10 ; } return sum ; } static void elementsHavingDigitSumK ( int [ ] arr , int N , int K ) { int count = 0 ; for ( int i = 0 ; i < N ; ++ i ) { if ( sumOfDigits ( arr [ i ] ) == K ) { count ++ ; } } System . out . println ( count ) ; } public static void main ( String args [ ] ) { int [ ] arr = { 23 , 54 , 87 , 29 , 92 , 62 } ; int K = 11 ; int N = arr . length ; elementsHavingDigitSumK ( arr , N , K ) ; } }


"Count array elements that can be maximized by adding any permutation of first N natural numbers | Java program for the above approach ; Function to get the count of values that can have the maximum value ; Sort array in decreasing order ; Stores the answer ; mark stores the maximum value till each index i ; Check if arr [ i ] can be maximum ; Update the mark ; Print the total count ; Driver Code ; Given array arr [ ] ; Function call"
How can the above be solved in Java?

import java . util . * ; class GFG { static void countMaximum ( Integer [ ] a , int n ) { Arrays . sort ( a , Collections . reverseOrder ( ) ) ; int count = 0 ; int mark = 0 ; for ( int i = 0 ; i < n ; ++ i ) { if ( ( a [ i ] + n >= mark ) ) { count += 1 ; } mark = Math . max ( mark , a [ i ] + i + 1 ) ; } System . out . print ( count ) ; } public static void main ( String [ ] args ) { Integer arr [ ] = { 8 , 9 , 6 } ; int N = arr . length ; countMaximum ( arr , N ) ; } }


"Count array elements that can be represented as sum of at least two consecutive array elements | Java Program for above approach ; Function to find the number of array elements that can be represented as the sum of two or more consecutive array elements ; Stores the frequencies of array elements ; Stores required count ; Update frequency of each array element ; Find sum of all subarrays ; Increment ans by cnt [ sum ] ; Reset cnt [ sum ] by 0 ; Return ans ; Driver Code ; Given array ; Function call"
How can the above be solved in Java?

import java . util . * ; class GFG { static int countElements ( int [ ] a , int n ) { int [ ] cnt = new int [ n + 1 ] ; int ans = 0 ; for ( int k : a ) { ++ cnt [ k ] ; } for ( int l = 0 ; l < n ; ++ l ) { int sum = 0 ; for ( int r = l ; r < n ; ++ r ) { sum += a [ r ] ; if ( l == r ) continue ; if ( sum <= n ) { ans += cnt [ sum ] ; cnt [ sum ] = 0 ; } } } return ans ; } public static void main ( String [ ] args ) { int [ ] a = { 1 , 1 , 1 , 1 , 1 } ; System . out . println ( countElements ( a , a . length ) ) ; } }


"Count array elements whose all distinct digits appear in K | Java program for the above approach ; Function to check a digit occurs in the digit of K or not ; Iterate over all possible digits of K ; If current digit equal to digit ; Update K ; Function to find the count of array elements whose distinct digits are a subset of digits of K ; Stores count of array elements whose distinct digits are subset of digits of K ; Traverse the array , arr [ ] ; Stores the current element ; Check if all the digits arr [ i ] is a subset of the digits of K or not ; Iterate over all possible digits of arr [ i ] ; Stores current digit ; If current digit does not appear in K ; Update flag ; Update no ; If all the digits arr [ i ] appear in K ; Update count ; Finally print count ; Driver Code"
How can the above be solved in Java?

import java . io . * ; class GFG { static boolean isValidDigit ( int digit , int K ) { while ( K != 0 ) { if ( K % 10 == digit ) { return true ; } K = K / 10 ; } return false ; } static int noOfValidNumbers ( int K , int arr [ ] ) { int count = 0 ; for ( int i = 0 ; i < arr . length ; i ++ ) { int no = arr [ i ] ; boolean flag = true ; while ( no != 0 ) { int digit = no % 10 ; if ( ! isValidDigit ( digit , K ) ) { flag = false ; break ; } no = no / 10 ; } if ( flag == true ) { count ++ ; } } return count ; } public static void main ( String [ ] args ) { int K = 12 ; int arr [ ] = { 1 , 12 , 1222 , 13 , 2 } ; System . out . println ( noOfValidNumbers ( K , arr ) ) ; } }


"Count array elements whose all distinct digits appear in K | Java program to implement the above approach ; Function to the count of array elements whose distinct digits are a subset of the digits of K ; Stores distinct digits of K ; Iterate over all the digits of K ; Insert current digit into set ; Update K ; Stores the count of array elements whose distinct digits are a subset of the digits of K ; Traverse the array , arr [ ] ; Stores current element ; Check if all the digits of arr [ i ] are present in K or not ; Iterate over all the digits of arr [ i ] ; Stores current digit ; If digit not present in the set ; Update flag ; Update no ; If all the digits of arr [ i ] present in set ; Update count ; Driver Code"
How can the above be solved in Java?

import java . io . * ; import java . util . * ; class GFG { static int noOfValidKbers ( int K , int arr [ ] ) { HashSet < Integer > set = new HashSet < > ( ) ; while ( K != 0 ) { set . add ( K % 10 ) ; K = K / 10 ; } int count = 0 ; for ( int i = 0 ; i < arr . length ; i ++ ) { int no = arr [ i ] ; boolean flag = true ; while ( no != 0 ) { int digit = no % 10 ; if ( ! set . contains ( digit ) ) { flag = false ; break ; } no = no / 10 ; } if ( flag == true ) { count ++ ; } } return count ; } public static void main ( String [ ] args ) { int K = 12 ; int arr [ ] = { 1 , 12 , 1222 , 13 , 2 } ; System . out . println ( noOfValidKbers ( K , arr ) ) ; } }


"Count array elements whose count of divisors is a prime number | Java program for the above approach ; Function to count the array elements whose count of divisors is prime ; Stores the maximum element ; Find the maximum element ; Store if i - th element is prime ( 0 ) or non - prime ( 1 ) ; Base Case ; If i is a prime number ; Mark all multiples of i as non - prime ; Stores the count of divisors ; Base Case ; Iterate to count factors ; Stores the count of array elements whose count of divisors is a prime number ; Traverse the array arr [ ] ; If count of divisors is prime ; Return the resultant count ; Driver Code"
How can the above be solved in Java?

public class GFG { public static int primeDivisors ( int [ ] arr , int N ) { int K = arr [ 0 ] ; for ( int i = 1 ; i < N ; i ++ ) { K = Math . max ( K , arr [ i ] ) ; } int [ ] prime = new int [ K + 1 ] ; prime [ 0 ] = 1 ; prime [ 1 ] = 1 ; for ( int i = 2 ; i < K + 1 ; i ++ ) { if ( prime [ i ] == 0 ) { for ( int j = 2 * i ; j < K + 1 ; j += i ) { prime [ j ] = 1 ; } } } int [ ] factor = new int [ K + 1 ] ; factor [ 0 ] = 0 ; factor [ 1 ] = 1 ; for ( int i = 2 ; i < K + 1 ; i ++ ) { factor [ i ] += 1 ; for ( int j = i ; j < K + 1 ; j += i ) { factor [ j ] += 1 ; } } int count = 0 ; for ( int i = 0 ; i < N ; i ++ ) { if ( prime [ factor [ arr [ i ] ] ] == 0 ) count ++ ; } return count ; } public static void main ( String args [ ] ) { int [ ] arr = { 10 , 13 , 17 , 25 } ; int N = arr . length ; System . out . println ( primeDivisors ( arr , N ) ) ; } }


"Count array elements whose highest power of 2 less than or equal to that number is present in the given array | Java program for the above approach ; Function to count array elements whose highest power of 2 is less than or equal to that number is present in the given array ; Stores the resultant count of array elements ; Stores frequency of visited array elements ; Traverse the array ; Calculate log base 2 of the element arr [ i ] ; Highest power of 2 whose value is at most arr [ i ] ; Increment the count by 1 ; Return the resultant count ; Driver Code"
How can the above be solved in Java?

import java . util . HashMap ; import java . io . * ; class GFG { static int log2 ( int N ) { int result = ( int ) ( Math . log ( N ) / Math . log ( 2 ) ) ; return result ; } static int countElement ( int arr [ ] , int N ) { int count = 0 ; HashMap < Integer , Integer > m = new HashMap < > ( ) ; for ( int i = 0 ; i < N ; i ++ ) { if ( m . containsKey ( arr [ i ] ) ) { m . put ( arr [ i ] , m . get ( arr [ i ] ) + 1 ) ; } else { m . put ( arr [ i ] , 1 ) ; } } for ( int i = 0 ; i < N ; i ++ ) { int lg = log2 ( arr [ i ] ) ; int p = ( int ) Math . pow ( 2 , lg ) ; if ( m . containsKey ( p ) ) { count ++ ; } } return count ; } public static void main ( String [ ] args ) { int arr [ ] = { 3 , 4 , 6 , 9 } ; int N = arr . length ; System . out . println ( countElement ( arr , N ) ) ; } }


"Count array elements whose product of digits is a Composite Number | Java program for the above approach ; Function to generate prime numbers using Sieve of Eratosthenes ; Set 0 and 1 as non - prime ; If p is a prime ; Set all multiples of p as non - prime ; Function to calculate the product of digits of the given number ; Stores the product of digits ; Extract digits and add to the sum ; Return the product of its digits ; Function to print number of distinct values with digit product as composite ; Initialize set ; Initialize boolean array ; Pre - compute primes ; Traverse array ; Stores the product of digits of the current array element ; If Product of digits is less than or equal to 1 ; If Product of digits is not a prime ; Print the answer ; Driver Code ; Given array ; Given size ; Function call"
How can the above be solved in Java?

import java . io . * ; import java . util . * ; class GFG { static int N = 100005 ; static void SieveOfEratosthenes ( boolean prime [ ] , int p_size ) { prime [ 0 ] = false ; prime [ 1 ] = false ; for ( int p = 2 ; p * p <= p_size ; p ++ ) { if ( prime [ p ] ) { for ( int i = p * 2 ; i <= p_size ; i += p ) prime [ i ] = false ; } } } static int digitProduct ( int number ) { int res = 1 ; while ( number > 0 ) { res *= ( number % 10 ) ; number /= 10 ; } return res ; } static void DistinctCompositeDigitProduct ( int arr [ ] , int n ) { TreeSet < Integer > output = new TreeSet < Integer > ( ) ; boolean prime [ ] = new boolean [ N + 1 ] ; Arrays . fill ( prime , true ) ; SieveOfEratosthenes ( prime , N ) ; for ( int i = 0 ; i < n ; i ++ ) { int ans = digitProduct ( arr [ i ] ) ; if ( ans <= 1 ) { continue ; } if ( ! prime [ ans ] ) { output . add ( ans ) ; } } System . out . print ( output . size ( ) ) ; } public static void main ( String [ ] args ) { int arr [ ] = { 13 , 55 , 7 , 13 , 11 , 71 , 233 , 233 , 144 , 89 } ; int n = arr . length ; DistinctCompositeDigitProduct ( arr , n ) ; } }


"Count array elements with rank not exceeding K | Java program for the above approach ; Function to find count of array elements with rank less than or equal to k ; Initialize rank and position ; Sort the given array ; Traverse array from right to left ; Update rank with position , if adjacent elements are unequal ; Return position - 1 , if rank greater than k ; Increase position ; Driver Code ; Given array ; Given K ; Function Call"
How can the above be solved in Java?

import java . util . * ; import java . lang . * ; class GFG { static int rankLessThanK ( int [ ] arr , int k , int n ) { int rank = 1 ; int position = 1 ; Arrays . sort ( arr ) ; for ( int i = n - 1 ; i >= 0 ; i -- ) { if ( i == n - 1 arr [ i ] != arr [ i + 1 ] ) { rank = position ; if ( rank > k ) return position - 1 ; } position ++ ; } return n ; } public static void main ( String [ ] args ) { int arr [ ] = { 2 , 2 , 3 , 4 , 5 } ; int N = arr . length ; int K = 4 ; System . out . println ( rankLessThanK ( arr , K , N ) ) ; } }


"Count arrays having at least K elements exceeding XOR of all given array elements by X given operations | Java program for the above approach ; Stores the final answer ; Utility function to count arrays having at least K elements exceeding XOR of all given array elements ; If no operations are left ; Stores the count of possible arrays ; Count array elements are greater than XOR ; Stores first element ; Delete first element ; Recursive call ; Insert first element into vector ; Stores the last element ; Remove last element from vector ; Recursive call ; Push last element into vector ; Increment first element ; Recursive call ; Decrement first element ; Increment last element ; Recursive call ; Decrement last element ; Function to find the count of arrays having atleast K elements greater than XOR of array ; Stores the XOR value of original array ; Traverse the vector ; Print the answer ; Driver Code ; Given vector ; Convert the input as ArrayList ; Given value of X & K"
How can the above be solved in Java?

import java . util . ArrayList ; class GFG { static int ans = 0 ; public static void countArraysUtil ( ArrayList < Integer > arr , int X , int K , int xorVal ) { if ( X == 0 ) { int cnt = 0 ; for ( int i = 0 ; i < arr . size ( ) ; i ++ ) { if ( arr . get ( i ) > xorVal ) cnt ++ ; } if ( cnt >= K ) ans ++ ; return ; } int temp = arr . get ( 0 ) ; arr . remove ( 0 ) ; countArraysUtil ( arr , X - 1 , K , xorVal ) ; arr . add ( 0 , temp ) ; temp = arr . get ( arr . size ( ) - 1 ) ; arr . remove ( arr . size ( ) - 1 ) ; countArraysUtil ( arr , X - 1 , K , xorVal ) ; arr . add ( temp ) ; arr . set ( 0 , arr . get ( 0 ) + 1 ) ; countArraysUtil ( arr , X - 1 , K , xorVal ) ; arr . set ( 0 , arr . get ( 0 ) - 1 ) ; arr . set ( arr . size ( ) - 1 , arr . get ( arr . size ( ) - 1 ) + 1 ) ; countArraysUtil ( arr , X - 1 , K , xorVal ) ; arr . set ( arr . size ( ) - 1 , arr . get ( arr . size ( ) - 1 ) - 1 ) ; } public static void countArrays ( ArrayList < Integer > arr , int X , int K ) { int xorVal = 0 ; for ( int i = 0 ; i < arr . size ( ) ; i ++ ) xorVal = xorVal ^ arr . get ( i ) ; countArraysUtil ( arr , X , K , xorVal ) ; System . out . println ( ans ) ; } public static void main ( String arg [ ] ) { int [ ] input = { 10 , 2 , 10 , 5 } ; ArrayList < Integer > arr = new ArrayList < Integer > ( ) ; for ( int i : input ) { arr . add ( i ) ; } int X = 3 , K = 3 ; countArrays ( arr , X , K ) ; } }


"Count arrays of length K whose product of elements is same as that of given array | Java implementation of the approach ; To store the smallest prime factor for every number ; Initialize map to store count of prime factors ; Function to calculate SPF ( Smallest Prime Factor ) for every number till MAXN ; Marking smallest prime factor for every number to be itself ; Separately marking spf for every even number as 2 ; Checking if i is prime ; Marking SPF for all numbers divisible by i ; Marking spf [ j ] if it is not previously marked ; Function to factorize using spf and store in cnt ; Function to return n ! % p ; Initialize result ; Iterative Function to calculate ( x ^ y ) % p in O ( log y ) ; Initialize result ; Update x if it is >= p ; If y is odd , multiply x with result ; y must be even now y = y / 2 ; Function that returns n ^ ( - 1 ) mod p ; Function that returns nCr % p using Fermat 's little theorem ; Base case ; Fill factorial array so that we can find all factorial of r , n and n - r ; Function to return the count the number of possible arrays mod P of length K such that the product of all elements of that array is equal to the product of all elements of the given array of length N ; Initialize result ; Call sieve to get spf ; Factorize arr [ i ] , count and store its factors in cnt ; Driver code"
How can the above be solved in Java?

import java . util . HashMap ; class GFG { static long MAXN = 100001L , mod = 1000000007L ; static long [ ] spf = new long [ ( int ) MAXN ] ; static HashMap < Long , Long > cnt = new HashMap < > ( ) ; public static void sieve ( ) { spf [ 1 ] = 1 ; for ( int i = 2 ; i < MAXN ; i ++ ) spf [ i ] = i ; for ( int i = 4 ; i < MAXN ; i += 2 ) spf [ i ] = 2 ; for ( int i = 3 ; i * i < MAXN ; i ++ ) { if ( spf [ i ] == i ) { for ( int j = i * i ; j < MAXN ; j += i ) if ( spf [ j ] == j ) spf [ j ] = i ; } } } public static void factorize ( long f ) { while ( f > 1 ) { long x = spf [ ( int ) f ] ; while ( f % x == 0 ) { if ( cnt . containsKey ( x ) ) { long z = cnt . get ( x ) ; cnt . put ( x , ++ z ) ; } else cnt . put ( x , ( long ) 1 ) ; f /= x ; } } } public static long factorial ( long n , long p ) { long res = 1 ; for ( long i = 2 ; i <= n ; i ++ ) res = ( res * i ) % p ; return res ; } public static long power ( long x , long y , long p ) { long res = 1 ; x = x % p ; while ( y > 0 ) { if ( y % 2 == 1 ) res = ( res * x ) % p ; y = y >> 1 ; x = ( x * x ) % p ; } return res ; } public static long modInverse ( long n , long p ) { return power ( n , p - 2 , p ) ; } public static long nCrModP ( long n , long r , long p ) { if ( r == 0 ) return 1 ; long [ ] fac = new long [ ( int ) n + 1 ] ; fac [ 0 ] = 1 ; for ( int i = 1 ; i <= n ; i ++ ) fac [ i ] = fac [ i - 1 ] * i % p ; return ( fac [ ( int ) n ] * modInverse ( fac [ ( int ) r ] , p ) % p * modInverse ( fac [ ( int ) ( n - r ) ] , p ) % p ) % p ; } public static long countArrays ( long [ ] arr , long N , long K , long P ) { long res = 1 ; sieve ( ) ; for ( int i = 0 ; i < N ; i ++ ) { factorize ( arr [ i ] ) ; } for ( HashMap . Entry < Long , Long > entry : cnt . entrySet ( ) ) { long ci = entry . getValue ( ) ; res = ( res * nCrModP ( ci + K - 1 , K - 1 , P ) ) % P ; } return res ; } public static void main ( String [ ] args ) { long [ ] arr = { 1 , 3 , 5 , 2 } ; long K = 3 ; long N = arr . length ; System . out . println ( countArrays ( arr , N , K , mod ) ) ; } }


"Count balanced nodes present in a binary tree | Java program to implement the above approach ; Structure of a Tree Node ; Function to get the sum of left subtree and right subtree ; Base case ; Store the sum of left subtree ; Store the sum of right subtree ; Check if node is balanced or not ; Increase count of balanced nodes ; Return subtree sum ; Driver Code ; Insert nodes in tree ; Store the count of balanced nodes"
How can the above be solved in Java?

class GFG { static int res = 0 ; static class Node { int data ; Node left ; Node right ; Node ( int val ) { data = val ; left = right = null ; } } ; static int Sum ( Node root ) { if ( root == null ) { return 0 ; } int leftSubSum = Sum ( root . left ) ; int rightSubSum = Sum ( root . right ) ; if ( root . left != null && root . right != null && leftSubSum == rightSubSum ) res += 1 ; return root . data + leftSubSum + rightSubSum ; } public static void main ( String [ ] args ) { Node root = new Node ( 9 ) ; root . left = new Node ( 2 ) ; root . left . left = new Node ( - 1 ) ; root . left . right = new Node ( 3 ) ; root . right = new Node ( 4 ) ; root . right . right = new Node ( 0 ) ; res = 0 ; Sum ( root ) ; System . out . print ( res ) ; } }


"Count bases which contains a set bit as the Most Significant Bit in the representation of N | Java program for the above approach ; Function to count bases having MSB of N as a set bit ; Store the required count ; Iterate over the range [ 2 , N ] ; Store the MSB of N ; If MSB is 1 , then increment the count by 1 ; Return the count ; DRIVER CODE"
How can the above be solved in Java?

import java . io . * ; class GFG { public static int countOfBase ( int N ) { int count = 0 ; for ( int i = 2 ; i <= N ; ++ i ) { int highestPower = ( int ) ( Math . log ( N ) / Math . log ( i ) ) ; int firstDigit = N / ( int ) Math . pow ( i , highestPower ) ; if ( firstDigit == 1 ) { ++ count ; } } return count ; } public static void main ( String [ ] args ) { int N = 6 ; System . out . println ( countOfBase ( N ) ) ; } }


"Count binary strings of length same as given string after removal of substrings "01" and "00" that consists of at least one '1' | Java program for the above approach ; Function to count the strings consisting of at least 1 set bit ; Initialize count ; Iterate through string ; The answer is 2 ^ N - 1 ; Driver Code ; Given string ; Function call"
How can the above be solved in Java?

import java . util . * ; class GFG { static void countString ( String S ) { int count = 0 ; for ( char it : S . toCharArray ( ) ) { if ( it == '0' && count > 0 ) { count -- ; } else { count ++ ; } } System . out . print ( ( 1 << count ) - 1 ) ; } public static void main ( String [ ] args ) { String S = "1001" ; countString ( S ) ; } }


"Count binary strings with k times appearing adjacent two set bits | Java program to count number of binary strings with k times appearing consecutive 1 's. ; dp [ i ] [ j ] [ 0 ] stores count of binary strings of length i with j consecutive 1 ' s ▁ and ▁ ending ▁ at ▁ 0 . ▁ ▁ dp [ i ] [ j ] [1 ] ▁ stores ▁ count ▁ of ▁ binary ▁ ▁ strings ▁ of ▁ length ▁ i ▁ with ▁ j ▁ consecutive ▁ ▁ 1' s and ending at 1. ; If n = 1 and k = 0. ; number of adjacent 1 's can not exceed i-1 ; Driver code"
How can the above be solved in Java?


"Count binary strings with twice zeros in first half | Java program for finding number of binary strings number of '0' in first half is double the number of '0' in second half of string ; pre define some constant ; global values for pre computation ; function to print number of required string ; calculate answer using proposed algorithm ; main function"
How can the above be solved in Java?

class GFG { static final long mod = 1000000007 ; static final long max = 1001 ; static long nCr [ ] [ ] = new long [ 1003 ] [ 1003 ] ; static void preComputeCoeff ( ) { for ( int i = 0 ; i < max ; i ++ ) { for ( int j = 0 ; j <= i ; j ++ ) { if ( j == 0 j == i ) nCr [ i ] [ j ] = 1 ; else nCr [ i ] [ j ] = ( nCr [ i - 1 ] [ j - 1 ] + nCr [ i - 1 ] [ j ] ) % mod ; } } } static long computeStringCount ( int N ) { int n = N / 2 ; long ans = 0 ; for ( int i = 2 ; i <= n ; i += 2 ) ans = ( ans + ( ( nCr [ n ] [ i ] * nCr [ n ] [ i / 2 ] ) % mod ) ) % mod ; return ans ; } public static void main ( String [ ] args ) { preComputeCoeff ( ) ; int N = 3 ; System . out . println ( computeStringCount ( N ) ) ; } }


"Count cells in a grid from which maximum number of cells can be reached by K vertical or horizontal jumps | Java program for the above approach ; Function to count the number of cells in the grid such that maximum cell is reachable with a jump of K ; Maximum reachable rows from the current row ; Stores the count of cell that are reachable from the current row ; Count of reachable rows ; Update the maximum value ; Add it to the count ; Maximum reachable columns from the current column ; Stores the count of cell that are reachable from the current column ; Count of rechable columns ; Update the maximum value ; Add it to the count ; Return the total count of cells ; Driver Code"
How can the above be solved in Java?

class GFG { public static long countCells ( int n , int m , int s ) { int mx1 = - 1 ; int cont1 = 0 ; for ( int i = 0 ; i < s && i < n ; ++ i ) { int aux = ( n - ( i + 1 ) ) / s + 1 ; if ( aux > mx1 ) { mx1 = cont1 = aux ; } else if ( aux == mx1 ) cont1 += aux ; } int mx2 = - 1 ; int cont2 = 0 ; for ( int i = 0 ; i < s && i < m ; ++ i ) { int aux = ( m - ( i + 1 ) ) / s + 1 ; if ( aux > mx2 ) mx2 = cont2 = aux ; else if ( aux == mx2 ) cont2 += aux ; } return ( long ) ( cont1 * cont2 ) ; } public static void main ( String args [ ] ) { int N = 5 , M = 5 , K = 2 ; System . out . println ( countCells ( N , M , K ) ) ; } }


"Count changes in Led Lights to display digits one by one | Java program to count number of on offs to display digits of a number . ; store the led lights required to display a particular number . ; compute the change in led and keep on adding the change ; Driver code"
How can the above be solved in Java?

import java . io . * ; class GFG { static int countOnOff ( String n ) { int Led [ ] = { 6 , 2 , 5 , 5 , 4 , 5 , 6 , 3 , 7 , 5 } ; int len = n . length ( ) ; int sum = Led [ n . charAt ( 0 ) - '0' ] ; for ( int i = 1 ; i < len ; i ++ ) { sum = sum + Math . abs ( Led [ n . charAt ( i ) - '0' ] - Led [ n . charAt ( i - 1 ) - '0' ] ) ; } return sum ; } public static void main ( String args [ ] ) { String n = "082" ; System . out . println ( countOnOff ( n ) ) ; } }


"Count characters at same position as in English alphabet | Java program to find number of characters at same position as in English alphabets ; Traverse input string ; Check that index of characters of string is same as of English alphabets by using ASCII values and the fact that all lower case alphabetic characters come together in same order in ASCII table . And same is true for upper case . ; Driver code"
How can the above be solved in Java?

class GFG { static int findCount ( String str ) { int result = 0 ; for ( int i = 0 ; i < str . length ( ) ; i ++ ) { if ( i == ( str . charAt ( i ) - ' a ' ) || i == ( str . charAt ( i ) - ' A ' ) ) { result ++ ; } } return result ; } public static void main ( String [ ] args ) { String str = " AbgdeF " ; System . out . print ( findCount ( str ) ) ; } }


"Count characters in a string whose ASCII values are prime | Java implementation of above approach ; Function to find prime characters in the String ; USE SIEVE TO FIND ALL PRIME NUMBERS LESS THAN OR EQUAL TO max_val Create a Boolean array " prime [ 0 . . n ] " . A value in prime [ i ] will finally be false if i is Not a prime , else true . ; initialize the value ; 0 and 1 are not primes ; If prime [ p ] is not changed , then it is a prime ; Update all multiples of p ; Traverse all the characters ; Driver program ; print required answer"
How can the above be solved in Java?

class Solution { static final int max_val = 257 ; static int PrimeCharacters ( String s ) { boolean prime [ ] = new boolean [ max_val + 1 ] ; for ( int i = 0 ; i <= max_val ; i ++ ) prime [ i ] = true ; prime [ 0 ] = false ; prime [ 1 ] = false ; for ( int p = 2 ; p * p <= max_val ; p ++ ) { if ( prime [ p ] == true ) { for ( int i = p * 2 ; i <= max_val ; i += p ) prime [ i ] = false ; } } int count = 0 ; for ( int i = 0 ; i < s . length ( ) ; ++ i ) { if ( prime [ ( int ) ( s . charAt ( i ) ) ] ) count ++ ; } return count ; } public static void main ( String args [ ] ) { String S = " geeksforgeeks " ; System . out . print ( PrimeCharacters ( S ) ) ; } }


"Count characters of a string which when removed individually makes the string equal to another string | Java program for the above approach ; Function to count characters from string A whose removal makes the strings A and B equal ; Stores the index of the longest prefix ; Stores the index of the longest suffix ; Traverse the string B ; Traverse the string B ; If N - M is equal to 1 and Y is less than or equal to X ; Print the count of characters ; Print the positions of the characters ; Otherwise ; Driver Code"
How can the above be solved in Java?

class GFG { static void RemoveOneChar ( String A , String B , int N , int M ) { int X = 0 ; int Y = N - 1 ; for ( int i = 0 ; i < M ; i ++ ) { if ( A . charAt ( X ) != B . charAt ( i ) ) break ; X ++ ; } for ( int i = M - 1 ; i >= 0 ; i -- ) { if ( A . charAt ( Y ) != B . charAt ( i ) ) break ; Y -- ; } if ( N - M == 1 && Y < X ) { System . out . println ( X - Y + 1 ) ; for ( int i = Y ; i <= X ; i ++ ) System . out . print ( i + 1 + " ▁ " ) ; System . out . println ( ) ; } else System . out . println ( - 1 ) ; } static public void main ( String [ ] args ) { String A = " abaac " ; String B = " abac " ; int N = A . length ( ) ; int M = B . length ( ) ; RemoveOneChar ( A , B , N , M ) ; } }


"Count characters to be shifted from the start or end of a string to obtain another string | Java Program for the above approach ; Function to find the minimum cost to convert string A to string B ; Length of string ; Initialize maxlen as 0 ; Traverse the string A ; Stores the length of substrings of string A ; Traversing string B for each character of A ; Shift i pointer towards right and increment length , if A [ i ] equals B [ j ] ; If traverse till end ; Update maxlen ; Return minimum cost ; Driver Code ; Given two strings A and B ; Function call"
How can the above be solved in Java?

import java . util . * ; import java . lang . * ; class GFG { static int minCost ( String A , String B ) { int n = A . length ( ) ; int i = 0 ; int maxlen = 0 ; while ( i < n ) { int length = 0 ; for ( int j = 0 ; j < n ; ++ j ) { if ( A . charAt ( i ) == B . charAt ( j ) ) { ++ i ; ++ length ; if ( i == n ) break ; } } maxlen = Math . max ( maxlen , length ) ; } return n - maxlen ; } public static void main ( String [ ] args ) { String A = " edacb " ; String B = " abcde " ; System . out . println ( minCost ( A , B ) ) ; } }


"Count characters with same neighbors | Java implementation of the above approach ; Function to count the characters with same adjacent characters ; if length is less than 3 then return length as there will be only two characters ; Traverse the string ; Increment the count if the previous and next character is same ; Return count ; Driver code"
How can the above be solved in Java?

class GFG { static int countChar ( String str ) { int n = str . length ( ) ; if ( n <= 2 ) return n ; int count = 2 ; for ( int i = 1 ; i < n - 1 ; i ++ ) if ( str . charAt ( i - 1 ) == str . charAt ( i + 1 ) ) count ++ ; return count ; } public static void main ( String [ ] args ) { String str = " egeeksk " ; System . out . println ( countChar ( str ) ) ; } }


"Count common characters in two strings | Java implementation of the approach ; Function to return the count of valid indices pairs ; To store the frequencies of characters of string s1 and s2 ; To store the count of valid pairs ; Update the frequencies of the characters of string s1 ; Update the frequencies of the characters of string s2 ; Find the count of valid pairs ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { static int countPairs ( String s1 , int n1 , String s2 , int n2 ) { int [ ] freq1 = new int [ 26 ] ; int [ ] freq2 = new int [ 26 ] ; Arrays . fill ( freq1 , 0 ) ; Arrays . fill ( freq2 , 0 ) ; int i , count = 0 ; for ( i = 0 ; i < n1 ; i ++ ) freq1 [ s1 . charAt ( i ) - ' a ' ] ++ ; for ( i = 0 ; i < n2 ; i ++ ) freq2 [ s2 . charAt ( i ) - ' a ' ] ++ ; for ( i = 0 ; i < 26 ; i ++ ) count += ( Math . min ( freq1 [ i ] , freq2 [ i ] ) ) ; return count ; } public static void main ( String args [ ] ) { String s1 = " geeksforgeeks " , s2 = " platformforgeeks " ; int n1 = s1 . length ( ) , n2 = s2 . length ( ) ; System . out . println ( countPairs ( s1 , n1 , s2 , n2 ) ) ; } }


"Count common elements in two arrays containing multiples of N and M | Java implementation of the above approach ; Recursive function to find gcd using euclidean algorithm ; Function to find lcm of two numbers using gcd ; Driver code"
How can the above be solved in Java?

import java . util . * ; import java . lang . * ; import java . io . * ; class GFG { static int gcd ( int a , int b ) { if ( a == 0 ) return b ; return gcd ( b % a , a ) ; } static int lcm ( int n , int m ) { return ( n * m ) / gcd ( n , m ) ; } public static void main ( String [ ] args ) { int n = 2 , m = 3 , k = 5 ; System . out . print ( k / lcm ( n , m ) ) ; } }


"Count common subsequence in two strings | Java program to count common subsequence in two strings ; return the number of common subsequence in two strings ; for each character of S ; for each character in T ; if character are same in both the string ; Driver code"
How can the above be solved in Java?

public class GFG { static int CommomSubsequencesCount ( String s , String t ) { int n1 = s . length ( ) ; int n2 = t . length ( ) ; int dp [ ] [ ] = new int [ n1 + 1 ] [ n2 + 1 ] ; char ch1 , ch2 ; for ( int i = 0 ; i <= n1 ; i ++ ) { for ( int j = 0 ; j <= n2 ; j ++ ) { dp [ i ] [ j ] = 0 ; } } for ( int i = 1 ; i <= n1 ; i ++ ) { for ( int j = 1 ; j <= n2 ; j ++ ) { ch1 = s . charAt ( i - 1 ) ; ch2 = t . charAt ( j - 1 ) ; if ( ch1 == ch2 ) dp [ i ] [ j ] = 1 + dp [ i ] [ j - 1 ] + dp [ i - 1 ] [ j ] ; else dp [ i ] [ j ] = dp [ i ] [ j - 1 ] + dp [ i - 1 ] [ j ] - dp [ i - 1 ] [ j - 1 ] ; } } return dp [ n1 ] [ n2 ] ; } public static void main ( String args [ ] ) { String s = " ajblqcpdz " ; String t = " aefcnbtdi " ; System . out . println ( CommomSubsequencesCount ( s , t ) ) ; } }


"Count consecutive pairs of same elements | Java implementation of the approach ; Function to return the count of consecutive elements in the array which are equal ; If consecutive elements are same ; Driver Code"
How can the above be solved in Java?

public class GfG { static int countCon ( int ar [ ] , int n ) { int cnt = 0 ; for ( int i = 0 ; i < n - 1 ; i ++ ) { if ( ar [ i ] == ar [ i + 1 ] ) cnt ++ ; } return cnt ; } public static void main ( String [ ] args ) { int ar [ ] = { 1 , 2 , 2 , 3 , 4 , 4 , 5 , 5 , 5 , 5 } ; int n = ar . length ; System . out . println ( countCon ( ar , n ) ) ; } }


"Count consonants in a string ( Iterative and recursive methods ) | Iterative Java program to count total number of consonants ; Function to check for consonant ; To handle lower case ; To check is character is Consonant ; Driver code"
How can the above be solved in Java?

import java . io . * ; class GFG { static boolean isConsonant ( char ch ) { ch = Character . toUpperCase ( ch ) ; return ! ( ch == ' A ' ch == ' E ' ch == ' I ' ch == ' O ' ch == ' U ' ) && ch >= 65 && ch <= 90 ; } static int totalConsonants ( String str ) { int count = 0 ; for ( int i = 0 ; i < str . length ( ) ; i ++ ) if ( isConsonant ( str . charAt ( i ) ) ) ++ count ; return count ; } public static void main ( String args [ ] ) { String str = " abc ▁ de " ; System . out . println ( totalConsonants ( str ) ) ; } }


"Count consonants in a string ( Iterative and recursive methods ) | Recursive Java program to count total number of consonants ; Function to check for consonant ; To handle lower case ; to count total number of consonants from 0 to n - 1 ; Driver code"
How can the above be solved in Java?

import java . util . * ; import java . lang . * ; class GFG { static boolean isConsonant ( char ch ) { ch = Character . toUpperCase ( ch ) ; return ( ch == ' A ' ch == ' E ' ch == ' I ' ch == ' O ' ch == ' U ' ) == false && ch >= 65 && ch <= 90 ; } static int totalConsonants ( String str , int n ) { if ( n == 1 ) { if ( isConsonant ( str . charAt ( 0 ) ) ) return 1 ; else return 0 ; } if ( isConsonant ( str . charAt ( n - 1 ) ) ) return totalConsonants ( str , n - 1 ) + 1 ; else return totalConsonants ( str , n - 1 ) ; } public static void main ( String args [ ] ) { String str = " abc ▁ de " ; System . out . println ( totalConsonants ( str , str . length ( ) ) ) ; } }


"Count cubes of size K inscribed in a cube of size N | Java implementation of the above approach ; Function to find the number of the cubes of the size K ; Stores the number of cubes ; Stores the number of cubes of size k ; Driver Code ; Size of the bigger cube ; Size of the smaller cube"
How can the above be solved in Java?

class GFG { static int No_of_cubes ( int N , int K ) { int No = 0 ; No = ( N - K + 1 ) ; No = ( int ) Math . pow ( No , 3 ) ; return No ; } public static void main ( String [ ] args ) { int N = 5 ; int K = 2 ; System . out . print ( No_of_cubes ( N , K ) ) ; } }


"Count different Bitwise OR values of equal length strings S1 and S2 by swapping exactly one pair of characters from the first string | Java program for the above approach ; Function to find the number of ways to obtain different Bitwise OR ; Stores the count of pairs t00 , t10 , t01 , t11 ; Traverse the characters of the string S1 and S2 ; Count the pair ( 0 , 0 ) ; Count the pair ( 1 , 0 ) ; Count the pair ( 1 , 1 ) ; Count the pair ( 0 , 1 ) ; Number of ways to calculate the different bitwise OR ; Print the result ; Driver Code"
How can the above be solved in Java?

import java . util . * ; class GFG { static void differentBitwiseOR ( String s1 , String s2 ) { int n = s1 . length ( ) ; int t00 = 0 , t10 = 0 , t01 = 0 , t11 = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( s1 . charAt ( i ) == '0' && s2 . charAt ( i ) == '0' ) { t00 ++ ; } if ( s1 . charAt ( i ) == '1' && s2 . charAt ( i ) == '0' ) { t10 ++ ; } if ( s1 . charAt ( i ) == '1' && s2 . charAt ( i ) == '1' ) { t11 ++ ; } if ( s1 . charAt ( i ) == '0' && s2 . charAt ( i ) == '1' ) { t01 ++ ; } } int ans = t00 * t10 + t01 * t10 + t00 * t11 ; System . out . print ( ans ) ; } public static void main ( String [ ] args ) { String S1 = "01001" ; String S2 = "11011" ; differentBitwiseOR ( S1 , S2 ) ; } }


"Count different numbers possible using all the digits their frequency times | Java program to implement the above approach ; Initialize an array to store factorial values ; Function to calculate and store X ! values ; Iterative Function to calculate ( x ^ y ) % p in O ( log y ) ; x = x % p ; Update x if it is more than or equal to p ; If y is odd , multiply x with result ; y must be even now y = y >> 1 ; y = y / 2 ; Function that return modular inverse of x under modulo p ; Function that returns the count of different number possible by using along the digits its frequency times ; Preprocess factorial values ; Initialize the result and sum of aint the frequencies ; Calculate the sum of frequencies ; Putting res equal to x ! ; Multiplying res with modular inverse of X0 ! , X1 ! , . . , X9 ! ; Driver Code"
How can the above be solved in Java?

class GFG { static int MAXN = 100000 ; static int MOD = 1000000007 ; static long fact [ ] = new long [ MAXN ] ; static void factorial ( ) { fact [ 0 ] = 1 ; for ( int i = 1 ; i < MAXN ; i ++ ) fact [ i ] = ( fact [ i - 1 ] * i ) % MOD ; } static long power ( long x , long y , long p ) { while ( y > 0 ) { if ( y % 2 == 1 ) res = ( res * x ) % p ; x = ( x * x ) % p ; } return res ; } static long modInverse ( long x , long p ) { return power ( x , p - 2 , p ) ; } static long countDifferentNumbers ( long arr [ ] , long P ) { factorial ( ) ; long res = 0 , X = 0 ; for ( int i = 0 ; i < 10 ; i ++ ) X += arr [ i ] ; res = fact [ ( int ) X ] ; for ( int i = 0 ; i < 10 ; i ++ ) { if ( arr [ i ] > 1 ) res = ( res * modInverse ( fact [ ( int ) arr [ i ] ] , P ) ) % P ; } return res ; } public static void main ( String [ ] args ) { long arr [ ] = { 1 , 0 , 2 , 0 , 0 , 7 , 4 , 0 , 0 , 3 } ; System . out . println ( countDifferentNumbers ( arr , MOD ) ) ; } }


"Count different numbers that can be generated such that there digits sum is equal to ' n ' | Java program to count ways to write ' n ' as sum of digits ; Function to count ' num ' as sum of digits ( 1 , 2 , 3 , 4 ) ; Initialize dp [ ] array ; Base case ; Initialize the current dp [ ] array as '0' ; if i == j then there is only one way to write with element itself ' i ' ; If j == 1 , then there exist two ways , one from '1' and other from '4' ; if i - j is positive then pick the element from ' i - j ' element of dp [ ] array ; Check for modulas ; return the final answer ; Driver code"
How can the above be solved in Java?

import java . io . * ; public class GFG { static int countWays ( int num ) { int [ ] dp = new int [ num + 1 ] ; int MOD = ( int ) 1E9 + 7 ; dp [ 1 ] = 2 ; for ( int i = 2 ; i <= num ; ++ i ) { dp [ i ] = 0 ; for ( int j = 1 ; j <= 3 ; ++ j ) { if ( i - j == 0 ) dp [ i ] += 1 ; else if ( j == 1 ) dp [ i ] += dp [ i - j ] * 2 ; else if ( i - j > 0 ) dp [ i ] += dp [ i - j ] ; if ( dp [ i ] >= MOD ) dp [ i ] %= MOD ; } } return dp [ num ] ; } static public void main ( String [ ] args ) { int n = 3 ; System . out . println ( countWays ( n ) ) ; } }


"Count digit groupings of a number with given constraints | Java program to count number of ways to group digits of a number such that sum of digits in every subgroup is less than or equal to its immediate right subgroup . ; Function to find the subgroups ; Terminating Condition ; sum of digits ; Traverse all digits from current position to rest of the length of string ; If forward_sum is greater than the previous sum , then call the method again ; Note : We pass current sum as previous sum ; Total number of subgroups till current position ; Driver Code"
How can the above be solved in Java?

import java . io . * ; class GFG { static int countGroups ( int position , int previous_sum , int length , String num ) { if ( position == length ) return 1 ; int res = 0 ; int sum = 0 ; for ( int i = position ; i < length ; i ++ ) { sum += ( num . charAt ( i ) - '0' ) ; if ( sum >= previous_sum ) res += countGroups ( i + 1 , sum , length , num ) ; } return res ; } public static void main ( String [ ] args ) { String num = "1119" ; int len = num . length ( ) ; System . out . println ( countGroups ( 0 , 0 , len , num ) ) ; } }


"Count digit groupings of a number with given constraints | Java program to count the number of ways to group digits of a number such that sum of digits in every subgroup is less than or equal to its immediate right subgroup . ; Maximum length of input number string ; A memoization table to store results of subproblems length of string is 40 and maximum sum will be 9 * 40 = 360. ; Function to find the count of splits with given condition ; Terminating Condition ; If already evaluated for a given sub problem then return the value ; countGroups for current sub - group is 0 ; sum of digits ; Traverse all digits from current position to rest of the length of string ; If forward_sum is greater than the previous sum , then call the method again ; Note : We pass current sum as previous sum ; total number of subgroups till current position ; Driver Code ; Initialize dp table"
How can the above be solved in Java?

class GFG { static int MAX = 40 ; static int dp [ ] [ ] = new int [ MAX ] [ 9 * MAX + 1 ] ; static int countGroups ( int position , int previous_sum , int length , char [ ] num ) { if ( position == length ) return 1 ; if ( dp [ position ] [ previous_sum ] != - 1 ) return dp [ position ] [ previous_sum ] ; dp [ position ] [ previous_sum ] = 0 ; int res = 0 ; int sum = 0 ; for ( int i = position ; i < length ; i ++ ) { sum += ( num [ i ] - '0' ) ; if ( sum >= previous_sum ) res += countGroups ( i + 1 , sum , length , num ) ; } dp [ position ] [ previous_sum ] = res ; return res ; } public static void main ( String [ ] args ) { char num [ ] = "1119" . toCharArray ( ) ; int len = num . length ; for ( int i = 0 ; i < dp . length ; i ++ ) { for ( int j = 0 ; j < 9 * MAX + 1 ; j ++ ) { dp [ i ] [ j ] = - 1 ; } } System . out . println ( countGroups ( 0 , 0 , len , num ) ) ; } }


"Count digits in a factorial | Set 1 | Java program to find the number of digits in a factorial ; returns the number of digits present in n ! ; factorial exists only for n >= 0 ; base case ; else iterate through n and calculate the value ; Driver code"
How can the above be solved in Java?

import java . io . * ; import java . util . * ; class GFG { static int findDigits ( int n ) { if ( n < 0 ) return 0 ; if ( n <= 1 ) return 1 ; double digits = 0 ; for ( int i = 2 ; i <= n ; i ++ ) digits += Math . log10 ( i ) ; return ( int ) ( Math . floor ( digits ) ) + 1 ; } public static void main ( String [ ] args ) { System . out . println ( findDigits ( 1 ) ) ; System . out . println ( findDigits ( 5 ) ) ; System . out . println ( findDigits ( 10 ) ) ; System . out . println ( findDigits ( 120 ) ) ; } }


"Count digits in a factorial | Set 2 | An optimised java program to find the number of digits in a factorial ; Function returns the number of digits present in n ! since the result can be large , long long is used as return type ; factorial of - ve number doesn 't exists ; base case ; Use Kamenetsky formula to calculate the number of digits ; Driver Code"
How can the above be solved in Java?

import java . io . * ; import java . util . * ; class GFG { public static double M_E = 2.71828182845904523536 ; public static double M_PI = 3.141592654 ; static long findDigits ( int n ) { if ( n < 0 ) return 0 ; if ( n <= 1 ) return 1 ; double x = ( n * Math . log10 ( n / M_E ) + Math . log10 ( 2 * M_PI * n ) / 2.0 ) ; return ( long ) Math . floor ( x ) + 1 ; } public static void main ( String [ ] args ) { System . out . println ( findDigits ( 1 ) ) ; System . out . println ( findDigits ( 50000000 ) ) ; System . out . println ( findDigits ( 1000000000 ) ) ; System . out . println ( findDigits ( 120 ) ) ; } }


"Count digits in given number N which divide N | Java program to find number of digits in N that divide N . ; Utility function to check divisibility by digit ; ( N [ i ] - '0' ) gives the digit value and form the number ; Function to count digits which appears in N and divide N divide [ 10 ] -- > array which tells that particular digit divides N or not count [ 10 ] -- > counts frequency of digits which divide N ; We initialize all digits of N as not divisible by N . ; start checking divisibility of N by digits 2 to 9 ; if digit divides N then mark it as true ; Now traverse the number string to find and increment result whenever a digit divides N . ; Driver program to run the case"
How can the above be solved in Java?

import java . util . * ; class solution { static boolean divisible ( String N , int digit ) { int ans = 0 ; for ( int i = 0 ; i < N . length ( ) ; i ++ ) { ans = ( ans * 10 + ( N . charAt ( i ) - '0' ) ) ; ans %= digit ; } return ( ans == 0 ) ; } static int allDigits ( String N ) { Boolean [ ] divide = new Boolean [ 10 ] ; Arrays . fill ( divide , Boolean . FALSE ) ; for ( int digit = 2 ; digit <= 9 ; digit ++ ) { if ( divisible ( N , digit ) ) divide [ digit ] = true ; } int result = 0 ; for ( int i = 0 ; i < N . length ( ) ; i ++ ) { if ( divide [ N . charAt ( i ) - '0' ] == true ) result ++ ; } return result ; } public static void main ( String args [ ] ) { String N = "122324" ; System . out . println ( allDigits ( N ) ) ; } }


"Count digits present in each element of a given Matrix | Java program for the above approach ; Function to count the number of digits in each element of the given matrix ; Traverse each row of arr [ ] [ ] ; Traverse each column of arr [ ] [ ] ; Store the current matrix element ; Count the number of digits ; Print the result ; Driver Code ; Given matrix"
How can the above be solved in Java?

import java . util . * ; class GFG { static int M = 3 ; static int N = 3 ; static void countDigit ( int arr [ ] [ ] ) { for ( int i = 0 ; i < M ; i ++ ) { for ( int j = 0 ; j < N ; j ++ ) { int X = arr [ i ] [ j ] ; int d = ( int ) ( Math . floor ( Math . log10 ( X ) * 1.0 ) + 1 ) ; System . out . print ( d + " ▁ " ) ; } System . out . println ( ) ; } } public static void main ( String [ ] args ) { int arr [ ] [ ] = { { 27 , 173 , 5 } , { 21 , 6 , 624 } , { 5 , 321 , 49 } } ; countDigit ( arr ) ; } }


"Count distinct Bitwise OR of all Subarrays | Java implementation of the above approach ; function to calculate count of distinct bitwise OR of all subarrays . ; Driver code"
How can the above be solved in Java?

import java . io . * ; import java . util . * ; class GFG { static int distintBitwiseOR ( int arr [ ] , int n ) { HashSet < Integer > ans = new HashSet < > ( ) ; HashSet < Integer > prev = new HashSet < > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { HashSet < Integer > ne = new HashSet < > ( ) ; ne . add ( arr [ i ] ) ; for ( int x : prev ) { ne . add ( arr [ i ] x ) ; } for ( int x : ne ) { ans . add ( x ) ; } prev = ne ; } return ans . size ( ) ; } public static void main ( String [ ] args ) { int n = 3 ; int arr [ ] = { 1 , 2 , 4 } ; System . out . println ( distintBitwiseOR ( arr , n ) ) ; } }


"Count distinct elements after adding each element of First Array with Second Array | Java program for the above approach ; Function to find Occurrence of each element from 1 to 2 * MAX ; Initialise MAX ; Count vector to store count of each element from 1 to 2 * MAX ; Size of Arr1 and Arr2 ; Find the elements of arr3 [ ] and increase count of element by 1 ; Print the result ; Driver Code ; Given arrays arr1 [ ] and arr2 [ ] ; Function call"
How can the above be solved in Java?

 import java . util . * ; class GFG { static void findCount ( int [ ] Arr1 , int [ ] Arr2 ) { int MAX = Math . max ( Arrays . stream ( Arr1 ) . max ( ) . getAsInt ( ) , Arrays . stream ( Arr2 ) . max ( ) . getAsInt ( ) ) ; int [ ] Count = new int [ 2 * MAX + 1 ] ; int n = Arr1 . length , m = Arr2 . length ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = 0 ; j < m ; j ++ ) { int element = Arr1 [ i ] + Arr2 [ j ] ; Count [ element ] ++ ; } } for ( int i = 1 ; i <= 2 * MAX ; i ++ ) { if ( Count [ i ] > 0 ) { System . out . print ( i + " - > " + Count [ i ] + "
"); } } } public static void main ( String [ ] args ) { int [ ] arr1 = { 1 , 2 } ; int [ ] arr2 = { 1 , 2 , 1 } ; findCount ( arr1 , arr2 ) ; } }