"Swap upper and lower triangular halves of a given Matrix | Java program for the above approach ; Function to swap laterally inverted images of upper and lower triangular halves of a given matrix ; Store the matrix elements from upper & lower triangular halves ; Traverse the matrix mat [ ] [ ] ; Find the index ; If current element lies on the principal diagonal ; If current element lies below the principal diagonal ; If current element lies above the principal diagonal ; Traverse again to swap values ; Find the index ; Principal diagonal ; Below main diagonal ; Above main diagonal ; Traverse the matrix and print ; Driver Code ; Given Matrix mat [ ] [ ] ; Swap the upper and lower triangular halves"
How can the above be solved in Java?

import java . io . * ; class GFG { static void ReverseSwap ( int [ ] [ ] mat , int n ) { int [ ] lowerEle = new int [ n ] ; int [ ] upperEle = new int [ n ] ; int index ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = 0 ; j < n ; j ++ ) { index = Math . abs ( i - j ) ; if ( i == j ) { continue ; } else if ( j < i ) { lowerEle [ index ] = mat [ i ] [ j ] ; } else { upperEle [ index ] = mat [ i ] [ j ] ; } } } for ( int i = 0 ; i < n ; i ++ ) { for ( int j = 0 ; j < n ; j ++ ) { index = Math . abs ( i - j ) ; if ( i == j ) { continue ; } else if ( j < i ) { mat [ i ] [ j ] = upperEle [ index ] ; } else { mat [ i ] [ j ] = lowerEle [ index -- ] ; } } } for ( int i = 0 ; i < n ; i ++ ) { for ( int j = 0 ; j < n ; j ++ ) { System . out . print ( mat [ i ] [ j ] + " ▁ " ) ; } System . out . println ( ) ; } } public static void main ( String [ ] args ) { int [ ] [ ] mat = new int [ ] [ ] { { 1 , 2 } , { 4 , 5 } } ; int N = mat . length ; ReverseSwap ( mat , N ) ; } }


"Swapping four variables without temporary variable | Java program to swap 4 variables without using temporary variable . ; swapping a and b variables ; swapping b and c variables ; swapping c and d variables ; Driver code ; initialising variables ; Function call"
How can the above be solved in Java?

class GFG { static void swap ( int a , int b , int c , int d ) { a = a + b ; b = a - b ; a = a - b ; b = b + c ; c = b - c ; b = b - c ; c = c + d ; d = c - d ; c = c - d ; System . out . println ( " values ▁ after ▁ " + " swapping ▁ are ▁ : ▁ " ) ; System . out . println ( " a ▁ = ▁ " + a ) ; System . out . println ( " b ▁ = ▁ " + b ) ; System . out . println ( " c ▁ = ▁ " + c ) ; System . out . println ( " d ▁ = ▁ " + d ) ; } public static void main ( String [ ] args ) { int a = 1 ; int b = 2 ; int c = 3 ; int d = 4 ; System . out . println ( " values ▁ before ▁ " + " swapping ▁ are ▁ : ▁ " ) ; System . out . println ( " a ▁ = ▁ " + a ) ; System . out . println ( " b ▁ = ▁ " + b ) ; System . out . println ( " c ▁ = ▁ " + c ) ; System . out . println ( " d ▁ = ▁ " + d ) ; System . out . println ( " " ) ; swap ( a , b , c , d ) ; } }


"Sylvester 's sequence | JAVA Code for Sylvester sequence ; To store the product . ; To store the current number . ; Loop till n . ; Driver program to test above function"
How can the above be solved in Java?

import java . util . * ; class GFG { public static void printSequence ( int n ) { int a = 1 ; int ans = 2 ; int N = 1000000007 ; for ( int i = 1 ; i <= n ; i ++ ) { System . out . print ( ans + " ▁ " ) ; ans = ( ( a % N ) * ( ans % N ) ) % N ; a = ans ; ans = ( ans + 1 ) % N ; } } public static void main ( String [ ] args ) { int n = 6 ; printSequence ( n ) ; } }


"Symmetric Tree ( Mirror Image of itself ) | A Binary Tree Node ; returns true if trees with roots as root1 and root2are mirror ; if both trees are empty , then they are mirror image ; For two trees to be mirror images , the following three conditions must be true 1 - Their root node 's key must be same 2 - left subtree of left  tree and right subtree  of right tree have to be mirror images  3 - right subtree of left tree and left subtree  of right tree have to be mirror images ; if none of the above conditions is true then root1 and root2 are not mirror images ; returns true if the tree is symmetric i . e mirror image of itself ; check if tree is mirror of itself ; Driver code ; Let us construct the Tree shown in the above figure"
How can the above be solved in Java?

class Node { int key ; Node left , right ; Node ( int item ) { key = item ; left = right = null ; } } class BinaryTree { Node root ; boolean isMirror ( Node node1 , Node node2 ) { if ( node1 == null && node2 == null ) return true ; if ( node1 != null && node2 != null && node1 . key == node2 . key ) return ( isMirror ( node1 . left , node2 . right ) && isMirror ( node1 . right , node2 . left ) ) ; return false ; } boolean isSymmetric ( ) { return isMirror ( root , root ) ; } public static void main ( String args [ ] ) { BinaryTree tree = new BinaryTree ( ) ; tree . root = new Node ( 1 ) ; tree . root . left = new Node ( 2 ) ; tree . root . right = new Node ( 2 ) ; tree . root . left . left = new Node ( 3 ) ; tree . root . left . right = new Node ( 4 ) ; tree . root . right . left = new Node ( 4 ) ; tree . root . right . right = new Node ( 3 ) ; boolean output = tree . isSymmetric ( ) ; if ( output == true ) System . out . println ( " Symmetric " ) ; else System . out . println ( " Not ▁ symmetric " ) ; } }


"System of Linear Equations in three variables using Cramer 's Rule | Java program to calculate solutions of linear equations using cramer 's rule ; This functions finds the determinant of Matrix ; This function finds the solution of system of linear equations using cramer 's rule ; Matrix d using coeff as given in cramer 's rule ; Matrix d1 using coeff as given in cramer 's rule ; Matrix d2 using coeff as given in cramer 's rule ; Matrix d3 using coeff as given in cramer 's rule ; Calculating Determinant of Matrices d , d1 , d2 , d3 ; Case 1 ; Coeff have a unique solution . Apply Cramer 's Rule ; double z = D3 / D ; calculating z using cramer 's rule ; Case 2 ; Driver Code ; storing coefficients of linear equations in coeff matrix"
How can the above be solved in Java?

 class GFG { static double determinantOfMatrix ( double mat [ ] [ ] ) { double ans ; ans = mat [ 0 ] [ 0 ] * ( mat [ 1 ] [ 1 ] * mat [ 2 ] [ 2 ] - mat [ 2 ] [ 1 ] * mat [ 1 ] [ 2 ] ) - mat [ 0 ] [ 1 ] * ( mat [ 1 ] [ 0 ] * mat [ 2 ] [ 2 ] - mat [ 1 ] [ 2 ] * mat [ 2 ] [ 0 ] ) + mat [ 0 ] [ 2 ] * ( mat [ 1 ] [ 0 ] * mat [ 2 ] [ 1 ] - mat [ 1 ] [ 1 ] * mat [ 2 ] [ 0 ] ) ; return ans ; } static void findSolution ( double coeff [ ] [ ] ) { double d [ ] [ ] = { { coeff [ 0 ] [ 0 ] , coeff [ 0 ] [ 1 ] , coeff [ 0 ] [ 2 ] } , { coeff [ 1 ] [ 0 ] , coeff [ 1 ] [ 1 ] , coeff [ 1 ] [ 2 ] } , { coeff [ 2 ] [ 0 ] , coeff [ 2 ] [ 1 ] , coeff [ 2 ] [ 2 ] } , } ; double d1 [ ] [ ] = { { coeff [ 0 ] [ 3 ] , coeff [ 0 ] [ 1 ] , coeff [ 0 ] [ 2 ] } , { coeff [ 1 ] [ 3 ] , coeff [ 1 ] [ 1 ] , coeff [ 1 ] [ 2 ] } , { coeff [ 2 ] [ 3 ] , coeff [ 2 ] [ 1 ] , coeff [ 2 ] [ 2 ] } , } ; double d2 [ ] [ ] = { { coeff [ 0 ] [ 0 ] , coeff [ 0 ] [ 3 ] , coeff [ 0 ] [ 2 ] } , { coeff [ 1 ] [ 0 ] , coeff [ 1 ] [ 3 ] , coeff [ 1 ] [ 2 ] } , { coeff [ 2 ] [ 0 ] , coeff [ 2 ] [ 3 ] , coeff [ 2 ] [ 2 ] } , } ; double d3 [ ] [ ] = { { coeff [ 0 ] [ 0 ] , coeff [ 0 ] [ 1 ] , coeff [ 0 ] [ 3 ] } , { coeff [ 1 ] [ 0 ] , coeff [ 1 ] [ 1 ] , coeff [ 1 ] [ 3 ] } , { coeff [ 2 ] [ 0 ] , coeff [ 2 ] [ 1 ] , coeff [ 2 ] [ 3 ] } , } ; double D = determinantOfMatrix ( d ) ; double D1 = determinantOfMatrix ( d1 ) ; double D2 = determinantOfMatrix ( d2 ) ; double D3 = determinantOfMatrix ( d3 ) ; System . out . printf ( "D is : %.6f
", D); System . out . printf ( "D1 is : %.6f
", D1); System . out . printf ( "D2 is : %.6f
", D2); System . out . printf ( "D3 is : %.6f
", D3); if ( D != 0 ) { double x = D1 / D ; double y = D2 / D ; System . out . printf ( "Value of x is : %.6f
", x); System . out . printf ( "Value of y is : %.6f
", y); System . out . printf ( "Value of z is : %.6f
", z); } else { if ( D1 == 0 && D2 == 0 && D3 == 0 ) System . out . printf ( "Infinite solutions
"); else if ( D1 != 0 D2 != 0 D3 != 0 ) System . out . printf ( "No solutions
"); } }...


"Tail Recursion | A NON - tail - recursive function . The function is not tail recursive because the value returned by fact ( n - 1 ) is used in fact ( n ) and call to fact ( n - 1 ) is not the last thing done by fact ( n ) ; Driver program"
How can the above be solved in Java?

class GFG { static int fact ( int n ) { if ( n == 0 ) return 1 ; return n * fact ( n - 1 ) ; } public static void main ( String [ ] args ) { System . out . println ( fact ( 5 ) ) ; } }


"Tail Recursion | An example of tail recursive function ; The last executed statement is recursive call"
How can the above be solved in Java?

static void print ( int n ) { if ( n < 0 ) return ; System . out . print ( " ▁ " + n ) ; print ( n - 1 ) ; }


"Tail Recursion | Java Code for Tail Recursion ; A tail recursive function to calculate factorial ; A wrapper over factTR ; Driver code"
How can the above be solved in Java?

class GFG { static int factTR ( int n , int a ) { if ( n == 0 ) return a ; return factTR ( n - 1 , n * a ) ; } static int fact ( int n ) { return factTR ( n , 1 ) ; } static public void main ( String [ ] args ) { System . out . println ( fact ( 5 ) ) ; } }


"Tarjan 's off | A Java Program to implement Tarjan Offline LCA Algorithm ; number of nodes in input tree ; COLOUR ' WHITE ' is assigned value 1 ; COLOUR ' BLACK ' is assigned value 2 ; A binary tree node has data , pointer to left child and a pointer to right child ; subset [ i ] . parent - . Holds the parent of node - ' i ' subset [ i ] . rank - . Holds the rank of node - ' i ' subset [ i ] . ancestor - . Holds the LCA queries answers subset [ i ] . child - . Holds one of the child of node - ' i ' if present , else - '0' subset [ i ] . sibling - . Holds the right - sibling of node - ' i ' if present , else - '0' subset [ i ] . color - . Holds the colour of node - ' i ' ; Structure to represent a query A query consists of ( L , R ) and we will process the queries offline a / c to Tarjan 's oflline LCA algorithm ; Helper function that allocates a new node with the given data and null left and right pointers . ; A utility function to make set ; A utility function to find set of an element i ( uses path compression technique ) ; find root and make root as parent of i ( path compression ) ; A function that does union of two sets of x and y ( uses union by rank ) ; Attach smaller rank tree under root of high rank tree ( Union by Rank ) ; If ranks are same , then make one as root and increment its rank by one ; The main function that prints LCAs . u is root 's data. m is size of q[] ; Make Sets ; Initially , each node 's ancestor is the node  itself. ; This while loop doesn 't run for more than 2 times  as there can be at max. two children of a node ; This is basically an inorder traversal and we preprocess the arrays . child [ ] and sibling [ ] in " subset " with the tree structure using this function . ; Recur on left child ; Note that the below two lines can also be this - subsets [ node . data ] . child = node . right . data ; subsets [ node . right . data ] . sibling = node . left . data ; This is because if both left and right children of node - ' i ' are present then we can store any of them in subsets [ i ]..."
How can the above be solved in Java?

 import java . util . Arrays ; class GFG { static final int V = 5 ; static final int WHITE = 1 ; static final int BLACK = 2 ; static class Node { int data ; Node left , right ; } ; static class subset { int parent ; int rank ; int ancestor ; int child ; int sibling ; int color ; } ; static class Query { int L , R ; Query ( int L , int R ) { this . L = L ; this . R = R ; } } ; static Node newNode ( int data ) { Node node = new Node ( ) ; node . data = data ; node . left = node . right = null ; return ( node ) ; } static void makeSet ( subset subsets [ ] , int i ) { if ( i < 1 i > V ) return ; subsets [ i ] . color = WHITE ; subsets [ i ] . parent = i ; subsets [ i ] . rank = 0 ; return ; } static int findSet ( subset subsets [ ] , int i ) { if ( subsets [ i ] . parent != i ) subsets [ i ] . parent = findSet ( subsets , subsets [ i ] . parent ) ; return subsets [ i ] . parent ; } static void unionSet ( subset subsets [ ] , int x , int y ) { int xroot = findSet ( subsets , x ) ; int yroot = findSet ( subsets , y ) ; if ( subsets [ xroot ] . rank < subsets [ yroot ] . rank ) subsets [ xroot ] . parent = yroot ; else if ( subsets [ xroot ] . rank > subsets [ yroot ] . rank ) subsets [ yroot ] . parent = xroot ; else { subsets [ yroot ] . parent = xroot ; ( subsets [ xroot ] . rank ) ++ ; } } static void lcaWalk ( int u , Query q [ ] , int m , subset subsets [ ] ) { makeSet ( subsets , u ) ; subsets [ findSet ( subsets , u ) ] . ancestor = u ; int child = subsets [ u ] . child ; while ( child != 0 ) { lcaWalk ( child , q , m , subsets ) ; unionSet ( subsets , u , child ) ; subsets [ findSet ( subsets , u ) ] . ancestor = u ; child = subsets [ child ] . sibling ; } subsets [ u ] . color = BLACK ; for ( int i = 0 ; i < m ; i ++ ) { if ( q [ i ] . L == u ) { if ( subsets [ q [ i ] . R ] . color == BLACK ) { System . out . printf ( "LCA(%d %d)->%d
", q [ i ] . L , q [ i ] . R , subsets [ findSet ( subsets , q [ i ] . R ) ] . ancestor ) ; } } else if ( q [ i ] . R == u ) { if ( subsets [ q [ i ] . L ] . color == BLACK )...


"Temple Offerings | Java program to find total offerings required ; To store count of increasing order temples on left and right ( including current temple ) ; Returns count of minimum offerings for n temples of given heights . ; Initialize counts for all temples ; Values corner temples ; Filling left and right values using same values of previous ( or next ) ; Computing max of left and right for all temples and returing sum . ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { public static class Temple { public int L ; public int R ; } ; static int offeringNumber ( int n , int [ ] templeHeight ) { Temple [ ] chainSize = new Temple [ n ] ; for ( int i = 0 ; i < n ; ++ i ) { chainSize [ i ] = new Temple ( ) ; chainSize [ i ] . L = - 1 ; chainSize [ i ] . R = - 1 ; } chainSize [ 0 ] . L = 1 ; chainSize [ n - 1 ] . R = 1 ; for ( int i = 1 ; i < n ; ++ i ) { if ( templeHeight [ i - 1 ] < templeHeight [ i ] ) chainSize [ i ] . L = chainSize [ i - 1 ] . L + 1 ; else chainSize [ i ] . L = 1 ; } for ( int i = n - 2 ; i >= 0 ; -- i ) { if ( templeHeight [ i + 1 ] < templeHeight [ i ] ) chainSize [ i ] . R = chainSize [ i + 1 ] . R + 1 ; else chainSize [ i ] . R = 1 ; } int sum = 0 ; for ( int i = 0 ; i < n ; ++ i ) sum += Math . max ( chainSize [ i ] . L , chainSize [ i ] . R ) ; return sum ; } public static void main ( String [ ] s ) { int [ ] arr1 = { 1 , 2 , 2 } ; System . out . println ( offeringNumber ( 3 , arr1 ) ) ; int [ ] arr2 = { 1 , 4 , 3 , 6 , 2 , 1 } ; System . out . println ( offeringNumber ( 6 , arr2 ) ) ; } }


"Temple Offerings | Program to find minimum total offerings required ; Returns minimum offerings required ; Go through all temples one by one ; Go to left while height keeps increasing ; Go to right while height keeps increasing ; This temple should offer maximum of two values to follow the rule . ; Driver code"
How can the above be solved in Java?

import java . io . * ; class GFG { static int offeringNumber ( int n , int templeHeight [ ] ) { for ( int i = 0 ; i < n ; ++ i ) { int left = 0 , right = 0 ; for ( int j = i - 1 ; j >= 0 ; -- j ) { if ( templeHeight [ j ] < templeHeight [ j + 1 ] ) ++ left ; else break ; } for ( int j = i + 1 ; j < n ; ++ j ) { if ( templeHeight [ j ] < templeHeight [ j - 1 ] ) ++ right ; else break ; } sum += Math . max ( right , left ) + 1 ; } return sum ; } public static void main ( String [ ] args ) { int arr1 [ ] = { 1 , 2 , 2 } ; System . out . println ( offeringNumber ( 3 , arr1 ) ) ; int arr2 [ ] = { 1 , 4 , 3 , 6 , 2 , 1 } ; System . out . println ( offeringNumber ( 6 , arr2 ) ) ; } }


"Ternary number system or Base 3 numbers | Java program to convert a ternary number to decimal number ; Function to convert a ternary number to a decimal number ; If the number is greater than 0 , compute the decimal representation of the number ; Loop to iterate through the number ; Computing the decimal digit ; Driver code"
How can the above be solved in Java?

 class GFG { static void convertToDecimal ( int N ) { System . out . print ( " Decimal ▁ number ▁ of ▁ " + N + " ▁ is : ▁ " ) ; if ( N != 0 ) { int decimalNumber = 0 , i = 0 , remainder ; while ( N != 0 ) { remainder = N % 10 ; N /= 10 ; decimalNumber += remainder * Math . pow ( 3 , i ) ; ++ i ; } System . out . print ( decimalNumber + "
"); } else System . out . print ( "0" + "
"); } public static void main ( String [ ] args ) { int Ternary = 10202202 ; convertToDecimal ( Ternary ) ; } }


"Ternary number system or Base 3 numbers | Java program to convert decimal number to ternary number ; Function to convert a decimal number to a ternary number ; Base case ; Finding the remainder when N is divided by 3 ; Recursive function to call the function for the integer division of the value N / 3 ; Handling the negative cases ; Function to convert the decimal to ternary ; If the number is greater than 0 , compute the ternary representation of the number ; Driver Code"
How can the above be solved in Java?

import java . io . * ; class GFG { static void convertToTernary ( int N ) { if ( N == 0 ) return ; int x = N % 3 ; N /= 3 ; if ( x < 0 ) N += 1 ; convertToTernary ( N ) ; if ( x < 0 ) System . out . print ( x + ( 3 * - 1 ) ) ; else System . out . print ( x ) ; } static void convert ( int Decimal ) { System . out . print ( " Ternary ▁ number ▁ of ▁ " + Decimal + " ▁ is : ▁ " ) ; if ( Decimal != 0 ) { convertToTernary ( Decimal ) ; } else System . out . println ( "0" ) ; } public static void main ( String [ ] args ) { int Decimal = 2747 ; convert ( Decimal ) ; } }


"Ternary representation of Cantor set | Java implementation to find the cantor set for n levels and for a given start_num and end_num ; The Linked List Structure for the Cantor Set ; Function to initialize the Cantor Set List ; Function to propogate the list by adding new nodes for the next levels ; Modifying the start and end values for the next level ; Changing the pointers to the next node ; Recursively call the function to generate the Cantor Set for the entire level ; Function to print a level of the Set ; Function to build and display the Cantor Set for each level ; Driver code"
How can the above be solved in Java?

 class GFG { static class Cantor { double start , end ; Cantor next ; } ; static Cantor Cantor ; static Cantor startList ( Cantor head , double start_num , double end_num ) { if ( head == null ) { head = new Cantor ( ) ; head . start = start_num ; head . end = end_num ; head . next = null ; } return head ; } static Cantor propagate ( Cantor head ) { Cantor temp = head ; if ( temp != null ) { Cantor newNode = new Cantor ( ) ; double diff = ( ( ( temp . end ) - ( temp . start ) ) / 3 ) ; newNode . end = temp . end ; temp . end = ( ( temp . start ) + diff ) ; newNode . start = ( newNode . end ) - diff ; newNode . next = temp . next ; temp . next = newNode ; propagate ( temp . next . next ) ; } return head ; } static void print ( Cantor temp ) { while ( temp != null ) { System . out . printf ( " [ % f ] ▁ - - ▁ [ % f ] " , temp . start , temp . end ) ; temp = temp . next ; } System . out . printf ( "
"); } static void buildCantorSet ( int A , int B , int L ) { Cantor head = null ; head = startList ( head , A , B ) ; for ( int i = 0 ; i < L ; i ++ ) { System . out . printf ( " Level _ % d ▁ : ▁ " , i ) ; print ( head ) ; propagate ( head ) ; } System . out . printf ( " Level _ % d ▁ : ▁ " , L ) ; print ( head ) ; } public static void main ( String [ ] args ) { int A = 0 ; int B = 9 ; int L = 2 ; buildCantorSet ( A , B , L ) ; } }


"Tetracontadigonal Number | Java implementation for the above approach ; Function to find the nth Tetracontadigonal Number ; Driver Code"
How can the above be solved in Java?

import java . util . * ; class GFG { static int TetracontadigonalNum ( int n ) { return ( 40 * n * n - 38 * n ) / 2 ; } public static void main ( String [ ] args ) { int n = 3 ; System . out . print ( TetracontadigonalNum ( n ) ) ; } }


"Tetracontagon Number | Java program for above approach ; Finding the nth tetracontagon number ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { static int tetracontagonNum ( int n ) { return ( 38 * n * n - 36 * n ) / 2 ; } public static void main ( String [ ] args ) { int n = 3 ; System . out . println ( "3rd ▁ tetracontagon ▁ Number ▁ is ▁ = ▁ " + tetracontagonNum ( n ) ) ; } }


"Tetracontaoctagonal Number | Java program for above approach ; Function to find the nth TetracontaoctagonalNum Number ; Driver code"
How can the above be solved in Java?

class GFG { static int TetracontaoctagonalNum ( int n ) { return ( 46 * n * n - 44 * n ) / 2 ; } public static void main ( String [ ] args ) { int n = 3 ; System . out . print ( TetracontaoctagonalNum ( n ) ) ; } }


"Tetradic Primes | Java implementation to print all Tetradic primes smaller than or equal to N . ; Function to check if the number N having all digits lies in the set ( 0 , 1 , 8 ) ; Function to check if the number N is palindrome ; Function to check if a number N is Tetradic ; Function to generate all primes and checking whether number is Tetradic or not ; 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 ; Update all multiples of p ; Print all Tetradic prime numbers ; Checking whether the given number is prime Tetradic or not ; Driver Code"
How can the above be solved in Java?

import java . util . * ; class GFG { public static boolean isContaindigit ( int n ) { while ( n > 0 ) { if ( ! ( n % 10 == 0 n % 10 == 1 n % 10 == 8 ) ) return false ; n = n / 10 ; } return true ; } public static boolean ispalindrome ( int n ) { String temp = Integer . toString ( n ) ; int l = temp . length ( ) ; for ( int i = 0 ; i < l / 2 ; i ++ ) { if ( temp . charAt ( i ) != temp . charAt ( l - i - 1 ) ) return false ; } return true ; } public static boolean isTetradic ( int n ) { if ( ispalindrome ( n ) && isContaindigit ( n ) ) return true ; return false ; } public static void printTetradicPrimesLessThanN ( int n ) { boolean prime [ ] = new boolean [ n + 1 ] ; Arrays . fill ( prime , true ) ; int p = 2 ; while ( p * p <= n ) { if ( prime [ p ] ) { for ( int i = p * 2 ; i < n + 1 ; i += p ) prime [ i ] = false ; } p += 1 ; } for ( p = 2 ; p < n + 1 ; p ++ ) { if ( prime [ p ] && isTetradic ( p ) ) System . out . print ( p + " ▁ " ) ; } } public static void main ( String [ ] args ) { int n = 1000 ; printTetradicPrimesLessThanN ( n ) ; } }


"Tetrahedral Numbers | Java Program to find the nth tetrahedral number ; Function to find Tetrahedral Number ; Driver Code"
How can the above be solved in Java?

class GFG { static int tetrahedralNumber ( int n ) { return ( n * ( n + 1 ) * ( n + 2 ) ) / 6 ; } public static void main ( String [ ] args ) { int n = 5 ; System . out . println ( tetrahedralNumber ( n ) ) ; } }


"Thabit number | Java code to check for thabit number ; Utility function to check power of two ; function to check if the given number is Thabit Number ; Add 1 to the number ; Divide the number by 3 ; Check if the given number is power of 2 ; Driver Program ; Check if number is thabit number"
How can the above be solved in Java?

class GFG { static boolean isPowerOfTwo ( int n ) { return n != 0 && ( ( n & ( n - 1 ) ) == 0 ) ; } static boolean isThabitNumber ( int n ) { n = n + 1 ; if ( n % 3 == 0 ) n = n / 3 ; else return false ; if ( isPowerOfTwo ( n ) ) return true ; else return false ; } public static void main ( String [ ] args ) { int n = 47 ; if ( isThabitNumber ( n ) ) { System . out . println ( " YES " ) ; } else { System . out . println ( " NO " ) ; } } }


"The Celebrity Problem | Java program to find celebrity ; Max # of persons in the party ; Person with 2 is celebrity ; Returns - 1 if celebrity is not present . If present , returns id ( value from 0 to n - 1 ) . ; the graph needs not be constructed as the edges can be found by using knows function degree array ; ; query for all edges ; set the degrees ; find a person with indegree n - 1 and out degree 0 ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { static final int N = 8 ; static int MATRIX [ ] [ ] = { { 0 , 0 , 1 , 0 } , { 0 , 0 , 1 , 0 } , { 0 , 0 , 0 , 0 } , { 0 , 0 , 1 , 0 } } ; static int knows ( int a , int b ) { return MATRIX [ a ] [ b ] ; } static int findCelebrity ( int n ) { int [ ] indegree = new int [ n ] ; int [ ] outdegree = new int [ n ] ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = 0 ; j < n ; j ++ ) { int x = knows ( i , j ) ; outdegree [ i ] += x ; indegree [ j ] += x ; } } for ( int i = 0 ; i < n ; i ++ ) if ( indegree [ i ] == n - 1 && outdegree [ i ] == 0 ) return i ; return - 1 ; } public static void main ( String [ ] args ) { int n = 4 ; int id = findCelebrity ( n ) ; if ( id == - 1 ) System . out . print ( " No ▁ celebrity " ) ; else System . out . print ( " Celebrity ▁ ID ▁ " + id ) ; } }


"The Knight 's tour problem | Backtracking | Java program for Knight Tour problem ; A utility function to check if i , j are valid indexes for N * N chessboard ; A utility function to print solution matrix sol [ N ] [ N ] ; This function solves the Knight Tour problem using Backtracking . This function mainly uses solveKTUtil ( ) to solve the problem . It returns false if no complete tour is possible , otherwise return true and prints the tour . Please note that there may be more than one solutions , this function prints one of the feasible solutions . ; Initialization of solution matrix ; xMove [ ] and yMove [ ] define next move of Knight . xMove [ ] is for next value of x coordinate yMove [ ] is for next value of y coordinate ; Since the Knight is initially at the first block ; Start from 0 , 0 and explore all tours using solveKTUtil ( ) ; A recursive utility function to solve Knight Tour problem ; Try all next moves from the current coordinate x , y ; backtracking ; Driver Code ; Function Call"
How can the above be solved in Java?

class KnightTour { static int N = 8 ; static boolean isSafe ( int x , int y , int sol [ ] [ ] ) { return ( x >= 0 && x < N && y >= 0 && y < N && sol [ x ] [ y ] == - 1 ) ; } static void printSolution ( int sol [ ] [ ] ) { for ( int x = 0 ; x < N ; x ++ ) { for ( int y = 0 ; y < N ; y ++ ) System . out . print ( sol [ x ] [ y ] + " ▁ " ) ; System . out . println ( ) ; } } static boolean solveKT ( ) { int sol [ ] [ ] = new int [ 8 ] [ 8 ] ; for ( int x = 0 ; x < N ; x ++ ) for ( int y = 0 ; y < N ; y ++ ) sol [ x ] [ y ] = - 1 ; int xMove [ ] = { 2 , 1 , - 1 , - 2 , - 2 , - 1 , 1 , 2 } ; int yMove [ ] = { 1 , 2 , 2 , 1 , - 1 , - 2 , - 2 , - 1 } ; sol [ 0 ] [ 0 ] = 0 ; if ( ! solveKTUtil ( 0 , 0 , 1 , sol , xMove , yMove ) ) { System . out . println ( " Solution ▁ does ▁ not ▁ exist " ) ; return false ; } else printSolution ( sol ) ; return true ; } static boolean solveKTUtil ( int x , int y , int movei , int sol [ ] [ ] , int xMove [ ] , int yMove [ ] ) { int k , next_x , next_y ; if ( movei == N * N ) return true ; for ( k = 0 ; k < 8 ; k ++ ) { next_x = x + xMove [ k ] ; next_y = y + yMove [ k ] ; if ( isSafe ( next_x , next_y , sol ) ) { sol [ next_x ] [ next_y ] = movei ; if ( solveKTUtil ( next_x , next_y , movei + 1 , sol , xMove , yMove ) ) return true ; else sol [ next_x ] [ next_y ] = - 1 ; } } return false ; } public static void main ( String args [ ] ) { solveKT ( ) ; } }


"The Lazy Caterer 's Problem | Java program to find the solution to The Lazy Caterer 's Problem ; This function returns the maximum number of pieces that can be made form pancake using n cuts ; Use the formula ; Driver program to test above function"
How can the above be solved in Java?

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


"The Slowest Sorting Algorithms | Java program for the stooge sort ; Function to implement stooge sort ; Base Case ; If first element is smaller than last element , swap them ; If there are more than 2 elements in the array ; Recursively sort the first 2 / 3 elements ; Recursively sort the last 2 / 3 elements ; Recursively sort the first 2 / 3 elements again ; Driver Code ; Function Call ; Display the sorted array"
How can the above be solved in Java?

class GFG { static void stoogesort ( int arr [ ] , int l , int h ) { if ( l >= h ) return ; if ( arr [ l ] > arr [ h ] ) { int temp = arr [ l ] ; arr [ l ] = arr [ h ] ; arr [ h ] = temp ; } if ( h - l + 1 > 2 ) { int t = ( h - l + 1 ) / 3 ; stoogesort ( arr , l , h - t ) ; stoogesort ( arr , l + t , h ) ; stoogesort ( arr , l , h - t ) ; } } public static void main ( String [ ] args ) { int arr [ ] = { 2 , 4 , 5 , 3 , 1 } ; int N = arr . length ; stoogesort ( arr , 0 , N - 1 ) ; for ( int i = 0 ; i < N ; i ++ ) { System . out . print ( arr [ i ] + " ▁ " ) ; } } }


"The Stock Span Problem | Java implementation for brute force method to calculate stock span values ; method to calculate stock span values ; Span value of first day is always 1 ; Calculate span value of remaining days by linearly checking previous days ; Initialize span value ; Traverse left while the next element on left is smaller than price [ i ] ; A utility function to print elements of array ; Driver program to test above functions ; Fill the span values in array S [ ] ; print the calculated span values"
How can the above be solved in Java?

import java . util . Arrays ; class GFG { static void calculateSpan ( int price [ ] , int n , int S [ ] ) { S [ 0 ] = 1 ; for ( int i = 1 ; i < n ; i ++ ) { S [ i ] = 1 ; for ( int j = i - 1 ; ( j >= 0 ) && ( price [ i ] >= price [ j ] ) ; j -- ) S [ i ] ++ ; } } static void printArray ( int arr [ ] ) { System . out . print ( Arrays . toString ( arr ) ) ; } public static void main ( String [ ] args ) { int price [ ] = { 10 , 4 , 5 , 90 , 120 , 80 } ; int n = price . length ; int S [ ] = new int [ n ] ; calculateSpan ( price , n , S ) ; printArray ( S ) ; } }


"The Stock Span Problem | Java linear time solution for stock span problem ; A stack based efficient method to calculate stock span values ; Create a stack and push index of first element to it ; Span value of first element is always 1 ; Calculate span values for rest of the elements ; Pop elements from stack while stack is not empty and top of stack is smaller than price [ i ] ; If stack becomes empty , then price [ i ] is greater than all elements on left of it , i . e . , price [ 0 ] , price [ 1 ] , . . price [ i - 1 ] . Else price [ i ] is greater than elements after top of stack ; Push this element to stack ; A utility function to print elements of array ; Driver method ; Fill the span values in array S [ ] ; print the calculated span values"
How can the above be solved in Java?

import java . util . Stack ; import java . util . Arrays ; public class GFG { static void calculateSpan ( int price [ ] , int n , int S [ ] ) { Stack < Integer > st = new Stack < > ( ) ; st . push ( 0 ) ; S [ 0 ] = 1 ; for ( int i = 1 ; i < n ; i ++ ) { while ( ! st . empty ( ) && price [ st . peek ( ) ] <= price [ i ] ) st . pop ( ) ; S [ i ] = ( st . empty ( ) ) ? ( i + 1 ) : ( i - st . peek ( ) ) ; st . push ( i ) ; } } static void printArray ( int arr [ ] ) { System . out . print ( Arrays . toString ( arr ) ) ; } public static void main ( String [ ] args ) { int price [ ] = { 10 , 4 , 5 , 90 , 120 , 80 } ; int n = price . length ; int S [ ] = new int [ n ] ; calculateSpan ( price , n , S ) ; printArray ( S ) ; } }


"The Stock Span Problem | Java program for a linear time solution for stock span problem without using stack ; An efficient method to calculate stock span values implementing the same idea without using stack ; Span value of first element is always 1 ; Calculate span values for rest of the elements ; A utility function to print elements of array ; Driver code ; Fill the span values in array S [ ] ; print the calculated span values"
How can the above be solved in Java?

class GFG { static void calculateSpan ( int A [ ] , int n , int ans [ ] ) { ans [ 0 ] = 1 ; for ( int i = 1 ; i < n ; i ++ ) { int counter = 1 ; while ( ( i - counter ) >= 0 && A [ i ] >= A [ i - counter ] ) { counter += ans [ i - counter ] ; } ans [ i ] = counter ; } } static void printArray ( int arr [ ] , int n ) { for ( int i = 0 ; i < n ; i ++ ) System . out . print ( arr [ i ] + " ▁ " ) ; } public static void main ( String [ ] args ) { int price [ ] = { 10 , 4 , 5 , 90 , 120 , 80 } ; int n = price . length ; int S [ ] = new int [ n ] ; calculateSpan ( price , n , S ) ; printArray ( S , n ) ; } }


"The biggest possible circle that can be inscribed in a rectangle | Java Program to find the biggest circle which can be inscribed within the rectangle ; Function to find the area of the biggest circle ; the length and breadth cannot be negative ; area of the circle ; Driver code"
How can the above be solved in Java?

class GFG { static float circlearea ( float l , float b ) { if ( l < 0 b < 0 ) return - 1 ; if ( l < b ) return ( float ) ( 3.14 * Math . pow ( l / 2 , 2 ) ) ; else return ( float ) ( 3.14 * Math . pow ( b / 2 , 2 ) ) ; } public static void main ( String [ ] args ) { float l = 4 , b = 8 ; System . out . println ( circlearea ( l , b ) ) ; } }


"The dice problem | Java program for the above approach ; Function to find number written on the opposite face of the dice ; Stores number on opposite face of dice ; Print the answer ; Driver Code ; Given value of N ; Function call to find number written on the opposite face of the dice"
How can the above be solved in Java?

import java . io . * ; class GFG { static void oppositeFaceOfDice ( int N ) { int ans = 7 - N ; System . out . println ( ans ) ; } public static void main ( String [ ] args ) { int N = 2 ; oppositeFaceOfDice ( N ) ; } }


"The painter 's partition problem |  ; sum from 1 to i elements of arr"
How can the above be solved in Java?

int sum [ ] = new int [ n + 1 ] ; for ( int i = 1 ; i <= n ; i ++ ) sum [ i ] = sum [ i - 1 ] + arr [ i - 1 ] ; for ( int i = 1 ; i <= n ; i ++ ) dp [ 1 ] [ i ] = sum [ i ] ; and using it to calculate the result as : best = Math . min ( best , Math . max ( dp [ i - 1 ] [ p ] , sum [ j ] - sum [ p ] ) ) ;


"The painter 's partition problem | A DP based Java program for painter 's partition problem ; function to calculate sum between two indices in array ; bottom up tabular dp ; initialize table ; base cases k = 1 ; n = 1 ; 2 to k partitions for ( int i = 2 ; i <= k ; i ++ ) { 2 to n boards ; track minimum ; i - 1 th separator before position arr [ p = 1. . j ] ; required ; Driver code ; Calculate size of array ."
How can the above be solved in Java?

import java . util . * ; import java . io . * ; class GFG { static int sum ( int arr [ ] , int from , int to ) { int total = 0 ; for ( int i = from ; i <= to ; i ++ ) total += arr [ i ] ; return total ; } static int findMax ( int arr [ ] , int n , int k ) { int dp [ ] [ ] = new int [ k + 1 ] [ n + 1 ] ; for ( int i = 1 ; i <= n ; i ++ ) dp [ 1 ] [ i ] = sum ( arr , 0 , i - 1 ) ; for ( int i = 1 ; i <= k ; i ++ ) dp [ i ] [ 1 ] = arr [ 0 ] ; for ( int j = 2 ; j <= n ; j ++ ) { int best = Integer . MAX_VALUE ; for ( int p = 1 ; p <= j ; p ++ ) best = Math . min ( best , Math . max ( dp [ i - 1 ] [ p ] , sum ( arr , p , j - 1 ) ) ) ; dp [ i ] [ j ] = best ; } } return dp [ k ] [ n ] ; } public static void main ( String args [ ] ) { int arr [ ] = { 10 , 20 , 60 , 50 , 30 , 40 } ; int n = arr . length ; int k = 3 ; System . out . println ( findMax ( arr , n , k ) ) ; } }


"The painter 's partition problem |"
How can the above be solved in Java?

for ( int i = k - 1 ; i <= n ; i ++ ) best = Math . min ( best , Math . max ( partition ( arr , i , k - 1 ) , sum ( arr , i , n - 1 ) ) ) ;


"Third largest element in an array of distinct elements | Java program to find third Largest element in an array ; There should be atleast three elements ; Initialize first , second and third Largest element ; Traverse array elements to find the third Largest ; If current element is greater than first , then update first , second and third ; If arr [ i ] is in between first and second ; If arr [ i ] is in between second and third ; Driver program to test above function"
How can the above be solved in Java?

 class GFG { static void thirdLargest ( int arr [ ] , int arr_size ) { if ( arr_size < 3 ) { System . out . printf ( " ▁ Invalid ▁ Input ▁ " ) ; return ; } int first = arr [ 0 ] , second = Integer . MIN_VALUE , third = Integer . MIN_VALUE ; for ( int i = 1 ; i < arr_size ; i ++ ) { if ( arr [ i ] > first ) { third = second ; second = first ; first = arr [ i ] ; } else if ( arr [ i ] > second ) { third = second ; second = arr [ i ] ; } else if ( arr [ i ] > third ) { third = arr [ i ] ; } } System . out . printf ( "The third Largest element is %d
", third); } public static void main ( String [ ] args ) { int arr [ ] = { 12 , 13 , 1 , 10 , 34 , 16 } ; int n = arr . length ; thirdLargest ( arr , n ) ; } }


"Third largest element in an array of distinct elements | Java program to find third Largest element in an array of distinct elements ; There should be atleast three elements ; Find first largest element ; Find second largest element ; Find third largest element ; Driver code"
How can the above be solved in Java?

 class GFG { static void thirdLargest ( int arr [ ] , int arr_size ) { if ( arr_size < 3 ) { System . out . printf ( " ▁ Invalid ▁ Input ▁ " ) ; return ; } int first = arr [ 0 ] ; for ( int i = 1 ; i < arr_size ; i ++ ) if ( arr [ i ] > first ) first = arr [ i ] ; int second = Integer . MIN_VALUE ; for ( int i = 0 ; i < arr_size ; i ++ ) if ( arr [ i ] > second && arr [ i ] < first ) second = arr [ i ] ; int third = Integer . MIN_VALUE ; for ( int i = 0 ; i < arr_size ; i ++ ) if ( arr [ i ] > third && arr [ i ] < second ) third = arr [ i ] ; System . out . printf ( " The ▁ third ▁ Largest ▁ " + "element is %d
", third); } public static void main ( String [ ] args ) { int arr [ ] = { 12 , 13 , 1 , 10 , 34 , 16 } ; int n = arr . length ; thirdLargest ( arr , n ) ; } }


"Threaded Binary Tree | Utility function to find leftmost node in a tree rooted with n ; C code to do inorder traversal in a threaded binary tree ; If this node is a thread node , then go to inorder successor ; Else go to the leftmost child in right ; subtree"
How can the above be solved in Java?

Node leftMost ( Node n ) { if ( n == null ) return null ; while ( n . left != null ) n = n . left ; return n ; } static void inOrder ( Node root ) { Node cur = leftMost ( root ) ; while ( cur != null ) { System . out . printf ( " % d ▁ " , cur . data ) ; if ( cur . rightThread ) cur = cur . right ; else cur = leftmost ( cur . right ) ; } }


"Threaded Binary Tree |"
How can the above be solved in Java?

static class Node { int data ; Node left , right ; boolean rightThread ; }


"Three numbers in a BST that adds upto zero | A Java program to check if there is a triplet with sum equal to 0 in a given BST ; A BST node has key , and left and right pointers ; A function to convert given BST to Doubly Linked List . left pointer is used as previous pointer and right pointer is used as next pointer . The function sets * head to point to first and * tail to point to last node of converted DLL ; Base case ; First convert the left subtree ; Then change left of current root as last node of left subtree ; If tail is not null , then set right of tail as root , else current node is head ; Update tail ; Finally , convert right subtree ; This function returns true if there is pair in DLL with sum equal to given sum . The algorithm is similar to hasArrayTwoCandidates ( ) tinyurl . com / dy6palr in method 1 of http : ; The main function that returns true if there is a 0 sum triplet in BST otherwise returns false ; Check if the given BST is empty ; Convert given BST to doubly linked list . head and tail store the pointers to first and last nodes in DLLL ; Now iterate through every node and find if there is a pair with sum equal to - 1 * heaf . key where head is current node ; If there is a pair with sum equal to - 1 * head . key , then return true else move forward ; If we reach here , then there was no 0 sum triplet ; A utility function to create a new BST node with key as given num ; A utility function to insert a given key to BST ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { static class node { int key ; node left ; node right ; } ; static node head ; static node tail ; static void convertBSTtoDLL ( node root ) { if ( root == null ) return ; if ( root . left != null ) convertBSTtoDLL ( root . left ) ; root . left = tail ; if ( tail != null ) ( tail ) . right = root ; else head = root ; tail = root ; if ( root . right != null ) convertBSTtoDLL ( root . right ) ; } static boolean isPresentInDLL ( node head , node tail , int sum ) { while ( head != tail ) { int curr = head . key + tail . key ; if ( curr == sum ) return true ; else if ( curr > sum ) tail = tail . left ; else head = head . right ; } return false ; } static boolean isTripletPresent ( node root ) { if ( root == null ) return false ; head = null ; tail = null ; convertBSTtoDLL ( root ) ; while ( ( head . right != tail ) && ( head . key < 0 ) ) { if ( isPresentInDLL ( head . right , tail , - 1 * head . key ) ) return true ; else head = head . right ; } return false ; } static node newNode ( int num ) { node temp = new node ( ) ; temp . key = num ; temp . left = temp . right = null ; return temp ; } static node insert ( node root , int key ) { if ( root == null ) return newNode ( key ) ; if ( root . key > key ) root . left = insert ( root . left , key ) ; else root . right = insert ( root . right , key ) ; return root ; } public static void main ( String [ ] args ) { node root = null ; root = insert ( root , 6 ) ; root = insert ( root , - 13 ) ; root = insert ( root , 14 ) ; root = insert ( root , - 8 ) ; root = insert ( root , 15 ) ; root = insert ( root , 13 ) ; root = insert ( root , 7 ) ; if ( isTripletPresent ( root ) ) System . out . print ( " Present " ) ; else System . out . print ( " Not ▁ Present " ) ; } }


"Three way partitioning of an array around a given range | Java program to implement three way partitioning around a given range . ; Partitions arr [ 0. . n - 1 ] around [ lowVal . . highVal ] ; Initialize ext available positions for smaller ( than range ) and greater lements ; Traverse elements from left ; If current element is smaller than range , put it on next available smaller position . ; If current element is greater than range , put it on next available greater position . ; Driver code"
How can the above be solved in Java?

import java . io . * ; class GFG { public static void threeWayPartition ( int [ ] arr , int lowVal , int highVal ) { int n = arr . length ; int start = 0 , end = n - 1 ; for ( int i = 0 ; i <= end ; ) { if ( arr [ i ] < lowVal ) { int temp = arr [ start ] ; arr [ start ] = arr [ i ] ; arr [ i ] = temp ; start ++ ; i ++ ; } else if ( arr [ i ] > highVal ) { int temp = arr [ end ] ; arr [ end ] = arr [ i ] ; arr [ i ] = temp ; end -- ; } else i ++ ; } } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 14 , 5 , 20 , 4 , 2 , 54 , 20 , 87 , 98 , 3 , 1 , 32 } ; threeWayPartition ( arr , 10 , 20 ) ; System . out . println ( " Modified ▁ array ▁ " ) ; for ( int i = 0 ; i < arr . length ; i ++ ) { System . out . print ( arr [ i ] + " ▁ " ) ; } } }


"Tidy Number ( Digits in non | Java program to check if a number is Tidy or not . ; Returns true if num is Tidy ; To store previous digit ( Assigning initial value which is more than any digit ) ; Traverse all digits from right to left and check if any digit is smaller than previous . ; Driver method"
How can the above be solved in Java?

class Test { static boolean isTidy ( int num ) { int prev = 10 ; while ( num != 0 ) { int rem = num % 10 ; num /= 10 ; if ( rem > prev ) return false ; prev = rem ; } return true ; } public static void main ( String [ ] args ) { int num = 1556 ; System . out . println ( isTidy ( num ) ? " Yes " : " No " ) ; } }


"Tiling with Dominoes | Java program to find no . of ways to fill a 3 xn board with 2 x1 dominoes . ; Driver code"
How can the above be solved in Java?

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


"TimSort | Java program to perform TimSort . ; Becomes 1 if any 1 bits are shifted off ; This function sorts array from left index to to right index which is of size atmost RUN ; Merge function merges the sorted runs ; Original array is broken in two parts left and right array ; After comparing , we merge those two array in larger sub array ; Copy remaining elements of left , if any ; Copy remaining element of right , if any ; Iterative Timsort function to sort the array [ 0. . . n - 1 ] ( similar to merge sort ) ; Sort individual subarrays of size RUN ; Start merging from size RUN ( or 32 ) . It will merge to form size 64 , then 128 , 256 and so on ... . ; Pick starting point of left sub array . We are going to merge arr [ left . . left + size - 1 ] and arr [ left + size , left + 2 * size - 1 ] After every merge , we increase left by 2 * size ; Find ending point of left sub array mid + 1 is starting point of right sub array ; Merge sub array arr [ left ... . . mid ] & arr [ mid + 1. ... right ] ; Utility function to print the Array ; Driver code ; Function Call"
How can the above be solved in Java?

 class GFG { static int MIN_MERGE = 32 ; public static int minRunLength ( int n ) { assert n >= 0 ; int r = 0 ; while ( n >= MIN_MERGE ) { r |= ( n & 1 ) ; n >>= 1 ; } return n + r ; } public static void insertionSort ( int [ ] arr , int left , int right ) { for ( int i = left + 1 ; i <= right ; i ++ ) { int temp = arr [ i ] ; int j = i - 1 ; while ( j >= left && arr [ j ] > temp ) { arr [ j + 1 ] = arr [ j ] ; j -- ; } arr [ j + 1 ] = temp ; } } public static void merge ( int [ ] arr , int l , int m , int r ) { int len1 = m - l + 1 , len2 = r - m ; int [ ] left = new int [ len1 ] ; int [ ] right = new int [ len2 ] ; for ( int x = 0 ; x < len1 ; x ++ ) { left [ x ] = arr [ l + x ] ; } for ( int x = 0 ; x < len2 ; x ++ ) { right [ x ] = arr [ m + 1 + x ] ; } int i = 0 ; int j = 0 ; int k = l ; while ( i < len1 && j < len2 ) { if ( left [ i ] <= right [ j ] ) { arr [ k ] = left [ i ] ; i ++ ; } else { arr [ k ] = right [ j ] ; j ++ ; } k ++ ; } while ( i < len1 ) { arr [ k ] = left [ i ] ; k ++ ; i ++ ; } while ( j < len2 ) { arr [ k ] = right [ j ] ; k ++ ; j ++ ; } } public static void timSort ( int [ ] arr , int n ) { int minRun = minRunLength ( MIN_MERGE ) ; for ( int i = 0 ; i < n ; i += minRun ) { insertionSort ( arr , i , Math . min ( ( i + MIN_MERGE - 1 ) , ( n - 1 ) ) ) ; } for ( int size = minRun ; size < n ; size = 2 * size ) { for ( int left = 0 ; left < n ; left += 2 * size ) { int mid = left + size - 1 ; int right = Math . min ( ( left + 2 * size - 1 ) , ( n - 1 ) ) ; if ( mid < right ) merge ( arr , left , mid , right ) ; } } } public static void printArray ( int [ ] arr , int n ) { for ( int i = 0 ; i < n ; i ++ ) { System . out . print ( arr [ i ] + " ▁ " ) ; } System . out . print ( "
"); } public static void main ( String [ ] args ) { int [ ] arr = { - 2 , 7 , 15 , - 14 , 0 , 15 , 0 , 7 , - 7 , - 4 , - 13 , 5 , 8 , - 14 , 12 } ; int n = arr . length ; System . out . println ( " Given ▁ Array ▁ is " ) ; printArray ( arr , n ) ; timSort ( arr , n ) ; System . out . println ( " After ▁ Sorting ▁...


"Time Complexity and Space Complexity | Java program for the above approach ; Function to find a pair in the given array whose sum is equal to z ; Iterate through all the pairs ; Check if the sum of the pair ( a [ i ] , a [ j ] ) is equal to z ; Driver code ; Given Input ; Function Call"
How can the above be solved in Java?

import java . lang . * ; import java . util . * ; class GFG { static boolean findPair ( int a [ ] , int n , int z ) { for ( int i = 0 ; i < n ; i ++ ) for ( int j = 0 ; j < n ; j ++ ) if ( i != j && a [ i ] + a [ j ] == z ) return true ; return false ; } public static void main ( String [ ] args ) { int a [ ] = { 1 , - 2 , 1 , 0 , 5 } ; int z = 0 ; int n = a . length ; if ( findPair ( a , n , z ) ) System . out . println ( " True " ) ; else System . out . println ( " False " ) ; } }


"Time required to meet in equilateral triangle | Java code to find time taken by animals to meet ; function to calculate time to meet ; Driver Code"
How can the above be solved in Java?

import java . io . * ; public class GFG { static void timeToMeet ( double s , double v ) { double V = 3 * v / 2 ; double time = s / V ; System . out . println ( ( float ) time ) ; } static public void main ( String [ ] args ) { double s = 25 , v = 56 ; timeToMeet ( s , v ) ; } }


"Time taken by Loop unrolling vs Normal loop | Java program to compare normal loops and loops with unrolling technique ; n is 8 lakhs ; t to note start time ; to store the sum ; Normal loop ; to mark end time ; to mark start time of unrolling ; Unrolling technique ( assuming that n is a multiple of 8 ) . ; to mark the end of loop"
How can the above be solved in Java?

class GFG { public static void main ( String [ ] args ) { int n = 800000 ; double t = ( double ) System . nanoTime ( ) ; long sum = 0 ; for ( int i = 1 ; i <= n ; i ++ ) sum += i ; t = ( double ) System . nanoTime ( ) - t ; System . out . println ( " sum ▁ is : ▁ " + Double . toString ( sum ) ) ; System . out . println ( " time ▁ taken ▁ by ▁ normal ▁ loops : " + Double . toString ( t / Math . pow ( 10.0 , 9.0 ) ) ) ; t = ( double ) System . nanoTime ( ) ; sum = 0 ; for ( int i = 1 ; i <= n ; i += 8 ) { sum += i ; sum += ( i + 1 ) ; sum += ( i + 2 ) ; sum += ( i + 3 ) ; sum += ( i + 4 ) ; sum += ( i + 5 ) ; sum += ( i + 6 ) ; sum += ( i + 7 ) ; } t = ( double ) System . nanoTime ( ) - t ; System . out . println ( " sum ▁ is : ▁ " + Double . toString ( sum ) ) ; System . out . println ( " time ▁ taken ▁ by ▁ normal ▁ loops : " + Double . toString ( t / Math . pow ( 10.0 , 9.0 ) ) ) ; } }


"Time taken by two persons to meet on a circular track | Java implementation of above approach ; Function to return the time when both the persons will meet at the starting point ; Time to cover 1 round by both ; Finding LCM to get the meeting point ; Function to return the time when both the persons will meet for the first time ; Driver Code ; Calling function"
How can the above be solved in Java?

public class GFG { static int startingPoint ( int Length , int Speed1 , int Speed2 ) { int result1 = 0 , result2 = 0 ; int time1 = Length / Speed1 ; int time2 = Length / Speed2 ; result1 = __gcd ( time1 , time2 ) ; result2 = time1 * time2 / ( result1 ) ; return result2 ; } static int __gcd ( int a , int b ) { if ( b == 0 ) { return a ; } return __gcd ( b , a % b ) ; } static float firstTime ( int Length , int Speed1 , int Speed2 ) { float result = 0 ; int relativeSpeed = Math . abs ( Speed1 - Speed2 ) ; result = ( ( float ) Length / relativeSpeed ) ; return result ; } public static void main ( String [ ] args ) { int L = 30 , S1 = 5 , S2 = 2 ; float first_Time = firstTime ( L , S1 , S2 ) ; int starting_Point = startingPoint ( L , S1 , S2 ) ; System . out . println ( " Met ▁ first ▁ time ▁ after ▁ " + first_Time + " ▁ hrs " ) ; System . out . println ( " Met ▁ at ▁ starting ▁ point ▁ after ▁ " + starting_Point + " ▁ hrs " ) ; } }


"Time taken per hour for stoppage of Car | Java implementation of the approach ; Function to return the time taken per hour for stoppage ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { static int numberOfMinutes ( int S , int S1 ) { int Min = 0 ; Min = ( int ) ( ( ( S - S1 ) / Math . floor ( S ) ) * 60 ) ; return Min ; } public static void main ( String [ ] args ) { int S = 30 , S1 = 10 ; System . out . println ( numberOfMinutes ( S , S1 ) + " ▁ min " ) ; } }


"Time until distance gets equal to X between two objects moving in opposite direction | Java implementation of the approach ; Function to return the time for which the two policemen can communicate ; time = distance / speed ; Driver code"
How can the above be solved in Java?

class GFG { static double getTime ( int u , int v , int x ) { double speed = u + v ; double time = x / speed ; return time ; } public static void main ( String [ ] args ) { int u = 3 , v = 3 , x = 3 ; System . out . println ( getTime ( u , v , x ) ) ; } }


"Time | Java program to find Nth Fibonacci number using recursion ; Function to find Nth Fibonacci term ; Base Case ; Recursively computing the term using recurrence relation ; Driver Code ; Function Call"
How can the above be solved in Java?

class GFG { static int Fibonacci ( int N ) { if ( N < 2 ) return N ; return Fibonacci ( N - 1 ) + Fibonacci ( N - 2 ) ; } public static void main ( String [ ] args ) { int N = 5 ; System . out . print ( Fibonacci ( N ) ) ; } }


"Times required by Simple interest for the Principal to become Y times itself | Java implementation of the approach ; Function to return the no . of years ; Driver code"
How can the above be solved in Java?

class GFG { static float noOfYears ( int t1 , int n1 , int t2 ) { float years = ( ( t2 - 1 ) * n1 / ( float ) ( t1 - 1 ) ) ; return years ; } public static void main ( String [ ] args ) { int T1 = 3 , N1 = 5 , T2 = 6 ; System . out . println ( noOfYears ( T1 , N1 , T2 ) ) ; } }


"To Generate a One Time Password or Unique Identification URL | A Java Program to generate OTP ( One Time Password ) ; A Function to generate a unique OTP everytime ; All possible characters of my OTP ; String to hold my OTP ; Driver code ; Declare the length of OTP"
How can the above be solved in Java?

class GFG { static String generateOTP ( int len ) { String str = " abcdefghijklmnopqrstuvwxyzABCD " + " EFGHIJKLMNOPQRSTUVWXYZ0123456789" ; int n = str . length ( ) ; String OTP = " " ; for ( int i = 1 ; i <= len ; i ++ ) OTP += ( str . charAt ( ( int ) ( ( Math . random ( ) * 10 ) % n ) ) ) ; return ( OTP ) ; } public static void main ( String [ ] args ) { int len = 6 ; System . out . printf ( " Your ▁ OTP ▁ is ▁ - ▁ % s " , generateOTP ( len ) ) ; } }


"To check a number is palindrome or not without using any extra space | Java program to find number is palindrome or not without using any extra space ; Function to check if given number is palindrome or not without using the extra space ; Find the appropriate divisor to extract the leading digit ; If first and last digit not same return false ; Removing the leading and trailing digit from number ; Reducing divisor by a factor of 2 as 2 digits are dropped ; Driver code"
How can the above be solved in Java?

public class GFG { static boolean isPalindrome ( int n ) { bool isPalindrome ( int n ) { int divisor = 1 ; while ( n / divisor >= 10 ) divisor *= 10 ; while ( n != 0 ) { int leading = n / divisor ; int trailing = n % 10 ; if ( leading != trailing ) return false ; n = ( n % divisor ) / 10 ; divisor = divisor / 100 ; } return true ; } public static void main ( String args [ ] ) { if ( isPalindrome ( 1001 ) ) System . out . println ( " Yes , ▁ it ▁ is ▁ Palindrome " ) ; else System . out . println ( " No , ▁ not ▁ Palindrome " ) ; } }


"To check divisibility of any large number by 999 | Java for divisibility of number by 999 ; Method to check divisibility ; Append required 0 s at the beginning . ; add digits in group of three in gSum ; group saves 3 - digit group ; calculate result till 3 digit sum ; Driver method"
How can the above be solved in Java?

class Test { static boolean isDivisible999 ( String num ) { int n = num . length ( ) ; if ( n == 0 && num . charAt ( 0 ) == '0' ) return true ; if ( n % 3 == 1 ) num = "00" + num ; if ( n % 3 == 2 ) num = "0" + num ; int gSum = 0 ; for ( int i = 0 ; i < n ; i ++ ) { int group = 0 ; group += ( num . charAt ( i ++ ) - '0' ) * 100 ; group += ( num . charAt ( i ++ ) - '0' ) * 10 ; group += num . charAt ( i ) - '0' ; gSum += group ; } if ( gSum > 1000 ) { num = Integer . toString ( gSum ) ; n = num . length ( ) ; gSum = isDivisible999 ( num ) ? 1 : 0 ; } return ( gSum == 999 ) ; } public static void main ( String args [ ] ) { String num = "1998" ; System . out . println ( isDivisible999 ( num ) ? " Divisible " : " Not ▁ divisible " ) ; } }


"Toggle all bits after most significant bit | Java program to toggle set bits starting from MSB ; Function to toggle bits starting from MSB ; temporary variable to use XOR with one of a n ; Run loop until the only set bit in temp crosses MST of n . ; Toggle bit of n corresponding to current set bit in temp . ; Move set bit to next higher position . ; Driver code"
How can the above be solved in Java?

class GFG { static int toggle ( int n ) { int temp = 1 ; while ( temp <= n ) { n = n ^ temp ; temp = temp << 1 ; } return n ; } public static void main ( String arg [ ] ) { int n = 10 ; n = toggle ( n ) ; System . out . print ( n ) ; } }


"Toggle all bits after most significant bit | Java program to toggle set bits starting from MSB ; Returns a number which has all set bits starting from MSB of n ; This makes sure two bits ( From MSB and including MSB ) are set ; This makes sure 4 bits ( From MSB and including MSB ) are set ; Driver code"
How can the above be solved in Java?

class GFG { static int setAllBitsAfterMSB ( int n ) { n |= n >> 1 ; n |= n >> 2 ; n |= n >> 4 ; n |= n >> 8 ; n |= n >> 16 ; return n ; } static int toggle ( int n ) { n = n ^ setAllBitsAfterMSB ( n ) ; return n ; } public static void main ( String arg [ ] ) { int n = 10 ; n = toggle ( n ) ; System . out . print ( n ) ; } }


"Toggle all even bits of a number | Java code to Toggle all even bit of a number ; Returns a number which has all even bits of n toggled . ; Generate number form of 101010 . . till of same order as n ; if bit is even then generate number and or with res ; return toggled number ; Driver code"
How can the above be solved in Java?

import java . io . * ; class GFG { static int evenbittogglenumber ( int n ) { int res = 0 , count = 0 ; for ( int temp = n ; temp > 0 ; temp >>= 1 ) { if ( count % 2 == 1 ) res |= ( 1 << count ) ; count ++ ; } return n ^ res ; } public static void main ( String args [ ] ) { int n = 11 ; System . out . println ( evenbittogglenumber ( n ) ) ; } }


"Toggle all odd bits of a number | Toggle all odd bit of a number ; Returns a number which has all odd bits of n toggled . ; Generate number form of 101010. . . . . till of same order as n ; if bit is odd , then generate number and or with res ; return toggled number ; Driver code"
How can the above be solved in Java?

import java . io . * ; class GFG { static int evenbittogglenumber ( int n ) { int res = 0 , count = 0 ; for ( int temp = n ; temp > 0 ; temp >>= 1 ) { if ( count % 2 == 0 ) res |= ( 1 << count ) ; count ++ ; } return n ^ res ; } public static void main ( String args [ ] ) { int n = 11 ; System . out . println ( evenbittogglenumber ( n ) ) ; } }


"Toggle bits in the given range | Java implementation to toggle bits in the given range ; Function to toggle bits in the given range ; calculating a number ' num ' having ' r ' number of bits and bits in the range l to r are the only set bits ; toggle bits in the range l to r in ' n ' and return the number Besides this , we can calculate num as : num = ( 1 << r ) - l . ; driver program"
How can the above be solved in Java?

import java . io . * ; class GFG { static int toggleBitsFromLToR ( int n , int l , int r ) { int num = ( ( 1 << r ) - 1 ) ^ ( ( 1 << ( l - 1 ) ) - 1 ) ; return ( n ^ num ) ; } public static void main ( String [ ] args ) { int n = 50 ; int l = 2 , r = 5 ; System . out . println ( toggleBitsFromLToR ( n , l , r ) ) ; } }


"Toggle case of a string using Bitwise Operators | program to get toggle case of a string ; tOGGLE cASE = swaps CAPS to lower case and lower case to CAPS ; Bitwise EXOR with 32 ; Driver program"
How can the above be solved in Java?

public class Test { static int x = 32 ; static String toggleCase ( char [ ] a ) { for ( int i = 0 ; i < a . length ; i ++ ) { a [ i ] ^= 32 ; } return new String ( a ) ; } public static void main ( String [ ] args ) { String str = " CheRrY " ; System . out . print ( " Toggle ▁ case : ▁ " ) ; str = toggleCase ( str . toCharArray ( ) ) ; System . out . println ( str ) ; System . out . print ( " Original ▁ string : ▁ " ) ; str = toggleCase ( str . toCharArray ( ) ) ; System . out . println ( str ) ; } }


"Toggle first and last bits of a number | Java program to toggle first and last bits of a number ; Returns a number which has same bit count as n and has only first and last bits as set . ; set all the bit of the number ; Adding one to n now unsets all bits and moves MSB to one place . Now we shift the number by 1 and add 1. ; if number is 1 ; take XOR with first and last set bit number ; Driver code"
How can the above be solved in Java?

import java . io . * ; class GFG { static int takeLandFsetbits ( int n ) { n |= n >> 1 ; n |= n >> 2 ; n |= n >> 4 ; n |= n >> 8 ; n |= n >> 16 ; return ( ( n + 1 ) >> 1 ) + 1 ; } static int toggleFandLbits ( int n ) { if ( n == 1 ) return 0 ; return n ^ takeLandFsetbits ( n ) ; } public static void main ( String args [ ] ) { int n = 10 ; System . out . println ( toggleFandLbits ( n ) ) ; } }


"Toggle the last m bits | Java implementation to toggle the last m bits ; function to toggle the last m bits ; calculating a number ' num ' having ' m ' bits and all are set ; toggle the last m bits and return the number ; Driver function"
How can the above be solved in Java?

import java . util . * ; import java . lang . * ; public class GfG { public static int toggleLastMBits ( int n , int m ) { int num = ( 1 << m ) - 1 ; return ( n ^ num ) ; } public static void main ( String argc [ ] ) { int n = 107 ; int m = 4 ; n = toggleLastMBits ( n , m ) ; System . out . println ( n ) ; } }


"Tomohiko Sakamoto 's Algorithm | A java program to implement the Tomohiko Sakamoto Algorithm ; function to implement tomohiko sakamoto algorithm ; array with leading number of days values ; if month is less than 3 reduce year by 1 ; Driver Code"
How can the above be solved in Java?

class tomohiko_sakamoto { public static int day_of_the_week ( int y , int m , int d ) { int t [ ] = { 0 , 3 , 2 , 5 , 0 , 3 , 5 , 1 , 4 , 6 , 2 , 4 } ; if ( m < 3 ) y -= 1 ; return ( y + y / 4 - y / 100 + y / 400 + t [ m - 1 ] + d ) % 7 ; } public static void main ( String args [ ] ) { int day = 13 , month = 7 , year = 2017 ; System . out . println ( day_of_the_week ( year , month , day ) ) ; } }


"Top three elements in binary tree | Java program to find largest three elements in a binary tree . ; Helper function that allocates a new Node with the given data and null left and right pointers . ; function to find three largest element ; if data is greater than first large number update the top three list ; if data is greater than second large number and not equal to first update the bottom two list ; if data is greater than third large number and not equal to first & second update the third highest list ; driver function"
How can the above be solved in Java?

import java . util . * ; class GFG { static class Node { int data ; Node left ; Node right ; } ; static int first , second , third ; static Node newNode ( int data ) { Node node = new Node ( ) ; node . data = data ; node . left = null ; node . right = null ; return ( node ) ; } static void threelargest ( Node root ) { if ( root == null ) return ; if ( root . data > first ) { third = second ; second = first ; first = root . data ; } else if ( root . data > second && root . data != first ) { third = second ; second = root . data ; } else if ( root . data > third && root . data != first && root . data != second ) third = root . data ; threelargest ( root . left ) ; threelargest ( root . right ) ; } public static void main ( String [ ] args ) { Node root = newNode ( 1 ) ; root . left = newNode ( 2 ) ; root . right = newNode ( 3 ) ; root . left . left = newNode ( 4 ) ; root . left . right = newNode ( 5 ) ; root . right . left = newNode ( 4 ) ; root . right . right = newNode ( 5 ) ; first = 0 ; second = 0 ; third = 0 ; threelargest ( root ) ; System . out . print ( " three ▁ largest ▁ elements ▁ are ▁ " + first + " ▁ " + second + " ▁ " + third ) ; } }


"Total area of two overlapping rectangles | Java program to find total area of two overlapping Rectangles ; Returns Total Area of two overlap rectangles ; Area of 1 st Rectangle ; Area of 2 nd Rectangle ; Length of intersecting part i . e start from max ( l1 . x , l2 . x ) of x - coordinate and end at min ( r1 . x , r2 . x ) x - coordinate by subtracting start from end we get required lengths ; Driver Code ; Function Call"
How can the above be solved in Java?

class GFG { static class Point { int x , y ; public Point ( int x , int y ) { this . x = x ; this . y = y ; } } ; static int overlappingArea ( Point l1 , Point r1 , Point l2 , Point r2 ) { int area1 = Math . abs ( l1 . x - r1 . x ) * Math . abs ( l1 . y - r1 . y ) ; int area2 = Math . abs ( l2 . x - r2 . x ) * Math . abs ( l2 . y - r2 . y ) ; int x_dist = ( Math . min ( r1 . x , r2 . x ) - Math . max ( l1 . x , l2 . x ) ; int y_dist = ( Math . min ( r1 . y , r2 . y ) - Math . max ( l1 . y , l2 . y ) ; int areaI = 0 ; if ( x_dist > 0 && y_dist > 0 ) { areaI = x_dist * y_dist ; } return ( area1 + area2 - areaI ) ; } public static void main ( String [ ] args ) { Point l1 = new Point ( 2 , 2 ) , r1 = new Point ( 5 , 7 ) ; Point l2 = new Point ( 3 , 4 ) , r2 = new Point ( 6 , 9 ) ; System . out . println ( overlappingArea ( l1 , r1 , l2 , r2 ) ) ; } }


"Total count of sorted numbers upto N digits in range [ L , R ] ( Magnificent necklace combinatorics problem ) | Java program for the above approach ; Function to count total number of ways ; Stores all DP - states ; Stores the result ; Traverse the range [ 0 , N ] ; Traverse the range [ 1 , R - L ] ; Update dp [ i ] [ j ] ; Assign dp [ 0 ] [ R - L ] to ans ; Traverse the range [ 1 , N ] ; Traverse the range [ 1 , R - L ] ; Update dp [ i ] [ j ] ; Increment ans by dp [ i - 1 ] [ j ] ; Return ans ; Driver Code ; Input ; Function call"
How can the above be solved in Java?

import java . util . * ; class GFG { static int Count ( int N , int L , int R ) { int [ ] [ ] dp = new int [ N ] [ R - L + 1 ] ; int ans = 0 ; for ( int i = 0 ; i < N ; i ++ ) { dp [ i ] [ 0 ] = 1 ; } for ( int i = 1 ; i < dp [ 0 ] . length ; i ++ ) { dp [ 0 ] [ i ] = dp [ 0 ] [ i - 1 ] + 1 ; } ans = dp [ 0 ] [ R - L ] ; for ( int i = 1 ; i < N ; i ++ ) { for ( int j = 1 ; j < dp [ 0 ] . length ; j ++ ) { dp [ i ] [ j ] = dp [ i - 1 ] [ j ] + dp [ i ] [ j - 1 ] ; } ans += dp [ i ] [ R - L ] ; } return ans ; } public static void main ( String args [ ] ) { int N = 3 ; int L = 6 ; int R = 9 ; System . out . println ( Count ( N , L , R ) ) ; } }


"Total coverage of all zeros in a binary matrix | Java program to get total coverage of all zeros in a binary matrix ; Returns total coverage of all zeros in mat [ ] [ ] ; looping for all rows of matrix ; 1 is not seen yet ; looping in columns from left to right direction to get left ones ; If one is found from left ; If 0 is found and we have found a 1 before . ; Repeat the above process for right to left direction . ; Traversing across columms for up and down directions . ; 1 is not seen yet ; Driver code"
How can the above be solved in Java?

import java . io . * ; class GFG { static int R = 4 ; static int C = 4 ; static int getTotalCoverageOfMatrix ( int [ ] [ ] mat ) { int res = 0 ; for ( int i = 0 ; i < R ; i ++ ) { boolean isOne = false ; for ( int j = 0 ; j < C ; j ++ ) { if ( mat [ i ] [ j ] == 1 ) isOne = true ; else if ( isOne ) res ++ ; } isOne = false ; for ( int j = C - 1 ; j >= 0 ; j -- ) { if ( mat [ i ] [ j ] == 1 ) isOne = true ; else if ( isOne ) res ++ ; } } for ( int j = 0 ; j < C ; j ++ ) { boolean isOne = false ; for ( int i = 0 ; i < R ; i ++ ) { if ( mat [ i ] [ j ] == 1 ) isOne = true ; else if ( isOne ) res ++ ; } isOne = false ; for ( int i = R - 1 ; i >= 0 ; i -- ) { if ( mat [ i ] [ j ] == 1 ) isOne = true ; else if ( isOne ) res ++ ; } } return res ; } static public void main ( String [ ] args ) { int [ ] [ ] mat = { { 0 , 0 , 0 , 0 } , { 1 , 0 , 0 , 1 } , { 0 , 1 , 1 , 0 } , { 0 , 1 , 0 , 0 } } ; System . out . println ( getTotalCoverageOfMatrix ( mat ) ) ; } }


"Total length of string from given Array of strings composed using given characters | Java implementation to find total length of string composed of given characters formed from given Array of strings ; Function to count the total length ; Map for keeping frequency of characters ; Calculate the frequency ; Iterate in the N strings ; Iterates in the string ; Checks if given character of string string appears in it or not ; Adds the length of string if all characters are present ; Return the final result ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { static int countCharacters ( List < String > strings , String chars ) { int res = 0 ; Map < Character , Integer > freq = new HashMap < > ( ) ; for ( int i = 0 ; i < chars . length ( ) ; i ++ ) { freq . put ( chars . charAt ( i ) , freq . getOrDefault ( chars . charAt ( i ) , 0 ) + 1 ) ; } for ( String st : strings ) { boolean flag = true ; for ( char c : st . toCharArray ( ) ) { if ( ! freq . containsKey ( c ) ) { flag = false ; break ; } } if ( flag ) res += st . length ( ) ; } return res ; } public static void main ( String [ ] args ) { List < String > strings = Arrays . asList ( " hi " , " data " , " geeksforgeeks " ) ; String chars = " tiadhae " ; System . out . println ( countCharacters ( strings , chars ) ) ; } }


"Total money to be paid after traveling the given number of hours | Java implementation of the above approach ; calculating hours travelled"
How can the above be solved in Java?

import java . io . * ; class GFG { public static void main ( String [ ] args ) { float m = 50 , n = 5 , x = 67 , h = 2927 ; int z = ( int ) ( Math . ceil ( h / 60 * 1.0 ) ) ; if ( z <= n ) System . out . println ( z * m ) ; else System . out . println ( n * m + ( z - n ) * x ) ; } }


"Total no of 1 's in numbers | / Java code to count the frequency of 1 in numbers less than or equal to the given number . ; function to count the frequency of 1. ; Driver Code"
How can the above be solved in Java?

import java . io . * ; class GFG { static int countDigitOne ( int n ) { int countr = 0 ; for ( int i = 1 ; i <= n ; i *= 10 ) { int divider = i * 10 ; countr += ( n / divider ) * i + Math . min ( Math . max ( n % divider - i + 1 , 0 ) , i ) ; } return countr ; } public static void main ( String [ ] args ) { int n = 13 ; System . out . println ( countDigitOne ( n ) ) ; n = 113 ; System . out . println ( countDigitOne ( n ) ) ; n = 205 ; System . out . println ( countDigitOne ( n ) ) ; } }


"Total no of 1 's in numbers | Java code to count the frequency of 1 in numbers less than or equal to the given number . ; Driver Code"
How can the above be solved in Java?

class GFG { static int countDigitOne ( int n ) { int countr = 0 ; for ( int i = 1 ; i <= n ; i ++ ) { String str = String . valueOf ( i ) ; countr += str . split ( "1" , - 1 ) . length - 1 ; } return countr ; } public static void main ( String [ ] args ) { int n = 13 ; System . out . println ( countDigitOne ( n ) ) ; n = 131 ; System . out . println ( countDigitOne ( n ) ) ; n = 159 ; System . out . println ( countDigitOne ( n ) ) ; } }


"Total nodes traversed in Euler Tour Tree | Java program to check the number of nodes in Euler Tour tree . ; Adjacency list representation of tree ; Function to add edges to tree ; Program to check if calculated Value is equal to 2 * size - 1 ; Add out - degree of each node ; Driver Code ; Constructing 1 st tree from example ; Out_deg [ node [ i ] ] is equal to adj [ i ] . size ( ) ; clear previous stored tree ; Constructing 2 nd tree from example ; Out_deg [ node [ i ] ] is equal to adj [ i ] . size ( )"
How can the above be solved in Java?

 import java . util . * ; class GFG { static final int MAX = 1001 ; static Vector < Integer > [ ] adj = new Vector [ MAX ] ; static void add_edge ( int u , int v ) { adj [ u ] . add ( v ) ; } static void checkTotalNumberofNodes ( int actualAnswer , int size ) { int calculatedAnswer = size ; for ( int i = 1 ; i <= size ; i ++ ) calculatedAnswer += adj [ i ] . size ( ) ; if ( actualAnswer == calculatedAnswer ) System . out . print ( " Calculated ▁ Answer ▁ is ▁ " + calculatedAnswer + " and is Equal to Actual Answer
"); else System . out . print ( "Calculated Answer is Incorrect
"); } public static void main ( String [ ] args ) { for ( int i = 0 ; i < MAX ; i ++ ) adj [ i ] = new Vector < Integer > ( ) ; int N = 8 ; add_edge ( 1 , 2 ) ; add_edge ( 1 , 3 ) ; add_edge ( 2 , 4 ) ; add_edge ( 2 , 5 ) ; add_edge ( 3 , 6 ) ; add_edge ( 3 , 7 ) ; add_edge ( 6 , 8 ) ; checkTotalNumberofNodes ( 2 * N - 1 , N ) ; for ( int i = 1 ; i <= N ; i ++ ) adj [ i ] . clear ( ) ; N = 9 ; add_edge ( 1 , 2 ) ; add_edge ( 1 , 3 ) ; add_edge ( 2 , 4 ) ; add_edge ( 2 , 5 ) ; add_edge ( 2 , 6 ) ; add_edge ( 3 , 9 ) ; add_edge ( 5 , 7 ) ; add_edge ( 5 , 8 ) ; checkTotalNumberofNodes ( 2 * N - 1 , N ) ; } }


"Total number of Subsets of size at most K | Java code to find total number of Subsets of size at most K ; Function to compute the value of Binomial Coefficient C ( n , k ) ; Calculate value of Binomial Coefficient in bottom up manner ; Base Cases ; Calculate value using previously stored values ; Function to calculate sum of nCj from j = 1 to k ; Calling the nCr function for each value of j ; Driver code"
How can the above be solved in Java?

import java . lang . * ; class GFG { public static int binomialCoeff ( int n , int k ) { int [ ] [ ] C = new int [ n + 1 ] [ k + 1 ] ; int i , j ; for ( i = 0 ; i <= n ; i ++ ) { for ( j = 0 ; j <= Math . min ( i , k ) ; j ++ ) { if ( j == 0 j == i ) C [ i ] [ j ] = 1 ; else C [ i ] [ j ] = C [ i - 1 ] [ j - 1 ] + C [ i - 1 ] [ j ] ; } } return C [ n ] [ k ] ; } public static int count ( int n , int k ) { int sum = 0 ; for ( int j = 1 ; j <= k ; j ++ ) { sum = sum + binomialCoeff ( n , j ) ; } return sum ; } public static void main ( String args [ ] ) { GFG g = new GFG ( ) ; int n = 3 , k = 2 ; System . out . print ( count ( n , k ) ) ; int n1 = 5 , k1 = 2 ; System . out . print ( count ( n1 , k1 ) ) ; } }


"Total number of cells covered in a matrix after D days | Java implementation to find the total number of cells covered in a matrix after D days ; Function to return the total infected cells after d days ; Top extension ; Bottom extension ; Left extension ; Right extension ; Calculating the cells in each quadrilateral ; Sum all of them to get total cells in each quadrilateral ; Add the singleblocks along the lines of top , down , left , right ; Return the ans ; Driver code ; Dimensions of cell ; Starting coordinates ; Number of days ; Function call"
How can the above be solved in Java?

import java . util . * ; class GFG { static int solve ( int n , int m , int x , int y , int d ) { int top = Math . min ( d , x - 1 ) ; int down = Math . min ( d , n - x ) ; int left = Math . min ( d , y - 1 ) ; int right = Math . min ( d , m - y ) ; int quad1 = top * left ; int quad2 = left * down ; int quad3 = down * right ; int quad4 = right * top ; int totalsq = quad1 + quad2 + quad3 + quad4 ; int singleBlocks = top + down + left + right + 1 ; return totalsq + singleBlocks ; } public static void main ( String [ ] args ) { int n = 10 , m = 10 ; int x = 7 , y = 8 ; int d = 4 ; d -- ; System . out . println ( solve ( n , m , x , y , d ) ) ; } }


"Total number of different staircase that can made from N boxes | Java program to find the total number of different staircase that can made from N boxes ; Function to find the total number of different staircase that can made from N boxes ; DP table , there are two states . First describes the number of boxes and second describes the step ; Initialize all the elements of the table to zero ; Base case ; When step is equal to 2 ; When step is greater than 2 ; Count the total staircase from all the steps ; Driver Code"
How can the above be solved in Java?

import java . util . * ; class GFG { static int countStaircases ( int N ) { int [ ] [ ] memo = new int [ N + 5 ] [ N + 5 ] ; for ( int i = 0 ; i <= N ; i ++ ) { for ( int j = 0 ; j <= N ; j ++ ) { memo [ i ] [ j ] = 0 ; } } memo [ 3 ] [ 2 ] = memo [ 4 ] [ 2 ] = 1 ; for ( int i = 5 ; i <= N ; i ++ ) { for ( int j = 2 ; j <= i ; j ++ ) { if ( j == 2 ) { memo [ i ] [ j ] = memo [ i - j ] [ j ] + 1 ; } else { memo [ i ] [ j ] = memo [ i - j ] [ j ] + memo [ i - j ] [ j - 1 ] ; } } } int answer = 0 ; for ( int i = 1 ; i <= N ; i ++ ) answer = answer + memo [ N ] [ i ] ; return answer ; } public static void main ( String [ ] args ) { int N = 7 ; System . out . println ( countStaircases ( N ) ) ; } }


"Total number of divisors for a given number | Java program for finding number of divisor ; program for finding no . of divisors ; sieve method for prime calculation ; Traversing through all prime numbers ; calculate number of divisor with formula total div = ( p1 + 1 ) * ( p2 + 1 ) * ... . . * ( pn + 1 ) where n = ( a1 ^ p1 ) * ( a2 ^ p2 ) . ... * ( an ^ pn ) ai being prime divisor for n and pi are their respective power in factorization ; Driver Code"
How can the above be solved in Java?

import java . io . * ; import java . util . * ; import java . lang . * ; class GFG { static int divCount ( int n ) { boolean hash [ ] = new boolean [ n + 1 ] ; Arrays . fill ( hash , true ) ; for ( int p = 2 ; p * p < n ; p ++ ) if ( hash [ p ] == true ) for ( int i = p * 2 ; i < n ; i += p ) hash [ i ] = false ; int total = 1 ; for ( int p = 2 ; p <= n ; p ++ ) { if ( hash [ p ] ) { int count = 0 ; if ( n % p == 0 ) { while ( n % p == 0 ) { n = n / p ; count ++ ; } total = total * ( count + 1 ) ; } } } return total ; } public static void main ( String [ ] args ) { int n = 24 ; System . out . print ( divCount ( n ) ) ; } }


"Total number of non |  ; dp [ i ] [ j ] contains total count of non decreasing numbers ending with digit i and of length j ; Fill table for non decreasing numbers of length 1 Base cases 0 , 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 ; Fill the table in bottom - up manner ; Compute total numbers of non decreasing numbers of length ' len ' ; sum of all numbers of length of len - 1 in which last digit x is <= ' digit ' ; There total nondecreasing numbers of length n wiint be dp [ 0 ] [ n ] + dp [ 1 ] [ n ] . . + dp [ 9 ] [ n ] ; Driver program"
How can the above be solved in Java?

class NDN { static int countNonDecreasing ( int n ) { int dp [ ] [ ] = new int [ 10 ] [ n + 1 ] ; for ( int i = 0 ; i < 10 ; i ++ ) dp [ i ] [ 1 ] = 1 ; for ( int digit = 0 ; digit <= 9 ; digit ++ ) { for ( int len = 2 ; len <= n ; len ++ ) { for ( int x = 0 ; x <= digit ; x ++ ) dp [ digit ] [ len ] += dp [ x ] [ len - 1 ] ; } } int count = 0 ; for ( int i = 0 ; i < 10 ; i ++ ) count += dp [ i ] [ n ] ; return count ; } public static void main ( String args [ ] ) { int n = 3 ; System . out . println ( countNonDecreasing ( n ) ) ; } }


"Total number of non | java program to count non - decreasing numner with n digits ; Compute value of N * ( N + 1 ) / 2 * ( N + 2 ) / 3 * ... . * ( N + n - 1 ) / n ; Driver code"
How can the above be solved in Java?

public class GFG { static long countNonDecreasing ( int n ) { int N = 10 ; long count = 1 ; for ( int i = 1 ; i <= n ; i ++ ) { count *= ( N + i - 1 ) ; count /= i ; } return count ; } public static void main ( String args [ ] ) { int n = 3 ; System . out . print ( countNonDecreasing ( n ) ) ; } }


"Total number of possible Binary Search Trees and Binary Trees with n keys | See https : www . geeksforgeeks . org / program - nth - catalan - number / for reference of below code . ; A function to find factorial of a given number ; Calculate value of [ 1 * ( 2 ) * -- - * ( n - k + 1 ) ] / [ k * ( k - 1 ) * -- - * 1 ] ; Since C ( n , k ) = C ( n , n - k ) ; Calculate value of [ n * ( n - 1 ) * -- - * ( n - k + 1 ) ] / [ k * ( k - 1 ) * -- - * 1 ] ; A Binomial coefficient based function to find nth catalan number in O ( n ) time ; Calculate value of 2 nCn ; return 2 nCn / ( n + 1 ) ; A function to count number of BST with n nodes using catalan ; find nth catalan number ; return nth catalan number ; A function to count number of binary trees with n nodes ; find count of BST with n numbers ; return count * n ! ; Driver Code ; find count of BST and binary trees with n nodes ; print count of BST and binary trees with n nodes"
How can the above be solved in Java?

import java . io . * ; class GFG { static int factorial ( int n ) { int res = 1 ; for ( int i = 1 ; i <= n ; ++ i ) { res *= i ; } return res ; } static int binomialCoeff ( int n , int k ) { int res = 1 ; if ( k > n - k ) k = n - k ; for ( int i = 0 ; i < k ; ++ i ) { res *= ( n - i ) ; res /= ( i + 1 ) ; } return res ; } static int catalan ( int n ) { int c = binomialCoeff ( 2 * n , n ) ; return c / ( n + 1 ) ; } static int countBST ( int n ) { int count = catalan ( n ) ; return count ; } static int countBT ( int n ) { int count = catalan ( n ) ; return count * factorial ( n ) ; } public static void main ( String [ ] args ) { int count1 , count2 , n = 5 ; count1 = countBST ( n ) ; count2 = countBT ( n ) ; System . out . println ( " Count ▁ of ▁ BST ▁ with ▁ " + n + " ▁ nodes ▁ is ▁ " + count1 ) ; System . out . println ( " Count ▁ of ▁ binary ▁ " + " trees ▁ with ▁ " + n + " ▁ nodes ▁ is ▁ " + count2 ) ; } }


"Total number of triangles formed when there are H horizontal and V vertical lines | Java implementation of the approach ; Function to return total triangles ; Only possible triangle is the given triangle ; If only vertical lines are present ; If only horizontal lines are present ; Return total triangles ; Driver code"
How can the above be solved in Java?

class GFG { public static int totalTriangles ( int h , int v ) { if ( h == 0 && v == 0 ) return 1 ; if ( h == 0 ) return ( ( v + 1 ) * ( v + 2 ) / 2 ) ; if ( v == 0 ) return ( h + 1 ) ; int total = ( h + 1 ) * ( ( v + 1 ) * ( v + 2 ) / 2 ) ; return total ; } public static void main ( String [ ] args ) { int h = 2 , v = 2 ; System . out . print ( totalTriangles ( h , v ) ) ; } }


"Total number of triplets ( A , B , C ) in which the points B and C are Equidistant to A | Java implementation to find the total number of Triplets in which the points are Equidistant ; Function to size ( ) such triplets ; Iterate over all the points ; Iterate over all points other than the current point ; Compute squared euclidean distance for the current point ; Compute nP2 that is n * ( n - 1 ) ; Return the final result ; Driver code"
How can the above be solved in Java?

import java . util . * ; @ SuppressWarnings ( " unchecked " ) class GFG { static class pair { public int first , second ; public pair ( int first , int second ) { this . first = first ; this . second = second ; } } static int numTrip ( ArrayList points ) { int res = 0 ; for ( int i = 0 ; i < points . size ( ) ; ++ i ) { HashMap < Long , Integer > map = new HashMap < > ( ) ; for ( int j = 0 ; j < points . size ( ) ; ++ j ) { if ( j == i ) continue ; int dy = ( ( pair ) points . get ( i ) ) . second - ( ( pair ) points . get ( j ) ) . second ; int dx = ( ( pair ) points . get ( i ) ) . first - ( ( pair ) points . get ( j ) ) . first ; long key = dy * dy ; key += dx * dx ; if ( map . containsKey ( key ) ) { map . put ( key , map . get ( key ) + 1 ) ; } else { map . put ( key , 1 ) ; } } for ( int p : map . values ( ) ) res += p * ( p - 1 ) ; } return res ; } public static void main ( String [ ] args ) { ArrayList mat = new ArrayList ( ) ; mat . add ( new pair ( 0 , 0 ) ) ; mat . add ( new pair ( 1 , 0 ) ) ; mat . add ( new pair ( 2 , 0 ) ) ; System . out . println ( numTrip ( mat ) ) ; } }


"Total number of unit cells covered by all given Rectangles | Java program to find the number of cells enclosed by the given rectangles ; Update the coordinates lying within the rectangle ; Update arr [ i ] [ j ] for all ( i , j ) lying within the rectangle ; Function to return the total area covered by rectangles ; Stores the number of cells ; arr [ i ] ] [ [ j ] == 1 means that grid is filled by some rectangle ; Driver Code ; ( A [ i ] [ 0 ] , A [ i ] [ 1 ] ) denotes the coordinate of the bottom left of the rectangle ( A [ i ] [ 2 ] , A [ i ] [ 3 ] ) denotes the coordinate of upper right of the rectangle ; Update the coordinates that lie within the rectangle"
How can the above be solved in Java?

class GFG { static final int MAX = 1001 ; static boolean [ ] [ ] arr = new boolean [ MAX ] [ MAX ] ; static void updateArray ( int x1 , int y1 , int x2 , int y2 ) { for ( int i = x1 ; i < x2 ; i ++ ) { for ( int j = y1 ; j < y2 ; j ++ ) { arr [ i ] [ j ] = true ; } } } static int findAreaCovered ( ) { int area = 0 ; for ( int i = 0 ; i < MAX ; i ++ ) { for ( int j = 0 ; j < MAX ; j ++ ) { if ( arr [ i ] [ j ] == true ) { area ++ ; } } } return area ; } public static void main ( String [ ] args ) { int N = 3 ; int [ ] [ ] A = { { 1 , 3 , 4 , 5 } , { 3 , 1 , 7 , 4 } , { 5 , 3 , 8 , 6 } } ; for ( int i = 0 ; i < N ; i ++ ) { updateArray ( A [ i ] [ 0 ] , A [ i ] [ 1 ] , A [ i ] [ 2 ] , A [ i ] [ 3 ] ) ; } int area = findAreaCovered ( ) ; System . out . print ( area ) ; } }


"Total number of ways to place X and Y at n places such that no two X are together | Java program to find the number of ways Calculate total ways to place ' x ' and ' y ' at n places such that no two ' x ' are together ; Function to return number of ways ; for n = 1 ; for n = 2 ; iterate to find Fibonacci term ; total number of places"
How can the above be solved in Java?

public class GFG { static int ways ( int n ) { int first = 2 ; int second = 3 ; int res = 0 ; for ( int i = 3 ; i <= n ; i ++ ) { res = first + second ; first = second ; second = res ; } return res ; } public static void main ( String [ ] args ) { int n = 7 ; System . out . print ( " Total ▁ ways ▁ are : ▁ " + ways ( n ) ) ; } }


"Total numbers with no repeated digits in a range | Java implementation of above idea ; Maximum ; Prefix Array ; Function to check if the given number has repeated digit or not ; Traversing through each digit ; if the digit is present more than once in the number ; return 0 if the number has repeated digit ; return 1 if the number has no repeated digit ; Function to pre calculate the Prefix array ; Traversing through the numbers from 2 to MAX ; Generating the Prefix array ; Calclute Function ; Answer ; Driver Code ; Pre - calculating the Prefix array . ; Calling the calculate function to find the total number of number which has no repeated digit"
How can the above be solved in Java?

import java . util . * ; class GFG { static int MAX = 100 ; static Vector < Integer > Prefix = new Vector < > ( ) ; static int repeated_digit ( int n ) { HashSet < Integer > a = new HashSet < > ( ) ; int d ; while ( n != 0 ) { d = n % 10 ; if ( a . contains ( d ) ) return 0 ; a . add ( d ) ; n /= 10 ; } return 1 ; } static void pre_calculations ( ) { Prefix . add ( 0 ) ; Prefix . add ( repeated_digit ( 1 ) ) ; for ( int i = 2 ; i < MAX + 1 ; i ++ ) Prefix . add ( repeated_digit ( i ) + Prefix . elementAt ( i - 1 ) ) ; } static int calculate ( int L , int R ) { return Prefix . elementAt ( R ) - Prefix . elementAt ( L - 1 ) ; } public static void main ( String [ ] args ) { int L = 1 , R = 100 ; pre_calculations ( ) ; System . out . println ( calculate ( L , R ) ) ; } }


"Total numbers with no repeated digits in a range | Java implementation of brute force solution . ; Function to check if the given number has repeated digit or not ; Traversing through each digit ; if the digit is present more than once in the number ; return 0 if the number has repeated digit ; return 1 if the number has no repeated digit ; Function to find total number in the given range which has no repeated digit ; Traversing through the range ; Add 1 to the answer if i has no repeated digit else 0 ; Driver Code ; Calling the calculate"
How can the above be solved in Java?

import java . util . LinkedHashSet ; class GFG { static int repeated_digit ( int n ) { LinkedHashSet < Integer > s = new LinkedHashSet < > ( ) ; while ( n != 0 ) { int d = n % 10 ; if ( s . contains ( d ) ) { return 0 ; } s . add ( d ) ; n = n / 10 ; } return 1 ; } static int calculate ( int L , int R ) { int answer = 0 ; for ( int i = L ; i < R + 1 ; ++ i ) { answer = answer + repeated_digit ( i ) ; } return answer ; } public static void main ( String [ ] args ) { int L = 1 , R = 100 ; System . out . println ( calculate ( L , R ) ) ; } }


"Total pairs in an array such that the bitwise AND , bitwise OR and bitwise XOR of LSB is 1 | Java implementation of the approach ; Function to find the count of required pairs ; To store the count of elements which give remainder 0 i . e . even values ; To store the count of elements which give remainder 1 i . e . odd values ; Driver code"
How can the above be solved in Java?

class GFG { static void CalculatePairs ( int a [ ] , int n ) { int cnt_zero = 0 ; int cnt_one = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( a [ i ] % 2 == 0 ) cnt_zero += 1 ; else cnt_one += 1 ; } int total_XOR_pairs = cnt_zero * cnt_one ; int total_AND_pairs = ( cnt_one ) * ( cnt_one - 1 ) / 2 ; int total_OR_pairs = cnt_zero * cnt_one + ( cnt_one ) * ( cnt_one - 1 ) / 2 ; System . out . println ( " cntXOR ▁ = ▁ " + total_XOR_pairs ) ; System . out . println ( " cntAND ▁ = ▁ " + total_AND_pairs ) ; System . out . println ( " cntOR ▁ = ▁ " + total_OR_pairs ) ; } public static void main ( String [ ] args ) { int a [ ] = { 1 , 3 , 4 , 2 } ; int n = a . length ; CalculatePairs ( a , n ) ; } }


"Total position where king can reach on a chessboard in exactly M moves | Java implementation of above approach ; Function to return the number of squares that the king can reach in the given number of moves ; Calculate initial and final coordinates ; Since chessboard is of size 8 X8 so if any coordinate is less than 1 or greater than 8 make it 1 or 8. ; Calculate total positions ; Driver code"
How can the above be solved in Java?

class GFG { static int Square ( int row , int column , int moves ) { int a = 0 , b = 0 , c = 0 , d = 0 , total = 0 ; a = row - moves ; b = row + moves ; c = column - moves ; d = column + moves ; if ( a < 1 ) a = 1 ; if ( c < 1 ) c = 1 ; if ( b > 8 ) b = 8 ; if ( d > 8 ) d = 8 ; total = ( b - a + 1 ) * ( d - c + 1 ) - 1 ; return total ; } public static void main ( String [ ] args ) { int R = 4 , C = 5 , M = 2 ; System . out . println ( Square ( R , C , M ) ) ; } }


"Total ways of choosing X men and Y women from a total of M men and W women | JAVA implementation of the approach ; Function to return the value of ncr effectively ; Initialize the answer ; Divide simultaneously by i to avoid overflow ; Function to return the count of required ways ; Driver code"
How can the above be solved in Java?

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


"Total ways of selecting a group of X men from N men with or without including a particular man | Java implementation of the approach ; Function to return the value of nCr ; Initialize the answer ; Divide simultaneously by i to avoid overflow ; Function to return the count of ways ; Driver code"
How can the above be solved in Java?

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


"Tower of Hanoi | Set 2 | Java program for the above approach ; Function to print order of movement of N disks across three rods to place all disks on the third rod from the first - rod using binary representation ; Iterate over the range [ 0 , 2 ^ N - 1 ] ; Print the movement of the current rod ; Driver Code"
How can the above be solved in Java?

 class GFG { static void TowerOfHanoi ( int N ) { for ( int x = 1 ; x <= Math . pow ( 2 , N ) - 1 ; x ++ ) { System . out . print ( " Move ▁ from ▁ Rod ▁ " + ( ( x & x - 1 ) % 3 + 1 ) + " ▁ to ▁ Rod ▁ " + ( ( ( x x - 1 ) + 1 ) % 3 + 1 ) + "
"); } } public static void main ( String [ ] args ) { int N = 3 ; TowerOfHanoi ( N ) ; } }


"Tracking current Maximum Element in a Stack | Java program to keep track of maximum element in a stack ; main stack ; tack to keep track of max element ; If current element is greater than the top element of track stack , push the current element to track stack otherwise push the element at top of track stack again into it . ; Driver program to test above functions"
How can the above be solved in Java?

import java . util . * ; class GfG { static class StackWithMax { static Stack < Integer > mainStack = new Stack < Integer > ( ) ; static Stack < Integer > trackStack = new Stack < Integer > ( ) ; static void push ( int x ) { mainStack . push ( x ) ; if ( mainStack . size ( ) == 1 ) { trackStack . push ( x ) ; return ; } if ( x > trackStack . peek ( ) ) trackStack . push ( x ) ; else trackStack . push ( trackStack . peek ( ) ) ; } static int getMax ( ) { return trackStack . peek ( ) ; } static void pop ( ) { mainStack . pop ( ) ; trackStack . pop ( ) ; } } ; public static void main ( String [ ] args ) { StackWithMax s = new StackWithMax ( ) ; s . push ( 20 ) ; System . out . println ( s . getMax ( ) ) ; s . push ( 10 ) ; System . out . println ( s . getMax ( ) ) ; s . push ( 50 ) ; System . out . println ( s . getMax ( ) ) ; } }


"Trailing number of 0 s in product of two factorials | Java program for count number of trailing zeros in N ! * M ! ; Returns number of zeros in factorial n ; dividing x by powers of 5 and update count ; Returns count of trailing zeros in M ! x N ! ; Driver program"
How can the above be solved in Java?

import java . io . * ; class GFG { static int trailingZero ( int x ) { int i = 5 , count = 0 ; while ( x > i ) { count = count + x / i ; i = i * 5 ; } return count ; } static int countProductTrailing ( int M , int N ) { return trailingZero ( N ) + trailingZero ( M ) ; } public static void main ( String args [ ] ) { int N = 67 , M = 98 ; System . out . println ( countProductTrailing ( N , M ) ) ; } }


"Transform N to Minimum possible value | JAVA program to transform N to the minimum value ; Initialising the answer ; Function to find the digitsum ; Iterate over all digits and add them ; Return the digit su , ; Function to transform N to the minimum value ; If the final value is lesser than least value ; If final value is equal to least value then check for lesser number of steps to reach this value ; The value will be obtained in less than 15 steps as proved so applying normal recursive operations ; Driver code ; Function call ; Print the answers"
How can the above be solved in Java?

import java . util . * ; class GFG { static int min_val = Integer . MAX_VALUE ; static int min_steps = 0 ; static int sumOfDigits ( int n ) { String s = String . valueOf ( n ) ; int sum = 0 ; for ( int i = 0 ; i < s . length ( ) ; i ++ ) { sum += ( s . charAt ( i ) - '0' ) ; } return sum ; } static void Transform ( int n , int d , int steps ) { if ( n < min_val ) { min_val = n ; min_steps = steps ; } else if ( n == min_val ) { min_steps = Math . min ( min_steps , steps ) ; } if ( steps < 15 ) { Transform ( sumOfDigits ( n ) , d , steps + 1 ) ; Transform ( n + d , d , steps + 1 ) ; } } public static void main ( String [ ] args ) { int N = 9 , D = 3 ; Transform ( N , D , 0 ) ; System . out . print ( min_val + " ▁ " + min_steps ) ; } }


"Transform a string such that it has abcd . . z as a subsequence | Java Program to transform the given string to contain the required subsequence ; function to transform string with string passed as reference ; initializing the variable ch to ' a ' ; if the length of string is less than 26 , we can 't obtain the required  subsequence ; if ch has reached ' z ' , it means we have transformed our string such that required subsequence can be obtained ; current character is not greater than ch , then replace it with ch and increment ch ; Driver Code"
How can the above be solved in Java?

import java . io . * ; public class GFG { static boolean transformString ( StringBuilder s ) { char ch = ' a ' ; if ( s . length ( ) < 26 ) return false ; for ( int i = 0 ; i < s . length ( ) ; i ++ ) { if ( ( int ) ch > ( int ) ' z ' ) break ; if ( s . charAt ( i ) <= ch ) { s . setCharAt ( i , ch ) ; ch = ( char ) ( ( int ) ch + 1 ) ; } } if ( ch <= ' z ' ) return false ; return true ; } public static void main ( String args [ ] ) { StringBuilder str = new StringBuilder ( " aaaaaaaaaaaaaaaaaaaaaaaaaa " ) ; if ( transformString ( str ) ) System . out . println ( str . toString ( ) ) ; else System . out . println ( " Not ▁ Possible " ) ; } }