"Find the Mth element of the Array after K left rotations | Java program for the above approach ; Function to return Mth element of array after k left rotations ; The array comes to original state after N rotations ; Mth element after k left rotations is ( K + M - 1 ) % N th element of the original array ; Return the result ; Driver code ; Array initialization ; Size of the array ; Given K rotation and Mth element to be found after K rotation ; Function call"
How can the above be solved in Java?

import java . util . * ; class GFG { public static int getFirstElement ( int [ ] a , int N , int K , int M ) { K %= N ; int index = ( K + M - 1 ) % N ; int result = a [ index ] ; return result ; } public static void main ( String [ ] args ) { int a [ ] = { 3 , 4 , 5 , 23 } ; int N = a . length ; int K = 2 , M = 1 ; System . out . println ( getFirstElement ( a , N , K , M ) ) ; } }


"Find the N | Java program to find the N - th lexicographic permutation of String using Factroid method ; Function to calculate nth permutation of String ; Creating an empty stack ; Subtracting 1 from N because the permutations start from 0 in factroid method ; Loop to generate the factroid of the sequence ; Loop to generate nth permutation ; Remove 1 - element in each cycle ; Final answer ; Driver code"
How can the above be solved in Java?

 import java . util . * ; class GFG { static void String_permutation ( int n , String str ) { Stack < Integer > s = new Stack < Integer > ( ) ; String result = " " ; n = n - 1 ; for ( int i = 1 ; i < str . length ( ) + 1 ; i ++ ) { s . add ( n % i ) ; n = n / i ; } for ( int i = 0 ; i < str . length ( ) ; i ++ ) { int a = s . peek ( ) ; result += str . charAt ( a ) ; int j ; for ( j = a ; j < str . length ( ) - 1 ; j ++ ) str = str . substring ( 0 , j ) + str . charAt ( j + 1 ) + str . substring ( j + 1 ) ; str = str . substring ( 0 , j + 1 ) ; s . pop ( ) ; } System . out . print ( result + "
"); } public static void main ( String [ ] args ) { String str = " abcde " ; int n = 11 ; String_permutation ( n , str ) ; } }


"Find the Next perfect square greater than a given number | Java implementation of above approach ; Function to find the next perfect square ; Driver Code"
How can the above be solved in Java?

import java . util . * ; import java . lang . * ; import java . io . * ; class GFG { static int nextPerfectSquare ( int N ) { int nextN = ( int ) Math . floor ( Math . sqrt ( N ) ) + 1 ; return nextN * nextN ; } public static void main ( String args [ ] ) { int n = 35 ; System . out . println ( nextPerfectSquare ( n ) ) ; } }


"Find the Nth Hogben Numbers | Java program to print N - th Hogben Number ; Function returns N - th Hogben Number ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { public static int HogbenNumber ( int a ) { int p = ( int ) ( Math . pow ( a , 2 ) - a + 1 ) ; return p ; } public static void main ( String args [ ] ) { int N = 10 ; System . out . print ( HogbenNumber ( N ) ) ; } }


"Find the Nth Mosaic number | Java implementation of the approach ; Function to return the nth mosaic number ; Iterate from 2 to the number ; If i is the factor of n ; Find the count where i ^ count is a factor of n ; Divide the number by i ; Increase the count ; Multiply the answer with count and i ; Return the answer ; Driver code"
How can the above be solved in Java?

import java . io . * ; class GFG { static int mosaic ( int n ) { int i , ans = 1 ; for ( i = 2 ; i <= n ; i ++ ) { if ( n % i == 0 && n > 0 ) { int count = 0 ; while ( n % i == 0 ) { n /= i ; count ++ ; } ans *= count * i ; } } return ans ; } public static void main ( String [ ] args ) { int n = 36 ; System . out . println ( mosaic ( n ) ) ; } }


"Find the Nth Pure number | Java program to find the Nth pure number ; Function to check if it is a power of 2 or not ; if a number belongs to 4 series it should lie between 2 ^ blocks - 1 to 2 ^ blocks + 2 ^ ( blocks - 1 ) - 1 ; Method to find pure number ; Iterate from 1 to N ; Check if number is power of two ; Distance to previous block numbers ; Distance to previous block numbers ; Driver Code ; Create an object of the class ; Function call to find the Nth pure number"
How can the above be solved in Java?

import java . io . * ; class PureNumbers { public boolean isPowerOfTwo ( int N ) { double number = Math . log ( N ) / Math . log ( 2 ) ; int checker = ( int ) number ; return number - checker == 0 ; } public boolean isSeriesFour ( int N , int digits ) { int upperBound = ( int ) ( Math . pow ( 2 , digits ) + Math . pow ( 2 , digits - 1 ) - 1 ) ; int lowerBound = ( int ) ( Math . pow ( 2 , digits ) - 1 ) ; return ( N >= lowerBound ) && ( N < upperBound ) ; } public String getPureNumber ( int N ) { String [ ] numbers = new String [ N + 1 ] ; numbers [ 0 ] = " " ; int blocks = 0 ; int displacement = 0 ; for ( int i = 1 ; i < N + 1 ; i ++ ) { if ( isPowerOfTwo ( i + 1 ) ) { blocks = blocks + 1 ; } if ( isSeriesFour ( i , blocks ) ) { displacement = ( int ) Math . pow ( 2 , blocks - 1 ) ; numbers [ i ] = "4" + numbers [ i - displacement ] + "4" ; } else { displacement = ( int ) Math . pow ( 2 , blocks ) ; numbers [ i ] = "5" + numbers [ i - displacement ] + "5" ; } } return numbers [ N ] ; } public static void main ( String [ ] args ) throws Exception { int N = 5 ; PureNumbers ob = new PureNumbers ( ) ; String pure = ob . getPureNumber ( N ) ; System . out . println ( pure ) ; } }


"Find the Nth digit from right in base B of the given number in Decimal base | Java Implementation to find Nth digit from right in base B ; Function to compute Nth digit from right in base B ; Skip N - 1 Digits in Base B ; Nth Digit from right in Base B ; Driver Code"
How can the above be solved in Java?

import java . util . * ; class GFG { static int nthDigit ( int a , int n , int b ) { for ( int i = 1 ; i < n ; i ++ ) a = a / b ; return a % b ; } public static void main ( String [ ] args ) { int a = 100 ; int n = 3 ; int b = 4 ; System . out . print ( nthDigit ( a , n , b ) ) ; } }


"Find the Nth digit in the proper fraction of two numbers | Java implementation of the approach ; Function to print the Nth digit in the fraction ( p / q ) ; To store the resultant digit ; While N > 0 compute the Nth digit by dividing p and q and store the result into variable res and go to next digit ; Driver code"
How can the above be solved in Java?

class GFG { static int findNthDigit ( int p , int q , int N ) { int res = 0 ; while ( N > 0 ) { N -- ; p *= 10 ; res = p / q ; p %= q ; } return res ; } public static void main ( String args [ ] ) { int p = 1 , q = 2 , N = 1 ; System . out . println ( findNthDigit ( p , q , N ) ) ; } }


"Find the Nth element of the modified Fibonacci series | Java implementation of the approach ; Function to return the Nth number of the modified Fibonacci series where A and B are the first two terms ; To store the current element which is the sum of previous two elements of the series ; This loop will terminate when the Nth element is found ; Return the Nth element ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { static int findNthNumber ( int A , int B , int N ) { int sum = 0 ; for ( int i = 2 ; i < N ; i ++ ) { sum = A + B ; A = B ; B = sum ; } return sum ; } public static void main ( String [ ] args ) { int A = 5 , B = 7 , N = 10 ; System . out . println ( findNthNumber ( A , B , N ) ) ; } }


"Find the Nth natural number which is not divisible by A | Java code to Find the Nth number which is not divisible by A from the series ; Find the quotient and the remainder when k is divided by n - 1 ; If the remainder is not 0 multiply n by q and subtract 1 if remainder is 0 then multiply n by q and add the remainder ; Print the answer ; Driver code"
How can the above be solved in Java?

class GFG { static void findNum ( int n , int k ) { int q = k / ( n - 1 ) ; int r = k % ( n - 1 ) ; int a = 0 ; if ( r != 0 ) a = ( n * q ) + r ; else a = ( n * q ) - 1 ; System . out . println ( a ) ; } public static void main ( String [ ] args ) { int A = 4 ; int N = 6 ; findNum ( A , N ) ; } }


"Find the Nth occurrence of a character in the given String | Java implementation to find the Nth occurrence of a character ; Function to find the Nth occurrence of a character ; Loop to find the Nth occurrence of the character ; Driver Code"
How can the above be solved in Java?

import java . util . * ; class GFG { static int findNthOccur ( String str , char ch , int N ) { int occur = 0 ; for ( int i = 0 ; i < str . length ( ) ; i ++ ) { if ( str . charAt ( i ) == ch ) { occur += 1 ; } if ( occur == N ) return i ; } return - 1 ; } public static void main ( String [ ] args ) { String str = " geeks " ; char ch = ' e ' ; int N = 2 ; System . out . print ( findNthOccur ( str , ch , N ) ) ; } }


"Find the Nth row in Pascal 's Triangle | Java Program to find the Nth index row in Pascal 's triangle ; Function to find the elements of rowIndex in Pascal 's Triangle ; 1 st element of every row is 1 ; Check if the row that has to be returned is the first row ; Generate the previous row ; Generate the elements of the current row by the help of the previous row ; Return the row ; Driver Program"
How can the above be solved in Java?

import java . util . ArrayList ; public class geeks { public static ArrayList < Integer > getRow ( int rowIndex ) { ArrayList < Integer > currow = new ArrayList < Integer > ( ) ; currow . add ( 1 ) ; if ( rowIndex == 0 ) { return currow ; } ArrayList < Integer > prev = getRow ( rowIndex - 1 ) ; for ( int i = 1 ; i < prev . size ( ) ; i ++ ) { int curr = prev . get ( i - 1 ) + prev . get ( i ) ; currow . add ( curr ) ; } currow . add ( 1 ) ; return currow ; } public static void main ( String [ ] args ) { int n = 3 ; ArrayList < Integer > arr = getRow ( n ) ; for ( int i = 0 ; i < arr . size ( ) ; i ++ ) { if ( i == arr . size ( ) - 1 ) System . out . print ( arr . get ( i ) ) ; else System . out . print ( arr . get ( i ) + " , ▁ " ) ; } } }


"Find the Nth term divisible by a or b or c | Java implementation of the approach ; Function to return gcd of a and b ; Function to return the lcm of a and b ; Function to return the count of numbers from 1 to num which are divisible by a , b or c ; Calculate number of terms divisible by a and by b and by c then , remove the terms which is are divisible by both a and b , both b and c , both c and a and then add which are divisible by a and b and c ; Function to find the nth term divisible by a , b or c by using binary search ; Set low to 1 and high to max ( a , b , c ) * n ; If the current term is less than n then we need to increase low to mid + 1 ; If current term is greater than equal to n then high = mid ; Driver code"
How can the above be solved in Java?

class GFG { static int gcd ( int a , int b ) { if ( a == 0 ) return b ; return gcd ( b % a , a ) ; } static int lcm ( int a , int b ) { return ( a * b ) / gcd ( a , b ) ; } static int divTermCount ( int a , int b , int c , int num ) { return ( ( num / a ) + ( num / b ) + ( num / c ) - ( num / lcm ( a , b ) ) - ( num / lcm ( b , c ) ) - ( num / lcm ( a , c ) ) + ( num / lcm ( a , lcm ( b , c ) ) ) ) ; } static int findNthTerm ( int a , int b , int c , int n ) { int low = 1 , high = Integer . MAX_VALUE , mid ; while ( low < high ) { mid = low + ( high - low ) / 2 ; if ( divTermCount ( a , b , c , mid ) < n ) low = mid + 1 ; else high = mid ; } return low ; } public static void main ( String [ ] args ) { int a = 2 , b = 3 , c = 5 , n = 10 ; System . out . println ( findNthTerm ( a , b , c , n ) ) ; } }


"Find the Nth term in series 12 , 35 , 81 , 173 , 357 , ... | Java program to find the Nth term in series 12 , 35 , 81 , 173 , 357 , ... ; Function to find Nth term ; Nth term ; Driver code"
How can the above be solved in Java?

 class GFG { static int nthTerm ( int N ) { int nth = 0 , first_term = 12 ; nth = ( int ) ( ( first_term * ( Math . pow ( 2 , N - 1 ) ) ) + 11 * ( ( Math . pow ( 2 , N - 1 ) ) - 1 ) ) ; return nth ; } public static void main ( String [ ] args ) { int N = 5 ; System . out . print ( nthTerm ( N ) + "
"); } }


"Find the Nth term of the series 14 , 28 , 20 , 40 , ... . . | Java program to find the Nth term of the series 14 , 28 , 20 , 40 , ; Function to find the N - th term ; initializing the 1 st number ; loop from 2 nd term to nth term ; if i is even , double the previous number ; if i is odd , subtract 8 from previous number ; Driver Code"
How can the above be solved in Java?

import java . io . * ; class GFG { static int findNth ( int N ) { int b = 14 ; int i ; for ( i = 2 ; i <= N ; i ++ ) { if ( i % 2 == 0 ) b = b * 2 ; else b = b - 8 ; } return b ; } public static void main ( String [ ] args ) { int N = 6 ; System . out . print ( findNth ( N ) ) ; } }


"Find the Nth term of the series 2 + 6 + 13 + 23 + . . . | Java program to find Nth term of the series 2 + 6 + 13 + 23 + 36 + ... ; calculate Nth term of given series ; Driver code"
How can the above be solved in Java?

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


"Find the Nth term of the series 2 , 15 , 41 , 80 , 132. . . | Java program for the above approach ; Recursive function to find Nth term ; Base Case ; Recursive Call according to Nth term of the series ; Driver Code ; Input Nth term ; Function call"
How can the above be solved in Java?

 class GFG { static int nthTerm ( int N ) { if ( N == 1 ) { return 2 ; } return ( ( N - 1 ) * 13 ) + nthTerm ( N - 1 ) ; } public static void main ( String [ ] args ) { int N = 17 ; System . out . print ( nthTerm ( N ) + "
"); } }


"Find the Nth term of the series 9 , 45 , 243 , 1377 | Java implementation of the approach ; Function to return the nth term of the given series ; nth term ; Driver code"
How can the above be solved in Java?

import java . util . * ; import java . lang . * ; import java . io . * ; public class GFG { static int nthTerm ( int n ) { int An = ( ( int ) Math . pow ( 1 , n ) + ( int ) Math . pow ( 2 , n ) ) * ( int ) Math . pow ( 3 , n ) ; return An ; } public static void main ( String [ ] args ) { int n = 3 ; System . out . println ( nthTerm ( n ) ) ; } }


"Find the Number Occurring Odd Number of Times | Java program to find the element occurring odd number of times ; function to find the element occurring odd number of times ; Putting all elements into the HashMap ; If array element is already present then increase the count of that element . ; if array element is not present then put element into the HashMap and initialize the count to one . ; Checking for odd occurrence of each element present in the HashMap ; driver code"
How can the above be solved in Java?

import java . io . * ; import java . util . HashMap ; class OddOccurrence { static int getOddOccurrence ( int arr [ ] , int n ) { HashMap < Integer , Integer > hmap = new HashMap < > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( hmap . containsKey ( arr [ i ] ) ) { int val = hmap . get ( arr [ i ] ) ; hmap . put ( arr [ i ] , val + 1 ) ; } else hmap . put ( arr [ i ] , 1 ) ; } for ( Integer a : hmap . keySet ( ) ) { if ( hmap . get ( a ) % 2 != 0 ) return a ; } return - 1 ; } public static void main ( String [ ] args ) { int arr [ ] = new int [ ] { 2 , 3 , 5 , 4 , 5 , 2 , 4 , 3 , 5 , 2 , 4 , 4 , 2 } ; int n = arr . length ; System . out . println ( getOddOccurrence ( arr , n ) ) ; } }


"Find the Number Occurring Odd Number of Times | Java program to find the element occurring odd number of times ; function to find the element occurring odd number of times ; driver code ; Function calling"
How can the above be solved in Java?

class OddOccurrence { static int getOddOccurrence ( int arr [ ] , int arr_size ) { int i ; for ( i = 0 ; i < arr_size ; i ++ ) { int count = 0 ; for ( int j = 0 ; j < arr_size ; j ++ ) { if ( arr [ i ] == arr [ j ] ) count ++ ; } if ( count % 2 != 0 ) return arr [ i ] ; } return - 1 ; } public static void main ( String [ ] args ) { int arr [ ] = new int [ ] { 2 , 3 , 5 , 4 , 5 , 2 , 4 , 3 , 5 , 2 , 4 , 4 , 2 } ; int n = arr . length ; System . out . println ( getOddOccurrence ( arr , n ) ) ; } }


"Find the Number of Maximum Product Quadruples | Java program to find the number of Quadruples having maximum product ; Returns the number of ways to select r objects out of available n choices ; ncr = ( n * ( n - 1 ) * ( n - 2 ) * ... . . ... ( n - r + 1 ) ) / ( r * ( r - 1 ) * ... * 1 ) ; Returns the number of quadruples having maximum product ; stores the frequency of each element ; remaining_choices denotes the remaining elements to select inorder to form quadruple ; Getting an iterator ; If Frequency of element < remaining choices , select all of these elements , else select only the number of elements required ; Decrement remaining_choices acc to the number of the current elements selected ; if the quadruple is formed stop the algorithm ; Driver Code"
How can the above be solved in Java?

import java . util . * ; class Solution { static int NCR ( int n , int r ) { int numerator = 1 ; int denominator = 1 ; while ( r > 0 ) { numerator *= n ; denominator *= r ; n -- ; r -- ; } return ( numerator / denominator ) ; } static int findWays ( int arr [ ] , int n ) { HashMap < Integer , Integer > count = new HashMap < Integer , Integer > ( ) ; if ( n < 4 ) return 0 ; for ( int i = 0 ; i < n ; i ++ ) { count . put ( arr [ i ] , ( count . get ( arr [ i ] ) == null ? 0 int ) count . get ( arr [ i ] ) ) ) ; } int remaining_choices = 4 ; int ans = 1 ; Iterator hmIterator = count . entrySet ( ) . iterator ( ) ; while ( hmIterator . hasNext ( ) ) { Map . Entry mapElement = ( Map . Entry ) hmIterator . next ( ) ; int number = ( int ) mapElement . getKey ( ) ; int frequency = ( int ) mapElement . getValue ( ) ; int toSelect = Math . min ( remaining_choices , frequency ) ; ans = ans * NCR ( frequency , toSelect ) ; remaining_choices -= toSelect ; if ( remaining_choices == 0 ) { break ; } } return ans ; } public static void main ( String args [ ] ) { int arr [ ] = { 1 , 2 , 3 , 3 , 3 , 5 } ; int n = arr . length ; int maxQuadrupleWays = findWays ( arr , n ) ; System . out . print ( maxQuadrupleWays ) ; } }


"Find the Number of Permutations that satisfy the given condition in an array | Java program to find the number of permutations that satisfy the given condition in an array ; Function to calculate x ^ y recursively ; Function to return the number of permutations that satisfy the given condition in an array ; If there is only one element then only one permutation is available ; Sort the array for calculating the number of elements occurring twice ; If the maximum element is occurring twice , then the number of permutations satisfying the condition is 0 ; This variable will store the number of element occurring twice ; Loop to check the number of elements occurring twice ; Check if this element is occurring twice ; If this element is occurring twice then check if this number is occurring more than twice ; If element occurring thrice then no permutation will satisfy the given condition ; Since we have checked the next element as well , then we can increment the loop variable ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { static int pow ( int x , int y ) { if ( y == 1 ) return x ; if ( y == 0 ) return 1 ; int temp = pow ( x , y / 2 ) ; temp *= temp ; if ( y % 2 == 1 ) temp *= x ; return temp ; } static int noOfPermutations ( int [ ] a , int n ) { if ( n == 1 ) { return 1 ; } Arrays . sort ( a ) ; if ( a [ n - 1 ] == a [ n - 2 ] ) { return 0 ; } int x = 0 ; for ( int i = 0 ; i < n - 2 ; ++ i ) { if ( a [ i ] == a [ i + 1 ] ) { if ( a [ i ] == a [ i + 2 ] ) { return 0 ; } x ++ ; i ++ ; } } return pow ( 2 , n - 2 * x - 1 ) ; } public static void main ( String [ ] args ) { int a [ ] = { 1 , 2 , 2 , 3 , 4 } ; int n = a . length ; int num = noOfPermutations ( a , n ) ; System . out . print ( num ) ; } }


"Find the Number which contain the digit d | Java program to print the number which contain the digit d from 0 to n ; Returns true if d is present as digit in number x . ; Breal loop if d is present as digit ; If loop broke ; function to display the values ; Check all numbers one by one ; checking for digit ; Driver code"
How can the above be solved in Java?

class GFG { static boolean isDigitPresent ( int x , int d ) { while ( x > 0 ) { if ( x % 10 == d ) break ; x = x / 10 ; } return ( x > 0 ) ; } static void printNumbers ( int n , int d ) { for ( int i = 0 ; i <= n ; i ++ ) if ( i == d || isDigitPresent ( i , d ) ) System . out . print ( i + " ▁ " ) ; } public static void main ( String [ ] args ) { int n = 47 , d = 7 ; printNumbers ( n , d ) ; } }


"Find the Number which contain the digit d | Java program to print the number which contain the digit d from 0 to n ; function to display the values ; Converting d to character ; Loop to check each digit one by one . ; initialize the string ; checking for digit ; Driver code"
How can the above be solved in Java?

public class GFG { static void printNumbers ( int n , int d ) { String st = " " + d ; char ch = st . charAt ( 0 ) ; for ( int i = 0 ; i <= n ; i ++ ) { st = " " ; st = st + i ; if ( i == d || st . indexOf ( ch ) >= 0 ) System . out . print ( i + " ▁ " ) ; } } public static void main ( String [ ] args ) { int n = 100 , d = 5 ; printNumbers ( n , d ) ; } }


"Find the Product of first N Prime Numbers | Java implementation of above solution ; 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 . ; If prime [ p ] is not changed , then it is a prime ; Set all multiples of p to non - prime ; find the product of 1 st N prime numbers ; count of prime numbers ; product of prime numbers ; if the number is prime add it ; increase the count ; get to next number ; Driver code ; create the sieve ; find the value of 1 st n prime numbers"
How can the above be solved in Java?

class GFG { static int MAX = 10000 ; static boolean [ ] prime = new boolean [ MAX + 1 ] ; static void SieveOfEratosthenes ( ) { prime [ 1 ] = true ; for ( int p = 2 ; p * p <= MAX ; p ++ ) { if ( prime [ p ] == false ) { for ( int i = p * 2 ; i <= MAX ; i += p ) prime [ i ] = true ; } } } static int solve ( int n ) { int count = 0 , num = 1 ; int prod = 1 ; while ( count < n ) { if ( ! prime [ num ] ) { prod *= num ; count ++ ; } num ++ ; } return prod ; } public static void main ( String [ ] args ) { SieveOfEratosthenes ( ) ; int n = 5 ; System . out . println ( solve ( n ) ) ; } }


"Find the Rotation Count in Rotated Sorted array | Java program to find number of rotations in a sorted and rotated array . ; Returns count of rotations for an array which is first sorted in ascending order , then rotated ; This condition is needed to handle the case when array is not rotated at all ; If there is only one element left ; Find mid ; Check if element ( mid + 1 ) is minimum element . Consider the cases like { 3 , 4 , 5 , 1 , 2 } ; Check if mid itself is minimum element ; Decide whether we need to go to left half or right half ; Driver program to test above functions"
How can the above be solved in Java?

import java . util . * ; import java . lang . * ; import java . io . * ; class BinarySearch { static int countRotations ( int arr [ ] , int low , int high ) { if ( high < low ) return 0 ; if ( high == low ) return low ; int mid = low + ( high - low ) / 2 ; if ( mid < high && arr [ mid + 1 ] < arr [ mid ] ) return ( mid + 1 ) ; if ( mid > low && arr [ mid ] < arr [ mid - 1 ] ) return mid ; if ( arr [ high ] > arr [ mid ] ) return countRotations ( arr , low , mid - 1 ) ; return countRotations ( arr , mid + 1 , high ) ; } public static void main ( String [ ] args ) { int arr [ ] = { 15 , 18 , 2 , 3 , 6 , 12 } ; int n = arr . length ; System . out . println ( countRotations ( arr , 0 , n - 1 ) ) ; } }


"Find the Rotation Count in Rotated Sorted array | Java program to find number of rotations in a sorted and rotated array . ; Returns count of rotations for an array which is first sorted in ascending order , then rotated ; We basically find index of minimum element ; Driver program to test above functions"
How can the above be solved in Java?

import java . util . * ; import java . lang . * ; import java . io . * ; class LinearSearch { static int countRotations ( int arr [ ] , int n ) { int min = arr [ 0 ] , min_index = - 1 ; for ( int i = 0 ; i < n ; i ++ ) { if ( min > arr [ i ] ) { min = arr [ i ] ; min_index = i ; } } return min_index ; } public static void main ( String [ ] args ) { int arr [ ] = { 15 , 18 , 2 , 3 , 6 , 12 } ; int n = arr . length ; System . out . println ( countRotations ( arr , n ) ) ; } }


"Find the Side of the smallest Square that can contain given 4 Big Squares | Java program to Find the Side of the smallest Square that can contain given 4 Big Squares Java implementation of the approach ; Function to find the maximum of two values ; Function to find the smallest side of the suitable suitcase ; sort array to find the smallest and largest side of suitcases ; side of the suitcase will be smallest if they arranged in 2 x 2 way so find all possible sides of that arrangement ; since suitcase should be square so find maximum of all four side ; now find greatest side and that will be the smallest square ; return the result ; Driver program ; Get the side of the 4 small squares ; Find the smallest side ; Get the side of the 4 small squares ; Find the smallest side"
How can the above be solved in Java?

import java . util . Arrays ; class GFG { static long max ( long a , long b ) { if ( a > b ) return a ; else return b ; } static long smallestSide ( long a [ ] ) { Arrays . sort ( a ) ; long side1 , side2 , side3 , side4 , side11 , side12 , sideOfSquare ; side1 = a [ 0 ] + a [ 3 ] ; side2 = a [ 1 ] + a [ 2 ] ; side3 = a [ 0 ] + a [ 1 ] ; side4 = a [ 2 ] + a [ 3 ] ; side11 = max ( side1 , side2 ) ; side12 = max ( side3 , side4 ) ; sideOfSquare = max ( side11 , side12 ) ; return sideOfSquare ; } public static void main ( String [ ] args ) { long side [ ] = new long [ 4 ] ; System . out . println ( " Test ▁ Case ▁ 1" ) ; side [ 0 ] = 2 ; side [ 1 ] = 2 ; side [ 2 ] = 2 ; side [ 3 ] = 2 ; System . out . println ( smallestSide ( side ) ) ; System . out . println ( " Test Case 2 "); side [ 0 ] = 100000000000000L ; side [ 1 ] = 123450000000000L ; side [ 2 ] = 987650000000000L ; side [ 3 ] = 987654321000000L ; System . out . println ( smallestSide ( side ) ) ; } }


"Find the Smallest number that divides X ^ X | Java implementation of above approach ; Function to find the required smallest number ; Finding smallest number that divides n ; i divides n and return this value immediately ; If n is a prime number then answer should be n , as we can 't take 1 as our answer. ; Driver Code"
How can the above be solved in Java?

 class GFG { static int SmallestDiv ( int n ) { for ( int i = 2 ; i * i <= n ; i ++ ) { if ( n % i == 0 ) { return i ; } } return n ; } public static void main ( String [ ] args ) { int X = 385 ; int ans = SmallestDiv ( X ) ; System . out . print ( ans + "
"); } }


"Find the String having each substring with exactly K distinct characters | Java program to find the string having each substring with exactly K distinct characters ; Function to find the required output string ; Each element at index i is modulus of K ; Driver code ; Initialise integers N and K"
How can the above be solved in Java?

import java . io . * ; class GFG { static void findString ( int N , int K ) { for ( int i = 0 ; i < N ; i ++ ) { System . out . print ( ( char ) ( ' A ' + i % K ) ) ; } } public static void main ( String [ ] args ) { int N = 10 ; int K = 3 ; findString ( N , K ) ; } }


"Find the Sub | Java program to find subarray with sum closest to 0 ; Function to find the subarray ; Pick a starting point ; Consider current starting point as a subarray and update minimum sum and subarray indexes ; Try all subarrays starting with i ; update minimum sum and subarray indexes ; Return starting and ending indexes ; Drivers code"
How can the above be solved in Java?

class GFG { static class Pair { int first , second ; public Pair ( int first , int second ) { this . first = first ; this . second = second ; } } static Pair findSubArray ( int arr [ ] , int n ) { int start = 0 , end = 0 , min_sum = Integer . MAX_VALUE ; for ( int i = 0 ; i < n ; i ++ ) { int curr_sum = arr [ i ] ; if ( min_sum > Math . abs ( curr_sum ) ) { min_sum = Math . abs ( curr_sum ) ; start = i ; end = i ; } for ( int j = i + 1 ; j < n ; j ++ ) { curr_sum = curr_sum + arr [ j ] ; if ( min_sum > Math . abs ( curr_sum ) ) { min_sum = Math . abs ( curr_sum ) ; start = i ; end = j ; } } } Pair p = new Pair ( start , end ) ; return p ; } public static void main ( String [ ] args ) { int arr [ ] = { 2 , - 5 , 4 , - 6 , - 3 } ; int n = arr . length ; Pair point = findSubArray ( arr , n ) ; System . out . println ( " Subarray ▁ starting ▁ from ▁ " + point . first + " ▁ to ▁ " + point . second ) ; } }


"Find the Sub | Java program to find subarray with sum closest to 0 ; Returns subarray with sum closest to 0. ; To consider the case of subarray starting from beginning of the array ; Store prefix sum with index ; Sort on the basis of sum ; Find two consecutive elements with minimum difference ; Update minimum difference and starting and ending indexes ; Return starting and ending indexes ; Driver code"
How can the above be solved in Java?

import java . util . * ; class Prefix { int sum , index ; } class Pair { int first , second ; Pair ( int a , int b ) { first = a ; second = b ; } } class GFG { static Pair findSubArray ( int arr [ ] , int n ) { int start = - 1 , end = - 1 , min_diff = Integer . MAX_VALUE ; Prefix pre_sum [ ] = new Prefix [ n + 1 ] ; for ( int i = 0 ; i < n + 1 ; i ++ ) pre_sum [ i ] = new Prefix ( ) ; pre_sum [ 0 ] . sum = 0 ; pre_sum [ 0 ] . index = - 1 ; for ( int i = 1 ; i <= n ; i ++ ) { pre_sum [ i ] . sum = pre_sum [ i - 1 ] . sum + arr [ i - 1 ] ; pre_sum [ i ] . index = i - 1 ; } Arrays . sort ( pre_sum , ( ( a , b ) -> a . sum - b . sum ) ) ; for ( int i = 1 ; i <= n ; i ++ ) { int diff = pre_sum [ i ] . sum - pre_sum [ i - 1 ] . sum ; if ( min_diff > diff ) { min_diff = diff ; start = pre_sum [ i - 1 ] . index ; end = pre_sum [ i ] . index ; } } Pair p = new Pair ( start + 1 , end ) ; return p ; } public static void main ( String [ ] args ) { int arr [ ] = { 2 , 3 , - 4 , - 1 , 6 } ; int n = arr . length ; Pair point = findSubArray ( arr , n ) ; System . out . print ( " Subarray ▁ starting ▁ from ▁ " ) ; System . out . println ( point . first + " ▁ to ▁ " + point . second ) ; } }


"Find the Substring with maximum product | Java program to find the maximum product subString ; Function to return the value of a character ; Function to find the maximum product subString ; To store subStrings ; Check if current product is maximum possible or not ; If product is 0 ; Return the subString with maximum product ; Driver code ; Function call"
How can the above be solved in Java?

 class GFG { static int value ( char x ) { return ( int ) ( x - ' a ' ) ; } static String maximumProduct ( String str , int n ) { String answer = " " , curr = " " ; long maxProduct = 0 , product = 1 ; for ( int i = 0 ; i < n ; i ++ ) { product *= 1L * value ( str . charAt ( i ) ) ; curr += str . charAt ( i ) ; if ( product >= maxProduct ) { maxProduct = product ; answer = curr ; } if ( product == 0 ) { product = 1 ; curr = " " ; } } return answer ; } public static void main ( String [ ] args ) { String str = " sdtfakdhdahdzz " ; int n = str . length ( ) ; System . out . print ( maximumProduct ( str , n ) + "
"); } }


"Find the Sum of the series 1 + 1 / 3 + 1 / 5 + 1 / 7 + ... till N terms | Java program to find the sum of the series 1 + 1 / 3 + 1 / 5 + ... ; Function to find the sum of the given series ; Initialise the sum to 0 ; Generate the ith term and add it to the sum ; Print the final sum ; Driver Code"
How can the above be solved in Java?

class GFG { static void printSumSeries ( int N ) { float sum = 0 ; for ( int i = 1 ; i <= N ; i ++ ) { sum += 1.0 / ( 2 * i - 1 ) ; } System . out . println ( sum ) ; } public static void main ( String [ ] args ) { int N = 6 ; printSumSeries ( N ) ; } }


"Find the Sum of the series 1 + 2 + 9 + 64 + 625 + 7776 . . . till N terms | Java program for the above approach ; Function to find the sum of series ; Generate the ith term and add it to the sum ; Print the sum ; Driver Code"
How can the above be solved in Java?

 class GFG { static void printSeriesSum ( int N ) { long sum = 0 ; for ( int i = 1 ; i <= N ; i ++ ) { sum += Math . pow ( i , i - 1 ) ; } System . out . print ( sum + "
"); } public static void main ( String [ ] args ) { int N = 5 ; printSeriesSum ( N ) ; } }


"Find the Sum of the series 1 , 2 , 3 , 6 , 9 , 18 , 27 , 54 , ... till N terms | Java program for the above series ; Function to find the sum of series ; Flag to find the multiplicating factor . . i . e , by 2 or 3 / 2 ; First term ; If flag is true , multiply by 2 ; If flag is false , multiply by 3 / 2 ; Update the previous element to nextElement ; Print the sum ; Driver Code"
How can the above be solved in Java?

class GFG { static void printSeriesSum ( int N ) { double sum = 0 ; int a = 1 ; int cnt = 0 ; boolean flag = true ; sum += a ; while ( cnt < N ) { int nextElement ; if ( flag == true ) { nextElement = a * 2 ; sum += nextElement ; flag = ! flag ; } else { nextElement = a * 3 / 2 ; sum += nextElement ; flag = ! flag ; } a = nextElement ; cnt ++ ; } System . out . println ( sum ) ; } public static void main ( String [ ] args ) { int N = 8 ; printSeriesSum ( N ) ; } }


"Find the Sum of the series 1 / 2 | Java program for the above approach ; Function to find the sum of series ; Generate the ith term and add it to the sum if i is even and subtract if i is odd ; Print the sum ; Driver Code"
How can the above be solved in Java?

 class GFG { static void printSeriesSum ( int N ) { double sum = 0 ; for ( int i = 1 ; i <= N ; i ++ ) { if ( i % 2 == 1 ) { sum += ( double ) i / ( i + 1 ) ; } else { sum -= ( double ) i / ( i + 1 ) ; } } System . out . print ( sum + "
"); } public static void main ( String [ ] args ) { int N = 10 ; printSeriesSum ( N ) ; } }


"Find the Surface area of a 3D figure | Java program to find the Surface area of a 3D figure ; Declaring the size of the matrix ; Absolute Difference between the height of two consecutive blocks ; Function To calculate the Total surfaceArea . ; Traversing the matrix . ; If we are traveling the topmost row in the matrix , we declare the wall above it as 0 as there is no wall above it . ; If we are traveling the leftmost column in the matrix , we declare the wall left to it as 0 as there is no wall left it . ; If its not the topmost row ; If its not the leftmost column ; Summing up the contribution of by the current block ; If its the rightmost block of the matrix it will contribute area equal to its height as a wall on the right of the figure ; If its the lowest block of the matrix it will contribute area equal to its height as a wall on the bottom of the figure ; Adding the contribution by the base and top of the figure ; Driver code"
How can the above be solved in Java?

class GFG { static final int M = 3 ; static final int N = 3 ; static int contribution_height ( int current , int previous ) { return Math . abs ( current - previous ) ; } static int surfaceArea ( int A [ ] [ ] ) { int ans = 0 ; for ( int i = 0 ; i < N ; i ++ ) { for ( int j = 0 ; j < M ; j ++ ) { int up = 0 ; int left = 0 ; if ( i > 0 ) up = A [ i - 1 ] [ j ] ; if ( j > 0 ) left = A [ i ] [ j - 1 ] ; ans += contribution_height ( A [ i ] [ j ] , up ) + contribution_height ( A [ i ] [ j ] , left ) ; if ( i == N - 1 ) ans += A [ i ] [ j ] ; if ( j == M - 1 ) ans += A [ i ] [ j ] ; } } ans += N * M * 2 ; return ans ; } public static void main ( String [ ] args ) { int A [ ] [ ] = { { 1 , 3 , 4 } , { 2 , 2 , 3 } , { 1 , 2 , 4 } } ; System . out . println ( surfaceArea ( A ) ) ; } }


"Find the XOR of first N Prime Numbers | Java implementation of the approach ; 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 . ; If prime [ p ] is not changed , then it is a prime ; Set all multiples of p to non - prime ; Function to return the xor of 1 st N prime numbers ; Count of prime numbers ; XOR of prime numbers ; If the number is prime xor it ; Increment the count ; Get to the next number ; Driver code ; Create the sieve ; Find the xor of 1 st n prime numbers"
How can the above be solved in Java?

class GFG { static final int MAX = 10000 ; static boolean prime [ ] = new boolean [ MAX + 1 ] ; static void SieveOfEratosthenes ( ) { int i ; for ( i = 0 ; i < MAX + 1 ; i ++ ) { prime [ i ] = true ; } prime [ 1 ] = false ; for ( int p = 2 ; p * p <= MAX ; p ++ ) { if ( prime [ p ] == true ) { for ( i = p * 2 ; i <= MAX ; i += p ) prime [ i ] = false ; } } } static int xorFirstNPrime ( int n ) { int count = 0 , num = 1 ; int xorVal = 0 ; while ( count < n ) { if ( prime [ num ] ) { xorVal ^= num ; count ++ ; } num ++ ; } return xorVal ; } public static void main ( String [ ] args ) { SieveOfEratosthenes ( ) ; int n = 4 ; System . out . println ( xorFirstNPrime ( n ) ) ; } }


"Find the XOR of first half and second half elements of an array | Java program to find the xor of the first half elements and second half elements of an array ; Function to find the xor of the first half elements and second half elements of an array ; xor of elements in FirstHalfXOR ; xor of elements in SecondHalfXOR ; Driver Code ; Function call"
How can the above be solved in Java?

 class GFG { static void XOROfElements ( int arr [ ] , int n ) { int FirstHalfXOR = 0 ; int SecondHalfXOR = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( i < n / 2 ) FirstHalfXOR ^= arr [ i ] ; else SecondHalfXOR ^= arr [ i ] ; } System . out . print ( FirstHalfXOR + " , " + SecondHalfXOR + "
"); } public static void main ( String [ ] args ) { int arr [ ] = { 20 , 30 , 50 , 10 , 55 , 15 , 42 } ; int N = arr . length ; XOROfElements ( arr , N ) ; } }


"Find the XOR of the elements in the given range [ L , R ] with the value K for a given set of queries | Java implementation to perform the XOR range updates on an array ; Function to perform the update operation on the given array ; Converting the indices to 0 indexing . ; Saving the XOR of K from the starting index in the range [ L , R ] . ; Saving the XOR of K at the ending index in the given [ L , R ] . ; Function to display the resulting array ; Finding the resultant value in the result array ; Combining the effects of the updates with the original array without changing the initial array . ; Driver code ; Query 1 ; Query 2 ; Query 3"
How can the above be solved in Java?

class GFG { static void update ( int res [ ] , int L , int R , int K ) { L -= 1 ; R -= 1 ; res [ L ] ^= K ; res [ R + 1 ] ^= K ; } static void display ( int arr [ ] , int res [ ] , int n ) { int i ; for ( i = 1 ; i < n ; i ++ ) { res [ i ] = res [ i ] ^ res [ i - 1 ] ; } for ( i = 0 ; i < n ; i ++ ) { System . out . print ( ( arr [ i ] ^ res [ i ] ) + " ▁ " ) ; } System . out . println ( ) ; } public static void main ( String [ ] args ) { int arr [ ] = { 2 , 4 , 6 , 8 , 10 } ; int N = arr . length ; int res [ ] = new int [ N ] ; int L = 1 , R = 3 , K = 2 ; update ( res , L , R , K ) ; L = 2 ; R = 4 ; K = 3 ; update ( res , L , R , K ) ; display ( arr , res , N ) ; } }


"Find the absolute difference between the nearest powers of two given integers for every array element | Java program for the above approach ; Function to print the array ; Traverse the array ; Function to modify array elements by absolute difference of the nearest perfect power of a and b ; Traverse the array arr [ ] ; Find the log a of arr [ i ] ; Find the power of a less than and greater than a ; Find the log b of arr [ i ] ; Find the power of b less than and greater than b ; Update arr [ i ] with absolute difference of log_a & log _b ; Print the modified array ; Driver Code"
How can the above be solved in Java?

import java . io . * ; class GFG { static void printArray ( int [ ] arr , int N ) { for ( int i = 0 ; i < N ; i ++ ) { System . out . print ( arr [ i ] + " ▁ " ) ; } } static void nearestPowerDiff ( int [ ] arr , int N , int a , int b ) { for ( int i = 0 ; i < N ; i ++ ) { int log_a = ( int ) ( Math . log ( arr [ i ] ) / Math . log ( a ) ) ; int A = ( int ) ( Math . pow ( a , log_a ) ) ; int B = ( int ) ( Math . pow ( a , log_a + 1 ) ) ; if ( ( arr [ i ] - A ) < ( B - arr [ i ] ) ) log_a = A ; else log_a = B ; int log_b = ( int ) ( Math . log ( arr [ i ] ) / Math . log ( b ) ) ; A = ( int ) ( Math . pow ( b , log_b ) ) ; B = ( int ) ( Math . pow ( b , log_b + 1 ) ) ; if ( ( arr [ i ] - A ) < ( B - arr [ i ] ) ) log_b = A ; else log_b = B ; arr [ i ] = Math . abs ( log_a - log_b ) ; } printArray ( arr , N ) ; } public static void main ( String [ ] args ) { int [ ] arr = { 5 , 12 , 25 } ; int A = 2 , B = 3 ; int N = arr . length ; nearestPowerDiff ( arr , N , A , B ) ; } }


"Find the altitude and area of an isosceles triangle | Java program to find the Altitude Area of an isosceles triangle ; function to find the altitude ; return altitude ; function to find the area ; return area ; Driver Code"
How can the above be solved in Java?

import java . io . * ; class GFG { static float altitude ( float a , float b ) { return ( float ) ( Math . sqrt ( Math . pow ( a , 2 ) - ( Math . pow ( b , 2 ) / 4 ) ) ) ; } static float area ( float b , float h ) { return ( 1 * b * h ) / 2 ; } public static void main ( String [ ] args ) { float a = 2 , b = 3 ; float h = altitude ( a , b ) ; System . out . print ( " Altitude = ▁ " + h + " , ▁ " ) ; System . out . print ( " Area = ▁ " + area ( b , h ) ) ; } }


"Find the amplitude and number of waves for the given array | Java program for the above approach ; Function to find the amplitude and number of waves for the given array ; Check for both sides adjacent elements that both must be less or both must be greater than current element ; Update amplitude with max value ; Print the Amplitude ; Driver Code ; Given array a [ ] ; Calculate number of waves ; Function Call"
How can the above be solved in Java?

import java . util . * ; class GFG { static boolean check ( int a [ ] , int n ) { int ma = a [ 1 ] - a [ 0 ] ; for ( int i = 1 ; i < n - 1 ; i ++ ) { if ( ( a [ i ] > a [ i - 1 ] && a [ i + 1 ] < a [ i ] ) || ( a [ i ] < a [ i - 1 ] && a [ i + 1 ] > a [ i ] ) ) ma = Math . max ( ma , Math . abs ( a [ i ] - a [ i + 1 ] ) ) ; else return false ; } System . out . print ( " Amplitude ▁ = ▁ " + ma ) ; System . out . println ( ) ; return true ; } public static void main ( String [ ] args ) { int a [ ] = { 1 , 2 , 1 , 5 , 0 , 7 , - 6 } ; int n = a . length ; int wave = ( n - 1 ) / 2 ; if ( check ( a , n ) ) System . out . print ( " Waves ▁ = ▁ " + wave ) ; else System . out . print ( " - 1" ) ; } }


"Find the angle between tangents drawn from a given external point to a Circle | java program for the above approach ; Function to find the distance between center and the exterior point ; Find the difference between the x and y coordinates ; Using the distance formula ; Function to find the angle between the pair of tangents drawn from the point ( X2 , Y2 ) to the circle . ; Calculate the distance between the center and exterior point ; Invalid Case ; Find the angle using the formula ; Print the resultant angle ; Driver Code"
How can the above be solved in Java?

import java . io . * ; import java . lang . * ; import java . util . * ; class GFG { static double point_distance ( int x1 , int y1 , int x2 , int y2 ) { int p = ( x2 - x1 ) ; int q = ( y2 - y1 ) ; double distance = Math . sqrt ( p * p + q * q ) ; return distance ; } static void tangentAngle ( int x1 , int y1 , int x2 , int y2 , double radius ) { double distance = point_distance ( x1 , y1 , x2 , y2 ) ; if ( radius / distance > 1 radius / distance < - 1 ) { System . out . println ( - 1 ) ; } double result = 2 * Math . asin ( radius / distance ) * 180 / 3.1415 ; System . out . println ( String . format ( " % .4f " , result ) + " ▁ degrees " ) ; } public static void main ( String [ ] args ) { int radius = 4 ; int x1 = 7 , y1 = 12 ; int x2 = 3 , y2 = 4 ; tangentAngle ( x1 , y1 , x2 , y2 , radius ) ; } }


"Find the angle of Rotational Symmetry of an N | Java program to find the angle of Rotational Symmetry of an N - sided regular polygon ; function to find required minimum angle of rotation ; Store the answer in a double variable ; Calculating the angle of rotation and type - casting the integer N to double type ; Driver code"
How can the above be solved in Java?

import java . io . * ; class GFG { static double minAnglRot ( int N ) { double res ; res = 360 / ( double ) N ; return res ; } public static void main ( String [ ] args ) { int N = 4 ; System . out . println ( " Angle ▁ of ▁ Rotational ▁ Symmetry : ▁ " + minAnglRot ( N ) ) ; } }


"Find the area of largest circle inscribed in ellipse | Java Program to find the area of circle ; Area of the Reuleaux triangle ; Driver code"
How can the above be solved in Java?

class GFG { static double areaCircle ( double b ) { double area = ( double ) 3.1415926 * b * b ; return area ; } public static void main ( String args [ ] ) { float a = 10 , b = 8 ; System . out . println ( areaCircle ( b ) ) ; } }


"Find the area of quadrilateral when diagonal and the perpendiculars to it from opposite vertices are given | Java program to find the area of quadrilateral ; Function to find the area of quadrilateral ; Driver code"
How can the above be solved in Java?

class GFG { static float Area ( int d , int h1 , int h2 ) { float area ; area = ( float ) 0.5 * d * ( h1 + h2 ) ; return area ; } public static void main ( String [ ] args ) { int d = 6 , h1 = 4 , h2 = 3 ; System . out . println ( " Area ▁ of ▁ Quadrilateral ▁ = ▁ " + Area ( d , h1 , h2 ) ) ; } }


"Find the area of rhombus from given Angle and Side length | Java Program to calculate area of rhombus from given angle and side length ; Function to return the area of rhombus using one angle and side . ; Driver Code ; Function Call ; Print the final answer"
How can the above be solved in Java?

class GFG { static final double RADIAN = 0.01745329252 ; static double Area_of_Rhombus ( int a , int theta ) { double area = ( a * a ) * Math . sin ( ( RADIAN * theta ) ) ; return area ; } public static void main ( String [ ] args ) { int a = 4 ; int theta = 60 ; double ans = Area_of_Rhombus ( a , theta ) ; System . out . printf ( " % .2f " , ans ) ; } }


"Find the area of the shaded region formed by the intersection of four semicircles in a square | Java implementation of the approach ; Function to return the area of the shaded region ; Area of the square ; Area of the semicircle ; There are 4 semicircles shadedArea = Area of 4 semicircles - Area of square ; Driver code"
How can the above be solved in Java?

class GFG { static float findAreaShaded ( float a ) { float sqArea = a * a ; float semiCircleArea = ( float ) ( 3.14 * ( a * a ) / 8 ) ; float ShadedArea = 4 * semiCircleArea - sqArea ; return ShadedArea ; } public static void main ( String [ ] args ) { float a = 10 ; System . out . println ( findAreaShaded ( a ) ) ; } }


"Find the arrangement of queue at given time | Java program to find the arrangement of queue at time = t ; prints the arrangement at time = t ; Checking the entire queue for every moment from time = 1 to time = t . ; If current index contains ' B ' and next index contains ' G ' then swap . ; Driver function"
How can the above be solved in Java?

import java . io . * ; class Geek { static void solve ( int n , int t , char s [ ] ) { for ( int i = 0 ; i < t ; i ++ ) for ( int j = 0 ; j < n - 1 ; j ++ ) if ( s [ j ] == ' B ' && s [ j + 1 ] == ' G ' ) { char temp = s [ j ] ; s [ j ] = s [ j + 1 ] ; s [ j + 1 ] = temp ; j ++ ; } System . out . print ( s ) ; } public static void main ( String args [ ] ) { int n = 6 , t = 2 ; String s = " BBGBBG " ; char str [ ] = s . toCharArray ( ) ; solve ( n , t , str ) ; } }


"Find the array element from indices not divisible by K having largest composite product of digits | Java program to implement the above approach ; Function to check if a number is a composite number or not ; Corner cases ; Check if number is divisible by 2 or 3 ; Check if number is a multiple of any other prime number ; Function to calculate the product of digits of a number ; Stores the product of digits ; Extract digits of a number ; Calculate product of digits ; Function to check if the product of digits of a number is a composite number or not ; Stores product of digits ; If product of digits is equal to 1 ; If product of digits is not prime ; Function to find the number with largest composite product of digits from the indices not divisible by k from the given array ; Traverse the array ; If index is divisible by k ; Check if product of digits is a composite number or not ; Sort the products ; Driver Code"
How can the above be solved in Java?

 import java . util . * ; class GFG { static class pair { int first , second ; public pair ( int first , int second ) { this . first = first ; this . second = second ; } } static boolean isComposite ( int n ) { if ( n <= 1 ) return false ; if ( n <= 3 ) return false ; if ( n % 2 == 0 n % 3 == 0 ) return true ; for ( int i = 5 ; i * i <= n ; i = i + 6 ) if ( n % i == 0 || n % ( i + 2 ) == 0 ) return true ; return false ; } static int digitProduct ( int number ) { int product = 1 ; while ( number > 0 ) { product *= ( number % 10 ) ; number /= 10 ; } return product ; } static boolean compositedigitProduct ( int num ) { int res = digitProduct ( num ) ; if ( res == 1 ) { return false ; } if ( isComposite ( res ) ) { return true ; } return false ; } static int largestCompositeDigitProduct ( int a [ ] , int n , int k ) { Vector < pair > pq = new Vector < pair > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( ( i % k ) == 0 ) { continue ; } if ( compositedigitProduct ( a [ i ] ) ) { int b = digitProduct ( a [ i ] ) ; pq . add ( new pair ( b , a [ i ] ) ) ; } } Collections . sort ( pq , ( x , y ) -> x . first - y . first ) ; return pq . get ( pq . size ( ) - 1 ) . second ; } public static void main ( String [ ] args ) { int arr [ ] = { 233 , 144 , 89 , 71 , 13 , 21 , 11 , 34 , 55 , 23 } ; int n = arr . length ; int k = 3 ; int ans = largestCompositeDigitProduct ( arr , n , k ) ; System . out . print ( ans + "
"); } }


"Find the array element having equal count of Prime Numbers on its left and right | Java program for the above approach ; Function to find the index of the array such that the count of prime numbers to its either ends are same ; Store the maximum value in the array ; Traverse the array arr [ ] ; Stores all the numbers ; Iterate over the range [ 1 , Max ] ; Increment the value of st [ i ] ; Removes 1 from the map St ; Perform Sieve of Prime Numbers ; While i * j is less than the maxValue ; If i * j is in map St ; Erase the value ( i * j ) ; Increment the value of j ; Stores the count of prime from index 0 to i ; Stores the count of prime numbers ; Traverse the array arr [ ] ; If arr [ i ] is present in the map st ; Stores the count of prime from index i to N - 1 ; Stores the count of prime numbers ; Iterate over the range [ 0 , N - 1 ] in reverse order ; If arr [ i ] is in map st ; Iterate over the range [ 0 , N - 1 ] ; If prefix [ i ] is equal to the Suffix [ i ] ; Return - 1 if no such index is present ; Driver code"
How can the above be solved in Java?

import java . util . HashMap ; public class GFG { static int findIndex ( int arr [ ] , int N ) { int maxValue = Integer . MIN_VALUE ; for ( int i = 0 ; i < N ; i ++ ) { maxValue = Math . max ( maxValue , arr [ i ] ) ; } HashMap < Integer , Integer > St = new HashMap < > ( ) ; for ( int i = 1 ; i <= maxValue ; i ++ ) { St . put ( i , St . getOrDefault ( i , 0 ) + 1 ) ; } if ( St . containsKey ( 1 ) ) { St . remove ( 1 ) ; } for ( int i = 2 ; i <= Math . sqrt ( maxValue ) ; i ++ ) { int j = 2 ; while ( ( i * j ) <= maxValue ) { if ( St . containsKey ( i * j ) ) { St . remove ( i * j ) ; } j ++ ; } } int LeftCount = 0 ; int Prefix [ ] = new int [ N ] ; for ( int i = 0 ; i < N ; i ++ ) { Prefix [ i ] = LeftCount ; if ( St . containsKey ( arr [ i ] ) ) { LeftCount ++ ; } } int RightCount = 0 ; int Suffix [ ] = new int [ N ] ; for ( int i = N - 1 ; i >= 0 ; i -- ) { Suffix [ i ] = RightCount ; if ( St . containsKey ( arr [ i ] ) ) { RightCount ++ ; } } for ( int i = 0 ; i < N ; i ++ ) { if ( Prefix [ i ] == Suffix [ i ] ) { return i ; } } return - 1 ; } public static void main ( String [ ] args ) { int arr [ ] = { 2 , 3 , 4 , 7 , 5 , 10 , 1 , 8 } ; int N = arr . length ; System . out . println ( findIndex ( arr , N ) ) ; } }


"Find the array element having equal sum of Prime Numbers on its left and right | Java program for the above approach ; Function to find an index in the array having sum of prime numbers to its left and right equal ; Stores the maximum value present in the array ; Stores all positive elements which are <= max_value ; If 1 is present ; Remove 1 ; Sieve of Eratosthenes to store all prime numbers which are <= max_value in the Map ; Erase non - prime numbers ; Stores the sum of prime numbers from left ; Stores the sum of prime numbers to the left of each index ; Stores the sum of prime numbers to the left of the current index ; Add current value to the prime sum if the current value is prime ; Stores the sum of prime numbers from right ; Stores the sum of prime numbers to the right of each index ; Stores the sum of prime numbers to the right of the current index ; Add current value to the prime sum if the current value is prime ; Traverse through the two arrays to find the index ; Compare the values present at the current index ; Return the index where both the values are same ; No index is found . ; Driver code ; Given array arr [ ] ; Size of Array ; Function Call"
How can the above be solved in Java?

import java . lang . * ; import java . util . * ; class GFG { static int find_index ( 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 ] ) ; } Map < Integer , Integer > store = new HashMap < > ( ) ; for ( int i = 1 ; i <= max_value ; i ++ ) { store . put ( i , store . getOrDefault ( i , 0 ) + 1 ) ; } if ( store . containsKey ( 1 ) ) { store . remove ( 1 ) ; } for ( int i = 2 ; i <= Math . sqrt ( max_value ) ; i ++ ) { int multiple = 2 ; while ( ( i * multiple ) <= max_value ) { if ( store . containsKey ( i * multiple ) ) { store . remove ( i * multiple ) ; } multiple ++ ; } } int prime_sum_from_left = 0 ; int [ ] first_array = new int [ N ] ; for ( int i = 0 ; i < N ; i ++ ) { first_array [ i ] = prime_sum_from_left ; if ( store . containsKey ( arr [ i ] ) ) { prime_sum_from_left += arr [ i ] ; } } int prime_sum_from_right = 0 ; int [ ] second_array = new int [ N ] ; for ( int i = N - 1 ; i >= 0 ; i -- ) { second_array [ i ] = prime_sum_from_right ; if ( store . containsKey ( arr [ i ] ) ) { prime_sum_from_right += arr [ i ] ; } } for ( int i = 0 ; i < N ; i ++ ) { if ( first_array [ i ] == second_array [ i ] ) { return i ; } } return - 1 ; } public static void main ( String [ ] args ) { int arr [ ] = { 11 , 4 , 7 , 6 , 13 , 1 , 5 } ; int N = arr . length ; System . out . println ( find_index ( arr , N ) ) ; } }


"Find the array element having maximum frequency of the digit K | Java program for the above approach ; Function to find the count of digits , k in the given number n ; Stores count of occurrence of digit K in N ; Iterate over digits of N ; If current digit is k ; Update count ; Update N ; Utility function to find an array element having maximum frequency of digit k ; Stores frequency of digit K in arr [ i ] ; Stores maximum frequency of digit K in the array ; Stores an array element having maximum frequency of digit k ; Initialize max ; Traverse the array ; Count the frequency of digit k in arr [ i ] ; Update max with maximum frequency found so far ; Update ele ; If there is no array element having digit k in it ; Function to find an array element having maximum frequency of digit k ; Stores an array element having maximum frequency of digit k ; If there is no element found having digit k in it ; Print the element having max frequency of digit k ; Driver Code ; The digit whose max occurrence has to be found ; Given array ; Size of array ; Function Call"
How can the above be solved in Java?

class GFG { static int countFreq ( int N , int K ) { int count = 0 ; while ( N > 0 ) { if ( N % 10 == K ) { count ++ ; } N = N / 10 ; } return count ; } static int findElementUtil ( int arr [ ] , int N , int K ) { int c ; int max ; int ele = 0 ; max = 0 ; for ( int i = 0 ; i < N ; i ++ ) { c = countFreq ( arr [ i ] , K ) ; if ( c > max ) { max = c ; ele = arr [ i ] ; } } if ( max == 0 ) return - 1 ; else return ele ; } static void findElement ( int arr [ ] , int N , int K ) { int ele = findElementUtil ( arr , N , K ) ; if ( ele == - 1 ) System . out . print ( " - 1" ) ; else System . out . print ( ele ) ; } public static void main ( String [ ] args ) { int K = 3 ; int arr [ ] = { 3 , 77 , 343 , 456 } ; int N = arr . length ; findElement ( arr , K , N ) ; } }


"Find the average of first N natural numbers | Java Program to find the Average of first n natural numbers ; Return the average of first n natural numbers ; Driven Program"
How can the above be solved in Java?

import java . io . * ; class GFG { static float avgOfFirstN ( int n ) { return ( float ) ( 1 + n ) / 2 ; } public static void main ( String args [ ] ) { int n = 20 ; System . out . println ( avgOfFirstN ( n ) ) ; } }


"Find the average of k digits from the beginning and l digits from the end of the given number | Java implementation of the approach ; Function to return the count of digits in num ; Function to return the sum of first n digits of num ; Remove the unnecessary digits ; Function to return the sum of the last n digits of num ; If the average can 't be calculated without  using the same digit more than once ; Sum of the last l digits of n ; Sum of the first k digits of n ( totalDigits - k ) must be removed from the end of the number to get the remaining k digits from the beginning ; Return the average ; Driver code"
How can the above be solved in Java?

class GFG { public static int countDigits ( int num ) { int cnt = 0 ; while ( num > 0 ) { cnt ++ ; num /= 10 ; } return cnt ; } public static int sumFromStart ( int num , int n , int rem ) { num /= ( ( int ) Math . pow ( 10 , rem ) ) ; int sum = 0 ; while ( num > 0 ) { sum += ( num % 10 ) ; num /= 10 ; } return sum ; } public static int sumFromEnd ( int num , int n ) { int sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) { sum += ( num % 10 ) ; num /= 10 ; } return sum ; } public static float getAverage ( int n , int k , int l ) { int totalDigits = countDigits ( n ) ; if ( totalDigits < ( k + l ) ) return - 1 ; int sum1 = sumFromEnd ( n , l ) ; int sum2 = sumFromStart ( n , k , totalDigits - k ) ; return ( ( float ) ( sum1 + sum2 ) / ( float ) ( k + l ) ) ; } public static void main ( String args [ ] ) { int n = 123456 , k = 2 , l = 3 ; System . out . print ( getAverage ( n , k , l ) ) ; } }


"Find the center of the circle using endpoints of diameter | Java program to find the center of the circle ; function to find the center of the circle ; Driver Program to test above function"
How can the above be solved in Java?

class GFG { static void center ( int x1 , int x2 , int y1 , int y2 ) { System . out . print ( ( float ) ( x1 + x2 ) / 2 + " , ▁ " + ( float ) ( y1 + y2 ) / 2 ) ; } public static void main ( String arg [ ] ) { int x1 = - 9 , y1 = 3 , x2 = 5 , y2 = - 7 ; center ( x1 , x2 , y1 , y2 ) ; } }


"Find the character in first string that is present at minimum index in second string | Java implementation to find the character in first string that is present at minimum index in second string ; method to find the minimum index character ; map to store the first index of each character of ' str ' ; to store the index of character having minimum index ; lengths of the two strings ; store the first index of each character of ' str ' ; traverse the string ' patt ' ; if patt [ i ] is found in ' um ' , check if it has the minimum index or not accordingly update ' minIndex ' ; print the minimum index character ; if no character of ' patt ' is present in ' str ' ; Driver Method"
How can the above be solved in Java?

import java . util . HashMap ; public class GFG { static void printMinIndexChar ( String str , String patt ) { HashMap < Character , Integer > hm = new HashMap < > ( ) ; int minIndex = Integer . MAX_VALUE ; int m = str . length ( ) ; int n = patt . length ( ) ; for ( int i = 0 ; i < m ; i ++ ) if ( ! hm . containsKey ( str . charAt ( i ) ) ) hm . put ( str . charAt ( i ) , i ) ; for ( int i = 0 ; i < n ; i ++ ) if ( hm . containsKey ( patt . charAt ( i ) ) && hm . get ( patt . charAt ( i ) ) < minIndex ) minIndex = hm . get ( patt . charAt ( i ) ) ; if ( minIndex != Integer . MAX_VALUE ) System . out . println ( " Minimum ▁ Index ▁ Character ▁ = ▁ " + str . charAt ( minIndex ) ) ; else System . out . println ( " No ▁ character ▁ present " ) ; } public static void main ( String [ ] args ) { String str = " geeksforgeeks " ; String patt = " set " ; printMinIndexChar ( str , patt ) ; } }


"Find the character in first string that is present at minimum index in second string | Java implementation to find the character in first string that is present at minimum index in second string ; method to find the minimum index character ; to store the index of character having minimum index ; lengths of the two strings ; traverse ' patt ' ; for each character of ' patt ' traverse ' str ' ; if patt . charAt ( i ) is found in ' str ' , check if it has the minimum index or not . If yes , then update ' minIndex ' and break ; print the minimum index character ; if no character of ' patt ' is present in ' str ' ; Driver Method"
How can the above be solved in Java?

public class GFG { static void printMinIndexChar ( String str , String patt ) { int minIndex = Integer . MAX_VALUE ; int m = str . length ( ) ; int n = patt . length ( ) ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = 0 ; j < m ; j ++ ) { if ( patt . charAt ( i ) == str . charAt ( j ) && j < minIndex ) { minIndex = j ; break ; } } } if ( minIndex != Integer . MAX_VALUE ) System . out . println ( " Minimum ▁ Index ▁ Character ▁ = ▁ " + str . charAt ( minIndex ) ) ; else System . out . println ( " No ▁ character ▁ present " ) ; } public static void main ( String [ ] args ) { String str = " geeksforgeeks " ; String patt = " set " ; printMinIndexChar ( str , patt ) ; } }


"Find the character made by adding all the characters of the given string | Java implementation of the approach ; Function to return the required character ; To store the sum of the characters of the given string ; Add the current character to the sum ; Return the required character ; Driver code"
How can the above be solved in Java?

class GFG { static char getChar ( String str ) { int sum = 0 ; for ( int i = 0 ; i < str . length ( ) ; i ++ ) { sum += ( str . charAt ( i ) - ' a ' + 1 ) ; } if ( sum % 26 == 0 ) return ' z ' ; else { sum = sum % 26 ; return ( char ) ( ' a ' + sum - 1 ) ; } } public static void main ( String [ ] args ) { String str = " gfg " ; System . out . println ( getChar ( str ) ) ; } }


"Find the closest Fraction to given fraction having minimum absolute difference | Java code for the above approach ; Function to find the absolute value of x ; Function to find the fraction with minimum absolute difference ; Initialize the answer variables ; Iterate over the range ; Nearest fraction ; x / y - d / i < x / y - A / B ( B * x - y * A ) * ( i * y ) > ( i * x - y * d ) * ( B * y ) ; Check for d + 1 ; Print the answer ; Driver Code"
How can the above be solved in Java?

import java . io . * ; class GFG { static long ABS ( long x ) { return Math . max ( x , - x ) ; } static void findFraction ( long x , long y , long n ) { long A = - 1 , B = - 1 ; for ( long i = 1 ; i <= n ; i ++ ) { long d = ( i * x ) / y ; if ( d >= 0 && ( A == - 1 || ABS ( B * x - y * A ) * ABS ( i * y ) > ABS ( i * x - y * d ) * ABS ( B * y ) ) ) A = d ; B = i ; d ++ ; if ( d >= 0 && ( A == - 1 || ABS ( B * x - y * A ) * ABS ( i * y ) > ABS ( i * x - y * d ) * ABS ( B * y ) ) ) A = d ; B = i ; } A -- ; B -- ; System . out . println ( A + " / " + B ) ; } public static void main ( String [ ] args ) { long x = 3 ; long y = 7 ; long n = 6 ; findFraction ( x , y , n ) ; } }


"Find the closest and smaller tidy number | Java program to find closest tidy number smaller than the given number ; check whether string violates tidy property ; if string violates tidy property , then decrease the value stored at that index by 1 and replace all the value stored right to that index by 9 ; Driver code ; num will store closest tidy number"
How can the above be solved in Java?

import java . io . * ; class GFG { static String tidyNum ( String str1 , int len ) { char [ ] str = str1 . toCharArray ( ) ; for ( int i = len - 2 ; i >= 0 ; i -- ) { if ( str [ i ] > str [ i + 1 ] ) { str [ i ] -- ; for ( int j = i + 1 ; j < len ; j ++ ) str [ j ] = '9' ; } } return String . valueOf ( str ) ; } public static void main ( String [ ] args ) { String str = "11333445538" ; int len = str . length ( ) ; System . out . println ( tidyNum ( str , len ) ) ; } }


"Find the closest element in Binary Search Tree | Recursive Java program to find key closest to k in given Binary Search Tree . ; A binary tree node has key , pointer to left child and a pointer to right child ; Utility that allocates a new node with the given key and null left and right pointers . ; Function to find node with minimum absolute difference with given K min_diff - . minimum difference till now min_diff_key - . node having minimum absolute difference with K ; If k itself is present ; update min_diff and min_diff_key by checking current node value ; if k is less than ptr . key then move in left subtree else in right subtree ; Wrapper over maxDiffUtil ( ) ; Initialize minimum difference ; Find value of min_diff_key ( Closest key in tree with k ) ; Driver program to run the case"
How can the above be solved in Java?

class solution { static int min_diff , min_diff_key ; static class Node { int key ; Node left , right ; } ; static Node newnode ( int key ) { Node node = new Node ( ) ; node . key = key ; node . left = node . right = null ; return ( node ) ; } static void maxDiffUtil ( Node ptr , int k ) { if ( ptr == null ) return ; if ( ptr . key == k ) { min_diff_key = k ; return ; } if ( min_diff > Math . abs ( ptr . key - k ) ) { min_diff = Math . abs ( ptr . key - k ) ; min_diff_key = ptr . key ; } if ( k < ptr . key ) maxDiffUtil ( ptr . left , k ) ; else maxDiffUtil ( ptr . right , k ) ; } static int maxDiff ( Node root , int k ) { min_diff = 999999999 ; min_diff_key = - 1 ; maxDiffUtil ( root , k ) ; return min_diff_key ; } public static void main ( String args [ ] ) { Node root = newnode ( 9 ) ; root . left = newnode ( 4 ) ; root . right = newnode ( 17 ) ; root . left . left = newnode ( 3 ) ; root . left . right = newnode ( 6 ) ; root . left . right . left = newnode ( 5 ) ; root . left . right . right = newnode ( 7 ) ; root . right . right = newnode ( 22 ) ; root . right . right . left = newnode ( 20 ) ; int k = 18 ; System . out . println ( maxDiff ( root , k ) ) ; } }


"Find the closest leaf in a Binary Tree | Class containing left and right child of current node and key value ; A utility function to find minimum of x and y ; A utility function to find distance of closest leaf of the tree rooted under given root ; Base cases ; Return minimum of left and right , plus one ; Returns distance of the cloest leaf to a given key ' k ' . The array ancestors is used to keep track of ancestors of current node and ' index ' is used to keep track of curremt index in ' ancestors [ ] ' ; Base case ; If key found ; Find the cloest leaf under the subtree rooted with given key ; Traverse all ancestors and update result if any parent node gives smaller distance ; If key node found , store current node and recur for left and right childrens ; The main function that returns distance of the closest key to ' k ' . It mainly uses recursive function findClosestUtil ( ) to find the closes distance . ; Create an array to store ancestors Assumptiom : Maximum height of tree is 100 ; Driver program to test for above functions ; Let us construct the BST shown in the above figure"
How can the above be solved in Java?

class Node { int data ; Node left , right ; public Node ( int item ) { data = item ; left = right = null ; } } class BinaryTree { Node root ; int getMin ( int x , int y ) { return ( x < y ) ? x : y ; } int closestDown ( Node node ) { if ( node == null ) return Integer . MAX_VALUE ; if ( node . left == null && node . right == null ) return 0 ; return 1 + getMin ( closestDown ( node . left ) , closestDown ( node . right ) ) ; } int findClosestUtil ( Node node , char k , Node ancestors [ ] , int index ) { if ( node == null ) return Integer . MAX_VALUE ; if ( node . data == k ) { int res = closestDown ( node ) ; for ( int i = index - 1 ; i >= 0 ; i -- ) res = getMin ( res , index - i + closestDown ( ancestors [ i ] ) ) ; return res ; } ancestors [ index ] = node ; return getMin ( findClosestUtil ( node . left , k , ancestors , index + 1 ) , findClosestUtil ( node . right , k , ancestors , index + 1 ) ) ; } int findClosest ( Node node , char k ) { Node ancestors [ ] = new Node [ 100 ] ; return findClosestUtil ( node , k , ancestors , 0 ) ; } public static void main ( String args [ ] ) { BinaryTree tree = new BinaryTree ( ) ; tree . root = new Node ( ' A ' ) ; tree . root . left = new Node ( ' B ' ) ; tree . root . right = new Node ( ' C ' ) ; tree . root . right . left = new Node ( ' E ' ) ; tree . root . right . right = new Node ( ' F ' ) ; tree . root . right . left . left = new Node ( ' G ' ) ; tree . root . right . left . left . left = new Node ( ' I ' ) ; tree . root . right . left . left . right = new Node ( ' J ' ) ; tree . root . right . right . right = new Node ( ' H ' ) ; tree . root . right . right . right . left = new Node ( ' H ' ) ; char k = ' H ' ; System . out . println ( " Distance ▁ of ▁ the ▁ closest ▁ key ▁ from ▁ " + k + " ▁ is ▁ " + tree . findClosest ( tree . root , k ) ) ; k = ' C ' ; System . out . println ( " Distance ▁ of ▁ the ▁ closest ▁ key ▁ from ▁ " + k + " ▁ is ▁ " + tree . findClosest ( tree . root , k ) ) ; k = ' E ' ; System . out . println ( " Distance ▁ of ▁ the ▁ closest ▁...


"Find the closest pair from two sorted arrays | Java program to find closest pair in an array ; ar1 [ 0. . m - 1 ] and ar2 [ 0. . n - 1 ] are two given sorted arrays / and x is given number . This function prints the pair from both arrays such that the sum of the pair is closest to x . ; Initialize the diff between pair sum and x . ; res_l and res_r are result indexes from ar1 [ ] and ar2 [ ] respectively ; Start from left side of ar1 [ ] and right side of ar2 [ ] ; If this pair is closer to x than the previously found closest , then update res_l , res_r and diff ; If sum of this pair is more than x , move to smaller side ; move to the greater side ; Print the result ; Driver program to test above functions"
How can the above be solved in Java?

class ClosestPair { void printClosest ( int ar1 [ ] , int ar2 [ ] , int m , int n , int x ) { int diff = Integer . MAX_VALUE ; int res_l = 0 , res_r = 0 ; int l = 0 , r = n - 1 ; while ( l < m && r >= 0 ) { if ( Math . abs ( ar1 [ l ] + ar2 [ r ] - x ) < diff ) { res_l = l ; res_r = r ; diff = Math . abs ( ar1 [ l ] + ar2 [ r ] - x ) ; } if ( ar1 [ l ] + ar2 [ r ] > x ) r -- ; else l ++ ; } System . out . print ( " The ▁ closest ▁ pair ▁ is ▁ [ " + ar1 [ res_l ] + " , ▁ " + ar2 [ res_r ] + " ] " ) ; } public static void main ( String args [ ] ) { ClosestPair ob = new ClosestPair ( ) ; int ar1 [ ] = { 1 , 4 , 5 , 7 } ; int ar2 [ ] = { 10 , 20 , 30 , 40 } ; int m = ar1 . length ; int n = ar2 . length ; int x = 38 ; ob . printClosest ( ar1 , ar2 , m , n , x ) ; } }


"Find the color of given node in an infinite binary tree | JAVA program to find color of the node ; Function to find color of the node ; Maximum is to store maximum color ; Loop to check all the parent values to get maximum color ; Find the number into map and get maximum color ; Take the maximum color and assign into maximum variable ; Find parent index ; Return maximum color ; Function to build hash map with color ; To store color of each node ; For each number add a color number ; Assigning color ; Return hash map ; Driver code ; Build mapWithColor ; Print the maximum color"
How can the above be solved in Java?

import java . util . * ; class GFG { static int findColor ( HashMap < Integer , Integer > mapWithColor , int query ) { int maximum = 0 ; while ( query >= 1 ) { if ( mapWithColor . containsKey ( query ) ) { maximum = Math . max ( maximum , mapWithColor . get ( query ) ) ; } if ( query % 2 == 1 ) query = ( query - 1 ) / 2 ; else query = query / 2 ; } return maximum ; } static HashMap < Integer , Integer > buildMapWithColor ( int arr [ ] , int n ) { HashMap < Integer , Integer > mapWithColor = new HashMap < Integer , Integer > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { mapWithColor . put ( arr [ i ] , i + 1 ) ; } return mapWithColor ; } public static void main ( String [ ] args ) { int arr [ ] = { 3 , 2 , 1 , 3 } ; int n = arr . length ; int k = 7 ; HashMap < Integer , Integer > mapWithColor = buildMapWithColor ( arr , n ) ; System . out . print ( findColor ( mapWithColor , k ) ) ; } }


"Find the concentration of a solution using given Mass and Volume | Java program to find concentration of a solution using given Mass and Volume ; Function to calculate concentration from the given mass of solute and volume of a solution ; Driver code"
How can the above be solved in Java?

class GFG { static double get_concentration ( double mass , double volume ) { if ( volume == 0 ) return - 1 ; else return ( mass / volume ) * 1000 ; } public static void main ( String [ ] args ) { double mass , volume ; mass = 100.00 ; volume = 500.00 ; System . out . println ( get_concentration ( mass , volume ) ) ; } }


"Find the conjugate of a Complex number | Java implementation to Find the conjugate of a complex number ; Function to find conjugate of a complex number ; store index of ' + ' ; store index of ' - ' ; print the result ; Driver code ; initialise the complex number"
How can the above be solved in Java?

class GFG { static void solve ( String s ) { String z = s ; int l = s . length ( ) ; int i ; String str ; if ( s . indexOf ( ' + ' ) != - 1 ) { i = s . indexOf ( ' + ' ) ; str = s . replace ( ' + ' , ' - ' ) ; } else { i = s . indexOf ( ' - ' ) ; str = s . replace ( ' - ' , ' + ' ) ; } System . out . println ( " Conjugate ▁ of ▁ " + z + " ▁ = ▁ " + str ) ; } public static void main ( String [ ] args ) { String s = "3-4i " ; solve ( s ) ; } }


"Find the coordinate that does not belong to any square | Java program for above approach ; Function to find the point that is not a part of the side of a square ; Traverse each pair of coordinates ; Minimize x - coordinate in all the points except current point ; Maximize x - coordinate in all the points except the current point ; Minimize y - coordinate in all the points except current point ; Maximize y - coordinate in all the points except current point ; If x - coordinate matches with other same line ; If y coordinate matches with other same line ; Check if the condition for square exists or not ; Print the output ; Driver Code"
How can the above be solved in Java?

import java . util . ArrayList ; class GFG { static class pair < T , V > { T fi ; V se ; pair ( T a , V b ) { this . fi = a ; this . se = b ; } } static void findPoint ( int n , ArrayList < pair < Integer , Integer > > p ) { for ( int i = 0 ; i < n * 4 + 1 ; ++ i ) { int x1 = ( int ) 2e9 , x2 = ( int ) - 2e9 ; int y1 = ( int ) 2e9 , y2 = ( int ) - 2e9 ; for ( int j = 0 ; j < n * 4 + 1 ; ++ j ) if ( i != j ) { x1 = Math . min ( x1 , p . get ( j ) . fi ) ; x2 = Math . max ( x2 , p . get ( j ) . fi ) ; y1 = Math . min ( y1 , p . get ( j ) . se ) ; y2 = Math . max ( y2 , p . get ( j ) . se ) ; } boolean ok = true ; int c1 = 0 , c2 = 0 ; int c3 = 0 , c4 = 0 ; for ( int j = 1 ; j < n * 4 + 1 ; ++ j ) if ( i != j ) { if ( ( p . get ( j ) . fi == x1 || p . get ( j ) . fi == x2 ) || ( ( p . get ( j ) . se == y1 || p . get ( j ) . se == y2 ) ) ) { if ( p . get ( j ) . fi == x1 ) ++ c1 ; if ( p . get ( j ) . fi == x2 ) ++ c2 ; if ( p . get ( j ) . se == y1 ) ++ c3 ; if ( p . get ( j ) . se == y2 ) ++ c4 ; } else ok = false ; } if ( ok && c1 >= n && c2 >= n && c3 >= n && c4 >= n && x2 - x1 == y2 - y1 ) { System . out . println ( p . get ( i ) . fi + " ▁ " + p . get ( i ) . se ) ; } } } public static void main ( String [ ] args ) { int N = 2 ; ArrayList < pair < Integer , Integer > > arr = new ArrayList < > ( ) ; arr . add ( new pair < Integer , Integer > ( 0 , 0 ) ) ; arr . add ( new pair < Integer , Integer > ( 0 , 1 ) ) ; arr . add ( new pair < Integer , Integer > ( 0 , 2 ) ) ; arr . add ( new pair < Integer , Integer > ( 1 , 0 ) ) ; arr . add ( new pair < Integer , Integer > ( 1 , 1 ) ) ; arr . add ( new pair < Integer , Integer > ( 1 , 2 ) ) ; arr . add ( new pair < Integer , Integer > ( 2 , 0 ) ) ; arr . add ( new pair < Integer , Integer > ( 2 , 1 ) ) ; arr . add ( new pair < Integer , Integer > ( 2 , 2 ) ) ; findPoint ( N , arr ) ; } }


"Find the coordinates of a triangle whose Area = ( S / 2 ) | Java implementation of the approach ; Function to find the triangle with area = ( S / 2 ) ; Fix the two pairs of coordinates ; Find ( X3 , Y3 ) with integer coordinates ; Driver code"
How can the above be solved in Java?

class GFG { static final long MAX = 1000000000 ; static void findTriangle ( long S ) { long X1 = 0 , Y1 = 0 ; long X2 = MAX , Y2 = 1 ; long X3 = ( MAX - S % MAX ) % MAX ; long Y3 = ( S + X3 ) / MAX ; System . out . println ( " ( " + X1 + " , ▁ " + Y1 + " ) " ) ; System . out . println ( " ( " + X2 + " , ▁ " + Y2 + " ) " ) ; System . out . println ( " ( " + X3 + " , ▁ " + Y3 + " ) " ) ; } public static void main ( String [ ] args ) { long S = 4 ; findTriangle ( S ) ; } }


"Find the coordinates of the fourth vertex of a rectangle with given 3 vertices | Java implementation of the approach ; Function that return the coordinates of the fourth vertex of the rectangle ; Save the coordinates of the given vertices of the rectangle ; 1 - based indexing ; Driver Code"
How can the above be solved in Java?

import java . util . HashMap ; import java . util . Map ; class GfG { static Pair < Integer , Integer > findFourthVertex ( int n , int m , String s [ ] ) { HashMap < Integer , Integer > row = new HashMap < > ( ) ; HashMap < Integer , Integer > col = new HashMap < > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = 0 ; j < m ; j ++ ) { if ( s [ i ] . charAt ( j ) == ' * ' ) { if ( row . containsKey ( i ) ) { row . put ( i , row . get ( i ) + 1 ) ; } else { row . put ( i , 1 ) ; } if ( col . containsKey ( j ) ) { col . put ( j , col . get ( j ) + 1 ) ; } else { col . put ( j , 1 ) ; } } } } int x = 0 , y = 0 ; for ( Map . Entry < Integer , Integer > entry : row . entrySet ( ) ) { if ( entry . getValue ( ) == 1 ) x = entry . getKey ( ) ; } for ( Map . Entry < Integer , Integer > entry : col . entrySet ( ) ) { if ( entry . getValue ( ) == 1 ) y = entry . getKey ( ) ; } Pair < Integer , Integer > ans = new Pair < > ( x + 1 , y + 1 ) ; return ans ; } public static void main ( String [ ] args ) { String s [ ] = { " * . * " , " * . . " , " . . . " } ; int n = s . length ; int m = s [ 0 ] . length ( ) ; Pair < Integer , Integer > rs = findFourthVertex ( n , m , s ) ; System . out . println ( rs . first + " ▁ " + rs . second ) ; } } class Pair < A , B > { A first ; B second ; public Pair ( A first , B second ) { this . first = first ; this . second = second ; } }


"Find the count of M character words which have at least one character repeated | Java implementation of the approach ; Function to return the factorial of a number ; Function to return the value of nPr ; Function to return the total number of M length words which have at least a single character repeated more than once ; Driver code"
How can the above be solved in Java?

class GFG { static int fact ( int n ) { if ( n <= 1 ) return 1 ; return n * fact ( n - 1 ) ; } static int nPr ( int n , int r ) { return fact ( n ) / fact ( n - r ) ; } static int countWords ( int N , int M ) { return ( int ) Math . pow ( N , M ) - nPr ( N , M ) ; } public static void main ( String [ ] args ) { int N = 10 , M = 5 ; System . out . print ( countWords ( N , M ) ) ; } }


"Find the count of Smith Brothers Pairs in a given Array | Java program for the above approach ; Array to store all prime less than and equal to MAX ; Utility function for sieve of sundaram ; Main logic of Sundaram . ; Since 2 is a prime number ; Only primes are selected ; Function to check whether a number is a smith number . ; Find sum the digits of prime factors of n ; Add its digits of prime factors to pDigitSum . ; One prime factor is still to be summed up ; Now sum the digits of the original number ; Return the answer ; Function to check if X and Y are a Smith Brother Pair ; Function to find pairs from array ; Iterate through all pairs ; Increment count if there is a smith brother pair ; Driver code ; Preprocessing ; Input ; Function call"
How can the above be solved in Java?

import java . util . ArrayList ; class GFG { static int MAX = 10000 ; static ArrayList < Integer > primes = new ArrayList < Integer > ( ) ; public static void sieveSundaram ( ) { ArrayList < Boolean > marked = new ArrayList < Boolean > ( MAX / 2 + 100 ) ; for ( int i = 0 ; i < MAX / 2 + 100 ; i ++ ) { marked . add ( false ) ; } for ( int i = 1 ; i <= ( Math . sqrt ( MAX ) - 1 ) / 2 ; i ++ ) for ( int j = ( i * ( i + 1 ) ) << 1 ; j <= MAX / 2 ; j = j + 2 * i + 1 ) marked . set ( j , true ) ; primes . add ( 2 ) ; for ( int i = 1 ; i <= MAX / 2 ; i ++ ) if ( marked . get ( i ) == false ) primes . add ( 2 * i + 1 ) ; } public static Boolean isSmith ( int n ) { int original_no = n ; int pDigitSum = 0 ; for ( int i = 0 ; primes . get ( i ) <= n / 2 ; i ++ ) { while ( n % primes . get ( i ) == 0 ) { int p = primes . get ( i ) ; n = n / p ; while ( p > 0 ) { pDigitSum += ( p % 10 ) ; p = p / 10 ; } } } if ( n != 1 && n != original_no ) { while ( n > 0 ) { pDigitSum = pDigitSum + n % 10 ; n = n / 10 ; } } int sumDigits = 0 ; while ( original_no > 0 ) { sumDigits = sumDigits + original_no % 10 ; original_no = original_no / 10 ; } return ( pDigitSum == sumDigits ) ; } public static Boolean isSmithBrotherPair ( int X , int Y ) { return isSmith ( X ) && isSmith ( Y ) && Math . abs ( X - Y ) == 1 ; } public static Integer countSmithBrotherPairs ( int A [ ] , int N ) { int count = 0 ; for ( int i = 0 ; i < N ; i ++ ) for ( int j = i + 1 ; j < N ; j ++ ) { if ( isSmithBrotherPair ( A [ i ] , A [ j ] ) ) count ++ ; } return count ; } public static void main ( String args [ ] ) { sieveSundaram ( ) ; int A [ ] = { 728 , 729 , 28 , 2964 , 2965 } ; int N = A . length ; System . out . println ( countSmithBrotherPairs ( A , N ) ) ; } }


"Find the count of Smith Brothers Pairs in a given Array | Java program for the above approach ; array to store all prime less than and equal to MAX ; utility function for sieve of sundaram ; Main logic of Sundaram . ; Since 2 is a prime number ; only primes are selected ; Function to check whether a number is a smith number . ; Find sum the digits of prime factors of n ; add its digits of prime factors to pDigitSum . ; one prime factor is still to be summed up ; Now sum the digits of the original number ; return the answer ; Function to check if X and Y are a Smith Brother Pair ; Function to find pairs from array ; Variable to store number of Smith Brothers Pairs ; sort A ; check for consecutive numbers only ; Driver Code ; Preprocessing sieve of sundaram ; Input ; Function call"
How can the above be solved in Java?

import java . util . * ; class GFG { static int MAX = 10000 ; static ArrayList < Integer > primes = new ArrayList < Integer > ( ) ; static void sieveSundaram ( ) { ArrayList < Boolean > marked = new ArrayList < Boolean > ( MAX / 2 + 100 ) ; for ( int i = 0 ; i < MAX / 2 + 100 ; i ++ ) { marked . add ( false ) ; } for ( int i = 1 ; i <= ( Math . sqrt ( MAX ) - 1 ) / 2 ; i ++ ) for ( int j = ( i * ( i + 1 ) ) << 1 ; j <= MAX / 2 ; j = j + 2 * i + 1 ) marked . set ( j , true ) ; primes . add ( 2 ) ; for ( int i = 1 ; i <= MAX / 2 ; i ++ ) if ( marked . get ( i ) == false ) primes . add ( 2 * i + 1 ) ; } static Boolean isSmith ( int n ) { int original_no = n ; int pDigitSum = 0 ; for ( int i = 0 ; primes . get ( i ) <= n / 2 ; i ++ ) { while ( n % primes . get ( i ) == 0 ) { int p = primes . get ( i ) ; n = n / p ; while ( p > 0 ) { pDigitSum += ( p % 10 ) ; p = p / 10 ; } } } if ( n != 1 && n != original_no ) { while ( n > 0 ) { pDigitSum = pDigitSum + n % 10 ; n = n / 10 ; } } int sumDigits = 0 ; while ( original_no > 0 ) { sumDigits = sumDigits + original_no % 10 ; original_no = original_no / 10 ; } return ( pDigitSum == sumDigits ) ; } static Boolean isSmithBrotherPair ( int X , int Y ) { return isSmith ( X ) && isSmith ( Y ) ; } static Integer countSmithBrotherPairs ( int A [ ] , int N ) { int count = 0 ; Arrays . sort ( A ) ; for ( int i = 0 ; i < N - 2 ; i ++ ) if ( isSmithBrotherPair ( A [ i ] , A [ i + 1 ] ) ) count ++ ; return count ; } public static void main ( String [ ] args ) { sieveSundaram ( ) ; int A [ ] = { 728 , 729 , 28 , 2964 , 2965 } ; int N = A . length ; System . out . print ( countSmithBrotherPairs ( A , N ) ) ; } }


"Find the count of Strictly decreasing Subarrays | Java program to count number of strictly decreasing subarrays in O ( n ) time . ; Function to count the number of strictly decreasing subarrays ; Initialize length of current decreasing subarray ; Traverse through the array ; If arr [ i + 1 ] is less than arr [ i ] , then increment length ; Else Update count and reset length ; If last length is more than 1 ; Driver program"
How can the above be solved in Java?

import java . io . * ; class GFG { static int countDecreasing ( int A [ ] , int n ) { int len = 1 ; for ( int i = 0 ; i < n - 1 ; ++ i ) { if ( A [ i + 1 ] < A [ 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 ) { int A [ ] = { 100 , 3 , 1 , 13 } ; int n = A . length ; System . out . println ( countDecreasing ( A , n ) ) ; } }


"Find the count of distinct numbers in a range | Java Program to find the distinct elements in a range ; Function to perform queries in a range ; No overlap ; Totally Overlap ; Partial Overlap ; Finding the Answer for the left Child ; Finding the Answer for the right Child ; Combining the BitMasks ; Function to perform update operation in the Segment seg ; Forming the BitMask ; Updating the left Child ; Updating the right Child ; Updating the BitMask ; Building the Segment Tree ; Building the Initial BitMask ; Building the left seg tree ; Building the right seg tree ; Forming the BitMask ; Utility Function to answer the queries ; Counting the set bits which denote the distinct elements ; Updating the value ; Driver Code"
How can the above be solved in Java?

import java . util . * ; class GFG { static long query ( int start , int end , int left , int right , int node , long seg [ ] ) { if ( end < left start > right ) { return 0 ; } else if ( start >= left && end <= right ) { return seg [ node ] ; } else { int mid = ( start + end ) / 2 ; long leftChild = query ( start , mid , left , right , 2 * node , seg ) ; long rightChild = query ( mid + 1 , end , left , right , 2 * node + 1 , seg ) ; return ( leftChild rightChild ) ; } } static void update ( int left , int right , int index , int Value , int node , int ar [ ] , long seg [ ] ) { if ( left == right ) { ar [ index ] = Value ; seg [ node ] = ( 1L << Value ) ; return ; } int mid = ( left + right ) / 2 ; if ( index > mid ) { update ( mid + 1 , right , index , Value , 2 * node + 1 , ar , seg ) ; } else { update ( left , mid , index , Value , 2 * node , ar , seg ) ; } seg [ node ] = ( seg [ 2 * node ] seg [ 2 * node + 1 ] ) ; } static void build ( int left , int right , int node , int ar [ ] , long seg [ ] ) { if ( left == right ) { seg [ node ] = ( 1L << ar [ left ] ) ; return ; } int mid = ( left + right ) / 2 ; build ( left , mid , 2 * node , ar , seg ) ; build ( mid + 1 , right , 2 * node + 1 , ar , seg ) ; seg [ node ] = ( seg [ 2 * node ] seg [ 2 * node + 1 ] ) ; } static void getDistinctCount ( int [ ] [ ] queries , int ar [ ] , long seg [ ] , int n ) { for ( int i = 0 ; i < queries . length ; i ++ ) { int op = queries [ i ] [ 0 ] ; if ( op == 2 ) { int l = queries [ i ] [ 1 ] , r = queries [ i ] [ 2 ] ; long tempMask = query ( 0 , n - 1 , l - 1 , r - 1 , 1 , seg ) ; int countOfBits = 0 ; for ( int s = 63 ; s >= 0 ; s -- ) { if ( ( tempMask & ( 1L << s ) ) > 0 ) { countOfBits ++ ; } } System . out . println ( countOfBits ) ; } else { int index = queries [ i ] [ 1 ] ; int val = queries [ i ] [ 2 ] ; update ( 0 , n - 1 , index - 1 , val , 1 , ar , seg ) ; } } } public static void main ( String [ ] args ) { int n = 7 ; int ar [ ] = { 1 , 2 , 1 , 3 , 1 , 2 , 1 } ; long seg [ ] = new long [ 4 * n ] ; build ( 0 , n -...


"Find the count of even odd pairs in a given Array | Java program to count the pairs in array of the form ( even , odd ) ; Function to count the pairs in array of the form ( even , odd ) ; Check if number is even or not ; Driver code"
How can the above be solved in Java?

class GFG { static int findCount ( int arr [ ] , int n ) { int count = 0 , ans = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( arr [ i ] % 2 == 0 ) { count ++ ; } else { ans = ans + count ; } } return ans ; } public static void main ( String [ ] args ) { int a [ ] = { 5 , 4 , 1 , 2 , 3 } ; int n = a . length ; System . out . print ( findCount ( a , n ) ) ; } }


"Find the count of even odd pairs in a given Array | Java program to count the pairs in array of the form ( even , odd ) ; Function to count the pairs in array of the form ( even , odd ) ; Variable to store count of such pairs ; Iterate through all pairs ; Increment count if condition is satisfied ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { static int findCount ( int arr [ ] , int n ) { int res = 0 ; for ( int i = 0 ; i < n - 1 ; i ++ ) for ( int j = i + 1 ; j < n ; j ++ ) if ( ( arr [ i ] % 2 == 0 ) && ( arr [ j ] % 2 == 1 ) ) { res ++ ; } return res ; } public static void main ( String [ ] args ) { int a [ ] = { 5 , 4 , 1 , 2 , 3 } ; int n = a . length ; System . out . print ( findCount ( a , n ) ) ; } }


"Find the count of mountains in a given Matrix | Java program find the count of mountains in a given Matrix ; Function to count number of mountains in a given matrix of size n ; form another matrix with one extra layer of border elements . Border elements will contain Integer . MIN_VALUE value . ; For border elements , set value as Integer . MIN_VALUE ; For rest elements , just copy it into new matrix ; Check for mountains in the modified matrix ; check for all directions ; Driver code"
How can the above be solved in Java?


"Find the count of natural Hexadecimal numbers of size N | Java implementation of the approach ; Function to return the count of n - digit natural hexadecimal numbers ; Driver code"
How can the above be solved in Java?

class GFG { static int count ( int n ) { return ( int ) ( 15 * Math . pow ( 16 , n - 1 ) ) ; } public static void main ( String args [ ] ) { int n = 2 ; System . out . println ( count ( n ) ) ; } }


"Find the count of numbers that can be formed using digits 3 , 4 only and having length at max N . | Java program to find the count of numbers that can be formed using digits 3 , 4 only and having length at max N . ; Function to find the count of numbers that can be formed using digits 3 , 4 only and having length at max N . ; Driver code"
How can the above be solved in Java?

class GFG { static long numbers ( int n ) { return ( long ) ( Math . pow ( 2 , n + 1 ) ) - 2 ; } public static void main ( String args [ ] ) { int n = 2 ; System . out . println ( numbers ( n ) ) ; } }


"Find the count of palindromic sub | Java program to find the count of palindromic sub - string of a string in it 's ascending form ; function to return count of palindromic sub - string ; calculate frequency ; calculate count of palindromic sub - string ; return result ; driver program"
How can the above be solved in Java?

class GFG { final static int MAX_CHAR = 26 ; static int countPalindrome ( String str ) { int n = str . length ( ) ; int sum = 0 ; int hashTable [ ] = new int [ MAX_CHAR ] ; for ( int i = 0 ; i < n ; i ++ ) { hashTable [ str . charAt ( i ) - ' a ' ] ++ ; } for ( int i = 0 ; i < 26 ; i ++ ) { if ( hashTable [ i ] != 0 ) { sum += ( hashTable [ i ] * ( hashTable [ i ] + 1 ) / 2 ) ; } } return sum ; } public static void main ( String [ ] args ) { String str = " ananananddd " ; System . out . println ( countPalindrome ( str ) ) ; } }


"Find the count of sub | Java implementation of the approach ; Function to return the count of required occurrence ; To store the count of occurrences ; Check first four characters from ith position ; Variables for counting the required characters ; Check the four contiguous characters which can be reordered to form ' clap ' ; If all four contiguous characters are present then increment cnt variable ; Driver code"
How can the above be solved in Java?

class GFG { static int countOcc ( String s ) { int cnt = 0 ; for ( int i = 0 ; i < s . length ( ) - 3 ; i ++ ) { int c = 0 , l = 0 , a = 0 , p = 0 ; for ( int j = i ; j < i + 4 ; j ++ ) { switch ( s . charAt ( j ) ) { case ' c ' : c ++ ; break ; case ' l ' : l ++ ; break ; case ' a ' : a ++ ; break ; case ' p ' : p ++ ; break ; } } if ( c == 1 && l == 1 && a == 1 && p == 1 ) cnt ++ ; } return cnt ; } public static void main ( String args [ ] ) { String s = " clapc " ; System . out . print ( countOcc ( s . toLowerCase ( ) ) ) ; } }


"Find the count of subsequences where each element is divisible by K | Java implementation of the approach ; Function to return the count of all valid subsequences ; To store the count of elements which are divisible by k ; If current element is divisible by k then increment the count ; Total ( 2 ^ n - 1 ) non - empty subsequences are possible with n element ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { static int countSubSeq ( int arr [ ] , int n , int k ) { int count = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( arr [ i ] % k == 0 ) { count ++ ; } } return ( int ) ( Math . pow ( 2 , count ) - 1 ) ; } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 2 , 3 , 6 } ; int n = arr . length ; int k = 3 ; System . out . println ( countSubSeq ( arr , n , k ) ) ; } }


"Find the count of substrings in alphabetic order | Java to find the number of substrings in alphabetical order ; Function to find number of substrings ; Iterate over string length ; if any two chars are in alphabetic order ; find next char not in order ; return the result ; Driver function"
How can the above be solved in Java?

import java . util . * ; class Solution { static int findSubstringCount ( String str ) { int result = 0 ; int n = str . length ( ) ; for ( int i = 0 ; i < n - 1 ; i ++ ) { if ( str . charAt ( i ) + 1 == str . charAt ( i + 1 ) ) { result ++ ; while ( str . charAt ( i ) + 1 == str . charAt ( i + 1 ) ) { i ++ ; } } } return result ; } public static void main ( String args [ ] ) { String str = " alphabet " ; System . out . println ( findSubstringCount ( str ) ) ; } }


"Find the count of unvisited indices in an infinite array | Java implementation of the approach ; Function to return the count of unvisited indices starting from the index 0 ; Largest index that cannot be visited ; Push the index to the queue ; To store the required count ; Current index that cannot be visited ; Increment the count for the current index ; ( curr - m ) and ( curr - n ) are also unreachable if they are valid indices ; Return the required count ; Driver code"
How can the above be solved in Java?

import java . util . LinkedList ; import java . util . Queue ; class GFG { public static int countUnvisited ( int n , int m ) { int X = ( m * n ) - m - n ; Queue < Integer > queue = new LinkedList < > ( ) ; queue . add ( X ) ; int count = 0 ; while ( ! queue . isEmpty ( ) ) { int curr = queue . poll ( ) ; count ++ ; if ( curr - m > 0 ) queue . add ( curr - m ) ; if ( curr - n > 0 ) queue . add ( curr - n ) ; } return count ; } public static void main ( String args [ ] ) { int n = 2 , m = 5 ; System . out . print ( countUnvisited ( n , m ) ) ; } }


"Find the date after next half year from a given date | Java program for the above approach ; Function to find the date after the next half - year ; Stores the number of days in the months of a leap year ; List of months ; Days in half of a year ; Index of current month ; Starting day ; Decrement the value of cnt by 1 ; Increment cur_date ; If cnt is equal to 0 , then break out of the loop ; Update cur_month ; Update cur_date ; Print the resultant date ; Driver Code ; Function Call"
How can the above be solved in Java?

class GFG { public static void getDate ( int d , String m ) { int [ ] days = { 31 , 29 , 31 , 30 , 31 , 30 , 31 , 31 , 30 , 31 , 30 , 31 } ; String [ ] month = { " January " , " February " , " March " , " April " , " May " , " June " , " July " , " August " , " September " , " October " , " November " , " December " } ; int cnt = 183 ; int cur_month = 0 ; for ( int i = 0 ; i < 12 ; i ++ ) if ( m == month [ i ] ) cur_month = i ; int cur_date = d ; while ( true ) { while ( cnt > 0 && cur_date <= days [ cur_month ] ) { cnt -= 1 ; cur_date += 1 ; } if ( cnt == 0 ) break ; cur_month = ( cur_month + 1 ) % 12 ; cur_date = 1 ; } System . out . println ( cur_date + " ▁ " + month [ cur_month ] ) ; } public static void main ( String args [ ] ) { int D = 15 ; String M = " January " ; getDate ( D , M ) ; } }


"Find the deleted value from the array when average of original elements is given | Java implementation of the approach ; Function to return the missing element ; Find the sum of the array elements ; The numerator and the denominator of the equation ; If not divisible then X is not an integer it is a floating point number ; Return X ; Driver code"
How can the above be solved in Java?

class GFG { static int findMissing ( int arr [ ] , int n , int k , int avg ) { int sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) { sum += arr [ i ] ; } int num = ( avg * ( n + k ) ) - sum ; int den = k ; if ( num % den != 0 ) return - 1 ; return ( int ) ( num / den ) ; } public static void main ( String [ ] args ) { int k = 3 , avg = 4 ; int arr [ ] = { 2 , 7 , 3 } ; int n = arr . length ; System . out . println ( findMissing ( arr , n , k , avg ) ) ; } }