"Convert undirected connected graph to strongly connected directed graph | Java program for the above approach ; To store the assigned Edges ; Flag variable to check Bridges ; Function to implement DFS Traversal ; Mark the current node as visited ; Update the order of node v ; Update the bridge_detect for node v ; Traverse the adjacency list of Node v ; Ignores if same edge is traversed ; Ignores the edge u -- > v as v -- > u is already processed ; Finds a back Edges , cycle present ; Update the bridge_detect [ v ] ; Else DFS traversal for current node in the adjacency list ; Update the bridge_detect [ v ] ; Store the current directed Edge ; Condition for Bridges ; Return flag ; Function to print the direction of edges to make graph SCCs ; Arrays to store the visited , bridge_detect and order of Nodes ; DFS Traversal from vertex 1 ; If flag is zero , then Bridge is present in the graph ; Else print the direction of Edges assigned ; Function to create graph ; Traverse the Edges ; Push the edges in an adjacency list ; Driver code ; N vertices and M Edges ; To create Adjacency List ; Create an undirected graph ; Function Call"
How can the above be solved in Java?

import java . util . * ; import java . lang . * ; class GFG { static ArrayList < int [ ] > ans ; static int flag = 1 ; static int dfs ( ArrayList < ArrayList < Integer > > adj , int [ ] order , int [ ] bridge_detect , boolean [ ] mark , int v , int l ) { mark [ v ] = true ; order [ v ] = order [ l ] + 1 ; bridge_detect [ v ] = order [ v ] ; for ( int i = 0 ; i < adj . get ( v ) . size ( ) ; i ++ ) { int u = adj . get ( v ) . get ( i ) ; if ( u == l ) { continue ; } if ( order [ v ] < order [ u ] ) { continue ; } if ( mark [ u ] ) { bridge_detect [ v ] = Math . min ( order [ u ] , bridge_detect [ v ] ) ; } else { dfs ( adj , order , bridge_detect , mark , u , v ) ; } bridge_detect [ v ] = Math . min ( bridge_detect [ u ] , bridge_detect [ v ] ) ; ans . add ( new int [ ] { v , u } ) ; } if ( bridge_detect [ v ] == order [ v ] && l != 0 ) { flag = 0 ; } return flag ; } static void convert ( ArrayList < ArrayList < Integer > > adj , int n ) { int [ ] order = new int [ n ] ; int [ ] bridge_detect = new int [ n ] ; boolean mark [ ] = new boolean [ n ] ; int flag = dfs ( adj , order , bridge_detect , mark , 1 , 0 ) ; if ( flag == 0 ) { System . out . print ( " - 1" ) ; } else { for ( int [ ] it : ans ) { System . out . println ( it [ 0 ] + " - > " + it [ 1 ] ) ; } } } static void createGraph ( int Edges [ ] [ ] , ArrayList < ArrayList < Integer > > adj , int M ) { for ( int i = 0 ; i < M ; i ++ ) { int u = Edges [ i ] [ 0 ] ; int v = Edges [ i ] [ 1 ] ; adj . get ( u ) . add ( v ) ; adj . get ( v ) . add ( u ) ; } } public static void main ( String [ ] args ) { int N = 5 , M = 6 ; int Edges [ ] [ ] = { { 0 , 1 } , { 0 , 2 } , { 1 , 2 } , { 1 , 4 } , { 2 , 3 } , { 3 , 4 } } ; ArrayList < ArrayList < Integer > > adj = new ArrayList < > ( ) ; ans = new ArrayList < > ( ) ; for ( int i = 0 ; i < N ; i ++ ) adj . add ( new ArrayList < > ( ) ) ; createGraph ( Edges , adj , M ) ; convert ( adj , N ) ; } }


"Converting Decimal Number lying between 1 to 3999 to Roman Numerals | Java Program for above approach ; Function to calculate roman equivalent ; storing roman values of digits from 0 - 9 when placed at different places ; Converting to roman ; Driver program to test above function"
How can the above be solved in Java?

class GFG { static String intToRoman ( int num ) { String m [ ] = { " " , " M " , " MM " , " MMM " } ; String c [ ] = { " " , " C " , " CC " , " CCC " , " CD " , " D " , " DC " , " DCC " , " DCCC " , " CM " } ; String x [ ] = { " " , " X " , " XX " , " XXX " , " XL " , " L " , " LX " , " LXX " , " LXXX " , " XC " } ; String i [ ] = { " " , " I " , " II " , " III " , " IV " , " V " , " VI " , " VII " , " VIII " , " IX " } ; String thousands = m [ num / 1000 ] ; String hundereds = c [ ( num % 1000 ) / 100 ] ; String tens = x [ ( num % 100 ) / 10 ] ; String ones = i [ num % 10 ] ; String ans = thousands + hundereds + tens + ones ; return ans ; } public static void main ( String [ ] args ) { int number = 3549 ; System . out . println ( intToRoman ( number ) ) ; } }


"Converting Roman Numerals to Decimal lying between 1 to 3999 | Program to convert Roman Numerals to Numbers ; This function returns value of a Roman symbol ; If present value is less than next value , subtract present from next value and add the resultant to the sum variable . ; Driver Code ; Considering inputs given are valid"
How can the above be solved in Java?

import java . util . Map ; import java . util . HashMap ; class GFG { private static final Map < Character , Integer > roman = new HashMap < Character , Integer > ( ) { { put ( ' I ' , 1 ) ; put ( ' V ' , 5 ) ; put ( ' X ' , 10 ) ; put ( ' L ' , 50 ) ; put ( ' C ' , 100 ) ; put ( ' D ' , 500 ) ; put ( ' M ' , 1000 ) ; } } ; private static int romanToInt ( String s ) { int sum = 0 ; int n = s . length ( ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( i != n - 1 && roman . get ( s . charAt ( i ) ) < roman . get ( s . charAt ( i + 1 ) ) ) { sum += roman . get ( s . charAt ( i + 1 ) ) - roman . get ( s . charAt ( i ) ) ; i ++ ; } else { sum += roman . get ( s . charAt ( i ) ) ; } } return sum ; } public static void main ( String [ ] args ) { String input = " MCMIV " ; System . out . print ( " Integer ▁ form ▁ of ▁ Roman ▁ Numeral ▁ is ▁ " + romanToInt ( input ) ) ; } }


"Converting a Real Number ( between 0 and 1 ) to Binary String | Java program to Binary real number to String . ; Main function to convert Binary real number to String ; Check Number is Between 0 to 1 or Not ; Setting a limit on length : 32 characters , If the number cannot be represented accurately in binary with at most 32 characters ; It compare the number to . 5. ; Now it become 0.25 ; Driver Code ; double num1 = 0.625 ; Input value in Decimal"
How can the above be solved in Java?

import java . lang . * ; import java . io . * ; import java . util . * ; class BinaryToString { static String printBinary ( double num ) { if ( num >= 1 num <= 0 ) return " ERROR " ; StringBuilder binary = new StringBuilder ( ) ; double frac = 0.5 ; binary . append ( " . " ) ; while ( num > 0 ) { if ( binary . length ( ) >= 32 ) return " ERROR " ; if ( num >= frac ) { binary . append ( 1 ) ; num -= frac ; } else binary . append ( 0 ) ; frac /= 2 ; } return binary . toString ( ) ; } public static void main ( String [ ] args ) { String output = printBinary ( num1 ) ; System . out . println ( " ( 0" + output + " ) ▁ in ▁ base ▁ 2" ) ; double num2 = 0.72 ; output = printBinary ( num2 ) ; System . out . println ( " ( " + output + " ) ▁ " ) ; } }


"Converting one string to other using append and delete last operations | java Program to convert str1 to str2 in exactly k operations ; Returns true if it is possible to convert str1 to str2 using k operations . ; Case A ( i ) ; finding common length of both string ; Case A ( ii ) - ; Case B ; Driver program"
How can the above be solved in Java?

import java . io . * ; class GFG { static boolean isConvertible ( String str1 , String str2 , int k ) { if ( ( str1 . length ( ) + str2 . length ( ) ) < k ) return true ; int commonLength = 0 ; for ( int i = 0 ; i < Math . min ( str1 . length ( ) , str2 . length ( ) ) ; i ++ ) { if ( str1 == str2 ) commonLength ++ ; else break ; } if ( ( k - str1 . length ( ) - str2 . length ( ) + 2 * commonLength ) % 2 == 0 ) return true ; return false ; } public static void main ( String [ ] args ) { String str1 = " geek " ; String str2 = " geek " ; int k = 7 ; if ( isConvertible ( str1 , str2 , k ) ) System . out . println ( " Yes " ) ; else System . out . println ( " No " ) ; str1 = " geeks " ; str2 = " geek " ; k = 5 ; if ( isConvertible ( str1 , str2 , k ) ) System . out . println ( " Yes " ) ; else System . out . println ( " No " ) ; } }


"Coordinates of rectangle with given points lie inside | Program to find smallest rectangle to conquer all points ; function to print coordinate of smallest rectangle ; find Xmax and Xmin ; find Ymax and Ymin ; print all four coordinates ; Driver code"
How can the above be solved in Java?

import java . util . Arrays ; import java . util . Collections ; class GFG { static void printRect ( Integer X [ ] , Integer Y [ ] , int n ) { int Xmax = Collections . max ( Arrays . asList ( X ) ) ; int Xmin = Collections . min ( Arrays . asList ( X ) ) ; int Ymax = Collections . max ( Arrays . asList ( Y ) ) ; int Ymin = Collections . min ( Arrays . asList ( Y ) ) ; System . out . println ( " { " + Xmin + " , ▁ " + Ymin + " } " ) ; System . out . println ( " { " + Xmin + " , ▁ " + Ymax + " } " ) ; System . out . println ( " { " + Xmax + " , ▁ " + Ymax + " } " ) ; System . out . println ( " { " + Xmax + " , ▁ " + Ymin + " } " ) ; } public static void main ( String [ ] args ) { Integer X [ ] = { 4 , 3 , 6 , 1 , - 1 , 12 } ; Integer Y [ ] = { 4 , 1 , 10 , 3 , 7 , - 1 } ; int n = X . length ; printRect ( X , Y , n ) ; } }


"Coordinates of the last cell in a Matrix on which performing given operations exits from the Matrix | JAVA program for the above approach ; Function to check if the indices ( i , j ) are valid indices in a Matrix or not ; Cases for invalid cells ; Return true if valid ; Function to find indices of cells of a matrix from which traversal leads to out of the matrix ; Starting from cell ( 0 , 0 ) , traverse in right direction ; Stores direction changes ; Iterate until the current cell exceeds beyond the matrix ; Current index ; If the current cell is 1 ; Update arr [ i ] [ j ] = 0 ; Update indices according to the direction ; Otherwise ; Update indices according to the direction ; The exit cooridnates ; Driver Code ; Number of rows ; Number of columns ; Given matrix arr [ ] [ ]"
How can the above be solved in Java?

 import java . util . HashMap ; import java . util . Map ; class GFG { static boolean issafe ( int m , int n , int i , int j ) { if ( i < 0 ) return false ; if ( j < 0 ) return false ; if ( i >= m ) return false ; if ( j >= n ) return false ; return true ; } static int [ ] endpoints ( int [ ] [ ] arr , int m , int n ) { int i = 0 ; int j = 0 ; int current_i = 0 ; int current_j = 0 ; char current_d = ' r ' ; Map < Character , Character > rcd = new HashMap < > ( ) ; rcd . put ( ' l ' , ' u ' ) ; rcd . put ( ' u ' , ' r ' ) ; rcd . put ( ' r ' , ' d ' ) ; rcd . put ( ' d ' , ' l ' ) ; while ( issafe ( m , n , i , j ) ) { current_i = i ; current_j = j ; if ( arr [ i ] [ j ] == 1 ) { char move_in = rcd . get ( current_d ) ; arr [ i ] [ j ] = 0 ; if ( move_in == ' u ' ) i -= 1 ; else if ( move_in == ' d ' ) i += 1 ; else if ( move_in == ' l ' ) j -= 1 ; else if ( move_in == ' r ' ) j += 1 ; current_d = move_in ; } else { if ( current_d == ' u ' ) i -= 1 ; else if ( current_d == ' d ' ) i += 1 ; else if ( current_d == ' l ' ) j -= 1 ; else if ( current_d == ' r ' ) j += 1 ; } } return new int [ ] { current_i , current_j } ; } public static void main ( String [ ] args ) { int M = 3 ; int N = 5 ; int [ ] [ ] arr = { { 0 , 1 , 1 , 1 , 0 } , { 1 , 0 , 1 , 0 , 1 } , { 1 , 1 , 1 , 0 , 0 } } ; int [ ] p = endpoints ( arr , M , N ) ; System . out . print ( " ( " + p [ 0 ] + " , ▁ " + p [ 1 ] + " ) " + "
"); } }


"Coplanarity of Two Lines in 3D Geometry | Java program implement the above approach ; Function to generate determinant ; Return the sum ; Driver Code ; Position vector of first line ; Direction ratios of line to which first line is parallel ; Position vectors of second line ; Direction ratios of line to which second line is parallel ; Determinant to check coplanarity ; If determinant is zero ; Otherwise"
How can the above be solved in Java?


"Cost Based Tower of Hanoi | Java implementation of the approach ; Function to initialize the dp table ; Initialize with maximum value ; Function to return the minimum cost ; Base case ; If problem is already solved , return the pre - calculated answer ; Number of the auxiliary disk ; Initialize the minimum cost as Infinity ; Calculationg the cost for first case ; Calculating the cost for second case ; Minimum of both the above cases ; Store it in the dp table ; Return the minimum cost ; Driver code"
How can the above be solved in Java?

import java . io . * ; class GFG { static int RODS = 3 ; static int N = 3 ; static int [ ] [ ] [ ] dp = new int [ N + 1 ] [ RODS + 1 ] [ RODS + 1 ] ; static void initialize ( ) { for ( int i = 0 ; i <= N ; i += 1 ) { for ( int j = 1 ; j <= RODS ; j ++ ) { for ( int k = 1 ; k <= RODS ; k += 1 ) { dp [ i ] [ j ] [ k ] = Integer . MAX_VALUE ; } } } } static int mincost ( int idx , int src , int dest , int costs [ ] [ ] ) { if ( idx > N ) return 0 ; if ( dp [ idx ] [ src ] [ dest ] != Integer . MAX_VALUE ) return dp [ idx ] [ src ] [ dest ] ; int rem = 6 - ( src + dest ) ; int ans = Integer . MAX_VALUE ; int case1 = costs [ src - 1 ] [ dest - 1 ] + mincost ( idx + 1 , src , rem , costs ) + mincost ( idx + 1 , rem , dest , costs ) ; int case2 = costs [ src - 1 ] [ rem - 1 ] + mincost ( idx + 1 , src , dest , costs ) + mincost ( idx + 1 , dest , src , costs ) + costs [ rem - 1 ] [ dest - 1 ] + mincost ( idx + 1 , src , dest , costs ) ; ans = Math . min ( case1 , case2 ) ; dp [ idx ] [ src ] [ dest ] = ans ; return ans ; } public static void main ( String [ ] args ) { int [ ] [ ] costs = { { 0 , 1 , 2 } , { 2 , 0 , 1 } , { 3 , 2 , 0 } } ; initialize ( ) ; System . out . print ( mincost ( 1 , 1 , 3 , costs ) ) ; } }


"Cost of creating smallest subsequence with sum of difference between adjacent elements maximum |  ; Initializing cost = 0 ; To store the removed element ; This will store the sum of the subsequence ; Checking all the element of the vector ; Storing the value of arr [ i ] in temp variable ; If the situation like arr [ i - 1 ] < arr [ i ] < arr [ i + 1 ] or arr [ i - 1 ] > arr [ i ] > arr [ i + 1 ] occur remove arr [ i ] i . e , temp from sequence ; Insert the element in the set removedElements ; Storing the value of arr [ i ] in temp ; Taking the element not in removedElements ; Adding the value of elements of subsequence ; If we have to remove the element then we need to add the cost associated with the element ; Printing the sum of the subsequence with minimum length possible ; Printing the cost incurred in creating subsequence ; Driver code ; Calling the function"
How can the above be solved in Java?

import java . util . * ; class GFG { public static void costOfSubsequence ( int N , int [ ] arr , int [ ] costArray ) { int i , temp ; int cost = 0 ; Set < Integer > removedElements = new HashSet < Integer > ( ) ; int ans = 0 ; for ( i = 1 ; i < ( N - 1 ) ; i ++ ) { temp = arr [ i ] ; if ( ( ( arr [ i - 1 ] < temp ) && ( temp < arr [ i + 1 ] ) ) || ( ( arr [ i - 1 ] > temp ) && ( temp > arr [ i + 1 ] ) ) ) { removedElements . add ( temp ) ; } } for ( i = 0 ; i < ( N ) ; i ++ ) { temp = arr [ i ] ; if ( ! ( removedElements . contains ( temp ) ) ) { ans += arr [ i ] ; } else { cost += costArray [ i ] ; } } System . out . print ( ans + " , ▁ " ) ; System . out . print ( cost ) ; } public static void main ( String [ ] args ) { int N ; N = 4 ; int [ ] arr = { 1 , 3 , 4 , 2 } ; int [ ] costArray = { 0 , 1 , 0 , 0 } ; costOfSubsequence ( N , arr , costArray ) ; } }


"Cost of painting n * m grid | Java implementation of the approach ; Function to return the minimum cost ; Driver code"
How can the above be solved in Java?

class gfg { static int getMinCost ( int n , int m ) { int cost = ( n - 1 ) * m + ( m - 1 ) * n ; return cost ; } public static void main ( String [ ] args ) { int n = 4 , m = 5 ; System . out . println ( getMinCost ( n , m ) ) ; } }


"Cost of rearranging the array such that no element exceeds the sum of its adjacent elements | Java program to implement the above approach ; Function to check if given elements can be arranged such that sum of its neighbors is strictly greater ; Initialize the total cost ; Storing the original index of elements in a hashmap ; Sort the given array ; Check if a given condition is satisfies or not ; First number ; Add the cost to overall cost ; Last number ; Add the cost to overall cost ; Add the cost to overall cost ; Printing the cost ; Driver Code ; Given array ; Function call"
How can the above be solved in Java?

import java . util . * ; class GFG { static void Arrange ( int arr [ ] , int n ) { int cost = 0 ; HashMap < Integer , Integer > index = new HashMap < Integer , Integer > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { index . put ( arr [ i ] , i ) ; } Arrays . sort ( arr ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( i == 0 ) { if ( arr [ i ] > arr [ i + 1 ] + arr [ n - 1 ] ) { System . out . print ( " - 1" ) ; return ; } else { cost += Math . abs ( index . get ( arr [ i ] ) - i ) ; } } else if ( i == n - 1 ) { if ( arr [ i ] > arr [ i - 1 ] + arr [ 0 ] ) { System . out . print ( " - 1" ) ; return ; } else { cost += Math . abs ( index . get ( arr [ i ] ) - i ) ; } } else { if ( arr [ i ] > arr [ i - 1 ] + arr [ i + 1 ] ) { System . out . print ( " - 1" ) ; return ; } else { cost += Math . abs ( index . get ( arr [ i ] ) - i ) ; } } } System . out . print ( cost ) ; return ; } public static void main ( String [ ] args ) { int arr [ ] = { 2 , 4 , 5 , 1 , 3 } ; int N = arr . length ; Arrange ( arr , N ) ; } }


"Cost required to empty a given array by repeated removal of maximum obtained by given operations | Java program for the above approach ; Function to find the total cost of removing all array elements ; Sort the array in descending order ; Stores the total cost ; Contribution of i - th greatest element to the cost ; Remove the element ; If negative ; Add to the final cost ; Return the cost ; Driver Code ; Given array arr [ ] ; Function Call"
How can the above be solved in Java?

import java . util . * ; class GFG { static int findCost ( Integer [ ] a , int n ) { Arrays . sort ( a , Collections . reverseOrder ( ) ) ; int count = 0 ; for ( int j = 0 ; j < n ; j ++ ) { int p = a [ j ] - j ; a [ j ] = 0 ; if ( p < 0 ) { p = 0 ; continue ; } count += p ; } return count ; } public static void main ( String [ ] args ) { Integer arr [ ] = { 1 , 6 , 7 , 4 , 2 , 5 , 3 } ; int N = arr . length ; System . out . print ( findCost ( arr , N ) ) ; } }


"Cost to make a string Panagram | Java program to find the cost to make a string Panagram ; Function to return the total cost required to make the string Pangram ; Mark all the alphabets that occurred in the string ; Calculate the total cost for the missing alphabets ; Driver Code"
How can the above be solved in Java?

class GFG { static int pangramCost ( int arr [ ] , String str ) { int cost = 0 ; boolean [ ] occurred = new boolean [ 26 ] ; for ( int i = 0 ; i < 26 ; i ++ ) occurred [ i ] = false ; for ( int i = 0 ; i < str . length ( ) ; i ++ ) occurred [ str . charAt ( i ) - ' a ' ] = true ; for ( int i = 0 ; i < 26 ; i ++ ) { if ( occurred [ i ] == false ) cost += arr [ i ] ; } return cost ; } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 , 11 , 12 , 13 , 14 , 15 , 16 , 17 , 18 , 19 , 20 , 21 , 22 , 23 , 24 , 25 , 26 } ; String str = " abcdefghijklmopqrstuvwz " ; System . out . println ( pangramCost ( arr , str ) ) ; } }


"Cost to make a string Panagram | Set 2 | Java implementation of the approach ; Function to return the cost to make str a Panagram ; Count the occurrences of each lowercase character ; To store the total gain ; If some character is missing , it has to be added at twice the cost ; If some character appears more than once all of its occurrences except 1 can be traded for some gain ; If gain is more than the cost ; Return the total cost if gain < 0 ; Driver code"
How can the above be solved in Java?

public class GFG { static int costToPanagram ( String str , int cost [ ] ) { int i , n = str . length ( ) ; int occurrences [ ] = new int [ 26 ] ; for ( i = 0 ; i < n ; i ++ ) occurrences [ str . charAt ( i ) - ' a ' ] ++ ; int gain = 0 ; for ( i = 0 ; i < 26 ; i ++ ) { if ( occurrences [ i ] == 0 ) gain -= ( 2 * cost [ i ] ) ; else if ( occurrences [ i ] > 1 ) gain += ( cost [ i ] * ( occurrences [ i ] - 1 ) ) ; } if ( gain >= 0 ) return 0 ; return ( gain * - 1 ) ; } public static void main ( String [ ] args ) { int cost [ ] = { 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 } ; String str = " geeksforgeeks " ; System . out . println ( costToPanagram ( str , cost ) ) ; } }


"Count ' d ' digit positive integers with 0 as a digit | Java program to find the count of positive integer of a given number of digits that contain atleast one zero ; Returns count of ' d ' digit integers have 0 as a digit ; Driver Code"
How can the above be solved in Java?

import java . io . * ; class GFG { static int findCount ( int d ) { return 9 * ( ( int ) ( Math . pow ( 10 , d - 1 ) ) - ( int ) ( Math . pow ( 9 , d - 1 ) ) ) ; } public static void main ( String args [ ] ) { int d = 1 ; System . out . println ( findCount ( d ) ) ; d = 2 ; System . out . println ( findCount ( d ) ) ; d = 4 ; System . out . println ( findCount ( d ) ) ; } }


"Count 1 's in a sorted binary array | Java program to count 1 's in a sorted array ; Returns counts of 1 's in arr[low..high]. The  array is assumed to be sorted in non-increasing  order  ; get the middle index ; check if the element at middle index is last 1 ; If element is not last 1 , recur for right side ; else recur for left side ; Driver code"
How can the above be solved in Java?

class CountOnes { int countOnes ( int arr [ ] , int low , int high ) { if ( high >= low ) { int mid = low + ( high - low ) / 2 ; if ( ( mid == high arr [ mid + 1 ] == 0 ) && ( arr [ mid ] == 1 ) ) return mid + 1 ; if ( arr [ mid ] == 1 ) return countOnes ( arr , ( mid + 1 ) , high ) ; return countOnes ( arr , low , ( mid - 1 ) ) ; } return 0 ; } public static void main ( String args [ ] ) { CountOnes ob = new CountOnes ( ) ; int arr [ ] = { 1 , 1 , 1 , 1 , 0 , 0 , 0 } ; int n = arr . length ; System . out . println ( " Count ▁ of ▁ 1 ' s ▁ in ▁ given ▁ array ▁ is ▁ " + ob . countOnes ( arr , 0 , n - 1 ) ) ; } }


"Count 1 's in a sorted binary array | package whatever ; Returns counts of 1 's in arr[low..high]. The array is  assumed to be sorted in non-increasing order  ; get the middle index ; else recur for left side ; If element is not last 1 , recur for right side ; check if the element at middle index is last 1 ; Driver code"
How can the above be solved in Java?

import java . io . * ; class GFG { static int countOnes ( int arr [ ] , int n ) { int ans ; int low = 0 , high = n - 1 ; while ( low <= high ) { int mid = ( low + high ) / 2 ; if ( arr [ mid ] < 1 ) high = mid - 1 ; else if ( arr [ mid ] > 1 ) low = mid + 1 ; else { if ( mid == n - 1 arr [ mid + 1 ] != 1 ) return mid + 1 ; else low = mid + 1 ; } } return 0 ; } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 1 , 1 , 1 , 0 , 0 , 0 } ; int n = arr . length ; System . out . println ( " Count ▁ of ▁ 1 ' s ▁ in ▁ given ▁ array ▁ is ▁ " + countOnes ( arr , n ) ) ; } }


"Count 1 s in binary matrix having remaining indices of its row and column filled with 0 s | Java program for the above approach ; Function to count required 1 s from the given matrix ; Stores the dimensions of the mat [ ] [ ] ; Calculate sum of rows ; Calculate sum of columns ; Stores required count of 1 s ; If current cell is 1 and sum of row and column is 1 ; Increment count of 1 s ; Return the final count ; Driver Code ; Given matrix ; Function call"
How can the above be solved in Java?

 class GFG { static int numSpecial ( int [ ] [ ] mat ) { int m = mat . length ; int n = mat [ 0 ] . length ; int [ ] rows = new int [ m ] ; int [ ] cols = new int [ n ] ; int i , j ; for ( i = 0 ; i < m ; i ++ ) { rows [ i ] = 0 ; for ( j = 0 ; j < n ; j ++ ) rows [ i ] += mat [ i ] [ j ] ; } for ( i = 0 ; i < n ; i ++ ) { cols [ i ] = 0 ; for ( j = 0 ; j < m ; j ++ ) cols [ i ] += mat [ j ] [ i ] ; } int cnt = 0 ; for ( i = 0 ; i < m ; i ++ ) { for ( j = 0 ; j < n ; j ++ ) { if ( mat [ i ] [ j ] == 1 && rows [ i ] == 1 && cols [ j ] == 1 ) cnt ++ ; } } return cnt ; } public static void main ( String [ ] args ) { int [ ] [ ] mat = { { 1 , 0 , 0 } , { 0 , 0 , 1 } , { 0 , 0 , 0 } } ; System . out . print ( numSpecial ( mat ) + "
"); } }


"Count All Palindrome Sub | Java Program to count palindrome substring in a string ; Method which return count palindrome substring ; Iterate the loop twice ; Get each substring ; If length is greater than or equal to two Check for palindrome ; Use StringBuffer class to reverse the string ; Compare substring wih reverse of substring ; return the count ; Driver Code ; Declare and initialize the string ; Call the method"
How can the above be solved in Java?

public class PalindromeSubstring { static int countPS ( String str ) { String temp = " " ; StringBuffer stf ; int count = 0 ; for ( int i = 0 ; i < str . length ( ) ; i ++ ) { for ( int j = i + 1 ; j <= str . length ( ) ; j ++ ) { temp = str . substring ( i , j ) ; if ( temp . length ( ) >= 2 ) { stf = new StringBuffer ( temp ) ; stf . reverse ( ) ; if ( stf . toString ( ) . compareTo ( temp ) == 0 ) count ++ ; } } } return count ; } public static void main ( String args [ ] ) throws Exception { String str = " abbaeae " ; System . out . println ( countPS ( str ) ) ; }


"Count All Palindrome Sub | Java program to find palindromic substrings of a string ; Returns total number of palindrome substring of length greater then equal to 2 ; create empty 2 - D matrix that counts all palindrome substring . dp [ i ] [ j ] stores counts of palindromic substrings in st [ i . . j ] ; P [ i ] [ j ] = true if substring str [ i . . j ] is palindrome , else false ; palindrome of single length ; palindrome of length 2 ; Palindromes of length more than 2. This loop is similar to Matrix Chain Multiplication . We start with a gap of length 2 and fill the DP table in a way that gap between starting and ending indexes increases one by one by outer loop . ; Pick starting point for current gap ; Set ending point ; If current string is palindrome ; Add current palindrome substring ( + 1 ) and rest palindrome substring ( dp [ i ] [ j - 1 ] + dp [ i + 1 ] [ j ] ) remove common palindrome substrings ( - dp [ i + 1 ] [ j - 1 ] ) ; return total palindromic substrings ; Driver code"
How can the above be solved in Java?

public class GFG { static int CountPS ( char str [ ] , int n ) { int dp [ ] [ ] = new int [ n ] [ n ] ; boolean P [ ] [ ] = new boolean [ n ] [ n ] ; for ( int i = 0 ; i < n ; i ++ ) P [ i ] [ i ] = true ; for ( int i = 0 ; i < n - 1 ; i ++ ) { if ( str [ i ] == str [ i + 1 ] ) { P [ i ] [ i + 1 ] = true ; dp [ i ] [ i + 1 ] = 1 ; } } for ( int gap = 2 ; gap < n ; gap ++ ) { for ( int i = 0 ; i < n - gap ; i ++ ) { int j = gap + i ; if ( str [ i ] == str [ j ] && P [ i + 1 ] [ j - 1 ] ) P [ i ] [ j ] = true ; if ( P [ i ] [ j ] == true ) dp [ i ] [ j ] = dp [ i ] [ j - 1 ] + dp [ i + 1 ] [ j ] + 1 - dp [ i + 1 ] [ j - 1 ] ; else dp [ i ] [ j ] = dp [ i ] [ j - 1 ] + dp [ i + 1 ] [ j ] - dp [ i + 1 ] [ j - 1 ] ; } } return dp [ 0 ] [ n - 1 ] ; } public static void main ( String [ ] args ) { String str = " abaab " ; System . out . println ( CountPS ( str . toCharArray ( ) , str . length ( ) ) ) ; } }


"Count All Palindromic Subsequence in a given String | Java code to Count Palindromic Subsequence in a given String ; Function return the total palindromic subsequence ; create a 2D array to store the count of palindromic subsequence ; palindromic subsequence of length 1 ; check subsequence of length L is palindrome or not ; return total palindromic subsequence ; Driver program"
How can the above be solved in Java?

public class GFG { static int countPS ( String str ) { int N = str . length ( ) ; int [ ] [ ] cps = new int [ N ] [ N ] ; for ( int i = 0 ; i < N ; i ++ ) cps [ i ] [ i ] = 1 ; for ( int L = 2 ; L <= N ; L ++ ) { for ( int i = 0 ; i <= N - L ; i ++ ) { int k = L + i - 1 ; if ( str . charAt ( i ) == str . charAt ( k ) ) { cps [ i ] [ k ] = cps [ i ] [ k - 1 ] + cps [ i + 1 ] [ k ] + 1 ; } else { cps [ i ] [ k ] = cps [ i ] [ k - 1 ] + cps [ i + 1 ] [ k ] - cps [ i + 1 ] [ k - 1 ] ; } } } return cps [ 0 ] [ N - 1 ] ; } public static void main ( String args [ ] ) { String str = " abcb " ; System . out . println ( " Total ▁ palindromic ▁ " + " subsequence ▁ are ▁ : ▁ " + countPS ( str ) ) ; } }


"Count All Palindromic Subsequence in a given String | Java program to counts Palindromic Subsequence in a given String using recursion ; Function return the total palindromic subsequence ; Driver code"
How can the above be solved in Java?

class GFG { static int n ; static int [ ] [ ] dp = new int [ 1000 ] [ 1000 ] ; static String str = " abcb " ; static int countPS ( int i , int j ) { if ( i > j ) return 0 ; if ( dp [ i ] [ j ] != - 1 ) return dp [ i ] [ j ] ; if ( i == j ) return dp [ i ] [ j ] = 1 ; else if ( str . charAt ( i ) == str . charAt ( j ) ) return dp [ i ] [ j ] = countPS ( i + 1 , j ) + countPS ( i , j - 1 ) + 1 ; else return dp [ i ] [ j ] = countPS ( i + 1 , j ) + countPS ( i , j - 1 ) - countPS ( i + 1 , j - 1 ) ; } public static void main ( String [ ] args ) { for ( int i = 0 ; i < 1000 ; i ++ ) for ( int j = 0 ; j < 1000 ; j ++ ) dp [ i ] [ j ] = - 1 ; n = str . length ( ) ; System . out . println ( " Total ▁ palindromic ▁ subsequence " + " are ▁ : ▁ " + countPS ( 0 , n - 1 ) ) ; } }


"Count Arithmetic Progressions having sum N and common difference equal to 1 | Java program for the above approach ; Function to count all possible AP series with common difference 1 and sum of elements equal to N ; Stores the count of AP series ; Traverse through all factors of 2 * N ; Check for the given conditions ; Increment count ; Print count - 1 ; Driver code ; Given value of N ; Function call to count required number of AP series"
How can the above be solved in Java?

import java . io . * ; import java . lang . * ; import java . util . * ; class GFG { static void countAPs ( long N ) { long count = 0 ; for ( long i = 1 ; i * i <= 2 * N ; i ++ ) { long res = 2 * N ; if ( res % i == 0 ) { long op = res / i - i + 1 ; if ( op % 2 == 0 ) { count ++ ; } if ( i * i != res && ( i - res / i + 1 ) % 2 == 0 ) { count ++ ; } } } System . out . println ( count - 1 ) ; } public static void main ( String [ ] args ) { long N = 963761198400L ; countAPs ( N ) ; } }


"Count Arithmetic Progressions having sum S and common difference equal to D | Java program for above approach package whatever do not write package name here ; Function to count the number of APs with sum S and common difference D ; Multiply S by 2 ; Stores the count of APs ; Iterate over the factors of 2 * S ; Check if i is the factor or not ; Conditions to check if AP can be formed using factor F ; Return the total count of APs ; Driver code"
How can the above be solved in Java?

import java . io . * ; class GFG { static int countAPs ( int S , int D ) { S = S * 2 ; int answer = 0 ; for ( int i = 1 ; i <= Math . sqrt ( S ) ; i ++ ) { if ( S % i == 0 ) { if ( ( ( S / i ) - D * i + D ) % 2 == 0 ) answer ++ ; if ( ( D * i - ( S / i ) + D ) % 2 == 0 ) answer ++ ; } } return answer ; } public static void main ( String [ ] args ) { int S = 12 , D = 1 ; System . out . println ( countAPs ( S , D ) ) ; } }


"Count BST subtrees that lie in given range | Java program to count subtrees that lie in a given range ; A BST node ; int class ; A utility function to check if data of root is in range from low to high ; A recursive function to get count of nodes whose subtree is in range from low to hgih . This function returns true if nodes in subtree rooted under ' root ' are in range . ; Base case ; Recur for left and right subtrees ; If both left and right subtrees are in range and current node is also in range , then increment count and return true ; A wrapper over getCountUtil ( ) . This function initializes count as 0 and calls getCountUtil ( ) ; Utility function to create new node ; Driver code ; Let us con the BST shown in the above figure ; Let us construct BST shown in above example 10 / \ 5 50 / / \ 1 40 100"
How can the above be solved in Java?

class GfG { static class node { int data ; node left , right ; } ; static class INT { int a ; } static boolean inRange ( node root , int low , int high ) { return root . data >= low && root . data <= high ; } static boolean getCountUtil ( node root , int low , int high , INT count ) { if ( root == null ) return true ; boolean l = getCountUtil ( root . left , low , high , count ) ; boolean r = getCountUtil ( root . right , low , high , count ) ; if ( l && r && inRange ( root , low , high ) ) { ++ count . a ; return true ; } return false ; } static INT getCount ( node root , int low , int high ) { INT count = new INT ( ) ; count . a = 0 ; getCountUtil ( root , low , high , count ) ; return count ; } static node newNode ( int data ) { node temp = new node ( ) ; temp . data = data ; temp . left = temp . right = null ; return ( temp ) ; } public static void main ( String args [ ] ) { node root = newNode ( 10 ) ; root . left = newNode ( 5 ) ; root . right = newNode ( 50 ) ; root . left . left = newNode ( 1 ) ; root . right . left = newNode ( 40 ) ; root . right . right = newNode ( 100 ) ; int l = 5 ; int h = 45 ; System . out . println ( " Count ▁ of ▁ subtrees ▁ in ▁ [ " + l + " , ▁ " + h + " ] ▁ is ▁ " + getCount ( root , l , h ) . a ) ; } }


"Count Balanced Binary Trees of Height h | Java program to count number of balanced binary trees of height h . ; base cases ; Driver program"
How can the above be solved in Java?

class GFG { static final int MOD = 1000000007 ; public static long countBT ( int h ) { long [ ] dp = new long [ h + 1 ] ; dp [ 0 ] = 1 ; dp [ 1 ] = 1 ; for ( int i = 2 ; i <= h ; ++ i ) dp [ i ] = ( dp [ i - 1 ] * ( ( 2 * dp [ i - 2 ] ) % MOD + dp [ i - 1 ] ) % MOD ) % MOD ; return dp [ h ] ; } public static void main ( String [ ] args ) { int h = 3 ; System . out . println ( " No . ▁ of ▁ balanced ▁ binary ▁ trees ▁ of ▁ height ▁ " + h + " ▁ is : ▁ " + countBT ( h ) ) ; } }


"Count Derangements ( Permutation such that no element appears in its original position ) | A Dynamic programming based java program to count derangements ; Function to count derangements ; Create an array to store counts for subproblems ; Base cases ; Fill der [ 0. . n ] in bottom up manner using above recursive formula ; Return result for n ; Driver program"
How can the above be solved in Java?

import java . io . * ; class GFG { static int countDer ( int n ) { int der [ ] = new int [ n + 1 ] ; der [ 1 ] = 0 ; der [ 2 ] = 1 ; for ( int i = 3 ; i <= n ; ++ i ) der [ i ] = ( i - 1 ) * ( der [ i - 1 ] + der [ i - 2 ] ) ; return der [ n ] ; } public static void main ( String [ ] args ) { int n = 4 ; System . out . println ( " Count ▁ of ▁ Derangements ▁ is ▁ " + countDer ( n ) ) ; } }


"Count Derangements ( Permutation such that no element appears in its original position ) | A Naive Recursive java program to count derangements ; Function to count derangements ; Base cases ; countDer ( n ) = ( n - 1 ) [ countDer ( n - 1 ) + der ( n - 2 ) ] ; Driver Code"
How can the above be solved in Java?

import java . io . * ; class GFG { static int countDer ( int n ) { if ( n == 1 ) return 0 ; if ( n == 2 ) return 1 ; return ( n - 1 ) * ( countDer ( n - 1 ) + countDer ( n - 2 ) ) ; } public static void main ( String [ ] args ) { int n = 4 ; System . out . println ( " Count ▁ of ▁ Derangements ▁ is ▁ " + countDer ( n ) ) ; } }


"Count Derangements ( Permutation such that no element appears in its original position ) | Java implementation of the above approach ; Function to count derangements ; Base case ; Variable for storing prev values ; manner using above recursive formula ; Return result for n ; Driver Code"
How can the above be solved in Java?

import java . io . * ; class GFG { static int countDer ( int n ) { if ( n == 1 n == 2 ) { return n - 1 ; } int a = 0 ; int b = 1 ; for ( int i = 3 ; i <= n ; ++ i ) { int cur = ( i - 1 ) * ( a + b ) ; a = b ; b = cur ; } return b ; } public static void main ( String [ ] args ) { int n = 4 ; System . out . println ( " Count ▁ of ▁ Dearrangements ▁ is ▁ " + countDer ( n ) ) ; } }


"Count Distinct Non | An efficient Java program to find different ( x , y ) pairs that satisfy x * x + y * y < n . ; This function counts number of pairs ( x , y ) that satisfy the inequality x * x + y * y < n . ; Find the count of different y values for x = 0. ; One by one increase value of x , and find yCount forcurrent x . If yCount becomes 0 , then we have reached maximum possible value of x . ; Add yCount ( count of different possible values of y for current x ) to result ; Increment x ; Update yCount for current x . Keep reducing yCount while the inequality is not satisfied . ; Driver program"
How can the above be solved in Java?

import java . io . * ; class GFG { static int countSolutions ( int n ) { int x = 0 , yCount , res = 0 ; for ( yCount = 0 ; yCount * yCount < n ; yCount ++ ) ; while ( yCount != 0 ) { res += yCount ; x ++ ; while ( yCount != 0 && ( x * x + ( yCount - 1 ) * ( yCount - 1 ) >= n ) ) yCount -- ; } return res ; } public static void main ( String args [ ] ) { System . out . println ( " Total ▁ Number ▁ of ▁ distinct ▁ Non - Negative ▁ pairs ▁ is ▁ " + countSolutions ( 6 ) ) ; } }


"Count Distinct Non | Java code to Count Distinct Non - Negative Integer Pairs ( x , y ) that Satisfy the inequality x * x + y * y < n ; This function counts number of pairs ( x , y ) that satisfy the inequality x * x + y * y < n . ; Driver program"
How can the above be solved in Java?

import java . io . * ; class GFG { static int countSolutions ( int n ) { int res = 0 ; for ( int x = 0 ; x * x < n ; x ++ ) for ( int y = 0 ; x * x + y * y < n ; y ++ ) res ++ ; return res ; } public static void main ( String args [ ] ) { System . out . println ( " Total ▁ Number ▁ of ▁ distinct ▁ Non - Negative ▁ pairs ▁ is ▁ " + countSolutions ( 6 ) ) ; } }


"Count Distinct Strings present in an array using Polynomial rolling hash function | Java program to implement the above approach ; Function to find the hash value of a string ; Traverse the string ; Update hash_val ; Update mul ; Return hash_val of str ; Function to find the count of distinct strings present in the given array ; Store the hash values of the strings ; Traverse the array ; Stores hash value of arr [ i ] ; Sort hash [ ] array ; Stores count of distinct strings in the array ; Traverse hash [ ] array ; Update cntElem ; Driver Code"
How can the above be solved in Java?

import java . util . Arrays ; public class GFG { static int compute_hash ( String str ) { int p = 31 ; int MOD = ( int ) 1e9 + 7 ; int hash_val = 0 ; int mul = 1 ; for ( int i = 0 ; i < str . length ( ) ; i ++ ) { char ch = str . charAt ( i ) ; hash_val = ( hash_val + ( ch - ' a ' + 1 ) * mul ) % MOD ; mul = ( mul * p ) % MOD ; } return hash_val ; } static int distinct_str ( String arr [ ] , int n ) { int hash [ ] = new int [ n ] ; for ( int i = 0 ; i < n ; i ++ ) { hash [ i ] = compute_hash ( arr [ i ] ) ; } Arrays . sort ( hash ) ; int cntElem = 1 ; for ( int i = 1 ; i < n ; i ++ ) { if ( hash [ i ] != hash [ i - 1 ] ) { cntElem ++ ; } } return cntElem ; } public static void main ( String [ ] args ) { String arr [ ] = { " abcde " , " abcce " , " abcdf " , " abcde " } ; int N = arr . length ; System . out . println ( distinct_str ( arr , N ) ) ; } }


"Count Distinct Subsequences | Java Program for above approach ; Returns count of distinct subsequences of str . ; Iterate from 0 to s . length ( ) ; Iterate from 0 to s . length ( ) ; Check if i equal to 0 ; Replace levelCount withe allCount + 1 ; If map is less than 0 ; Return answer ; Driver Code"
How can the above be solved in Java?

import java . io . * ; import java . util . * ; class SubsequenceCount { public static int countSub ( String s ) { HashMap < Character , Integer > map = new HashMap < Character , Integer > ( ) ; for ( int i = 0 ; i < s . length ( ) ; i ++ ) { map . put ( s . charAt ( i ) , - 1 ) ; } int allCount = 0 ; int levelCount = 0 ; for ( int i = 0 ; i < s . length ( ) ; i ++ ) { char c = s . charAt ( i ) ; if ( i == 0 ) { allCount = 1 ; map . put ( c , 1 ) ; levelCount = 1 ; continue ; } levelCount = allCount + 1 ; if ( map . get ( c ) < 0 ) { allCount = allCount + levelCount ; } else { allCount = allCount + levelCount - map . get ( c ) ; } map . put ( c , levelCount ) ; } return allCount ; } public static void main ( String [ ] args ) { List < String > list = Arrays . asList ( " abab " , " gfg " ) ; for ( String s : list ) { int cnt = countSub ( s ) ; int withEmptyString = cnt + 1 ; System . out . println ( " With ▁ empty ▁ string ▁ count ▁ for ▁ " + s + " ▁ is ▁ " + withEmptyString ) ; System . out . println ( " Without ▁ empty ▁ string ▁ count ▁ for ▁ " + s + " ▁ is ▁ " + cnt ) ; } } }


"Count Divisors of Factorial | JAVA program to find count of divisors in n ! ; allPrimes [ ] stores all prime numbers less than or equal to n . ; Fills above vector allPrimes [ ] for a given n ; Create a boolean array " prime [ 0 . . n ] " and initialize all entries it as true . A value in prime [ i ] will finally be false if i is not a prime , else true . ; Loop to update prime [ ] ; If prime [ p ] is not changed , then it is a prime ; Update all multiples of p ; Store primes in the vector allPrimes ; Function to find all result of factorial number ; Initialize result ; find exponents of all primes which divides n and less than n ; Current divisor ; Find the highest power ( stored in exp ) ' ▁ ▁ of ▁ allPrimes [ i ] ▁ that ▁ divides ▁ n ▁ using ▁ ▁ Legendre ' s formula . ; Multiply exponents of all primes less than n ; return total divisors ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { static Vector < Integer > allPrimes = new Vector < Integer > ( ) ; static void sieve ( int n ) { boolean [ ] prime = new boolean [ n + 1 ] ; for ( int i = 0 ; i <= n ; i ++ ) prime [ i ] = true ; for ( int p = 2 ; p * p <= n ; p ++ ) { if ( prime [ p ] == true ) { for ( int i = p * 2 ; i <= n ; i += p ) prime [ i ] = false ; } } for ( int p = 2 ; p <= n ; p ++ ) if ( prime [ p ] ) allPrimes . add ( p ) ; } static long factorialDivisors ( int n ) { long result = 1 ; for ( int i = 0 ; i < allPrimes . size ( ) ; i ++ ) { long p = allPrimes . get ( i ) ; long exp = 0 ; while ( p <= n ) { exp = exp + ( n / p ) ; p = p * allPrimes . get ( i ) ; } result = result * ( exp + 1 ) ; } return result ; } public static void main ( String [ ] args ) { System . out . println ( factorialDivisors ( 6 ) ) ; } }


"Count Divisors of n in O ( n ^ 1 / 3 ) | JAVA implementation of Naive method to count all divisors ; function to count the divisors ; If divisors are equal , count only one ; else Otherwise count both ; Driver program to test above function"
How can the above be solved in Java?

import java . io . * ; import java . math . * ; class GFG { static int countDivisors ( int n ) { int cnt = 0 ; for ( int i = 1 ; i <= Math . sqrt ( n ) ; i ++ ) { if ( n % i == 0 ) { if ( n / i == i ) cnt ++ ; cnt = cnt + 2 ; } } return cnt ; } public static void main ( String args [ ] ) { System . out . println ( " Total ▁ distinct ▁ " + " divisors ▁ of ▁ 100 ▁ are ▁ : ▁ " + countDivisors ( 100 ) ) ; } }


"Count Full Prime numbers in a given range | Java program to implement the above approach ; Function to check if a number is prime or not ; If a divisor of n exists ; Function to check if a number is Full Prime or not ; If n is not a prime ; Otherwise ; Extract digit ; If any digit of n is non - prime ; Function to print count of Full Primes in a range [ L , R ] ; Stores count of full primes ; Check if i is full prime ; Driver Code ; Stores count of full primes"
How can the above be solved in Java?

import java . io . * ; import java . util . * ; class GFG { static boolean isPrime ( int num ) { if ( num <= 1 ) return false ; for ( int i = 2 ; i * i <= num ; i ++ ) if ( num % i == 0 ) return false ; return true ; } static boolean isFulPrime ( int n ) { if ( ! isPrime ( n ) ) return false ; else { while ( n > 0 ) { int rem = n % 10 ; if ( ! ( rem == 2 rem == 3 rem == 5 rem == 7 ) ) return false ; n = n / 10 ; } } return true ; } static int countFulPrime ( int L , int R ) { int cnt = 0 ; for ( int i = L ; i <= R ; i ++ ) { if ( ( i % 2 ) != 0 && isFulPrime ( i ) ) { cnt ++ ; } } return cnt ; } public static void main ( String [ ] args ) { int L = 1 , R = 100 ; int ans = 0 ; if ( L < 3 ) ans ++ ; System . out . println ( ans + countFulPrime ( L , R ) ) ; } }


"Count Inversions in an array | Set 1 ( Using Merge Sort ) | Java program to count inversions in an array ; Driver method to test the above function"
How can the above be solved in Java?

class Test { static int arr [ ] = new int [ ] { 1 , 20 , 6 , 4 , 5 } ; static int getInvCount ( int n ) { int inv_count = 0 ; for ( int i = 0 ; i < n - 1 ; i ++ ) for ( int j = i + 1 ; j < n ; j ++ ) if ( arr [ i ] > arr [ j ] ) inv_count ++ ; return inv_count ; } public static void main ( String [ ] args ) { System . out . println ( " Number ▁ of ▁ inversions ▁ are ▁ " + getInvCount ( arr . length ) ) ; } }


"Count Inversions of size three in a given array | A O ( n ^ 2 ) Java program to count inversions of size 3 ; returns count of inversion of size 3 ; initialize result ; count all smaller elements on right of arr [ i ] ; count all greater elements on left of arr [ i ] ; update inversion count by adding all inversions that have arr [ i ] as middle of three elements ; driver program to test above function"
How can the above be solved in Java?

class Inversion { int getInvCount ( int arr [ ] , int n ) { int invcount = 0 ; for ( int i = 0 ; i < n - 1 ; i ++ ) { int small = 0 ; for ( int j = i + 1 ; j < n ; j ++ ) if ( arr [ i ] > arr [ j ] ) small ++ ; int great = 0 ; for ( int j = i - 1 ; j >= 0 ; j -- ) if ( arr [ i ] < arr [ j ] ) great ++ ; invcount += great * small ; } return invcount ; } public static void main ( String args [ ] ) { Inversion inversion = new Inversion ( ) ; int arr [ ] = new int [ ] { 8 , 4 , 2 , 1 } ; int n = arr . length ; System . out . print ( " Inversion ▁ count ▁ : ▁ " + inversion . getInvCount ( arr , n ) ) ; } }


"Count Knights that can attack a given pawn in an N * N board | Java program to implement the above approach ; Function to count the knights that are attacking the pawn in an M * M board ; Stores count of knights that are attacking the pawn ; Traverse the knights [ ] [ ] array ; Stores absolute difference of X co - ordinate of i - th knight and pawn ; Stores absolute difference of Y co - ordinate of i - th knight and pawn ; If X is 1 and Y is 2 or X is 2 and Y is 1 ; Update cntKnights ; Driver code ; Stores total count of knights"
How can the above be solved in Java?

import java . io . * ; import java . lang . Math ; class GFG { static int cntKnightsAttackPawn ( int knights [ ] [ ] , int pawn [ ] , int M ) { int cntKnights = 0 ; for ( int i = 0 ; i < M ; i ++ ) { int X = Math . abs ( knights [ i ] [ 0 ] - pawn [ 0 ] ) ; int Y = Math . abs ( knights [ i ] [ 1 ] - pawn [ 1 ] ) ; if ( ( X == 1 && Y == 2 ) || ( X == 2 && Y == 1 ) ) { cntKnights ++ ; } } return cntKnights ; } public static void main ( String [ ] args ) { int [ ] [ ] knights = { { 0 , 4 } , { 4 , 5 } , { 1 , 4 } , { 3 , 1 } } ; int [ ] pawn = new int [ ] { 2 , 3 } ; int M = knights . length ; System . out . println ( cntKnightsAttackPawn ( knights , pawn , M ) ) ; } }


"Count L | Java program for the above approach ; Fumction to find the number of arrays of length L such that each element divides the next element ; Stores the number of sequences of length i that ends with j ; Base Case ; Iterate over the range [ 0 , l ] ; Iterate for all multiples of j ; Incrementing dp [ i + 1 ] [ k ] by dp [ i ] [ j ] as the next element is multiple of j ; Stores the number of arrays ; Add all array of length L that ends with i ; Return the resultant count ; Driver Code"
How can the above be solved in Java?

import java . io . * ; class GFG { static int numberOfArrays ( int n , int l ) { int [ ] [ ] dp = new int [ l + 1 ] [ n + 1 ] ; dp [ 0 ] [ 1 ] = 1 ; for ( int i = 0 ; i < l ; i ++ ) { for ( int j = 1 ; j <= n ; j ++ ) { for ( int k = j ; k <= n ; k += j ) { dp [ i + 1 ] [ k ] += dp [ i ] [ j ] ; } } } int ans = 0 ; for ( int i = 1 ; i <= n ; i ++ ) { ans += dp [ l ] [ i ] ; } return ans ; } public static void main ( String [ ] args ) { int N = 2 , L = 4 ; System . out . println ( numberOfArrays ( N , L ) ) ; } }


"Count N digits numbers with sum divisible by K | Java program to implement the above approach ; Function to count the N digit numbers whose sum is divisible by K ; Base case ; If already computed subproblem occurred ; Store the count of N digit numbers whoe sum is divisible by K ; Check if the number does not contain any leading 0. ; Recurrence relation ; Driver code ; Stores the values of overlapping subproblems"
How can the above be solved in Java?

import java . util . * ; import java . lang . * ; class GFG { static final int M = 1000 ; static int countNum ( int N , int sum , int K , int st , int dp [ ] [ ] [ ] ) { if ( N == 0 && sum == 0 ) { return 1 ; } if ( N < 0 ) { return 0 ; } if ( dp [ N ] [ sum ] [ st ] != - 1 ) { return dp [ N ] [ sum ] [ st ] ; } int res = 0 ; int start = st == 1 ? 0 : 1 ; for ( int i = start ; i <= 9 ; i ++ ) { res += countNum ( N - 1 , ( sum + i ) % K , K , ( ( st i ) > 0 ) ? 1 : 0 , dp ) ; } return dp [ N ] [ sum ] [ st ] = res ; } public static void main ( String [ ] args ) { int N = 2 , K = 7 ; int [ ] [ ] [ ] dp = new int [ M ] [ M ] [ 2 ] ; for ( int [ ] [ ] i : dp ) for ( int [ ] j : i ) Arrays . fill ( j , - 1 ) ; System . out . print ( countNum ( N , 0 , K , 0 , dp ) ) ; } }


"Count N |  ; Stores the dp states ; Check if a number is a prime or not ; Function to generate all prime numbers that are less than or equal to n ; Base cases . ; If prime [ p ] is not changed , then it is a prime ; Update all multiples of as non - prime ; Function to find the count of N - digit numbers such that the sum of digits is a prime number ; If end of array is reached ; If the sum is equal to a prime number ; Otherwise ; If the dp - states are already computed ; If index = 1 , any digit from [ 1 - 9 ] can be placed . If N = 1 , 0 also can be placed . ; Otherwise , any digit from [ 0 - 9 ] can be placed . ; Return the answer . ; Driver Code ; Initializing dp array with - 1 ; Initializing prime array to true ; Find all primes less than or equal to 1000 , which is sufficient for N upto 100 ; Given Input ; Function call"
How can the above be solved in Java?

import java . util . Arrays ; class GFG { public static int [ ] [ ] dp = new int [ 100 ] [ 1000 ] ; public static boolean [ ] prime = new boolean [ 1005 ] ; public static void SieveOfEratosthenes ( int n ) { prime [ 0 ] = prime [ 1 ] = false ; for ( int p = 2 ; p * p <= n ; p ++ ) { if ( prime [ p ] == true ) { for ( int i = p * p ; i <= n ; i += p ) prime [ i ] = false ; } } } public static int countOfNumbers ( int index , int sum , int N ) { if ( index == N + 1 ) { if ( prime [ sum ] == true ) { return 1 ; } return 0 ; } int val = dp [ index ] [ sum ] ; if ( val != - 1 ) { return val ; } val = 0 ; if ( index == 1 ) { for ( int digit = ( N == 1 ? 0 : 1 ) ; digit <= 9 ; ++ digit ) { val += countOfNumbers ( index + 1 , sum + digit , N ) ; } } else { for ( int digit = 0 ; digit <= 9 ; ++ digit ) { val += countOfNumbers ( index + 1 , sum + digit , N ) ; } } return val ; } public static void main ( String args [ ] ) { for ( int [ ] row : dp ) Arrays . fill ( row , - 1 ) ; Arrays . fill ( prime , true ) ; SieveOfEratosthenes ( 1000 ) ; int N = 6 ; System . out . println ( countOfNumbers ( 1 , 0 , N ) ) ; } }


"Count N | Java program for the above approach ; Function for calculate ( x ^ y ) % mod in O ( log y ) ; Base Condition ; Transition state of power Function ; Function for counting total numbers that can be formed such that digits X , Y are present in each number ; Calculate the given expression ; Return the final answer ; Driver Code"
How can the above be solved in Java?

 import java . util . * ; class GFG { static int mod = ( int ) ( 1e9 + 7 ) ; static long power ( int x , int y ) { if ( y == 0 ) return 1 ; int p = ( int ) ( power ( x , y / 2 ) % mod ) ; p = ( p * p ) % mod ; if ( y % 2 == 1 ) { p = ( x * p ) % mod ; } return p ; } static int TotalNumber ( int N ) { int ans = ( int ) ( ( power ( 10 , N ) - 2 * power ( 9 , N ) + power ( 8 , N ) + 2 * mod ) % mod ) ; return ans ; } public static void main ( String [ ] args ) { int N = 10 , X = 3 , Y = 4 ; System . out . print ( TotalNumber ( N ) + "
"); } }


"Count N | Java program for the above approach ; Function to calculate the power of n ^ k % p ; Update x if it is more than or equal to p ; In case x is divisible by p ; ; If y is odd , multiply x with result ; y must be even now y = y >> 1 ; y = y / 2 ; Function to count the number of arrays satisfying required conditions ; Calculating N ^ K ; Driver Code"
How can the above be solved in Java?

import java . io . * ; 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 ; x = ( x * x ) % p ; } return res ; } static int countArrays ( int n , int k ) { int mod = 1000000007 ; int ans = power ( n , k , mod ) ; return ans ; } public static void main ( String [ ] args ) { int n = 3 , k = 5 ; int ans = countArrays ( n , k ) ; System . out . println ( ans ) ; } }


"Count N | Java program for the above approach ; Function to count N - digit numbers such that each position is divisible by the digit occurring at that position ; Stores the answer . ; Iterate from indices 1 to N ; Stores count of digits that can be placed at the current index ; Iterate from digit 1 to 9 ; If index is divisible by digit ; Multiply answer with possible choices ; Driver Code ; Given Input ; Function call"
How can the above be solved in Java?

import java . lang . * ; import java . util . * ; class GFG { static int mod = 1000000007 ; static void countOfNumbers ( int N ) { int ans = 1 ; for ( int index = 1 ; index <= N ; ++ index ) { int choices = 0 ; for ( int digit = 1 ; digit <= 9 ; ++ digit ) { if ( index % digit == 0 ) { ++ choices ; } } ans = ( ans * choices ) % mod ; } System . out . println ( ans ) ; } public static void main ( String [ ] args ) { int N = 5 ; countOfNumbers ( N ) ; } }


"Count N | Java program for the above approach ; Function to count N - length strings consisting of vowels only sorted lexicographically ; Initializing vector to store count of strings . ; Summing up the total number of combinations . ; Return the result ; Function Call"
How can the above be solved in Java?

import java . util . * ; public class Main { static int findNumberOfStrings ( int N ) { Vector < Integer > counts = new Vector < Integer > ( ) ; for ( int i = 0 ; i < 5 ; i ++ ) { counts . add ( 1 ) ; } for ( int i = 2 ; i <= N ; i ++ ) { for ( int j = 3 ; j >= 0 ; j -- ) counts . set ( j , counts . get ( j ) + counts . get ( j + 1 ) ) ; } int ans = 0 ; for ( Integer c : counts ) ans += c ; return ans ; } public static void main ( String [ ] args ) { int N = 2 ; System . out . print ( findNumberOfStrings ( N ) ) ; } }


"Count N | Java program for the above approach ; Function to count N digit numbers whose digits are less than or equal to the absolute difference of previous two digits ; If all digits are traversed ; If the state has already been computed ; If the current digit is 1 , any digit from [ 1 - 9 ] can be placed . If N == 1 , 0 can also be placed . ; If the current digit is 2 , any digit from [ 0 - 9 ] can be placed ; For other digits , any digit from 0 to abs ( prev1 - prev2 ) can be placed ; Return the answer ; Driver Code ; Input ; Function call"
How can the above be solved in Java?

import java . util . * ; class GFG { static int dp [ ] [ ] [ ] = new int [ 50 ] [ 10 ] [ 10 ] ; static void initialize ( ) { for ( int i = 0 ; i < 50 ; i ++ ) { for ( int j = 0 ; j < 10 ; j ++ ) { for ( int k = 0 ; k < 10 ; k ++ ) { dp [ i ] [ j ] [ k ] = - 1 ; } } } } static int countOfNumbers ( int digit , int prev1 , int prev2 , int N ) { if ( digit == N + 1 ) return 1 ; if ( dp [ digit ] [ prev1 ] [ prev2 ] != - 1 ) return dp [ digit ] [ prev1 ] [ prev2 ] ; dp [ digit ] [ prev1 ] [ prev2 ] = 0 ; if ( digit == 1 ) { for ( int j = ( N == 1 ? 0 : 1 ) ; j <= 9 ; ++ j ) { dp [ digit ] [ prev1 ] [ prev2 ] += countOfNumbers ( digit + 1 , j , prev1 , N ) ; } } else if ( digit == 2 ) { for ( int j = 0 ; j <= 9 ; ++ j ) { dp [ digit ] [ prev1 ] [ prev2 ] += countOfNumbers ( digit + 1 , j , prev1 , N ) ; } } else { for ( int j = 0 ; j <= Math . abs ( prev1 - prev2 ) ; ++ j ) { dp [ digit ] [ prev1 ] [ prev2 ] += countOfNumbers ( digit + 1 , j , prev1 , N ) ; } } return dp [ digit ] [ prev1 ] [ prev2 ] ; } public static void main ( String [ ] args ) { initialize ( ) ; int N = 3 ; System . out . print ( countOfNumbers ( 1 , 0 , 0 , N ) ) ; } }


"Count N | Java program for the above approach ; Function to count binary strings of length N having substring "11" ; Initialize dp [ ] of size N + 1 ; Base Cases ; Stores the first N powers of 2 ; Generate ; Iterate over the range [ 2 , N ] ; Print total count of substrings ; Driver Code"
How can the above be solved in Java?

import java . util . * ; class GFG { static void binaryStrings ( int N ) { int [ ] dp = new int [ N + 1 ] ; dp [ 0 ] = 0 ; dp [ 1 ] = 0 ; int [ ] power = new int [ N + 1 ] ; power [ 0 ] = 1 ; for ( int i = 1 ; i <= N ; i ++ ) { power [ i ] = 2 * power [ i - 1 ] ; } for ( int i = 2 ; i <= N ; i ++ ) { dp [ i ] = dp [ i - 1 ] + dp [ i - 2 ] + power [ i - 2 ] ; } System . out . println ( dp [ N ] ) ; } public static void main ( String [ ] args ) { int N = 12 ; binaryStrings ( N ) ; } }


"Count N | Java program for the above approach ; Function to find the number of arrays following the given condition ; Initialize answer ; Calculate nPm ; Print ans ; Driver Code ; Given N and M ; Function Call"
How can the above be solved in Java?

class GFG { static void noOfArraysPossible ( int N , int M ) { int ans = 1 ; for ( int i = 0 ; i < N ; ++ i ) { ans = ans * ( M - i ) ; } System . out . print ( ans ) ; } public static void main ( String [ ] args ) { int N = 2 , M = 3 ; noOfArraysPossible ( N , M ) ; } }


"Count N | Java program for the above approach ; Function to find the value of x ^ y ; Stores the value of x ^ y ; Iterate until y is positive ; If y is odd ; Divide y by 2 ; Return the value of x ^ y ; Function to find the number of N - digit integers satisfying the given criteria ; Count of even positions ; Count of odd positions ; Return the resultant count ; Driver Code"
How can the above be solved in Java?

import java . io . * ; class GFG { static int m = 1000000007 ; static int power ( int x , int y ) { int res = 1 ; while ( y > 0 ) { if ( ( y & 1 ) != 0 ) res = ( res * x ) % m ; y = y >> 1 ; x = ( x * x ) % m ; } return res ; } static int countNDigitNumber ( int N ) { int ne = N / 2 + N % 2 ; int no = ( int ) Math . floor ( N / 2 ) ; return power ( 4 , ne ) * power ( 5 , no ) ; } public static void main ( String [ ] args ) { int N = 5 ; System . out . println ( countNDigitNumber ( N ) % m ) ; } }


"Count N | Java program for the above approach ; Stores the value of overlapping states ; Function to find the count of numbers that are formed by digits X and Y and whose sum of digit also have digit X or Y ; Initialize dp array ; Base Case ; Check if sum of digits formed by only X or Y ; Return the already computed ; Place the digit X at the current position ; Place the digit Y at the current position ; Update current state result ; Function to check whether a number have only digits X or Y or not ; Until sum is positive ; If any digit is not X or Y then return 0 ; Return 1 ; Driver Code ; Function Call"
How can the above be solved in Java?

import java . util . * ; public class Main { static int dp [ ] [ ] = new int [ 1000 + 5 ] [ 9000 + 5 ] ; static int mod = 1000000007 ; public static int countNumbers ( int n , int x , int y , int sum ) { for ( int i [ ] : dp ) Arrays . fill ( i , - 1 ) ; if ( n == 0 ) { return check ( sum , x , y ) ; } if ( dp [ n ] [ sum ] != - 1 ) { return dp [ n ] [ sum ] % mod ; } int option1 = countNumbers ( n - 1 , x , y , sum + x ) % mod ; int option2 = countNumbers ( n - 1 , x , y , sum + y ) % mod ; return dp [ n ] [ sum ] = ( option1 + option2 ) % mod ; } public static int check ( int sum , int x , int y ) { while ( sum > 0 ) { int ln = sum % 10 ; if ( ln != x && ln != y ) { return 0 ; } sum /= 10 ; } return 1 ; } public static void main ( String args [ ] ) { int N = 3 , X = 1 , Y = 5 ; System . out . println ( countNumbers ( N , X , Y , 0 ) % mod ) ; } }


"Count N | Java program to illustrate Count of N - length strings consisting only of vowels sorted lexicographically ; to keep the string in lexicographically sorted order use start index to add the vowels starting the from that index ; base case : if string length is 0 add to the count ; if last character in string is ' e ' add vowels starting from ' e ' i . e ' e ' , ' i ' , ' o ' , ' u ' ; decrease the length of string ; char arr [ 5 ] = { ' a ' , ' e ' , ' i ' , ' o ' , ' u ' } ; starting from index 0 add the vowels to strings"
How can the above be solved in Java?

import java . util . * ; public class Main { static int countstrings ( int n , int start ) { if ( n == 0 ) { return 1 ; } int cnt = 0 ; for ( int i = start ; i < 5 ; i ++ ) { cnt += countstrings ( n - 1 , i ) ; } return cnt ; } static int countVowelStrings ( int n ) { return countstrings ( n , 0 ) ; } public static void main ( String [ ] args ) { int n = 2 ; System . out . print ( countVowelStrings ( n ) ) ; } }


"Count N | Java program to implement the above approach ; Function to count N - length strings consisting of vowels only sorted lexicographically ; Driver Code ; Function Call"
How can the above be solved in Java?

import java . util . * ; class GFG { static int findNumberOfStrings ( int n ) { return ( n + 1 ) * ( n + 2 ) * ( n + 3 ) * ( n + 4 ) / 24 ; } public static void main ( String [ ] args ) { int N = 2 ; System . out . print ( findNumberOfStrings ( N ) ) ; } }


"Count N | Java program to implement the above approach ; Function to count N - length strings consisting of vowels only sorted lexicographically ; Stores count of strings consisting of vowels sorted lexicographically of all possible lengths ; Initialize DP [ 1 ] [ 1 ] ; Traverse the matrix row - wise ; Base Case ; Return the result ; Driver Code ; Function Call"
How can the above be solved in Java?

import java . util . * ; class GFG { static int findNumberOfStrings ( int n ) { int DP [ ] [ ] = new int [ n + 1 ] [ 6 ] ; DP [ 1 ] [ 1 ] = 1 ; for ( int i = 1 ; i < n + 1 ; i ++ ) { for ( int j = 1 ; j < 6 ; j ++ ) { if ( i == 1 ) { DP [ i ] [ j ] = DP [ i ] [ j - 1 ] + 1 ; } else { DP [ i ] [ j ] = DP [ i ] [ j - 1 ] + DP [ i - 1 ] [ j ] ; } } } return DP [ n ] [ 5 ] ; } public static void main ( String [ ] args ) { int N = 2 ; System . out . print ( findNumberOfStrings ( N ) ) ; } }


"Count Non | Java program of the above approach ; Function to find the gcd of the two numbers ; Function to find distinct elements in the array by repeatidely inserting the absolute difference of all possible pairs ; Stores largest element of the array ; Traverse the array , arr [ ] ; Update max_value ; Stores GCD of array ; Traverse the array , arr [ ] ; Update GCDArr ; Stores distinct elements in the array by repeatidely inserting absolute difference of all possible pairs ; Driver code ; Given array arr [ ]"
How can the above be solved in Java?

import java . util . * ; class GFG { static int gcd ( int a , int b ) { if ( a == 0 ) return b ; return gcd ( b % a , a ) ; } static int DistinctValues ( int arr [ ] , int N ) { int max_value = Integer . MIN_VALUE ; for ( int i = 0 ; i < N ; ++ i ) { max_value = Math . max ( max_value , arr [ i ] ) ; } int GCDArr = arr [ 0 ] ; for ( int i = 1 ; i < N ; ++ i ) { GCDArr = gcd ( GCDArr , arr [ i ] ) ; } int answer = ( max_value / GCDArr ) + 1 ; return answer ; } public static void main ( String [ ] args ) { int arr [ ] = { 4 , 12 , 16 , 24 } ; int N = arr . length ; System . out . println ( DistinctValues ( arr , N ) ) ; } }


"Count Non | Java program to count total number of non - leaf nodes in a binary tree ; A binary tree node has data , pointer to left child and a pointer to right child ; Helper function that allocates a new node with the given data and NULL left and right pointers . ; Computes the number of non - leaf nodes in a tree . ; Base cases . ; If root is Not NULL and its one of its child is also not NULL ; Driver program to test size function"
How can the above be solved in Java?

class GfG { static class Node { int data ; Node left ; Node right ; } static Node newNode ( int data ) { Node node = new Node ( ) ; node . data = data ; node . left = null ; node . right = null ; return ( node ) ; } static int countNonleaf ( Node root ) { if ( root == null || ( root . left == null && root . right == null ) ) return 0 ; return 1 + countNonleaf ( root . left ) + countNonleaf ( root . right ) ; } public static void main ( String [ ] args ) { Node root = newNode ( 1 ) ; root . left = newNode ( 2 ) ; root . right = newNode ( 3 ) ; root . left . left = newNode ( 4 ) ; root . left . right = newNode ( 5 ) ; System . out . println ( countNonleaf ( root ) ) ; } }


"Count Number of animals in a zoo from given number of head and legs | Java implementation of above approach ; Function that calculates Rabbits ; Driver code"
How can the above be solved in Java?

import java . util . * ; import java . lang . * ; class GFG { static int countRabbits ( int Heads , int Legs ) { int count = 0 ; count = ( Legs ) - 2 * ( Heads ) ; count = count / 2 ; return count ; } public static void main ( String args [ ] ) { int Heads = 100 , Legs = 300 ; int Rabbits = countRabbits ( Heads , Legs ) ; System . out . println ( " Rabbits ▁ = ▁ " + Rabbits ) ; System . out . println ( " Pigeons ▁ = ▁ " + ( Heads - Rabbits ) ) ; } }


"Count Numbers in Range with difference between Sum of digits at even and odd positions as Prime | Java implementation of the above approach ; Prime numbers upto 100 ; Function to return the count of required numbers from 0 to num ; Base Case ; check if the difference is equal to any prime number ; If this result is already computed simply return it ; Maximum limit upto which we can place digit . If tight is 1 , means number has already become smaller so we can place any digit , otherwise num [ pos ] ; If the current position is odd add it to currOdd , otherwise to currEven ; Function to convert x into its digit vector and uses count ( ) function to return the required count ; Initialize dp ; Driver Code"
How can the above be solved in Java?

import java . util . * ; class GFG { static int M = 18 ; static int a , b , dp [ ] [ ] [ ] [ ] = new int [ M ] [ 90 ] [ 90 ] [ 2 ] ; static int prime [ ] = { 2 , 3 , 5 , 7 , 11 , 13 , 17 , 19 , 23 , 29 , 31 , 37 , 43 , 47 , 53 , 59 , 61 , 67 , 71 , 73 , 79 , 83 , 89 , 97 } ; static int count ( int pos , int even , int odd , int tight , Vector < Integer > num ) { if ( pos == num . size ( ) ) { if ( ( num . size ( ) & 1 ) != 0 ) { int t = odd ; odd = even ; even = t ; } int d = even - odd ; for ( int i = 0 ; i < 24 ; i ++ ) if ( d == prime [ i ] ) return 1 ; return 0 ; } if ( dp [ pos ] [ even ] [ odd ] [ tight ] != - 1 ) return dp [ pos ] [ even ] [ odd ] [ tight ] ; int ans = 0 ; int limit = ( tight != 0 ? 9 : num . get ( pos ) ) ; for ( int d = 0 ; d <= limit ; d ++ ) { int currF = tight , currEven = even ; int currOdd = odd ; if ( d < num . get ( pos ) ) currF = 1 ; if ( ( pos & 1 ) != 0 ) currOdd += d ; else currEven += d ; ans += count ( pos + 1 , currEven , currOdd , currF , num ) ; } return dp [ pos ] [ even ] [ odd ] [ tight ] = ans ; } static int solve ( int x ) { Vector < Integer > num = new Vector < Integer > ( ) ; while ( x != 0 ) { num . add ( x % 10 ) ; x /= 10 ; } Collections . reverse ( num ) ; for ( int i = 0 ; i < dp . length ; i ++ ) for ( int j = 0 ; j < dp [ i ] . length ; j ++ ) for ( int k = 0 ; k < dp [ i ] [ j ] . length ; k ++ ) for ( int k1 = 0 ; k1 < dp [ i ] [ j ] [ k ] . length ; k1 ++ ) dp [ i ] [ j ] [ k ] [ k1 ] = - 1 ; return count ( 0 , 0 , 0 , 0 , num ) ; } public static void main ( String args [ ] ) { int L = 1 , R = 50 ; System . out . println ( solve ( R ) - solve ( L - 1 ) ) ; L = 50 ; R = 100 ; System . out . println ( solve ( R ) - solve ( L - 1 ) ) ; } }


"Count Numbers with N digits which consists of even number of 0 ’ s | Java program to count numbers with N digits which consists of odd number of 0 's ; Function to count Numbers with N digits which consists of odd number of 0 's ; Driver code"
How can the above be solved in Java?

import java . lang . * ; import java . util . * ; class GFG { static double countNumbers ( int N ) { return ( Math . pow ( 10 , N ) - 1 ) - ( Math . pow ( 10 , N ) - Math . pow ( 8 , N ) ) / 2 ; } static public void main ( String args [ ] ) { int n = 2 ; System . out . println ( countNumbers ( n ) ) ; } }


"Count Numbers with N digits which consists of odd number of 0 's | Java program to count numbers with N digits which consists of odd number of 0 's ; Function to count Numbers with N digits which consists of odd number of 0 's ; Driver code"
How can the above be solved in Java?

import java . io . * ; class GFG { static int countNumbers ( int N ) { return ( int ) ( Math . pow ( 10 , N ) - Math . pow ( 8 , N ) ) / 2 ; } public static void main ( String [ ] args ) { int n = 5 ; System . out . println ( countNumbers ( n ) ) ; } }


"Count Odd and Even numbers in a range from L to R | Java implementation of the above approach ; Return the number of odd numbers in the range [ L , R ] ; if either R or L is odd ; Driver code"
How can the above be solved in Java?

class GFG { static int countOdd ( int L , int R ) { int N = ( R - L ) / 2 ; if ( R % 2 != 0 L % 2 != 0 ) N ++ ; return N ; } public static void main ( String [ ] args ) { int L = 3 , R = 7 ; int odds = countOdd ( L , R ) ; int evens = ( R - L + 1 ) - odds ; System . out . println ( " Count ▁ of ▁ odd ▁ numbers ▁ is ▁ " + odds ) ; System . out . println ( " Count ▁ of ▁ even ▁ numbers ▁ is ▁ " + evens ) ; } }


"Count Pairs from two arrays with even sum | Java implementation of the approach ; Function to return count of required pairs ; Count of odd and even numbers from both the arrays ; Find the count of odd and even elements in a [ ] ; Find the count of odd and even elements in b [ ] ; Count the number of pairs ; Return the number of pairs ; Driver code"
How can the above be solved in Java?

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


"Count Possible Decodings of a given Digit Sequence in O ( N ) time and Constant Auxiliary space | Java implementation to count decodings ; A Dynamic programming based function to count decodings in digit sequence ; For base condition "01123" should return 0 ; Using last two calculated values , calculate for ith index ; Change boolean to int ; Return the required answer ; Driver Code ; Function call"
How can the above be solved in Java?

class GFG { static int countDecodingDP ( String digits , int n ) { if ( digits . charAt ( 0 ) == '0' ) { return 0 ; } int count0 = 1 , count1 = 1 , count2 ; for ( int i = 2 ; i <= n ; i ++ ) { int dig1 = 0 , dig2 , dig3 = 0 ; if ( digits . charAt ( i - 1 ) != '0' ) { dig1 = 1 ; } if ( digits . charAt ( i - 2 ) == '1' ) { dig2 = 1 ; } else dig2 = 0 ; if ( digits . charAt ( i - 2 ) == '2' && digits . charAt ( i - 1 ) < '7' ) { dig3 = 1 ; } count2 = dig1 * count1 + dig2 + dig3 * count0 ; count0 = count1 ; count1 = count2 ; } return count1 ; } public static void main ( String [ ] args ) { String digits = "1234" ; int n = digits . length ( ) ; System . out . print ( countDecodingDP ( digits , n ) ) ; } }


"Count Primes in Ranges | Java program to answer queries for count of primes in given range . ; prefix [ i ] is going to store count of primes till i ( including i ) . ; Create a boolean array " prime [ 0 . . n ] " . A value in prime [ i ] will finally be false if i is Not a prime , else true . ; If prime [ p ] is not changed , then it is a prime ; Update all multiples of p ; Build prefix array ; Returns count of primes in range from L to R ( both inclusive ) . ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { static final int MAX = 10000 ; static int prefix [ ] = new int [ MAX + 1 ] ; static void buildPrefix ( ) { boolean prime [ ] = new boolean [ MAX + 1 ] ; Arrays . fill ( prime , true ) ; for ( int p = 2 ; p * p <= MAX ; p ++ ) { if ( prime [ p ] == true ) { for ( int i = p * 2 ; i <= MAX ; i += p ) prime [ i ] = false ; } } prefix [ 0 ] = prefix [ 1 ] = 0 ; for ( int p = 2 ; p <= MAX ; p ++ ) { prefix [ p ] = prefix [ p - 1 ] ; if ( prime [ p ] ) prefix [ p ] ++ ; } } static int query ( int L , int R ) { return prefix [ R ] - prefix [ L - 1 ] ; } public static void main ( String [ ] args ) { buildPrefix ( ) ; int L = 5 , R = 10 ; System . out . println ( query ( L , R ) ) ; L = 1 ; R = 10 ; System . out . println ( query ( L , R ) ) ; } }


"Count Pronic numbers from a given range | Java program for the above approach ; Function to count pronic numbers in the range [ A , B ] ; Check upto sqrt N ; If product of consecutive numbers are less than equal to num ; Return N - 1 ; Function to count pronic numbers in the range [ A , B ] ; Subtract the count of pronic numbers which are <= ( A - 1 ) from the count f pronic numbers which are <= B ; Driver Code ; Function call to count pronic numbers in the range [ A , B ]"
How can the above be solved in Java?

import java . util . * ; class GFG { static int pronic ( int num ) { int N = ( int ) Math . sqrt ( num ) ; if ( N * ( N + 1 ) <= num ) { return N ; } return N - 1 ; } static int countPronic ( int A , int B ) { return pronic ( B ) - pronic ( A - 1 ) ; } public static void main ( String [ ] args ) { int A = 3 ; int B = 20 ; System . out . print ( countPronic ( A , B ) ) ; } }


"Count Pronic numbers from a given range | Java program to implement the above approach ; Function to check if x is a Pronic Number or not ; Check for Pronic Number by multiplying consecutive numbers ; Function to count pronic numbers in the range [ A , B ] ; Initialise count ; Iterate from A to B ; If i is pronic ; Increment count ; Print count ; Driver Code ; Function call to count pronic numbers in the range [ A , B ]"
How can the above be solved in Java?

import java . util . * ; class GFG { static boolean checkPronic ( int x ) { for ( int i = 0 ; i <= ( int ) ( Math . sqrt ( x ) ) ; i ++ ) { if ( ( x == i * ( i + 1 ) ) != false ) { return true ; } } return false ; } static void countPronic ( int A , int B ) { int count = 0 ; for ( int i = A ; i <= B ; i ++ ) { if ( checkPronic ( i ) != false ) { count ++ ; } } System . out . print ( count ) ; } public static void main ( String args [ ] ) { int A = 3 , B = 20 ; countPronic ( A , B ) ; } }


"Count Set | Java program to find number of set bist in a number ; Recursive function to find number of set bist in a number ; Base condition ; If Least significant bit is set ; If Least significant bit is not set ; Driver code ; Function call"
How can the above be solved in Java?

class GFG { static int CountSetBits ( int n ) { if ( n == 0 ) return 0 ; if ( ( n & 1 ) == 1 ) return 1 + CountSetBits ( n >> 1 ) ; else return CountSetBits ( n >> 1 ) ; } public static void main ( String [ ] args ) { int n = 21 ; System . out . println ( CountSetBits ( n ) ) ; } }


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

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


"Count Sexy Prime Pairs in the given array | Java program to count Sexy Prime pairs in array ; To store check the prime number ; A utility function that find the Prime Numbers till N ; Resize the Prime Number ; Loop till Math . sqrt ( N ) to find prime numbers and make their multiple false in the bool array Prime ; Function that returns the count of SPP ( Sexy Prime Pair ) Pairs ; Find the maximum element in the given array arr [ ] ; Function to calculate the prime numbers till N ; To store the count of pairs ; To store the frequency of element in the array arr [ ] ; Sort before traversing the array ; Traverse the array and find the pairs with SPP ( Sexy Prime Pair ) ; If current element is Prime , then check for ( current element + 6 ) ; Return the count of pairs ; Driver code ; Function call to find SPP ( Sexy Prime Pair ) pair"
How can the above be solved in Java?

import java . util . * ; class GFG { static boolean [ ] Prime ; static void computePrime ( int N ) { Prime = new boolean [ N + 1 ] ; Arrays . fill ( Prime , true ) ; Prime [ 0 ] = Prime [ 1 ] = false ; for ( int i = 2 ; i * i <= N ; i ++ ) { if ( Prime [ i ] ) { for ( int j = i * i ; j < N ; j += i ) { Prime [ j ] = false ; } } } } static int countSexyPairs ( int arr [ ] , int n ) { int maxE = Arrays . stream ( arr ) . max ( ) . getAsInt ( ) ; computePrime ( maxE ) ; int count = 0 ; int freq [ ] = new int [ maxE + 1 ] ; for ( int i = 0 ; i < n ; i ++ ) { freq [ arr [ i ] ] ++ ; } Arrays . sort ( arr ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( Prime [ arr [ i ] ] ) { if ( arr [ i ] + 6 < freq . length && freq [ arr [ i ] + 6 ] > 0 && Prime [ arr [ i ] + 6 ] ) { count ++ ; } } } return count ; } public static void main ( String [ ] args ) { int arr [ ] = { 6 , 7 , 5 , 11 , 13 } ; int n = arr . length ; System . out . print ( countSexyPairs ( arr , n ) ) ; } }


"Count Strictly Increasing Subarrays | Java program to count number of strictly increasing subarrays ; Initialize count of subarrays as 0 ; Pick starting point ; Pick ending point ; If subarray arr [ i . . j ] is not strictly increasing , then subarrays after it , i . e . , arr [ i . . j + 1 ] , arr [ i . . j + 2 ] , ... . cannot be strictly increasing ; Driver method to test the above function"
How can the above be solved in Java?

class Test { static int arr [ ] = new int [ ] { 1 , 2 , 2 , 4 } ; static int countIncreasing ( int n ) { int cnt = 0 ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = i + 1 ; j < n ; j ++ ) { if ( arr [ j ] > arr [ j - 1 ] ) cnt ++ ; else break ; } } return cnt ; } public static void main ( String [ ] args ) { System . out . println ( " Count ▁ of ▁ strictly ▁ increasing ▁ subarrays ▁ is ▁ " + countIncreasing ( arr . length ) ) ; } }


"Count Strictly Increasing Subarrays | Java program to count number of strictly increasing subarrays ; Initialize result ; Initialize length of current increasing subarray ; Traverse through the array ; If arr [ i + 1 ] is greater than arr [ i ] , then increment length ; Else Update count and reset length ; If last length is more than 1 ; Driver method to test the above function"
How can the above be solved in Java?

class Test { static int arr [ ] = new int [ ] { 1 , 2 , 2 , 4 } ; static int countIncreasing ( int n ) { int cnt = 0 ; int len = 1 ; for ( int i = 0 ; i < n - 1 ; ++ i ) { if ( arr [ i + 1 ] > arr [ i ] ) len ++ ; else { cnt += ( ( ( len - 1 ) * len ) / 2 ) ; len = 1 ; } } if ( len > 1 ) cnt += ( ( ( len - 1 ) * len ) / 2 ) ; return cnt ; } public static void main ( String [ ] args ) { System . out . println ( " Count ▁ of ▁ strictly ▁ increasing ▁ subarrays ▁ is ▁ " + countIncreasing ( arr . length ) ) ; } }


"Count Triplets such that one of the numbers can be written as sum of the other two | Java program to count Triplets such that at least one of the numbers can be written as a sum of the other two ; Function to count the number of ways to choose the triples ; compute the max value in the array and create frequency array of size max_val + 1. We can also use HashMap to store frequencies . We have used an array to keep remaining code simple . ; Case 1 : 0 , 0 , 0 ; Case 2 : 0 , x , x ; Case 3 : x , x , 2 * x ; Case 4 : x , y , x + y iterate through all pairs ( x , y ) ; Driver code"
How can the above be solved in Java?

class GFG { static int countWays ( int [ ] arr , int n ) { int max_val = 0 ; for ( int i = 0 ; i < n ; i ++ ) max_val = Math . max ( max_val , arr [ i ] ) ; int [ ] freq = new int [ max_val + 1 ] ; for ( int i = 0 ; i < n ; i ++ ) freq [ arr [ i ] ] ++ ; ans += freq [ 0 ] * ( freq [ 0 ] - 1 ) * ( freq [ 0 ] - 2 ) / 6 ; for ( int i = 1 ; i <= max_val ; i ++ ) ans += freq [ 0 ] * freq [ i ] * ( freq [ i ] - 1 ) / 2 ; for ( int i = 1 ; 2 * i <= max_val ; i ++ ) ans += freq [ i ] * ( freq [ i ] - 1 ) / 2 * freq [ 2 * i ] ; for ( int i = 1 ; i <= max_val ; i ++ ) { for ( int j = i + 1 ; i + j <= max_val ; j ++ ) ans += freq [ i ] * freq [ j ] * freq [ i + j ] ; } return ans ; } public static void main ( String [ ] args ) { int [ ] arr = new int [ ] { 1 , 2 , 3 , 4 , 5 } ; int n = arr . length ; System . out . println ( countWays ( arr , n ) ) ; } }


"Count all N digit numbers whose digits are multiple of X | Java program for the above approach ; Function to calculate x ^ n using binary - exponentiation ; Stores the resultant power ; Stores the value of x ^ ( n / 2 ) ; Function to count aint N - digit numbers whose digits are multiples of x ; Count aint digits which are multiples of x ; Check if current number is a multiple of X ; Increase count of multiples ; Check if it 's a 1 digit number ; Count the total numbers ; Return the total numbers ; Driver Code ; Given N and X ; Function Call"
How can the above be solved in Java?

class GFG { static int power ( int x , int n ) { int temp ; if ( n == 0 ) return 1 ; temp = power ( x , n / 2 ) ; if ( n % 2 == 0 ) return temp * temp ; else return x * temp * temp ; } static int count_Total_Numbers ( int n , int x ) { int total , multiples = 0 ; for ( int i = 0 ; i < 10 ; i ++ ) { if ( i % x == 0 ) multiples ++ ; } if ( n == 1 ) return multiples ; total = ( multiples - 1 ) * power ( multiples , n - 1 ) ; return total ; } public static void main ( String [ ] args ) { int N = 1 , X = 3 ; System . out . printf ( " % d ▁ " , count_Total_Numbers ( N , X ) ) ; } }


"Count all N | Java program for the above approach ; Function to print the count of arrays satisfying given condition ; First element of array is set as 1 ; Since the first element of arr [ ] is 1 , the second element can 't be 1 ; Traverse the remaining indices ; If arr [ i ] = 1 ; If arr [ i ] a 1 ; Since last element needs to be 1 ; Driver Code ; Stores the count of arrays where arr [ 0 ] = arr [ N - 1 ] = 1 ; Since arr [ 0 ] and arr [ N - 1 ] can be any number from 1 to M ; Print answer"
How can the above be solved in Java?

 import java . util . * ; class GFG { static int totalArrays ( int N , int M ) { int [ ] end_with_one = new int [ N + 1 ] ; int [ ] end_not_with_one = new int [ N + 1 ] ; end_with_one [ 0 ] = 1 ; end_not_with_one [ 0 ] = 0 ; end_with_one [ 1 ] = 0 ; end_not_with_one [ 1 ] = M - 1 ; for ( int i = 2 ; i < N ; i ++ ) { end_with_one [ i ] = end_not_with_one [ i - 1 ] ; end_not_with_one [ i ] = end_with_one [ i - 1 ] * ( M - 1 ) + end_not_with_one [ i - 1 ] * ( M - 2 ) ; } return end_with_one [ N - 1 ] ; } public static void main ( String [ ] args ) { int N = 3 , M = 3 ; int temp = totalArrays ( N , M ) ; int ans = M * temp ; System . out . print ( ans + "
"); } }


"Count all Prime Length Palindromic Substrings | Java implementation of the approach ; Function that returns true if sub - string starting at i and ending at j in str is a palindrome ; Function to count all palindromic substring whose lwngth is a prime number ; 0 and 1 are non - primes ; If prime [ p ] is not changed , then it is a prime ; Update all multiples of p greater than or equal to the square of it numbers which are multiple of p and are less than p ^ 2 are already been marked . ; To store the required number of sub - strings ; Starting from the smallest prime till the largest length of the sub - string possible ; If j is prime ; Check all the sub - strings of length j ; If current sub - string is a palindrome ; Driver code"
How can the above be solved in Java?

import java . util . Arrays ; class GfG { static boolean isPalindrome ( String str , int i , int j ) { while ( i < j ) { if ( str . charAt ( i ) != str . charAt ( j ) ) return false ; i ++ ; j -- ; } return true ; } static int countPrimePalindrome ( String str , int len ) { boolean [ ] prime = new boolean [ len + 1 ] ; Arrays . fill ( prime , true ) ; prime [ 0 ] = prime [ 1 ] = false ; for ( int p = 2 ; p * p <= len ; p ++ ) { if ( prime [ p ] ) { for ( int i = p * p ; i <= len ; i += p ) prime [ i ] = false ; } } int count = 0 ; for ( int j = 2 ; j <= len ; j ++ ) { if ( prime [ j ] ) { for ( int i = 0 ; i + j - 1 < len ; i ++ ) { if ( isPalindrome ( str , i , i + j - 1 ) ) count ++ ; } } } return count ; } public static void main ( String [ ] args ) { String s = " geeksforgeeks " ; int len = s . length ( ) ; System . out . println ( countPrimePalindrome ( s , len ) ) ; } }


"Count all disjoint pairs having absolute difference at least K from a given array | Java program for the above approach ; Function to check if it is possible to form M pairs with abs diff at least K ; Traverse the array over [ 0 , M ] ; If valid index ; Return 1 ; Function to count distinct pairs with absolute difference atleasr K ; Stores the count of all possible pairs ; Initialize left and right ; Sort the array ; Perform Binary Search ; Find the value of mid ; Check valid index ; Update ans ; Print the answer ; Driver Code ; Given array arr [ ] ; Given difference K ; Size of the array ; Function call"
How can the above be solved in Java?

import java . util . * ; class GFG { static int isValid ( int arr [ ] , int n , int m , int d ) { for ( int i = 0 ; i < m ; i ++ ) { if ( Math . abs ( arr [ n - m + i ] - arr [ i ] ) < d ) { return 0 ; } } return 1 ; } static void countPairs ( int arr [ ] , int N , int K ) { int ans = 0 ; int left = 0 , right = N / 2 + 1 ; Arrays . sort ( arr ) ; while ( left < right ) { int mid = ( left + right ) / 2 ; if ( isValid ( arr , N , mid , K ) == 1 ) { ans = mid ; left = mid + 1 ; } else right = mid - 1 ; } System . out . print ( ans ) ; } public static void main ( String args [ ] ) { int arr [ ] = { 1 , 3 , 3 , 5 } ; int K = 2 ; int N = arr . length ; countPairs ( arr , N , K ) ; } }


"Count all disjoint pairs having absolute difference at least K from a given array | Java program for the above approach ; Function to count distinct pairs with absolute difference atleast K ; Track the element that have been paired ; Stores count of distinct pairs ; Pick all elements one by one ; If already visited ; If already visited ; If difference is at least K ; Mark element as visited and increment the count ; Print the final count ; Driver Code ; Given arr [ ] ; Size of array ; Given difference K ; Function Call"
How can the above be solved in Java?

import java . util . * ; class GFG { static void countPairsWithDiffK ( int arr [ ] , int N , int K ) { int [ ] vis = new int [ N ] ; Arrays . fill ( vis , 0 ) ; int count = 0 ; for ( int i = 0 ; i < N ; i ++ ) { if ( vis [ i ] == 1 ) continue ; for ( int j = i + 1 ; j < N ; j ++ ) { if ( vis [ j ] == 1 ) continue ; if ( Math . abs ( arr [ i ] - arr [ j ] ) >= K ) { count ++ ; vis [ i ] = 1 ; vis [ j ] = 1 ; break ; } } } System . out . print ( count ) ; } public static void main ( String args [ ] ) { int arr [ ] = { 1 , 3 , 3 , 5 } ; int N = arr . length ; int K = 2 ; countPairsWithDiffK ( arr , N , K ) ; } }


"Count all distinct pairs of repeating elements from the array for every array element | Java program for the above approach ; Function to print the required count of pairs excluding the current element ; Store the frequency ; Find all the count ; Delete the contribution of each element for equal pairs ; Print the answer ; Driver Code ; Given array arr [ ] ; Function Call"
How can the above be solved in Java?

import java . util . * ; class GFG { static void solve ( int arr [ ] , int n ) { HashMap < Integer , Integer > mp = new HashMap < Integer , Integer > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( mp . containsKey ( arr [ i ] ) ) { mp . put ( arr [ i ] , mp . get ( arr [ i ] ) + 1 ) ; } else { mp . put ( arr [ i ] , 1 ) ; } } int cnt = 0 ; for ( Map . Entry < Integer , Integer > x : mp . entrySet ( ) ) { cnt += ( ( x . getValue ( ) ) * ( x . getValue ( ) - 1 ) / 2 ) ; } int [ ] ans = new int [ n ] ; for ( int i = 0 ; i < n ; i ++ ) { ans [ i ] = cnt - ( mp . get ( arr [ i ] ) - 1 ) ; } for ( int i = 0 ; i < n ; i ++ ) { System . out . print ( ans [ i ] + " ▁ " ) ; } } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 1 , 2 , 1 , 2 } ; int N = arr . length ; solve ( arr , N ) ; } }


"Count all distinct pairs with difference equal to k |  ;  ;  ;"
How can the above be solved in Java?

import java . io . * ; class GFG { static int BS ( int [ ] arr , int X , int low ) { int high = arr . length - 1 ; int ans = arr . length ; while ( low <= high ) { int mid = low + ( high - low ) / 2 ; if ( arr [ mid ] >= X ) { ans = mid ; high = mid - 1 ; } else low = mid + 1 ; } return ans ; } static int countPairsWithDiffK ( int [ ] arr , int N , int k ) { int count = 0 ; Arrays . sort ( arr ) ; for ( int i = 0 ; i < N ; ++ i ) { int X = BS ( arr , arr [ i ] + k , i + 1 ) ; if ( X != N ) { int Y = BS ( arr , arr [ i ] + k + 1 , i + 1 ) ; count += Y - X ; } } return count ; } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 3 , 5 , 8 , 6 , 4 , 6 } ; int n = arr . length ; int k = 2 ; System . out . println ( " Count ▁ of ▁ pairs ▁ with ▁ given ▁ diff ▁ is ▁ " + countPairsWithDiffK ( arr , n , k ) ) ; } }


"Count all distinct pairs with difference equal to k | A simple Java program to count pairs with difference k ; Pick all elements one by one ; See if there is a pair of this picked element ; Driver code"
How can the above be solved in Java?

import java . util . * ; import java . io . * ; class GFG { static int countPairsWithDiffK ( int arr [ ] , int n , int k ) { int count = 0 ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = i + 1 ; j < n ; j ++ ) if ( arr [ i ] - arr [ j ] == k arr [ j ] - arr [ i ] == k ) count ++ ; } return count ; } public static void main ( String args [ ] ) { int arr [ ] = { 1 , 5 , 3 , 4 , 2 } ; int n = arr . length ; int k = 3 ; System . out . println ( " Count ▁ of ▁ pairs ▁ with ▁ given ▁ diff ▁ is ▁ " + countPairsWithDiffK ( arr , n , k ) ) ; } }


"Count all distinct pairs with difference equal to k | A sorting base java program to count pairs with difference k ; Standard binary search function ; Returns count of pairs with difference k in arr [ ] of size n . ; Sort array elements ; Pick a first element point ; Driver code"
How can the above be solved in Java?

import java . util . * ; import java . io . * ; class GFG { static int binarySearch ( int arr [ ] , int low , int high , int x ) { if ( high >= low ) { int mid = low + ( high - low ) / 2 ; if ( x == arr [ mid ] ) return mid ; if ( x > arr [ mid ] ) return binarySearch ( arr , ( mid + 1 ) , high , x ) ; else return binarySearch ( arr , low , ( mid - 1 ) , x ) ; } return - 1 ; } static int countPairsWithDiffK ( int arr [ ] , int n , int k ) { int count = 0 , i ; Arrays . sort ( arr ) ; for ( i = 0 ; i < n - 1 ; i ++ ) if ( binarySearch ( arr , i + 1 , n - 1 , arr [ i ] + k ) != - 1 ) count ++ ; return count ; } public static void main ( String args [ ] ) { int arr [ ] = { 1 , 5 , 3 , 4 , 2 } ; int n = arr . length ; int k = 3 ; System . out . println ( " Count ▁ of ▁ pairs ▁ with ▁ given ▁ diff ▁ is ▁ " + countPairsWithDiffK ( arr , n , k ) ) ; } }


"Count all distinct pairs with difference equal to k | A sorting based Java program to count pairs with difference k ; Returns count of pairs with difference k in arr [ ] of size n . ; Sort array elements ; arr [ r ] - arr [ l ] < sum ; Driver program to test above function"
How can the above be solved in Java?

import java . util . * ; class GFG { static int countPairsWithDiffK ( int arr [ ] , int n , int k ) { int count = 0 ; Arrays . sort ( arr ) ; int l = 0 ; int r = 0 ; while ( r < n ) { if ( arr [ r ] - arr [ l ] == k ) { count ++ ; l ++ ; r ++ ; } else if ( arr [ r ] - arr [ l ] > k ) l ++ ; else r ++ ; } return count ; } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 5 , 3 , 4 , 2 } ; int n = arr . length ; int k = 3 ; System . out . println ( " Count ▁ of ▁ pairs ▁ with ▁ given ▁ diff ▁ is ▁ " + countPairsWithDiffK ( arr , n , k ) ) ; } }


"Count all distinct pairs with difference equal to k | An efficient program to count pairs with difference k when the range numbers is small ; Initialize count ; Initialize empty hashmap . ; Insert array elements to hashmap"
How can the above be solved in Java?

static int MAX = 100000 ; public static int countPairsWithDiffK ( int arr [ ] , int n , int k ) { int count = 0 ; boolean hashmap [ MAX ] = { false } ; for ( int i = 0 ; i < n ; i ++ ) hashmap [ arr [ i ] ] = true ; for ( int i = 0 ; i < n ; i ++ ) { int x = arr [ i ] ; if ( x - k >= 0 && hashmap [ x - k ] ) count ++ ; if ( x + k < MAX && hashmap [ x + k ] ) count ++ ; hashmap [ x ] = false ; } return count ; }


"Count all distinct pairs with product equal to K | Java program to count the number of pairs whose product is equal to K ; Function to count the number of pairs whose product is equal to K ; Initialize the count ; Initialize empty hashmap . ; Insert array elements to hashmap ; Checking if the index is a whole number and present in the hashmap ; Driver code"
How can the above be solved in Java?

class GFG { static int MAX = 100000 ; static int countPairsWithProductK ( int arr [ ] , int n , int k ) { int count = 0 ; int i ; boolean hashmap [ ] = new boolean [ MAX ] ; for ( i = 0 ; i < n ; i ++ ) hashmap [ arr [ i ] ] = true ; for ( i = 0 ; i < n ; i ++ ) { int x = arr [ i ] ; double index = 1.0 * k / arr [ i ] ; if ( index >= 0 && ( ( index - ( int ) ( index ) ) == 0 ) && hashmap [ k / x ] ) count ++ ; hashmap [ x ] = false ; } return count ; } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 5 , 3 , 4 , 2 } ; int N = arr . length ; int K = 3 ; System . out . print ( countPairsWithProductK ( arr , N , K ) ) ; } }


"Count all distinct pairs with product equal to K | Java program to count the number of pairs whose product is equal to K ; Function to count the number of pairs whose product is equal to K ; Pick all elements one by one ; Check if the product of this pair is equal to K ; Driver code"
How can the above be solved in Java?

class GFG { static int countPairsWithProdK ( int arr [ ] , int n , int k ) { int count = 0 ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = i + 1 ; j < n ; j ++ ) if ( arr [ i ] * arr [ j ] == k ) count ++ ; } return count ; } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 5 , 3 , 4 , 2 } ; int N = arr . length ; int K = 3 ; System . out . println ( countPairsWithProdK ( arr , N , K ) ) ; } }


"Count all increasing subsequences | Java program to count increasing subsequences in an array of digits . ; Function To Count all the sub - sequences possible in which digit is greater than all previous digits arr [ ] is array of n digits ; count [ ] array is used to store all sub - sequences possible using that digit count [ ] array covers all the digit from 0 to 9 ; scan each digit in arr [ ] ; count all possible sub - sequences by the digits less than arr [ i ] digit ; store sum of all sub - sequences plus 1 in count [ ] array ; now sum up the all sequences possible in count [ ] array ; Driver program to run the test case"
How can the above be solved in Java?

import java . io . * ; class GFG { static int countSub ( int arr [ ] , int n ) { int count [ ] = new int [ 10 ] ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = arr [ i ] - 1 ; j >= 0 ; j -- ) count [ arr [ i ] ] += count [ j ] ; count [ arr [ i ] ] ++ ; } int result = 0 ; for ( int i = 0 ; i < 10 ; i ++ ) result += count [ i ] ; return result ; } public static void main ( String [ ] args ) { int arr [ ] = { 3 , 2 , 4 , 5 , 4 } ; int n = arr . length ; System . out . println ( countSub ( arr , n ) ) ; } }


"Count all indices of cyclic regular parenthesis | Java program for the above approach ; Function to find all indices which cyclic shift leads to get balanced parenthesis ; Create auxiliary array ; Finding prefix sum and minimum element ; Update the minimum element ; Check if count of ' ( ' and ' ) ' are equal ; Find count of minimum element ; Find the frequency of mn ; Return the count ; Driver code ; Given string S ; length of the string S"
How can the above be solved in Java?

import java . util . * ; class GFG { static int countCyclicShifts ( String S , int n ) { int [ ] aux = new int [ n ] ; for ( int i = 0 ; i < n ; ++ i ) { if ( S . charAt ( i ) == ' ( ' ) aux [ i ] = 1 ; else aux [ i ] = - 1 ; } int mn = aux [ 0 ] ; for ( int i = 1 ; i < n ; ++ i ) { aux [ i ] += aux [ i - 1 ] ; mn = Math . min ( mn , aux [ i ] ) ; } if ( aux [ n - 1 ] != 0 ) return 0 ; int count = 0 ; for ( int i = 0 ; i < n ; ++ i ) { if ( aux [ i ] == mn ) count ++ ; } return count ; } public static void main ( String [ ] args ) { String S = " ) ( ) ( " ; int N = S . length ( ) ; System . out . print ( countCyclicShifts ( S , N ) ) ; } }