"Transform string str1 into str2 by taking characters from string str3 | Java program of the above approach ; Function to check whether str1 can be transformed to str2 ; To store the frequency of characters of String str3 ; Declare two pointers & flag ; Traverse both the String and check whether it can be transformed ; If both pointers point to same characters increment them ; If the letters don 't match check  if we can find it in String C ; If the letter is available in String str3 , decrement it 's  frequency & increment the ptr2 ; If letter isn 't present in str3[]  set the flag to false and break ; If the flag is true and both pointers points to their end of respective Strings then it is possible to transformed str1 into str2 , otherwise not . ; Driver Code ; Function Call"
How can the above be solved in Java?

 import java . util . * ; class GFG { static void convertString ( String str1 , String str2 , String str3 ) { HashMap < Character , Integer > freq = new HashMap < > ( ) ; for ( int i = 0 ; i < str3 . length ( ) ; i ++ ) { if ( freq . containsKey ( str3 . charAt ( i ) ) ) freq . put ( str3 . charAt ( i ) , freq . get ( str3 . charAt ( i ) ) + 1 ) ; else freq . put ( str3 . charAt ( i ) , 1 ) ; } int ptr1 = 0 ; int ptr2 = 0 ; boolean flag = true ; while ( ptr1 < str1 . length ( ) && ptr2 < str2 . length ( ) ) { if ( str1 . charAt ( ptr1 ) == str2 . charAt ( ptr2 ) ) { ptr1 ++ ; ptr2 ++ ; } else { if ( freq . containsKey ( str3 . charAt ( ptr2 ) ) ) if ( freq . get ( str3 . charAt ( ptr2 ) ) > 0 ) { freq . put ( str3 . charAt ( ptr2 ) , freq . get ( str3 . charAt ( ptr2 ) ) - 1 ) ; ptr2 ++ ; } else { flag = false ; break ; } } } if ( flag && ptr1 == str1 . length ( ) && ptr2 == str2 . length ( ) ) { System . out . print ( " YES " + "
"); } else { System . out . print ( " NO " + "
"); } } public static void main ( String [ ] args ) { String str1 = " abyzfe " ; String str2 = " abcdeyzf " ; String str3 = " popode " ; convertString ( str1 , str2 , str3 ) ; } }


"Trapezoidal Rule for Approximate Value of Definite Integral | Java program to implement Trapezoidal rule ; A sample function whose definite integral 's approximate value   is computed using Trapezoidal  rule ; Declaring the function f ( x ) = 1 / ( 1 + x * x ) ; Function to evaluate the value of integral ; Grid spacing ; Computing sum of first and last terms in above formula ; Adding middle terms in above formula ; h / 2 indicates ( b - a ) / 2 n . Multiplying h / 2 with s . ; Driver code ; Range of definite integral ; Number of grids . Higher value means more accuracy"
How can the above be solved in Java?

class GFG { static float y ( float x ) { return 1 / ( 1 + x * x ) ; } static float trapezoidal ( float a , float b , float n ) { float h = ( b - a ) / n ; float s = y ( a ) + y ( b ) ; for ( int i = 1 ; i < n ; i ++ ) s += 2 * y ( a + i * h ) ; return ( h / 2 ) * s ; } public static void main ( String [ ] args ) { float x0 = 0 ; float xn = 1 ; int n = 6 ; System . out . println ( " Value ▁ of ▁ integral ▁ is ▁ " + Math . round ( trapezoidal ( x0 , xn , n ) * 10000.0 ) / 10000.0 ) ; } }


"Trapping Rain Water |  ; Java implementation of the approach ; Function to return the maximum water that can be stored ; Stores the indices of the bars ; size of the array ; Stores the final result ; Loop through the each bar ; Remove bars from the stack until the condition holds ; store the height of the top and pop it . ; If the stack does not have any bars or the the popped bar has no left boundary ; Get the distance between the left and right boundary of popped bar ; Calculate the min . height ; If the stack is either empty or height of the current bar is less than or equal to the top bar of stack ; Driver code"
How can the above be solved in Java?

import java . util . * ; import java . io . * ; class GFG { public static int maxWater ( int [ ] height ) { Stack < Integer > stack = new Stack < > ( ) ; int n = height . length ; int ans = 0 ; for ( int i = 0 ; i < n ; i ++ ) { while ( ( ! stack . isEmpty ( ) ) && ( height [ stack . peek ( ) ] < height [ i ] ) ) { int pop_height = height [ stack . peek ( ) ] ; stack . pop ( ) ; if ( stack . isEmpty ( ) ) break ; int distance = i - stack . peek ( ) - 1 ; int min_height = Math . min ( height [ stack . peek ( ) ] , height [ i ] ) - pop_height ; ans += distance * min_height ; } stack . push ( i ) ; } return ans ; } public static void main ( String [ ] args ) { int arr [ ] = { 0 , 1 , 0 , 2 , 1 , 0 , 1 , 3 , 2 , 1 , 2 , 1 } ; System . out . print ( maxWater ( arr ) ) ; } }


"Trapping Rain Water | JAVA Code For Trapping Rain Water ; initialize output ; maximum element on left and right ; indices to traverse the array ; update max in left ; water on curr element = max - curr ; update right maximum ; Driver program to test above function"
How can the above be solved in Java?

import java . util . * ; class GFG { static int findWater ( int arr [ ] , int n ) { int result = 0 ; int left_max = 0 , right_max = 0 ; int lo = 0 , hi = n - 1 ; while ( lo <= hi ) { if ( arr [ lo ] < arr [ hi ] ) { if ( arr [ lo ] > left_max ) left_max = arr [ lo ] ; else result += left_max - arr [ lo ] ; lo ++ ; } else { if ( arr [ hi ] > right_max ) right_max = arr [ hi ] ; else result += right_max - arr [ hi ] ; hi -- ; } } return result ; } public static void main ( String [ ] args ) { int arr [ ] = { 0 , 1 , 0 , 2 , 1 , 0 , 1 , 3 , 2 , 1 , 2 , 1 } ; int n = arr . length ; System . out . println ( " Maximum ▁ water ▁ that ▁ " + " can ▁ be ▁ accumulated ▁ is ▁ " + findWater ( arr , n ) ) ; } }


"Trapping Rain Water | Java implementation of the approach ; Function to return the maximum water that can be stored ; Let the first element be stored as previous , we shall loop from index 1 ; To store previous wall 's index ; To store the water until a larger wall is found , if there are no larger walls then delete temp value from water ; If the current wall is taller than the previous wall then make current wall as the previous wall and its index as previous wall 's index  for the subsequent loops ; Because larger or same height wall is found ; Since current wall is shorter than the previous , we subtract previous wall ' s ▁ height ▁ from ▁ the ▁ current ▁ wall ' s height and add it to the water ; Store the same value in temp as well If we dont find any larger wall then we will subtract temp from water ; If the last wall was larger than or equal to the previous wall then prev_index would be equal to size of the array ( last element ) If we didn 't find a wall greater than or equal  to the previous wall from the left then  prev_index must be less than the index  of the last element ; Temp would ' ve ▁ stored ▁ the ▁ water ▁ collected ▁ ▁ from ▁ previous ▁ largest ▁ wall ▁ till ▁ the ▁ end ▁ ▁ of ▁ array ▁ if ▁ no ▁ larger ▁ wall ▁ was ▁ found ▁ then ▁ ▁ it ▁ has ▁ excess ▁ water ▁ and ▁ remove ▁ that ▁ ▁ from ▁ ' water ' var ; We start from the end of the array , so previous should be assigned to the last element ; Loop from the end of array up to the ' previous ▁ index ' which would contain the " largest ▁ wall ▁ from ▁ the ▁ left " ; Right end wall will be definitely smaller than the ' previous ▁ index ' wall ; Return the maximum water ; Driver code"
How can the above be solved in Java?

class GFG { public static int maxWater ( int arr [ ] , int n ) { int size = n - 1 ; int prev = arr [ 0 ] ; int prev_index = 0 ; int water = 0 ; int temp = 0 ; for ( int i = 1 ; i <= size ; i ++ ) { if ( arr [ i ] >= prev ) { prev = arr [ i ] ; prev_index = i ; temp = 0 ; } else { water += prev - arr [ i ] ; temp += prev - arr [ i ] ; } } if ( prev_index < size ) { water -= temp ; prev = arr [ size ] ; for ( int i = size ; i >= prev_index ; i -- ) { if ( arr [ i ] >= prev ) { prev = arr [ i ] ; } else { water += prev - arr [ i ] ; } } } return water ; } public static void main ( String [ ] args ) { int arr [ ] = { 0 , 1 , 0 , 2 , 1 , 0 , 1 , 3 , 2 , 1 , 2 , 1 } ; int n = arr . length ; System . out . print ( maxWater ( arr , n ) ) ; } }


"Trapping Rain Water | Java implementation of the approach ; Function to return the maximum water that can be stored ; To store the maximum water that can be stored ; For every element of the array except first and last element ; Find maximum element on its left ; Find maximum element on its right ; Update maximum water value ; Driver code"
How can the above be solved in Java?

class GFG { public static int maxWater ( int [ ] arr , int n ) { int res = 0 ; for ( int i = 1 ; i < n - 1 ; i ++ ) { int left = arr [ i ] ; for ( int j = 0 ; j < i ; j ++ ) { left = Math . max ( left , arr [ j ] ) ; } int right = arr [ i ] ; for ( int j = i + 1 ; j < n ; j ++ ) { right = Math . max ( right , arr [ j ] ) ; } res += Math . min ( left , right ) - arr [ i ] ; } return res ; } public static void main ( String [ ] args ) { int [ ] arr = { 0 , 1 , 0 , 2 , 1 , 0 , 1 , 3 , 2 , 1 , 2 , 1 } ; int n = arr . length ; System . out . print ( maxWater ( arr , n ) ) ; } }


"Trapping Rain Water | Java implementation of the approach ; indices to traverse the array ; To store Left max and right max for two pointers left and right ; To store the total amount of rain water trapped ; We need check for minimum of left and right max for each element ; Add the difference between current value and right max at index r ; Update right max ; Update right pointer ; Add the difference between current value and left max at index l ; Update left max ; Update left pointer ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { static int maxWater ( int [ ] arr , int n ) { int left = 0 ; int right = n - 1 ; int l_max = 0 ; int r_max = 0 ; int result = 0 ; while ( left <= right ) { if ( r_max <= l_max ) { result += Math . max ( 0 , r_max - arr [ right ] ) ; r_max = Math . max ( r_max , arr [ right ] ) ; right -= 1 ; } else { result += Math . max ( 0 , l_max - arr [ left ] ) ; l_max = Math . max ( l_max , arr [ left ] ) ; left += 1 ; } } return result ; } public static void main ( String [ ] args ) { int [ ] arr = { 0 , 1 , 0 , 2 , 1 , 0 , 1 , 3 , 2 , 1 , 2 , 1 } ; int n = arr . length ; System . out . print ( maxWater ( arr , n ) ) ; } }


"Trapping Rain Water | Java program to find maximum amount of water that can be trapped within given set of bars . ; Method for maximum amount of water ; left [ i ] contains height of tallest bar to the left of i 'th bar including itself ; Right [ i ] contains height of tallest bar to the right of ith bar including itself ; Initialize result ; Fill left array ; Fill right array ; Calculate the accumulated water element by element consider the amount of water on i 'th bar, the  amount of water accumulated on this particular  bar will be equal to min(left[i], right[i]) - arr[i] . ; Driver method to test the above function"
How can the above be solved in Java?

class Test { static int arr [ ] = new int [ ] { 0 , 1 , 0 , 2 , 1 , 0 , 1 , 3 , 2 , 1 , 2 , 1 } ; static int findWater ( int n ) { int left [ ] = new int [ n ] ; int right [ ] = new int [ n ] ; int water = 0 ; left [ 0 ] = arr [ 0 ] ; for ( int i = 1 ; i < n ; i ++ ) left [ i ] = Math . max ( left [ i - 1 ] , arr [ i ] ) ; right [ n - 1 ] = arr [ n - 1 ] ; for ( int i = n - 2 ; i >= 0 ; i -- ) right [ i ] = Math . max ( right [ i + 1 ] , arr [ i ] ) ; for ( int i = 0 ; i < n ; i ++ ) water += Math . min ( left [ i ] , right [ i ] ) - arr [ i ] ; return water ; } public static void main ( String [ ] args ) { System . out . println ( " Maximum ▁ water ▁ that ▁ can ▁ be ▁ accumulated ▁ is ▁ " + findWater ( arr . length ) ) ; } }


"Traveling Salesman Problem using Branch And Bound | Java program to solve Traveling Salesman Problem using Branch and Bound . ; final_path [ ] stores the final solution ie , the path of the salesman . ; visited [ ] keeps track of the already visited nodes in a particular path ; Stores the final minimum weight of shortest tour . ; Function to copy temporary solution to the final solution ; Function to find the minimum edge cost having an end at the vertex i ; function to find the second minimum edge cost having an end at the vertex i ; function that takes as arguments : curr_bound -> lower bound of the root node curr_weight -> stores the weight of the path so far level -> current level while moving in the search space tree curr_path [ ] -> where the solution is being stored which would later be copied to final_path [ ] ; base case is when we have reached level N which means we have covered all the nodes once ; check if there is an edge from last vertex in path back to the first vertex ; curr_res has the total weight of the solution we got ; Update final result and final path if current result is better . ; for any other level iterate for all vertices to build the search space tree recursively ; Consider next vertex if it is not same ( diagonal entry in adjacency matrix and not visited already ) ; different computation of curr_bound for level 2 from the other levels ; curr_bound + curr_weight is the actual lower bound for the node that we have arrived on If current lower bound < final_res , we need to explore the node further ; call TSPRec for the next level ; Else we have to prune the node by resetting all changes to curr_weight and curr_bound ; Also reset the visited array ; This function sets up final_path [ ] ; Calculate initial lower bound for the root node using the formula 1 / 2 * ( sum of first min + second min ) for all edges . Also initialize the curr_path and visited array ; Compute initial bound ; Rounding off the lower bound to an integer ; We start at vertex 1 so the first vertex in curr_path [ ]..."
How can the above be solved in Java?

import java . util . * ; class GFG { static int N = 4 ; static int final_path [ ] = new int [ N + 1 ] ; static boolean visited [ ] = new boolean [ N ] ; static int final_res = Integer . MAX_VALUE ; static void copyToFinal ( int curr_path [ ] ) { for ( int i = 0 ; i < N ; i ++ ) final_path [ i ] = curr_path [ i ] ; final_path [ N ] = curr_path [ 0 ] ; } static int firstMin ( int adj [ ] [ ] , int i ) { int min = Integer . MAX_VALUE ; for ( int k = 0 ; k < N ; k ++ ) if ( adj [ i ] [ k ] < min && i != k ) min = adj [ i ] [ k ] ; return min ; } static int secondMin ( int adj [ ] [ ] , int i ) { int first = Integer . MAX_VALUE , second = Integer . MAX_VALUE ; for ( int j = 0 ; j < N ; j ++ ) { if ( i == j ) continue ; if ( adj [ i ] [ j ] <= first ) { second = first ; first = adj [ i ] [ j ] ; } else if ( adj [ i ] [ j ] <= second && adj [ i ] [ j ] != first ) second = adj [ i ] [ j ] ; } return second ; } static void TSPRec ( int adj [ ] [ ] , int curr_bound , int curr_weight , int level , int curr_path [ ] ) { if ( level == N ) { if ( adj [ curr_path [ level - 1 ] ] [ curr_path [ 0 ] ] != 0 ) { int curr_res = curr_weight + adj [ curr_path [ level - 1 ] ] [ curr_path [ 0 ] ] ; if ( curr_res < final_res ) { copyToFinal ( curr_path ) ; final_res = curr_res ; } } return ; } for ( int i = 0 ; i < N ; i ++ ) { if ( adj [ curr_path [ level - 1 ] ] [ i ] != 0 && visited [ i ] == false ) { int temp = curr_bound ; curr_weight += adj [ curr_path [ level - 1 ] ] [ i ] ; if ( level == 1 ) curr_bound -= ( ( firstMin ( adj , curr_path [ level - 1 ] ) + firstMin ( adj , i ) ) / 2 ) ; else curr_bound -= ( ( secondMin ( adj , curr_path [ level - 1 ] ) + firstMin ( adj , i ) ) / 2 ) ; if ( curr_bound + curr_weight < final_res ) { curr_path [ level ] = i ; visited [ i ] = true ; TSPRec ( adj , curr_bound , curr_weight , level + 1 , curr_path ) ; } curr_weight -= adj [ curr_path [ level - 1 ] ] [ i ] ; curr_bound = temp ; Arrays . fill ( visited , false ) ; for ( int j = 0 ; j <= level - 1 ; j ++ ) visited [ curr_path [ j ] ] =...


"Travelling Salesman Problem implementation using BackTracking | Java implementation of the approach ; Function to find the minimum weight Hamiltonian Cycle ; If last node is reached and it has a link to the starting node i . e the source then keep the minimum value out of the total cost of traversal and " ans " Finally return to check for more possible values ; BACKTRACKING STEP Loop to traverse the adjacency list of currPos node and increasing the count by 1 and cost by graph [ currPos , i ] value ; Mark as visited ; Mark ith node as unvisited ; Driver code ; n is the number of nodes i . e . V ; Boolean array to check if a node has been visited or not ; Mark 0 th node as visited ; Find the minimum weight Hamiltonian Cycle ; ans is the minimum weight Hamiltonian Cycle"
How can the above be solved in Java?

class GFG { static int tsp ( int [ ] [ ] graph , boolean [ ] v , int currPos , int n , int count , int cost , int ans ) { if ( count == n && graph [ currPos ] [ 0 ] > 0 ) { ans = Math . min ( ans , cost + graph [ currPos ] [ 0 ] ) ; return ans ; } for ( int i = 0 ; i < n ; i ++ ) { if ( v [ i ] == false && graph [ currPos ] [ i ] > 0 ) { v [ i ] = true ; ans = tsp ( graph , v , i , n , count + 1 , cost + graph [ currPos ] [ i ] , ans ) ; v [ i ] = false ; } } return ans ; } public static void main ( String [ ] args ) { int n = 4 ; int [ ] [ ] graph = { { 0 , 10 , 15 , 20 } , { 10 , 0 , 35 , 25 } , { 15 , 35 , 0 , 30 } , { 20 , 25 , 30 , 0 } } ; boolean [ ] v = new boolean [ n ] ; v [ 0 ] = true ; int ans = Integer . MAX_VALUE ; ans = tsp ( graph , v , 0 , n , 1 , 0 , ans ) ; System . out . println ( ans ) ; } }


"Travelling Salesman Problem | Greedy Approach | Java program for the above approach ; Function to find the minimum cost path for all the paths ; Starting from the 0 th indexed city i . e . , the first city ; Traverse the adjacency matrix tsp [ ] [ ] ; Corner of the Matrix ; If this path is unvisited then and if the cost is less then update the cost ; Check all paths from the ith indexed city ; Update the ending city in array from city which was last visited ; Started from the node where we finished as well . ; Driver Code ; Input Matrix ; Function Call"
How can the above be solved in Java?

import java . util . * ; public class TSPGreedy { static void findMinRoute ( int [ ] [ ] tsp ) { int sum = 0 ; int counter = 0 ; int j = 0 , i = 0 ; int min = Integer . MAX_VALUE ; List < Integer > visitedRouteList = new ArrayList < > ( ) ; visitedRouteList . add ( 0 ) ; int [ ] route = new int [ tsp . length ] ; while ( i < tsp . length && j < tsp [ i ] . length ) { if ( counter >= tsp [ i ] . length - 1 ) { break ; } if ( j != i && ! ( visitedRouteList . contains ( j ) ) ) { if ( tsp [ i ] [ j ] < min ) { min = tsp [ i ] [ j ] ; route [ counter ] = j + 1 ; } } j ++ ; if ( j == tsp [ i ] . length ) { sum += min ; min = Integer . MAX_VALUE ; visitedRouteList . add ( route [ counter ] - 1 ) ; j = 0 ; i = route [ counter ] - 1 ; counter ++ ; } } i = route [ counter - 1 ] - 1 ; for ( j = 0 ; j < tsp . length ; j ++ ) { if ( ( i != j ) && tsp [ i ] [ j ] < min ) { min = tsp [ i ] [ j ] ; route [ counter ] = j + 1 ; } } sum += min ; System . out . print ( " Minimum ▁ Cost ▁ is ▁ : ▁ " ) ; System . out . println ( sum ) ; } public static void main ( String [ ] args ) { int [ ] [ ] tsp = { { - 1 , 10 , 15 , 20 } , { 10 , - 1 , 35 , 25 } , { 15 , 35 , - 1 , 30 } , { 20 , 25 , 30 , - 1 } } ; findMinRoute ( tsp ) ; } }


"Traverse the matrix in Diagonally Bottum | Java implementation to traverse the matrix in the bottom - up fashion using recursion ; Static variable for changing row and column ; Flag variable for handling bottum up diagonal traversing ; Recursive function to traverse the matrix diagonally bottom - up ; Base Condition ; Condition when to traverse Bottom Diagonal of the matrix ; Print matrix cell value ; Recursive function to traverse The matrix diagonally ; Recursive function to change diagonal ; Driver Code ; Initialize the 5 x 5 matrix ; Function call for traversing matrix"
How can the above be solved in Java?

class GFG { static int k1 = 0 , k2 = 0 ; static boolean flag = true ; static boolean traverseMatrixDiagonally ( int m [ ] [ ] , int i , int j , int row , int col ) { if ( i >= row j >= col ) { if ( flag ) { int a = k1 ; k1 = k2 ; k2 = a ; flag = ! flag ; k1 ++ ; } else { int a = k1 ; k1 = k2 ; k2 = a ; flag = ! flag ; } System . out . println ( ) ; return false ; } System . out . print ( m [ i ] [ j ] + " ▁ " ) ; if ( traverseMatrixDiagonally ( m , i + 1 , j + 1 , row , col ) ) { return true ; } if ( traverseMatrixDiagonally ( m , k1 , k2 , row , col ) ) { return true ; } return true ; } public static void main ( String [ ] args ) { int mtrx [ ] [ ] = { { 10 , 11 , 12 , 13 , 14 } , { 15 , 16 , 17 , 18 , 19 } , { 20 , 21 , 22 , 23 , 24 } , { 25 , 26 , 27 , 28 , 29 } , { 30 , 31 , 32 , 33 , 34 } } ; traverseMatrixDiagonally ( mtrx , 0 , 0 , 5 , 5 ) ; } }


"Tree Isomorphism Problem | A binary tree node has data , pointer to left and right children ; Given a binary tree , print its nodes in reverse level order ; Both roots are NULL , trees isomorphic by definition ; Exactly one of the n1 and n2 is NULL , trees not isomorphic ; There are two possible cases for n1 and n2 to be isomorphic Case 1 : The subtrees rooted at these nodes have NOT been " Flipped " . Both of these subtrees have to be isomorphic . Case 2 : The subtrees rooted at these nodes have been " Flipped " ; Driver program to test above functions ; Let us create trees shown in above diagram"
How can the above be solved in Java?

class Node { int data ; Node left , right ; Node ( int item ) { data = item ; left = right ; } } class BinaryTree { Node root1 , root2 ; boolean isIsomorphic ( Node n1 , Node n2 ) { if ( n1 == null && n2 == null ) return true ; if ( n1 == null n2 == null ) return false ; if ( n1 . data != n2 . data ) return false ; return ( isIsomorphic ( n1 . left , n2 . left ) && isIsomorphic ( n1 . right , n2 . right ) ) || ( isIsomorphic ( n1 . left , n2 . right ) && isIsomorphic ( n1 . right , n2 . left ) ) ; } public static void main ( String args [ ] ) { BinaryTree tree = new BinaryTree ( ) ; tree . root1 = new Node ( 1 ) ; tree . root1 . left = new Node ( 2 ) ; tree . root1 . right = new Node ( 3 ) ; tree . root1 . left . left = new Node ( 4 ) ; tree . root1 . left . right = new Node ( 5 ) ; tree . root1 . right . left = new Node ( 6 ) ; tree . root1 . left . right . left = new Node ( 7 ) ; tree . root1 . left . right . right = new Node ( 8 ) ; tree . root2 = new Node ( 1 ) ; tree . root2 . left = new Node ( 3 ) ; tree . root2 . right = new Node ( 2 ) ; tree . root2 . right . left = new Node ( 4 ) ; tree . root2 . right . right = new Node ( 5 ) ; tree . root2 . left . right = new Node ( 6 ) ; tree . root2 . right . right . left = new Node ( 8 ) ; tree . root2 . right . right . right = new Node ( 7 ) ; if ( tree . isIsomorphic ( tree . root1 , tree . root2 ) == true ) System . out . println ( " Yes " ) ; else System . out . println ( " No " ) ; } }


"Tree Sort | Java program to implement Tree Sort ; Class containing left and right child of current node and key value ; Root of BST ; Constructor ; This method mainly calls insertRec ( ) ; A recursive function to insert a new key in BST ; If the tree is empty , return a new node ; Otherwise , recur down the tree ; return the root ; A function to do inorder traversal of BST ; Driver Code"
How can the above be solved in Java?

class GFG { class Node { int key ; Node left , right ; public Node ( int item ) { key = item ; left = right = null ; } } Node root ; GFG ( ) { root = null ; } void insert ( int key ) { root = insertRec ( root , key ) ; } Node insertRec ( Node root , int key ) { if ( root == null ) { root = new Node ( key ) ; return root ; } if ( key < root . key ) root . left = insertRec ( root . left , key ) ; else if ( key > root . key ) root . right = insertRec ( root . right , key ) ; return root ; } void inorderRec ( Node root ) { if ( root != null ) { inorderRec ( root . left ) ; System . out . print ( root . key + " ▁ " ) ; inorderRec ( root . right ) ; } } void treeins ( int arr [ ] ) { for ( int i = 0 ; i < arr . length ; i ++ ) { insert ( arr [ i ] ) ; } } public static void main ( String [ ] args ) { GFG tree = new GFG ( ) ; int arr [ ] = { 5 , 4 , 7 , 2 , 11 } ; tree . treeins ( arr ) ; tree . inorderRec ( tree . root ) ; } }


"Tree Traversals ( Inorder , Preorder and Postorder ) | Class containing left and right child of current node and key value ; Root of Binary Tree ; Given a binary tree , print its nodes according to the " bottom - up " postorder traversal . ; first recur on left subtree ; then recur on right subtree ; now deal with the node ; Given a binary tree , print its nodes in inorder ; first recur on left child ; then print the data of node ; now recur on right child ; Given a binary tree , print its nodes in preorder ; first print data of node ; then recur on left sutree ; now recur on right subtree ; Wrappers over above recursive functions ; Driver method"
How can the above be solved in Java?

class Node { int key ; Node left , right ; public Node ( int item ) { key = item ; left = right = null ; } } class BinaryTree { Node root ; BinaryTree ( ) { root = null ; } void printPostorder ( Node node ) { if ( node == null ) return ; printPostorder ( node . left ) ; printPostorder ( node . right ) ; System . out . print ( node . key + " ▁ " ) ; } void printInorder ( Node node ) { if ( node == null ) return ; printInorder ( node . left ) ; System . out . print ( node . key + " ▁ " ) ; printInorder ( node . right ) ; } void printPreorder ( Node node ) { if ( node == null ) return ; System . out . print ( node . key + " ▁ " ) ; printPreorder ( node . left ) ; printPreorder ( node . right ) ; } void printPostorder ( ) { printPostorder ( root ) ; } void printInorder ( ) { printInorder ( root ) ; } void printPreorder ( ) { printPreorder ( 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 ( 3 ) ; tree . root . left . left = new Node ( 4 ) ; tree . root . left . right = new Node ( 5 ) ; System . out . println ( " Preorder ▁ traversal ▁ of ▁ binary ▁ tree ▁ is ▁ " ) ; tree . printPreorder ( ) ; System . out . println ( " Inorder traversal of binary tree is "); tree . printInorder ( ) ; System . out . println ( " Postorder traversal of binary tree is "); tree . printPostorder ( ) ; } }


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

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


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

class GFG { public static int triacontakaidigonNum ( int n ) { return ( 30 * n * n - 28 * n ) / 2 ; } public static void main ( String [ ] args ) { int n = 3 ; System . out . println ( "3rd ▁ triacontakaidigon ▁ Number ▁ is ▁ = ▁ " + triacontakaidigonNum ( n ) ) ; } }


"Trial division Algorithm for Prime Factorization | Java implementation of Trial Division Algorithm ; Function to check if a number is a prime number or not ; Initializing with the value 2 from where the number is checked ; Computing the square root of the number N ; While loop till the square root of N ; If any of the numbers between [ 2 , sqrt ( N ) ] is a factor of N Then the number is composite ; If none of the numbers is a factor , then it is a prime number ; Driver Code ; To check if a number is a prime or not"
How can the above be solved in Java?

import java . util . * ; class GFG { static int TrialDivision ( int N ) { int i = 2 ; int k = ( int ) Math . ceil ( Math . sqrt ( N ) ) ; while ( i <= k ) { if ( N % i == 0 ) return 0 ; i += 1 ; } return 1 ; } public static void main ( String [ ] args ) { int N = 49 ; int p = TrialDivision ( N ) ; if ( p != 0 ) System . out . print ( " Prime " ) ; else System . out . print ( " Composite " ) ; } }


"Triangle of numbers arising from Gilbreath 's conjecture | Java code for printing the Triangle of numbers arising from Gilbreath 's conjecture ; Check whether the number is prime or not ; Set the 0 th row of the matrix with c primes from 0 , 0 to 0 , c - 1 ; Find the n , k term of matrix of Gilbreath 's conjecture ; recursively find ; store the ans ; Print first n terms of Gilbreath sequence successive absolute differences of primes read by antidiagonals upwards . ; map to store the matrix and hash to check if the element is present or not ; set the primes of first row ; print the Gilbreath number ; increase the count ; anti diagonal upwards ; Driver code"
How can the above be solved in Java?

import java . util . * ; public class GFG { static boolean is_Prime ( int n ) { if ( n < 2 ) return false ; for ( int i = 2 ; i <= Math . sqrt ( n ) ; i ++ ) if ( n % i == 0 ) return false ; return true ; } static void set_primes ( HashMap < Integer , HashMap < Integer , Integer > > mp , HashMap < Integer , HashMap < Integer , Integer > > hash , int c ) { int count = 0 ; for ( int i = 2 ; count < c ; i ++ ) { if ( is_Prime ( i ) ) { if ( ! mp . containsKey ( 0 ) ) { mp . put ( 0 , new HashMap < Integer , Integer > ( ) ) ; } if ( ! mp . get ( 0 ) . containsKey ( count ) ) { mp . get ( 0 ) . put ( count , i ) ; } else { mp . get ( 0 ) . put ( count , i ) ; } count ++ ; if ( ! hash . containsKey ( 0 ) ) { hash . put ( 0 , new HashMap < Integer , Integer > ( ) ) ; } if ( ! hash . get ( 0 ) . containsKey ( count - 1 ) ) { hash . get ( 0 ) . put ( count - 1 , 1 ) ; } else { hash . get ( 0 ) . put ( count - 1 , 1 ) ; } } } } static int Gilbreath ( HashMap < Integer , HashMap < Integer , Integer > > mp , HashMap < Integer , HashMap < Integer , Integer > > hash , int n , int k ) { if ( hash . containsKey ( n ) && hash . get ( n ) . containsKey ( k ) && hash . get ( n ) . get ( k ) != 0 ) return mp . get ( n ) . get ( k ) ; int ans = Math . abs ( Gilbreath ( mp , hash , n - 1 , k + 1 ) - Gilbreath ( mp , hash , n - 1 , k ) ) ; if ( ! mp . containsKey ( n ) ) { mp . put ( n , new HashMap < Integer , Integer > ( ) ) ; } mp . get ( n ) . put ( k , ans ) ; return ans ; } static void solve ( int n ) { int i = 0 , j = 0 , count = 0 ; HashMap < Integer , HashMap < Integer , Integer > > mp = new HashMap < Integer , HashMap < Integer , Integer > > ( ) ; HashMap < Integer , HashMap < Integer , Integer > > hash = new HashMap < Integer , HashMap < Integer , Integer > > ( ) ; set_primes ( mp , hash , 100 ) ; while ( count < n ) { System . out . print ( Gilbreath ( mp , hash , i , j ) + " , ▁ " ) ; count ++ ; i -- ; j ++ ; if ( i < 0 ) { i = j ; j = 0 ; } } } public static void main ( String [ ] args ) { int n = 15 ; solve ( n ) ; } }


"Triangle with no point inside | Java program to find triangle with no point inside ; method to get square of distance between ( x1 , y1 ) and ( x2 , y2 ) ; Method prints points which make triangle with no point inside ; any point can be chosen as first point of triangle ; choose nearest point as second point of triangle ; Get distance from first point and choose nearest one ; Pick third point by finding the second closest point with different slope . ; if already chosen point then skip them ; get distance from first point ; here cross multiplication is compared instead of division comparison ; Driver code"
How can the above be solved in Java?

import java . io . * ; class GFG { static int getDistance ( int x1 , int y1 , int x2 , int y2 ) { return ( x2 - x1 ) * ( x2 - x1 ) + ( y2 - y1 ) * ( y2 - y1 ) ; } static void triangleWithNoPointInside ( int points [ ] [ ] , int N ) { int first = 0 ; int second = 0 ; int third = 0 ; int minD = Integer . MAX_VALUE ; for ( int i = 0 ; i < N ; i ++ ) { if ( i == first ) continue ; int d = getDistance ( points [ i ] [ 0 ] , points [ i ] [ 1 ] , points [ first ] [ 0 ] , points [ first ] [ 1 ] ) ; if ( minD > d ) { minD = d ; second = i ; } } minD = Integer . MAX_VALUE ; for ( int i = 0 ; i < N ; i ++ ) { if ( i == first i == second ) continue ; int d = getDistance ( points [ i ] [ 0 ] , points [ i ] [ 1 ] , points [ first ] [ 0 ] , points [ first ] [ 1 ] ) ; if ( ( points [ i ] [ 0 ] - points [ first ] [ 0 ] ) * ( points [ second ] [ 1 ] - points [ first ] [ 1 ] ) != ( points [ second ] [ 0 ] - points [ first ] [ 0 ] ) * ( points [ i ] [ 1 ] - points [ first ] [ 1 ] ) && minD > d ) { minD = d ; third = i ; } } System . out . println ( points [ first ] [ 0 ] + " , ▁ " + points [ first ] [ 1 ] ) ; System . out . println ( points [ second ] [ 0 ] + " , ▁ " + points [ second ] [ 1 ] ) ; System . out . println ( points [ third ] [ 0 ] + " , ▁ " + points [ third ] [ 1 ] ) ; } public static void main ( String [ ] args ) { int points [ ] [ ] = { { 0 , 0 } , { 0 , 2 } , { 2 , 0 } , { 2 , 2 } , { 1 , 1 } } ; int N = points . length ; triangleWithNoPointInside ( points , N ) ; } }


"Triangular Matchstick Number | Java program to find X - th triangular matchstick number ; Driver code"
How can the above be solved in Java?

public class TriangularPyramidNumber { public static int numberOfSticks ( int x ) { return ( 3 * x * ( x + 1 ) ) / 2 ; } public static void main ( String [ ] args ) { System . out . println ( numberOfSticks ( 7 ) ) ; } }


"Triangular Numbers | Java program to check if a number is a triangular number using quadratic equation . ; Returns true if num is triangular ; Considering the equation n * ( n + 1 ) / 2 = num The equation is : a ( n ^ 2 ) + bn + c = 0 "; ; Find roots of equation ; checking if root1 is natural ; checking if root2 is natural ; Driver code"
How can the above be solved in Java?

import java . io . * ; class GFG { static boolean isTriangular ( int num ) { if ( num < 0 ) return false ; int c = ( - 2 * num ) ; int b = 1 , a = 1 ; int d = ( b * b ) - ( 4 * a * c ) ; if ( d < 0 ) return false ; float root1 = ( - b + ( float ) Math . sqrt ( d ) ) / ( 2 * a ) ; float root2 = ( - b - ( float ) Math . sqrt ( d ) ) / ( 2 * a ) ; if ( root1 > 0 && Math . floor ( root1 ) == root1 ) return true ; if ( root2 > 0 && Math . floor ( root2 ) == root2 ) return true ; return false ; } public static void main ( String [ ] args ) { int num = 55 ; if ( isTriangular ( num ) ) System . out . println ( " The ▁ number ▁ is " + " ▁ a ▁ triangular ▁ number " ) ; else System . out . println ( " The ▁ number ▁ " + " is ▁ NOT ▁ a ▁ triangular ▁ number " ) ; } }


"Triangular Numbers | Java program to check if a number is a triangular number using simple approach ; Returns true if ' num ' is triangular , else false ; Base case ; A Triangular number must be sum of first n natural numbers ; Driver code"
How can the above be solved in Java?

class GFG { static boolean isTriangular ( int num ) { if ( num < 0 ) return false ; int sum = 0 ; for ( int n = 1 ; sum <= num ; n ++ ) { sum = sum + n ; if ( sum == num ) return true ; } return false ; } public static void main ( String [ ] args ) { int n = 55 ; if ( isTriangular ( n ) ) System . out . print ( " The ▁ number ▁ " + " is ▁ a ▁ triangular ▁ number " ) ; else System . out . print ( " The ▁ number " + " ▁ is ▁ NOT ▁ a ▁ triangular ▁ number " ) ; } }


"Tribonacci Numbers | A DP based Java program to print first n Tribonacci numbers . ; Driver code"
How can the above be solved in Java?

import java . io . * ; class GFG { static void printTrib ( int n ) { int dp [ ] = new int [ n ] ; dp [ 0 ] = dp [ 1 ] = 0 ; dp [ 2 ] = 1 ; for ( int i = 3 ; i < n ; i ++ ) dp [ i ] = dp [ i - 1 ] + dp [ i - 2 ] + dp [ i - 3 ] ; for ( int i = 0 ; i < n ; i ++ ) System . out . print ( dp [ i ] + " ▁ " ) ; } public static void main ( String args [ ] ) { int n = 10 ; printTrib ( n ) ; } }


"Tribonacci Numbers | A space optimized based Java program to print first n Tribinocci numbers . ; Initialize first three numbers ; Loop to add previous three numbers for each number starting from 3 and then assign first , second , third to second , third , and curr to third respectively ; Driver code"
How can the above be solved in Java?

import java . io . * ; class GFG { static void printTrib ( int n ) { if ( n < 1 ) return ; int first = 0 , second = 0 ; int third = 1 ; System . out . print ( first + " ▁ " ) ; if ( n > 1 ) System . out . print ( second + " ▁ " ) ; if ( n > 2 ) System . out . print ( second + " ▁ " ) ; for ( int i = 3 ; i < n ; i ++ ) { int curr = first + second + third ; first = second ; second = third ; third = curr ; System . out . print ( curr + " ▁ " ) ; } } public static void main ( String args [ ] ) { int n = 10 ; printTrib ( n ) ; } }


"Tribonacci Numbers | Java Program to print first n tribonacci numbers Matrix Multiplication function for 3 * 3 matrix ; Recursive function to raise the matrix T to the power n ; base condition . ; recursively call to square the matrix ; calculating square of the matrix T ; if n is odd multiply it one time with M ; base condition ; T [ 0 ] [ 0 ] contains the tribonacci number so return it ; Driver Code"
How can the above be solved in Java?


"Trimorphic Number | Java program to check if a number is Trimorphic ; Function to check Trimorphic number ; Store the cube ; Start Comparing digits ; Return false , if any digit of N doesn ' t ▁ match ▁ with ▁ ▁ its ▁ cube ' s digits from last ; Reduce N and cube ; Driver code"
How can the above be solved in Java?

class GFG { static boolean isTrimorphic ( int N ) { int cube = N * N * N ; while ( N > 0 ) { if ( N % 10 != cube % 10 ) return false ; N /= 10 ; cube /= 10 ; } return true ; } public static void main ( String [ ] args ) { int N = 24 ; if ( isTrimorphic ( N ) == true ) System . out . println ( " trimorphic " ) ; else System . out . println ( " not ▁ trimorphic " ) ; } }


"Trimorphic Number | Java program to find nth Trimorphic number ; Functions to find nth Trimorphic number ; Comparing the digits ; Return false , if any digit of num doesn ' t ▁ ▁ match ▁ with ▁ its ▁ cube ' s digits from last ; Reduce num and cube ; Check in max int size ; check number is Trimorphic or not ; if counter is equal to the n then return nth number ; Driver code"
How can the above be solved in Java?

class GFG { static int INT_MAX = 2147483647 ; static boolean checkTrimorphic ( int num ) { int cube = num * num * num ; while ( num > 0 ) { if ( num % 10 != cube % 10 ) return false ; num /= 10 ; cube /= 10 ; } return true ; } static int nthTrimorphic ( int n ) { int count = 0 ; for ( int i = 0 ; i < INT_MAX ; i ++ ) { if ( checkTrimorphic ( i ) ) count ++ ; if ( count == n ) return i ; } return - 1 ; } public static void main ( String [ ] args ) { int n = 9 ; System . out . println ( nthTrimorphic ( n ) ) ; } }


"Triplet with no element divisible by 3 and sum N | Java program to print a , b and c such that a + b + c = N ; Function to print a , b and c ; check if n - 2 is divisible by 3 or not ; Driver Code"
How can the above be solved in Java?

class GFG { static void printCombination ( int n ) { System . out . print ( 1 + " ▁ " ) ; if ( ( n - 2 ) % 3 == 0 ) System . out . print ( 2 + " ▁ " + ( n - 3 ) ) ; else System . out . print ( 1 + " ▁ " + ( n - 2 ) ) ; } public static void main ( String [ ] args ) { int n = 233 ; printCombination ( n ) ; } }


"Triplet with no element divisible by 3 and sum N | Java program to print a , b and c such that a + b + c = N ; Function to print a , b and c ; first loop ; check for 1 st number ; second loop ; check for 2 nd number ; third loop ; Check for 3 rd number ; Driver Code"
How can the above be solved in Java?

import java . io . * ; class GFG { static void printCombination ( int n ) { for ( int i = 1 ; i < n ; i ++ ) { if ( i % 3 != 0 ) { for ( int j = 1 ; j < n ; j ++ ) { if ( j % 3 != 0 ) { for ( int k = 1 ; k < n ; k ++ ) { if ( k % 3 != 0 && ( i + j + k ) == n ) { System . out . println ( i + " ▁ " + j + " ▁ " + k ) ; return ; } } } } } } } public static void main ( String [ ] args ) { int n = 233 ; printCombination ( n ) ; } }


"Triplets in array with absolute difference less than k | Java program to count triplets with difference less than k . ; Return the lower bound i . e smallest index of element having value greater or equal to value ; Return the number of triplet indices satisfies the three constraints ; sort the array ; for each element from index 2 to n - 1. ; finding the lower bound of arr [ i ] - k . ; If there are at least two elements between lower bound and current element . ; increment the count by lb - i C 2. ; Driver Code"
How can the above be solved in Java?

import java . io . * ; import java . util . * ; class GFG { static int binary_lower ( int value , int arr [ ] , int n ) { int start = 0 ; int end = n - 1 ; int ans = - 1 ; int mid ; while ( start <= end ) { mid = ( start + end ) / 2 ; if ( arr [ mid ] >= value ) { end = mid - 1 ; ans = mid ; } else { start = mid + 1 ; } } return ans ; } static int countTriplet ( int arr [ ] , int n , int k ) { int count = 0 ; Arrays . sort ( arr ) ; for ( int i = 2 ; i < n ; i ++ ) { int cur = binary_lower ( arr [ i ] - k , arr , n ) ; if ( cur <= i - 2 ) { count += ( ( i - cur ) * ( i - cur - 1 ) ) / 2 ; } } return count ; } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 1 , 2 , 2 , 3 } ; int k = 1 ; int n = arr . length ; System . out . println ( countTriplet ( arr , n , k ) ) ; } }


"Tug of War | Java program for Tug of war ; function that tries every possible solution by calling itself recursively ; checks whether the it is going out of bound ; checks that the numbers of elements left are not less than the number of elements required to form the solution ; consider the cases when current element is not included in the solution ; add the current element to the solution ; checks if a solution is formed ; checks if the solution formed is better than the best solution so far ; consider the cases where current element is included in the solution ; removes current element before returning to the caller of this function ; main function that generate an arr ; the boolean array that contains the inclusion and exclusion of an element in current set . The number excluded automatically form the other set ; The inclusion / exclusion array for final solution ; Find the solution using recursive function TOWUtil ( ) ; Print the solution ; Driver program to test above functions"
How can the above be solved in Java?

import java . util . * ; import java . lang . * ; import java . io . * ; class TugOfWar { public int min_diff ; void TOWUtil ( int arr [ ] , int n , boolean curr_elements [ ] , int no_of_selected_elements , boolean soln [ ] , int sum , int curr_sum , int curr_position ) { if ( curr_position == n ) return ; if ( ( n / 2 - no_of_selected_elements ) > ( n - curr_position ) ) return ; TOWUtil ( arr , n , curr_elements , no_of_selected_elements , soln , sum , curr_sum , curr_position + 1 ) ; no_of_selected_elements ++ ; curr_sum = curr_sum + arr [ curr_position ] ; curr_elements [ curr_position ] = true ; if ( no_of_selected_elements == n / 2 ) { if ( Math . abs ( sum / 2 - curr_sum ) < min_diff ) { min_diff = Math . abs ( sum / 2 - curr_sum ) ; for ( int i = 0 ; i < n ; i ++ ) soln [ i ] = curr_elements [ i ] ; } } else { TOWUtil ( arr , n , curr_elements , no_of_selected_elements , soln , sum , curr_sum , curr_position + 1 ) ; } curr_elements [ curr_position ] = false ; } void tugOfWar ( int arr [ ] ) { int n = arr . length ; boolean [ ] curr_elements = new boolean [ n ] ; boolean [ ] soln = new boolean [ n ] ; min_diff = Integer . MAX_VALUE ; int sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) { sum += arr [ i ] ; curr_elements [ i ] = soln [ i ] = false ; } TOWUtil ( arr , n , curr_elements , 0 , soln , sum , 0 , 0 ) ; System . out . print ( " The ▁ first ▁ subset ▁ is : ▁ " ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( soln [ i ] == true ) System . out . print ( arr [ i ] + " ▁ " ) ; } System . out . print ( " The second subset is : "); for ( int i = 0 ; i < n ; i ++ ) { if ( soln [ i ] == false ) System . out . print ( arr [ i ] + " ▁ " ) ; } } public static void main ( String [ ] args ) { int arr [ ] = { 23 , 45 , - 34 , 12 , 0 , 98 , - 99 , 4 , 189 , - 1 , 4 } ; TugOfWar a = new TugOfWar ( ) ; a . tugOfWar ( arr ) ; } }


"Turn off the rightmost set bit | Java program to unset the rightmost set bit of an integer . ; unsets the rightmost set bit of n and returns the result ; Driver code"
How can the above be solved in Java?

class GFG { static int fun ( int n ) { return n & ( n - 1 ) ; } public static void main ( String arg [ ] ) { int n = 7 ; System . out . print ( " The ▁ number ▁ after ▁ unsetting ▁ " + " the ▁ rightmost ▁ set ▁ bit ▁ " + fun ( n ) ) ; } }


"Twin Prime Numbers between 1 and n | Java program to print all Twin Prime Numbers using Sieve of Eratosthenes ; 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 ; to check for twin prime numbers display th twin prime ; Driver Program to test above function ; Calling the function"
How can the above be solved in Java?

import java . io . * ; class GFG { static void printTwinPrime ( int n ) { boolean prime [ ] = new boolean [ n + 1 ] ; for ( int i = 0 ; i <= n ; i ++ ) prime [ i ] = true ; for ( int p = 2 ; p * p <= n ; p ++ ) { if ( prime [ p ] == true ) { for ( int i = p * 2 ; i <= n ; i += p ) prime [ i ] = false ; } } for ( int i = 2 ; i <= n - 2 ; i ++ ) { if ( prime [ i ] == true && prime [ i + 2 ] == true ) System . out . print ( " ▁ ( " + i + " , ▁ " + ( i + 2 ) + " ) " ) ; } } public static void main ( String args [ ] ) { int n = 25 ; printTwinPrime ( n ) ; } }


"Twin Prime Numbers | JAVA Code for Twin Prime Numbers ; Please refer below post for details of this function https : goo . gl / Wv3fGv ; Corner cases ; This is checked so that we can skip middle five numbers in below loop ; Returns true if n1 and n2 are twin primes ; Driver program to test above function"
How can the above be solved in Java?

import java . util . * ; class GFG { static boolean isPrime ( int n ) { if ( n <= 1 ) return false ; if ( n <= 3 ) return true ; if ( n % 2 == 0 n % 3 == 0 ) return false ; for ( int i = 5 ; i * i <= n ; i = i + 6 ) if ( n % i == 0 || n % ( i + 2 ) == 0 ) return false ; return true ; } static boolean twinPrime ( int n1 , int n2 ) { return ( isPrime ( n1 ) && isPrime ( n2 ) && Math . abs ( n1 - n2 ) == 2 ) ; } public static void main ( String [ ] args ) { int n1 = 11 , n2 = 13 ; if ( twinPrime ( n1 , n2 ) ) System . out . println ( " Twin ▁ Prime " ) ; else System . out . println ( " Not ▁ Twin ▁ Prime " ) ; } }


"Twin Pythagorean triplets in an array | Java program for the above approach ; Function to check if there exist a twin pythagorean triplet in the given array ; Loop to check if there is a Pythagorean triplet in the array ; Check if there is consecutive triple ; Calculate square of array elements ; Driver Code ; Given array arr [ ] ; Function call"
How can the above be solved in Java?

import java . util . * ; class GFG { static boolean isTriplet ( int ar [ ] , int n ) { for ( int i = 0 ; i < n ; i ++ ) { for ( int j = i + 1 ; j < n ; j ++ ) { for ( int k = j + 1 ; k < n ; k ++ ) { if ( Math . abs ( ar [ i ] - ar [ j ] ) == 1 || Math . abs ( ar [ j ] - ar [ k ] ) == 1 || Math . abs ( ar [ i ] - ar [ k ] ) == 1 ) { int x = ar [ i ] * ar [ i ] , y = ar [ j ] * ar [ j ] , z = ar [ k ] * ar [ k ] ; if ( x == y + z y == x + z z == x + y ) return true ; } } } } return false ; } public static void main ( String [ ] args ) { int arr [ ] = { 3 , 1 , 4 , 6 , 5 } ; int ar_size = arr . length ; if ( isTriplet ( arr , ar_size ) ) System . out . print ( " Yes " ) ; else System . out . print ( " No " ) ; } }


"Two Balls Reachability Game | Java program to Find is it possible to have X white and Y black balls at the end . ; Recursive function to return gcd of a and b ; Function returns if it 's possible to have X white and Y black balls or not. ; Finding gcd of ( x , y ) and ( a , b ) ; If gcd is same , it 's always  possible to reach (x, y) ; Here it 's never possible  if gcd is not same ; Driver code"
How can the above be solved in Java?

 import java . io . * ; class GFG { static int gcd ( int a , int b ) { if ( b == 0 ) return a ; return gcd ( b , a % b ) ; } static void IsPossible ( int a , int b , int x , int y ) { int g = gcd ( x , y ) ; int initial = gcd ( a , b ) ; if ( initial == g ) { System . out . print ( "POSSIBLE
"); } else { System . out . print ( "NOT POSSIBLE
"); } } public static void main ( String args [ ] ) { int A = 1 , B = 2 , X = 4 , Y = 11 ; IsPossible ( A , B , X , Y ) ; A = 2 ; B = 2 ; X = 3 ; Y = 6 ; IsPossible ( A , B , X , Y ) ; } }


"Two Clique Problem ( Check if Graph can be divided in two Cliques ) | Java program to find out whether a given graph can be converted to two Cliques or not . ; This function returns true if subgraph reachable from src is Bipartite or not . ; Create a queue ( FIFO ) of vertex numbers and enqueue source vertex for BFS traversal ; Run while there are vertices in queue ( Similar to BFS ) ; Dequeue a vertex from queue ; Find all non - colored adjacent vertices ; An edge from u to v exists and destination v is not colored ; Assign alternate color to this adjacent v of u ; An edge from u to v exists and destination v is colored with same color as u ; If we reach here , then all adjacent vertices can be colored with alternate color ; Returns true if a Graph G [ ] [ ] is Bipartite or not . Note that G may not be connected . ; Create a color array to store colors assigned to all veritces . Vertex number is used as index in this array . The value ' - 1' of colorArr [ i ] is used to indicate that no color is assigned to vertex ' i ' . The value 1 is used to indicate first color is assigned and value 0 indicates second color is assigned . ; One by one check all not yet colored vertices . ; Returns true if G can be divided into two Cliques , else false . ; Find complement of G [ ] [ ] All values are complemented except diagonal ones ; Return true if complement is Bipartite else false . ; Driver program to test above function"
How can the above be solved in Java?

import java . util . ArrayDeque ; import java . util . Deque ; class GFG { static int V = 5 ; static boolean isBipartiteUtil ( int G [ ] [ ] , int src , int colorArr [ ] ) { colorArr [ src ] = 1 ; Deque < Integer > q = new ArrayDeque < > ( ) ; q . push ( src ) ; while ( ! q . isEmpty ( ) ) { int u = q . peek ( ) ; q . pop ( ) ; for ( int v = 0 ; v < V ; ++ v ) { if ( G [ u ] [ v ] == - 1 && colorArr [ v ] == - 1 ) { colorArr [ v ] = 1 - colorArr [ u ] ; q . push ( v ) ; } else if ( G [ u ] [ v ] == colorArr [ u ] && colorArr [ v ] == colorArr [ u ] ) return false ; } } return true ; } static boolean isBipartite ( int G [ ] [ ] ) { int colorArr [ ] = new int [ V ] ; for ( int i = 0 ; i < V ; ++ i ) colorArr [ i ] = - 1 ; for ( int i = 0 ; i < V ; i ++ ) if ( colorArr [ i ] == - 1 ) if ( isBipartiteUtil ( G , i , colorArr ) == false ) return false ; return true ; } static boolean canBeDividedinTwoCliques ( int G [ ] [ ] ) { int GC [ ] [ ] = new int [ V ] [ V ] ; for ( int i = 0 ; i < V ; i ++ ) for ( int j = 0 ; j < V ; j ++ ) GC [ i ] [ j ] = ( i != j ) ? - GC [ i ] [ j ] : 0 ; return isBipartite ( GC ) ; } public static void main ( String [ ] args ) { int G [ ] [ ] = { { 0 , 1 , 1 , 1 , 0 } , { 1 , 0 , 1 , 0 , 0 } , { 1 , 1 , 0 , 0 , 0 } , { 0 , 1 , 0 , 0 , 1 } , { 0 , 0 , 0 , 1 , 0 } } ; if ( canBeDividedinTwoCliques ( G ) ) System . out . println ( " Yes " ) ; else System . out . println ( " No " ) ; } }


"Two Dimensional Difference Array | Java program to implement the above approach ; Function to initialize the difference array ; Function to add k to the specified submatrix ( r1 , c1 ) to ( r2 , c2 ) ; Function to print the modified array ; Function to perform the given queries ; Difference array ; Function to initialize the difference array ; Count of queries ; Perform Queries ; Driver Code ; Given Matrix ; Given Queries"
How can the above be solved in Java?

import java . util . * ; class GFG { static int N = 3 ; static int M = 3 ; static void intializeDiff ( int D [ ] [ ] , int A [ ] [ ] ) { for ( int i = 0 ; i < N ; i ++ ) { D [ i ] [ 0 ] = A [ i ] [ 0 ] ; D [ i ] [ M ] = 0 ; } for ( int i = 0 ; i < N ; i ++ ) { for ( int j = 1 ; j < M ; j ++ ) D [ i ] [ j ] = A [ i ] [ j ] - A [ i ] [ j - 1 ] ; } } static void update ( int D [ ] [ ] , int k , int r1 , int c1 , int r2 , int c2 ) { for ( int i = r1 ; i <= r2 ; i ++ ) { D [ i ] [ c1 ] += k ; D [ i ] [ c2 + 1 ] -= k ; } } static void printArray ( int A [ ] [ ] , int D [ ] [ ] ) { for ( int i = 0 ; i < N ; i ++ ) { for ( int j = 0 ; j < M ; j ++ ) { if ( j == 0 ) A [ i ] [ j ] = D [ i ] [ j ] ; else A [ i ] [ j ] = D [ i ] [ j ] + A [ i ] [ j - 1 ] ; System . out . print ( A [ i ] [ j ] + " ▁ " ) ; } System . out . println ( ) ; } } static void performQueries ( int A [ ] [ ] , Vector < Vector < Integer > > Queries ) { int D [ ] [ ] = new int [ N ] [ M + 1 ] ; intializeDiff ( D , A ) ; int Q = Queries . size ( ) ; for ( int i = 0 ; i < Q ; i ++ ) { update ( D , Queries . get ( i ) . get ( 0 ) , Queries . get ( i ) . get ( 1 ) , Queries . get ( i ) . get ( 2 ) , Queries . get ( i ) . get ( 3 ) , Queries . get ( i ) . get ( 4 ) ) ; } printArray ( A , D ) ; } public static void main ( String [ ] args ) { int A [ ] [ ] = { { 1 , 2 , 3 } , { 1 , 1 , 0 } , { 4 , - 2 , 2 } } ; Vector < Vector < Integer > > Queries = new Vector < Vector < Integer > > ( ) ; Vector < Integer > list1 = new Vector < Integer > ( ) ; list1 . add ( 2 ) ; list1 . add ( 0 ) ; list1 . add ( 0 ) ; list1 . add ( 1 ) ; list1 . add ( 1 ) ; Vector < Integer > list2 = new Vector < Integer > ( ) ; list2 . add ( - 1 ) ; list2 . add ( 1 ) ; list2 . add ( 0 ) ; list2 . add ( 2 ) ; list2 . add ( 2 ) ; Queries . add ( list1 ) ; Queries . add ( list2 ) ; performQueries ( A , Queries ) ; } }


"Two Pointers Technique |  ; Two pointer technique based solution to find if there is a pair in A [ 0. . N - 1 ] with a given sum . ; represents first pointer ; represents second pointer ; If we find a pair ; If sum of elements at current pointers is less , we move towards higher values by doing i ++ ; If sum of elements at current pointers is more , we move towards lower values by doing j -- ; Driver code ; array declaration ; value to search ; size of the array ; Function call"
How can the above be solved in Java?

import java . io . * ; class GFG { public static int isPairSum ( int A [ ] , int N , int X ) { int i = 0 ; int j = N - 1 ; while ( i < j ) { if ( A [ i ] + A [ j ] == X ) return 1 ; else if ( A [ i ] + A [ j ] < X ) i ++ ; else j -- ; } return 0 ; } public static void main ( String [ ] args ) { int arr [ ] = { 3 , 5 , 9 , 2 , 8 , 10 , 11 } ; int val = 17 ; int arrSize = arr . length ; System . out . println ( isPairSum ( arr , arrSize , val ) ) ; } }


"Two Pointers Technique | Naive solution to find if there is a pair in A [ 0. . N - 1 ] with given sum . ; as equal i and j means same element ; pair exists ; as the array is sorted ; No pair found with given sum . ; Driver code ; Function call"
How can the above be solved in Java?

import java . io . * ; class GFG { private static int isPairSum ( int A [ ] , int N , int X ) { for ( int i = 0 ; i < N ; i ++ ) { for ( int j = 0 ; j < N ; j ++ ) { if ( i == j ) continue ; if ( A [ i ] + A [ j ] == X ) return true ; if ( A [ i ] + A [ j ] > X ) break ; } } return 0 ; } } public static void main ( String [ ] args ) { int arr [ ] = { 3 , 5 , 9 , 2 , 8 , 10 , 11 } ; int val = 17 ; System . out . println ( isPairSum ( arr , arr . length , val ) ) ; }


"Two elements whose sum is closest to zero | Java code to find Two elements whose sum is closest to zero ; Array should have at least two elements ; Initialization of values ; main function"
How can the above be solved in Java?

import java . util . * ; import java . lang . * ; class Main { static void minAbsSumPair ( int arr [ ] , int arr_size ) { int inv_count = 0 ; int l , r , min_sum , sum , min_l , min_r ; if ( arr_size < 2 ) { System . out . println ( " Invalid ▁ Input " ) ; return ; } min_l = 0 ; min_r = 1 ; min_sum = arr [ 0 ] + arr [ 1 ] ; for ( l = 0 ; l < arr_size - 1 ; l ++ ) { for ( r = l + 1 ; r < arr_size ; r ++ ) { sum = arr [ l ] + arr [ r ] ; if ( Math . abs ( min_sum ) > Math . abs ( sum ) ) { min_sum = sum ; min_l = l ; min_r = r ; } } } System . out . println ( " ▁ The ▁ two ▁ elements ▁ whose ▁ " + " sum ▁ is ▁ minimum ▁ are ▁ " + arr [ min_l ] + " ▁ and ▁ " + arr [ min_r ] ) ; } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 60 , - 10 , 70 , - 80 , 85 } ; minAbsSumPair ( arr , 6 ) ; } }


"Two elements whose sum is closest to zero | Java implementation using STL ; Modified to sort by abolute values ; Absolute value shows how close it is to zero ; If found an even close value update min and store the index ; Driver code"
How can the above be solved in Java?

import java . io . * ; class GFG { static void findMinSum ( int [ ] arr , int n ) { for ( int i = 1 ; i < n ; i ++ ) { if ( ! ( Math . abs ( arr [ i - 1 ] ) < Math . abs ( arr [ i ] ) ) ) { int temp = arr [ i - 1 ] ; arr [ i - 1 ] = arr [ i ] ; arr [ i ] = temp ; } } int min = Integer . MAX_VALUE ; int x = 0 , y = 0 ; for ( int i = 1 ; i < n ; i ++ ) { if ( Math . abs ( arr [ i - 1 ] + arr [ i ] ) <= min ) { min = Math . abs ( arr [ i - 1 ] + arr [ i ] ) ; x = i - 1 ; y = i ; } } System . out . println ( " The ▁ two ▁ elements ▁ whose ▁ " + " sum ▁ is ▁ minimum ▁ are ▁ " + arr [ x ] + " ▁ and ▁ " + arr [ y ] ) ; } public static void main ( String [ ] args ) { int [ ] arr = { 1 , 60 , - 10 , 70 , - 80 , 85 } ; int n = arr . length ; findMinSum ( arr , n ) ; } }


"Two equal sum segment range queries | Java implementation of the approach ; Function to find the required prefix sum ; Function to q all the values of prefix sum array in an unordered map ; Function to check if a range can be divided into two equal parts ; To store the value of sum of entire range ; If value of sum is odd ; To store p_arr [ l - 1 ] ; If the value exists in the map ; Driver code ; prefix - sum array ; Map to store the values of prefix - sum ; Perform queries"
How can the above be solved in Java?

import java . util . * ; class GFG { static void prefixSum ( int [ ] p_arr , int [ ] arr , int n ) { p_arr [ 0 ] = arr [ 0 ] ; for ( int i = 1 ; i < n ; i ++ ) p_arr [ i ] = arr [ i ] + p_arr [ i - 1 ] ; } static void qPrefixSum ( int [ ] p_arr , int n , HashSet < Integer > q ) { for ( int i = 0 ; i < n ; i ++ ) q . add ( p_arr [ i ] ) ; } static void canDivide ( int [ ] p_arr , int n , HashSet < Integer > q , int l , int r ) { int sum ; if ( l == 0 ) sum = p_arr [ r ] ; else sum = p_arr [ r ] - p_arr [ l - 1 ] ; if ( sum % 2 == 1 ) { System . out . println ( " No " ) ; return ; } int beg = 0 ; if ( l != 0 ) beg = p_arr [ l - 1 ] ; if ( q . contains ( beg + sum / 2 ) && ( beg + sum / 2 ) != ( int ) q . toArray ( ) [ q . size ( ) - 1 ] ) System . out . println ( " Yes " ) ; else System . out . println ( " No " ) ; } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 1 , 2 , 3 } ; int n = arr . length ; int p_arr [ ] = new int [ n ] ; prefixSum ( p_arr , arr , n ) ; HashSet < Integer > q = new HashSet < > ( ) ; qPrefixSum ( p_arr , n , q ) ; canDivide ( p_arr , n , q , 0 , 1 ) ; canDivide ( p_arr , n , q , 1 , 3 ) ; canDivide ( p_arr , n , q , 1 , 2 ) ; } }


"Two nodes of a BST are swapped , correct the BST | Set | Java implementation of the above approach ; A binary tree node has data , pointer to left child and a pointer to right child ; Utility function for insertion sort ; Utility function to create a vector with inorder traversal of a binary tree ; Base cases ; Recursive call for left subtree ; Insert node into vector ; Recursive call for right subtree ; Function to exchange data for incorrect nodes ; Base cases ; Recursive call to find the node in left subtree ; Check if current node is incorrect and exchange ; Recursive call to find the node in right subtree ; Primary function to fix the two nodes ; Vector to store the inorder traversal of tree ; Function call to insert nodes into vector ; create a copy of the vector ; Sort the original vector thereby making it a valid BST 's inorder ; Traverse through both vectors and compare misplaced values in original BST ; Find the mismatched values and interchange them ; Find and exchange the data of the two nodes ; As it given only two values are wrong we don 't need to check further ; Return the root of corrected BST ; A utility function to print Inorder traversal ; Driver code"
How can the above be solved in Java?

 import java . util . ArrayList ; class GFG { static class node { int data ; node left , right ; public node ( int x ) { data = x ; left = right = null ; } } ; static void insertionSort ( ArrayList < Integer > v , int n ) { int i , key , j ; for ( i = 1 ; i < n ; i ++ ) { key = v . get ( i ) ; j = i - 1 ; while ( j >= 0 && v . get ( j ) > key ) { v . set ( j + 1 , v . get ( i ) ) ; j = j - 1 ; } v . set ( j + 1 , key ) ; } } static void inorder ( node root , ArrayList < Integer > v ) { if ( root == null ) return ; inorder ( root . left , v ) ; v . add ( root . data ) ; inorder ( root . right , v ) ; } static void find ( node root , int res , int res2 ) { if ( root == null ) { return ; } find ( root . left , res , res2 ) ; if ( root . data == res ) { root . data = res2 ; } else if ( root . data == res2 ) { root . data = res ; } find ( root . right , res , res2 ) ; } static node correctBST ( node root ) { ArrayList < Integer > v = new ArrayList < > ( ) ; inorder ( root , v ) ; ArrayList < Integer > v1 = new ArrayList < > ( v ) ; insertionSort ( v , v . size ( ) ) ; for ( int i = 0 ; i < v . size ( ) ; i ++ ) { if ( v . get ( i ) != v1 . get ( i ) ) { find ( root , v1 . get ( i ) , v . get ( i ) ) ; break ; } } return root ; } static void printInorder ( node node ) { if ( node == null ) return ; printInorder ( node . left ) ; System . out . printf ( " % d ▁ " , node . data ) ; printInorder ( node . right ) ; } public static void main ( String [ ] args ) { node root = new node ( 6 ) ; root . left = new node ( 10 ) ; root . right = new node ( 2 ) ; root . left . left = new node ( 1 ) ; root . left . right = new node ( 3 ) ; root . right . right = new node ( 12 ) ; root . right . left = new node ( 7 ) ; System . out . printf ( " Inorder ▁ Traversal ▁ of ▁ the " ) ; System . out . printf ( "original tree
"); printInorder ( root ) ; correctBST ( root ) ; System . out . printf ( " Inorder Traversal of the "); System . out . printf ( "fixed tree
"); printInorder ( root ) ; } }


"Two odd occurring elements in an array where all other occur even times | Java code to find two odd occurring elements in an array where all other elements appear even number of times . ; Find XOR of all numbers ; Find a set bit in the XOR ( We find rightmost set bit here ) ; Traverse through all numbers and divide them in two groups ( i ) Having set bit set at same position as the only set bit in set_bit ( ii ) Having 0 bit at same position as the only set bit in set_bit ; XOR of two different sets are our required numbers . ; Driver code"
How can the above be solved in Java?

class GFG { static void printOdds ( int arr [ ] , int n ) { int res = 0 ; for ( int i = 0 ; i < n ; i ++ ) res = res ^ arr [ i ] ; int set_bit = res & ( ~ ( res - 1 ) ) ; int x = 0 , y = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( ( arr [ i ] & set_bit ) != 0 ) x = x ^ arr [ i ] ; else y = y ^ arr [ i ] ; } System . out . println ( x + " ▁ " + y ) ; } public static void main ( String [ ] args ) { int arr [ ] = { 2 , 3 , 3 , 4 , 4 , 5 } ; int n = arr . length ; printOdds ( arr , n ) ; } }


"Two player game in which a player can remove all occurrences of a number | Java implementation for Two player game in which a player can remove all occurrences of a number ; Function that print whether player1 can wins or loses ; Storing the number of occurrence of elements in unordered map ; variable to check if the occurrence of repeated elements is >= 4 and multiple of 2 or not ; count elements which occur more than once ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { public static void game ( int [ ] v , int n ) { HashMap < Integer , Integer > m = new HashMap < > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( ! m . containsKey ( v [ i ] ) ) m . put ( v [ i ] , 1 ) ; else m . replace ( v [ i ] , m . get ( v [ i ] ) + 1 ) ; } int count = 0 ; int check = 0 ; for ( Map . Entry < Integer , Integer > i : m . entrySet ( ) ) { if ( i . getValue ( ) > 1 ) { if ( i . getValue ( ) >= 4 && i . getValue ( ) % 2 == 0 ) check ++ ; count ++ ; } } boolean flag ; if ( check % 2 != 0 ) flag = false ; if ( check % 2 != 0 ) System . out . println ( " Yes " ) ; else if ( n % 2 == 0 && count % 2 == 0 ) System . out . println ( " No " ) ; else System . out . println ( " Yes " ) ; } public static void main ( String [ ] args ) { int [ ] arr = { 3 , 2 , 2 , 3 , 3 , 5 } ; int size = arr . length ; game ( arr , size ) ; } }


"Types of Linked List | Doubly linked list node"
How can the above be solved in Java?

static class Node { int data ; Node next ; Node prev ; } ;


"Types of Linked List | Java program to illustrate creation and traversal of Singly Linked List ; Structure of Node ; Function to print the content of linked list starting from the given node ; Iterate till n reaches null ; Print the data ; Driver Code ; Allocate 3 nodes in the heap ; Assign data in first node ; Link first node with second ; Assign data to second node ; Assign data to third node"
How can the above be solved in Java?

class GFG { static class Node { int data ; Node next ; } ; static void printList ( Node n ) { while ( n != null ) { System . out . print ( n . data + " ▁ " ) ; n = n . next ; } } public static void main ( String [ ] args ) { Node head = null ; Node second = null ; Node third = null ; head = new Node ( ) ; second = new Node ( ) ; third = new Node ( ) ; head . data = 1 ; head . next = second ; second . data = 2 ; second . next = third ; third . data = 3 ; third . next = null ; printList ( head ) ; } }


"Types of Linked List | Node of a doubly linked list"
How can the above be solved in Java?

static class Node { int data ; Node next ; } ;


"Types of Linked List | Structure for a node"
How can the above be solved in Java?


"URLify a given string ( Replace spaces is % 20 ) | Java implementation of above approach ; Instantiate the string ; Trim the given string ; Replace All space ( unicode is \\ s ) to % 20 ; Display the result"
How can the above be solved in Java?

class GFG { public static void main ( String [ ] args ) { String str = " Mr ▁ John ▁ Smith ▁ " ; str = str . trim ( ) ; str = str . replaceAll ( " \\ s " , " % 20" ) ; System . out . println ( str ) ; } }


"Ugly Numbers | Java program to find nth ugly number ; This function divides a by greatest divisible power of b ; Function to check if a number is ugly or not ; Function to get the nth ugly number ; ugly number count ; check for all integers until count becomes n ; Driver Code"
How can the above be solved in Java?

class GFG { static int maxDivide ( int a , int b ) { while ( a % b == 0 ) a = a / b ; return a ; } static int isUgly ( int no ) { no = maxDivide ( no , 2 ) ; no = maxDivide ( no , 3 ) ; no = maxDivide ( no , 5 ) ; return ( no == 1 ) ? 1 : 0 ; } static int getNthUglyNo ( int n ) { int i = 1 ; int count = 1 ; while ( n > count ) { i ++ ; if ( isUgly ( i ) == 1 ) count ++ ; } return i ; } public static void main ( String args [ ] ) { int no = getNthUglyNo ( 150 ) ; System . out . println ( "150th ▁ ugly ▁ " + " no . ▁ is ▁ " + no ) ; } }


"Ulam Number Sequence | JAVA code to print nth Ulam number ; Array to store Ulam Number ; Function to compute ulam Number ; push First 2 two term of the sequence in the array for further calculation ; loop to generate Ulam number ; traverse the array and check if i can be represented as sum of two distinct element of the array ; If count is 2 that means i can be represented as sum of two distinct terms of the sequence ; i is ulam number ; Driver code ; pre compute Ulam Number sequence ; print nth Ulam number"
How can the above be solved in Java?

import java . util . * ; class GFG { static final int MAX = 1000 ; static Vector < Integer > arr = new Vector < Integer > ( ) ; static void ulam ( ) { arr . add ( 1 ) ; arr . add ( 2 ) ; for ( int i = 3 ; i < MAX ; i ++ ) { int count = 0 ; for ( int j = 0 ; j < arr . size ( ) - 1 ; j ++ ) { for ( int k = j + 1 ; k < arr . size ( ) ; k ++ ) { if ( arr . get ( j ) + arr . get ( k ) == i ) { count ++ ; } if ( count > 1 ) break ; } if ( count > 1 ) break ; } if ( count == 1 ) { arr . add ( i ) ; } } } public static void main ( String [ ] args ) { ulam ( ) ; int n = 9 ; System . out . println ( arr . get ( n - 1 ) ) ; } }


"Ulam Number Sequence | JAVA code to print nth Ulam number ; Array to store Ulam Number ; function to compute ulam Number ; Set to search specific Ulam number efficiently ; push First 2 two term of the sequence in the array and set for further calculation ; loop to generate Ulam number ; traverse the array and check if i can be represented as sum of two distinct element of the array ; Check if i - arr [ j ] exist in the array or not using set If yes , Then i can be represented as sum of arr [ j ] + ( i - arr [ j ] ) ; if Count is greater than 2 break the loop ; If count is 2 that means i can be represented as sum of two distinct terms of the sequence ; i is ulam number ; Driver code ; pre compute Ulam Number sequence ; print nth Ulam number"
How can the above be solved in Java?

import java . util . * ; class GFG { static final int MAX = 10000 ; static Vector < Integer > arr = new Vector < Integer > ( ) ; static void ulam ( ) { Set < Integer > s = new HashSet < Integer > ( ) ; arr . add ( 1 ) ; s . add ( 1 ) ; arr . add ( 2 ) ; s . add ( 2 ) ; for ( int i = 3 ; i < MAX ; i ++ ) { int count = 0 ; for ( int j = 0 ; j < arr . size ( ) ; j ++ ) { if ( s . contains ( i - arr . get ( j ) ) && arr . get ( j ) != ( i - arr . get ( j ) ) ) count ++ ; if ( count > 2 ) break ; } if ( count == 2 ) { arr . add ( i ) ; s . add ( i ) ; } } } public static void main ( String [ ] args ) { ulam ( ) ; int n = 9 ; System . out . println ( arr . get ( n - 1 ) ) ; } }


"Unbounded Fractional Knapsack | Java implementation of the approach ; Function to return the maximum required value ; maxratio will store the maximum value to weight ratio we can have for any item and maxindex will store the index of that element ; Find the maximum ratio ; The item with the maximum value to weight ratio will be put into the knapsack repeatedly until full ; Driver code"
How can the above be solved in Java?

class GFG { static float knapSack ( int W , float wt [ ] , float val [ ] , int n ) { float maxratio = Integer . MIN_VALUE ; int maxindex = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( ( val [ i ] / wt [ i ] ) > maxratio ) { maxratio = ( val [ i ] / wt [ i ] ) ; maxindex = i ; } } return ( W * maxratio ) ; } public static void main ( String [ ] args ) { float val [ ] = { 14 , 27 , 44 , 19 } ; float wt [ ] = { 6 , 7 , 9 , 8 } ; int n = val . length ; int W = 50 ; System . out . println ( knapSack ( W , wt , val , n ) ) ; } }


"Unbounded Knapsack ( Repetition of items allowed ) | Java program to find maximum achievable value with a knapsack of weight W and multiple instances allowed . ; Returns the maximum value with knapsack of W capacity ; dp [ i ] is going to store maximum value with knapsack capacity i . ; Fill dp [ ] using above recursive formula ; Driver program"
How can the above be solved in Java?

public class UboundedKnapsack { private static int max ( int i , int j ) { return ( i > j ) ? i : j ; } private static int unboundedKnapsack ( int W , int n , int [ ] val , int [ ] wt ) { int dp [ ] = new int [ W + 1 ] ; for ( int i = 0 ; i <= W ; i ++ ) { for ( int j = 0 ; j < n ; j ++ ) { if ( wt [ j ] <= i ) { dp [ i ] = max ( dp [ i ] , dp [ i - wt [ j ] ] + val [ j ] ) ; } } } return dp [ W ] ; } public static void main ( String [ ] args ) { int W = 100 ; int val [ ] = { 10 , 30 , 20 } ; int wt [ ] = { 5 , 10 , 15 } ; int n = val . length ; System . out . println ( unboundedKnapsack ( W , n , val , wt ) ) ; } }


"Understanding The Coin Change Problem With Dynamic Programming | We have input values of N and an array Coins that holds all of the coins . We use data type of long because we want to be able to test large values without integer overflow ; Create the ways array to 1 plus the amount to stop overflow ; Set the first way to 1 because its 0 and there is 1 way to make 0 with 0 coins ; Go through all of the coins ; Make a comparison to each index value of ways with the coin value . ; Update the ways array ; return the value at the Nth position of the ways array . ; Driver Code"
How can the above be solved in Java?

class getWays { static long getNumberOfWays ( long N , long [ ] Coins ) { long [ ] ways = new long [ ( int ) N + 1 ] ; ways [ 0 ] = 1 ; for ( int i = 0 ; i < Coins . length ; i ++ ) { for ( int j = 0 ; j < ways . length ; j ++ ) { if ( Coins [ i ] <= j ) { ways [ j ] += ways [ ( int ) ( j - Coins [ i ] ) ] ; } } } return ways [ ( int ) N ] ; } static void printArray ( long [ ] coins ) { for ( long i : coins ) System . out . println ( i ) ; } public static void main ( String args [ ] ) { long Coins [ ] = { 1 , 5 , 10 } ; System . out . println ( " The ▁ Coins ▁ Array : " ) ; printArray ( Coins ) ; System . out . println ( " Solution : " ) ; System . out . println ( getNumberOfWays ( 12 , Coins ) ) ; } }


"Uniform Binary Search | Java implementation of above approach ; lookup table ; create the lookup table for an array of length n ; power and count variable ; multiply by 2 ; initialize the lookup table ; binary search ; mid point of the array ; count ; if the value is found ; if value is less than the mid value ; if value is greater than the mid value ; Driver code ; create the lookup table ; print the position of the array"
How can the above be solved in Java?

class GFG { static int MAX_SIZE = 1000 ; static int lookup_table [ ] = new int [ MAX_SIZE ] ; static void create_table ( int n ) { int pow = 1 ; int co = 0 ; do { pow <<= 1 ; lookup_table [ co ] = ( n + ( pow >> 1 ) ) / pow ; } while ( lookup_table [ co ++ ] != 0 ) ; } static int binary ( int arr [ ] , int v ) { int index = lookup_table [ 0 ] - 1 ; int co = 0 ; while ( lookup_table [ co ] != 0 ) { if ( v == arr [ index ] ) return index ; else if ( v < arr [ index ] ) { index -= lookup_table [ ++ co ] ; return index ; } else { index += lookup_table [ ++ co ] ; return index ; } } return index ; } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 3 , 5 , 6 , 7 , 8 , 9 } ; int n = arr . length ; create_table ( n ) ; System . out . println ( " Position ▁ of ▁ 3 ▁ in ▁ array ▁ = ▁ " + binary ( arr , 3 ) ) ; } }


"Union and Intersection of two Linked Lists | Java code for Union and Intersection of two Linked Lists ; head of list ; Linked list Node ; Utility function to print list ; Inserts a node at start of linked list ; 1 & 2 : Allocate the Node & Put in the data ; 3. Make next of new Node as head ; 4. Move the head to point to new Node ; A utility function that returns true if data is present in linked list else return false ; loop stores all the elements of list1 in hset ; For every element of list2 present in hset loop inserts the element into the result ; HashMap that will store the elements of the lists with their counts ; loop inserts the elements and the count of that element of list1 into the hmap ; loop further adds the elements of list2 with their counts into the hmap ; Eventually add all the elements into the result that are present in the hmap ; Driver program to test above functions ; create a linked list 10 -> 15 -> 4 -> 20 ; create a linked list 8 -> 4 -> 2 -> 10"
How can the above be solved in Java?

import java . util . HashMap ; import java . util . HashSet ; class LinkedList { Node head ; class Node { int data ; Node next ; Node ( int d ) { data = d ; next = null ; } } void printList ( ) { Node temp = head ; while ( temp != null ) { System . out . print ( temp . data + " ▁ " ) ; temp = temp . next ; } System . out . println ( ) ; } void push ( int new_data ) { Node new_node = new Node ( new_data ) ; new_node . next = head ; head = new_node ; } public void append ( int new_data ) { if ( this . head == null ) { Node n = new Node ( new_data ) ; this . head = n ; return ; } Node n1 = this . head ; Node n2 = new Node ( new_data ) ; while ( n1 . next != null ) { n1 = n1 . next ; } n1 . next = n2 ; n2 . next = null ; } boolean isPresent ( Node head , int data ) { Node t = head ; while ( t != null ) { if ( t . data == data ) return true ; t = t . next ; } return false ; } LinkedList getIntersection ( Node head1 , Node head2 ) { HashSet < Integer > hset = new HashSet < > ( ) ; Node n1 = head1 ; Node n2 = head2 ; LinkedList result = new LinkedList ( ) ; while ( n1 != null ) { if ( hset . contains ( n1 . data ) ) { hset . add ( n1 . data ) ; } else { hset . add ( n1 . data ) ; } n1 = n1 . next ; } while ( n2 != null ) { if ( hset . contains ( n2 . data ) ) { result . push ( n2 . data ) ; } n2 = n2 . next ; } return result ; } LinkedList getUnion ( Node head1 , Node head2 ) { HashMap < Integer , Integer > hmap = new HashMap < > ( ) ; Node n1 = head1 ; Node n2 = head2 ; LinkedList result = new LinkedList ( ) ; while ( n1 != null ) { if ( hmap . containsKey ( n1 . data ) ) { int val = hmap . get ( n1 . data ) ; hmap . put ( n1 . data , val + 1 ) ; } else { hmap . put ( n1 . data , 1 ) ; } n1 = n1 . next ; } while ( n2 != null ) { if ( hmap . containsKey ( n2 . data ) ) { int val = hmap . get ( n2 . data ) ; hmap . put ( n2 . data , val + 1 ) ; } else { hmap . put ( n2 . data , 1 ) ; } n2 = n2 . next ; } for ( int a : hmap . keySet ( ) ) { result . append ( a ) ; } return result ; } public static void main ( String...


"Union and Intersection of two sorted arrays | Java program to find intersection of two sorted arrays ; Function prints Intersection of arr1 [ ] and arr2 [ ] m is the number of elements in arr1 [ ] n is the number of elements in arr2 [ ] ; Driver program to test above function ; Function calling"
How can the above be solved in Java?

class FindIntersection { static void printIntersection ( int arr1 [ ] , int arr2 [ ] , int m , int n ) { int i = 0 , j = 0 ; while ( i < m && j < n ) { if ( arr1 [ i ] < arr2 [ j ] ) i ++ ; else if ( arr2 [ j ] < arr1 [ i ] ) j ++ ; else { System . out . print ( arr2 [ j ++ ] + " ▁ " ) ; i ++ ; } } } public static void main ( String args [ ] ) { int arr1 [ ] = { 1 , 2 , 4 , 5 , 6 } ; int arr2 [ ] = { 2 , 3 , 5 , 7 } ; int m = arr1 . length ; int n = arr2 . length ; printIntersection ( arr1 , arr2 , m , n ) ; } }


"Union and Intersection of two sorted arrays | Java program to find union of two sorted arrays ( Handling Duplicates ) ; Taking max element present in either array ; Finding elements from 1 st array ( non duplicates only ) . Using another array for storing union elements of both arrays Assuming max element present in array is not more than 10 ^ 7 ; First element is always present in final answer ; Incrementing the First element ' s ▁ count ▁ ▁ in ▁ it ' s corresponding index in newtable ; Starting traversing the first array from 1 st index till last ; Checking whether current element is not equal to it 's previous element ; Finding only non common elements from 2 nd array ; By checking whether it 's already  present in newtable or not ; Driver Code"
How can the above be solved in Java?

class FindUnion { static void UnionArray ( int arr1 [ ] , int arr2 [ ] ) { int m = arr1 [ arr1 . length - 1 ] ; int n = arr2 [ arr2 . length - 1 ] ; int ans = 0 ; if ( m > n ) { ans = m ; } else ans = n ; int newtable [ ] = new int [ ans + 1 ] ; System . out . print ( arr1 [ 0 ] + " ▁ " ) ; ++ newtable [ arr1 [ 0 ] ] ; for ( int i = 1 ; i < arr1 . length ; i ++ ) { if ( arr1 [ i ] != arr1 [ i - 1 ] ) { System . out . print ( arr1 [ i ] + " ▁ " ) ; ++ newtable [ arr1 [ i ] ] ; } } for ( int j = 0 ; j < arr2 . length ; j ++ ) { if ( newtable [ arr2 [ j ] ] == 0 ) { System . out . print ( arr2 [ j ] + " ▁ " ) ; ++ newtable [ arr2 [ j ] ] ; } } } public static void main ( String args [ ] ) { int arr1 [ ] = { 1 , 2 , 2 , 2 , 3 } ; int arr2 [ ] = { 2 , 3 , 4 , 5 } ; UnionArray ( arr1 , arr2 ) ; } }


"Union and Intersection of two sorted arrays | Java program to find union of two sorted arrays ; Function prints union of arr1 [ ] and arr2 [ ] m is the number of elements in arr1 [ ] n is the number of elements in arr2 [ ] ; Print remaining elements of the larger array ; Driver program to test above function"
How can the above be solved in Java?

class FindUnion { static int printUnion ( int arr1 [ ] , int arr2 [ ] , int m , int n ) { int i = 0 , j = 0 ; while ( i < m && j < n ) { if ( arr1 [ i ] < arr2 [ j ] ) System . out . print ( arr1 [ i ++ ] + " ▁ " ) ; else if ( arr2 [ j ] < arr1 [ i ] ) System . out . print ( arr2 [ j ++ ] + " ▁ " ) ; else { System . out . print ( arr2 [ j ++ ] + " ▁ " ) ; i ++ ; } } while ( i < m ) System . out . print ( arr1 [ i ++ ] + " ▁ " ) ; while ( j < n ) System . out . print ( arr2 [ j ++ ] + " ▁ " ) ; return 0 ; } public static void main ( String args [ ] ) { int arr1 [ ] = { 1 , 2 , 4 , 5 , 6 } ; int arr2 [ ] = { 2 , 3 , 5 , 7 } ; int m = arr1 . length ; int n = arr2 . length ; printUnion ( arr1 , arr2 , m , n ) ; } }


"Union | Java program to implement Union - Find with union by rank and path compression ; Arr to represent parent of index i ; Size to represent the number of nodes in subgxrph rooted at index i ; set parent of every node to itself and size of node to one ; Each time we follow a path , find function compresses it further until the path length is greater than or equal to 1. ; while we reach a node whose parent is equal to itself ; Skip one level ; Move to the new level ; A function that does union of two nodes x and y where xr is root node of x and yr is root node of y ; Make yr parent of xr ; Make xr parent of yr ; The main function to check whether a given gxrph contains cycle or not ; Itexrte through all edges of gxrph , find nodes connecting them . If root nodes of both are same , then there is cycle in gxrph . ; find root of i ; find root of adj [ i ] [ j ] ; If same parent ; Make them connect ; Driver Code ; Initialize the values for arxry Arr and Size ; Adjacency list for graph ; call is_cycle to check if it contains cycle"
How can the above be solved in Java?

 import java . util . * ; class GFG { static int MAX_VERTEX = 101 ; static int [ ] Arr = new int [ MAX_VERTEX ] ; static int [ ] size = new int [ MAX_VERTEX ] ; static void initialize ( int n ) { for ( int i = 0 ; i <= n ; i ++ ) { Arr [ i ] = i ; size [ i ] = 1 ; } } static int find ( int i ) { while ( Arr [ i ] != i ) { Arr [ i ] = Arr [ Arr [ i ] ] ; i = Arr [ i ] ; } return i ; } static void _union ( int xr , int yr ) { if ( size [ xr ] < size [ yr ] ) { Arr [ xr ] = Arr [ yr ] ; size [ yr ] += size [ xr ] ; } else { Arr [ yr ] = Arr [ xr ] ; size [ xr ] += size [ yr ] ; } } static int isCycle ( Vector < Integer > adj [ ] , int V ) { for ( int i = 0 ; i < V ; i ++ ) { for ( int j = 0 ; j < adj [ i ] . size ( ) ; j ++ ) { int x = find ( i ) ; int y = find ( adj [ i ] . get ( j ) ) ; if ( x == y ) return 1 ; _union ( x , y ) ; } } return 0 ; } public static void main ( String [ ] args ) { int V = 3 ; initialize ( V ) ; Vector < Integer > [ ] adj = new Vector [ V ] ; for ( int i = 0 ; i < V ; i ++ ) adj [ i ] = new Vector < Integer > ( ) ; adj [ 0 ] . add ( 1 ) ; adj [ 0 ] . add ( 2 ) ; adj [ 1 ] . add ( 2 ) ; if ( isCycle ( adj , V ) == 1 ) System . out . print ( "Graph contains Cycle.
"); else System . out . print ( "Graph does not contain Cycle.
"); } }


"Union | Naive implementation of find ; Naive implementation of union ( )"
How can the above be solved in Java?

static int find ( int parent [ ] , int i ) { if ( parent [ i ] == - 1 ) return i ; return find ( parent , parent [ i ] ) ; } static void Union ( int parent [ ] , int x , int y ) { int xset = find ( parent , x ) ; int yset = find ( parent , y ) ; parent [ xset ] = yset ; }


"Unique cells in a binary matrix | Efficient Java program to count unique cells in a binary matrix ; Count number of 1 s in each row and in each column ; Using above count arrays , find cells ; Driver code"
How can the above be solved in Java?

class GFG { static int MAX = 100 ; static int countUnique ( int mat [ ] [ ] , int n , int m ) { int [ ] rowsum = new int [ n ] ; int [ ] colsum = new int [ m ] ; for ( int i = 0 ; i < n ; i ++ ) for ( int j = 0 ; j < m ; j ++ ) if ( mat [ i ] [ j ] != 0 ) { rowsum [ i ] ++ ; colsum [ j ] ++ ; } int uniquecount = 0 ; for ( int i = 0 ; i < n ; i ++ ) for ( int j = 0 ; j < m ; j ++ ) if ( mat [ i ] [ j ] != 0 && rowsum [ i ] == 1 && colsum [ j ] == 1 ) uniquecount ++ ; return uniquecount ; } public static void main ( String [ ] args ) { int mat [ ] [ ] = { { 0 , 1 , 0 , 0 } , { 0 , 0 , 1 , 0 } , { 1 , 0 , 0 , 1 } } ; System . out . print ( countUnique ( mat , 3 , 4 ) ) ; } }


"Unique cells in a binary matrix | Efficient Java program to count unique cells in a binary matrix ; Returns true if mat [ i ] [ j ] is unique ; checking in row calculating sumrow will be moving column wise ; checking in column calculating sumcol will be moving row wise ; Driver code"
How can the above be solved in Java?

class GFG { static final int MAX = 100 ; static boolean isUnique ( int mat [ ] [ ] , int i , int j , int n , int m ) { int sumrow = 0 ; for ( int k = 0 ; k < m ; k ++ ) { sumrow += mat [ i ] [ k ] ; if ( sumrow > 1 ) return false ; } int sumcol = 0 ; for ( int k = 0 ; k < n ; k ++ ) { sumcol += mat [ k ] [ j ] ; if ( sumcol > 1 ) return false ; } return true ; } static int countUnique ( int mat [ ] [ ] , int n , int m ) { int uniquecount = 0 ; for ( int i = 0 ; i < n ; i ++ ) for ( int j = 0 ; j < m ; j ++ ) if ( mat [ i ] [ j ] != 0 && isUnique ( mat , i , j , n , m ) ) uniquecount ++ ; return uniquecount ; } static public void main ( String [ ] args ) { int mat [ ] [ ] = { { 0 , 1 , 0 , 0 } , { 0 , 0 , 1 , 0 } , { 1 , 0 , 0 , 1 } } ; System . out . print ( countUnique ( mat , 3 , 4 ) ) ; } }


"Unique element in an array where all elements occur K times except one | Set 2 | Java program for the above approach ; Function that find the unique element in the array arr [ ] ; Store all unique element in set ; Sum of all element of the array ; Sum of element in the set ; Print the unique element using formula ; Driver code ; Function call"
How can the above be solved in Java?

import java . util . * ; class GFG { static void findUniqueElements ( int arr [ ] , int N , int K ) { Set < Integer > s = new HashSet < > ( ) ; for ( int i = 0 ; i < N ; i ++ ) s . add ( arr [ i ] ) ; int arr_sum = 0 ; for ( int i = 0 ; i < N ; i ++ ) arr_sum += arr [ i ] ; int set_sum = 0 ; Iterator it = s . iterator ( ) ; while ( it . hasNext ( ) ) { set_sum += ( int ) it . next ( ) ; } System . out . println ( ( K * set_sum - arr_sum ) / ( K - 1 ) ) ; } public static void main ( String [ ] args ) { int arr [ ] = { 12 , 1 , 12 , 3 , 12 , 1 , 1 , 2 , 3 , 2 , 2 , 3 , 7 } ; int N = arr . length ; int K = 3 ; findUniqueElements ( arr , N , K ) ; } }


"Unique element in an array where all elements occur K times except one | Set 2 | Java program for the above approach ; Function to find single occurrence element ; By shifting 1 to left ith time and taking and with 1 will give us that ith bit of a [ j ] is 1 or 0 ; Taking modulo of p with k ; Generate result ; Loop for negative numbers ; Check if the calculated value res is present in array , then mark c = 1 and if c = 1 return res else res must be - ve ; Driver code ; Function call"
How can the above be solved in Java?

import java . util . Arrays ; class Main { public static int findunique ( int a [ ] , int k ) { int res = 0 ; for ( int i = 0 ; i < 32 ; i ++ ) { int p = 0 ; for ( int j = 0 ; j < a . length ; j ++ ) { p += ( Math . abs ( a [ j ] ) & ( 1 << i ) ) != 0 ? 1 : 0 ; } p %= k ; res += Math . pow ( 2 , i ) * p ; } int c = 0 ; for ( int x = 0 ; x < a . length ; x ++ ) if ( a [ x ] == res ) { c = 1 ; break ; } return c == 1 ? res : - res ; } public static void main ( String [ ] args ) { int a [ ] = { 12 , 12 , 2 , 2 , 3 } ; int k = 2 ; System . out . println ( findunique ( a , k ) ) ; } }


"Unique element in an array where all elements occur k times except one | Java program to find unique element where every element appears k times except one ; Create a count array to store count of numbers that have a particular bit set . count [ i ] stores count of array elements with i - th bit set . ; AND ( bitwise ) each element of the array with each set digit ( one at a time ) to get the count of set bits at each position ; Now consider all bits whose count is not multiple of k to form the required number . ; Driver Code"
How can the above be solved in Java?

class GFG { static int findUnique ( int a [ ] , int n , int k ) { byte sizeof_int = 4 ; int INT_SIZE = 8 * sizeof_int ; int count [ ] = new int [ INT_SIZE ] ; for ( int i = 0 ; i < INT_SIZE ; i ++ ) for ( int j = 0 ; j < n ; j ++ ) if ( ( a [ j ] & ( 1 << i ) ) != 0 ) count [ i ] += 1 ; int res = 0 ; for ( int i = 0 ; i < INT_SIZE ; i ++ ) res += ( count [ i ] % k ) * ( 1 << i ) ; return res ; } public static void main ( String [ ] args ) { int a [ ] = { 6 , 2 , 5 , 2 , 2 , 6 , 6 } ; int n = a . length ; int k = 3 ; System . out . println ( findUnique ( a , n , k ) ) ; } }


"Unique paths in a Grid with Obstacles | Java program for the above approach ; If obstacle is at starting position ; Initializing starting position ; first row all are '1' until obstacle ; No ways to reach at this index ; first column all are '1' until obstacle ; No ways to reach at this index ; If current cell has no obstacle ; No ways to reach at this index ; returning the bottom right corner of Grid ; Driver code"
How can the above be solved in Java?

class GFG { static int uniquePathsWithObstacles ( int [ ] [ ] A ) { int r = A . length ; int c = A [ 0 ] . length ; if ( A [ 0 ] [ 0 ] != 0 ) return 0 ; A [ 0 ] [ 0 ] = 1 ; for ( int j = 1 ; j < c ; j ++ ) { if ( A [ 0 ] [ j ] == 0 ) { A [ 0 ] [ j ] = A [ 0 ] [ j - 1 ] ; } else { A [ 0 ] [ j ] = 0 ; } } for ( int i = 1 ; i < r ; i ++ ) { if ( A [ i ] [ 0 ] == 0 ) { A [ i ] [ 0 ] = A [ i - 1 ] [ 0 ] ; } else { A [ i ] [ 0 ] = 0 ; } } for ( int i = 1 ; i < r ; i ++ ) { for ( int j = 1 ; j < c ; j ++ ) { if ( A [ i ] [ j ] == 0 ) { A [ i ] [ j ] = A [ i - 1 ] [ j ] + A [ i ] [ j - 1 ] ; } else { A [ i ] [ j ] = 0 ; } } } return A [ r - 1 ] ; } public static void main ( String [ ] args ) { int [ ] [ ] A = { { 0 , 0 , 0 } , { 0 , 1 , 0 } , { 0 , 0 , 0 } } ; System . out . print ( uniquePathsWithObstacles ( A ) ) ; } }


"Unique subsequences of length K with given sum | Java program for the above approach ; Function to find all the subsequences of a given length and having sum S ; Termination condition ; Add value to sum ; Check if the resultant sum equals to target sum ; If true ; Print resultant array ; End this recursion stack ; Check all the combinations using backtracking ; Check all the combinations using backtracking ; Driver Code ; Given array ; To store the subsequence ; Function Call"
How can the above be solved in Java?

import java . util . * ; class GFG { static void comb ( int [ ] arr , int len , int r , int ipos , int [ ] op , int opos , int sum ) { if ( opos == r ) { int sum2 = 0 ; for ( int i = 0 ; i < opos ; i ++ ) { sum2 = sum2 + op [ i ] ; } if ( sum == sum2 ) { for ( int i = 0 ; i < opos ; i ++ ) System . out . print ( op [ i ] + " , ▁ " ) ; System . out . println ( ) ; } return ; } if ( ipos < len ) { comb ( arr , len , r , ipos + 1 , op , opos , sum ) ; op [ opos ] = arr [ ipos ] ; comb ( arr , len , r , ipos + 1 , op , opos + 1 , sum ) ; } } public static void main ( String [ ] args ) { int arr [ ] = { 4 , 6 , 8 , 2 , 12 } ; int K = 3 ; int S = 20 ; int N = arr . length ; int op [ ] = new int [ N ] ; comb ( arr , N , K , 0 , op , 0 , S ) ; } }


"Unprimeable Numbers | Java program to check if n is unprimeable Number ; Function to check if N is prime ; Corner cases ; This is checked so that we can skip middle five numbers in below loop ; Function to check if n is a unprimeable Number ; Number should be composite ; Converting N to String ; Loop to change digit at every character one by one . ; Loop to store every digit one by one at index j ; Driver code ; Function Call"
How can the above be solved in Java?

class GFG { static boolean isPrime ( int n ) { if ( n <= 1 ) return false ; if ( n <= 3 ) return true ; if ( n % 2 == 0 n % 3 == 0 ) return false ; for ( int i = 5 ; i * i <= n ; i = i + 6 ) if ( n % i == 0 || n % ( i + 2 ) == 0 ) return false ; return true ; } static boolean isUnPrimeableNum ( int N ) { if ( isPrime ( N ) ) return false ; String s = String . valueOf ( N ) ; for ( int j = 0 ; j < s . length ( ) ; j ++ ) { char [ ] str = s . toCharArray ( ) ; for ( int i = 0 ; i <= 9 ; i ++ ) { char c = ( char ) ( '0' + i ) ; str [ j ] = c ; int Num = Integer . valueOf ( new String ( str ) ) ; if ( str [ j ] != s . charAt ( j ) && isPrime ( Num ) ) { return false ; } } } return true ; } public static void main ( String [ ] args ) { int n = 200 ; if ( isUnPrimeableNum ( n ) ) System . out . print ( " Yes " ) ; else System . out . print ( " No " ) ; } }


"Unset least significant K bits of a given number | Java program for the above approach ; Function to return the value after unsetting K LSBs ; Create a mask ; Bitwise AND operation with the number and the mask ; Driver Code ; Given N and K ; Function Call"
How can the above be solved in Java?

import java . util . * ; class GFG { static int clearLastBit ( int N , int K ) { int mask = ( - 1 << K + 1 ) ; return N = N & mask ; } public static void main ( String [ ] args ) { int N = 730 , K = 3 ; System . out . print ( clearLastBit ( N , K ) ) ; } }


"Untouchable Number | Java program for the above approach ; Function to calculate sum of all proper divisors of num ; Final result of summation of divisors ; Find all divisors of num ; If ' i ' is divisor of ' num ' ; If both divisors are same then add it only once else add both ; Add 1 to the result as 1 is also a divisor ; Function to check if N is a Untouchable Number ; Driver code ; Given Number N ; Function Call"
How can the above be solved in Java?

class GFG { static int divSum ( int num ) { int result = 0 ; for ( int i = 2 ; i <= Math . sqrt ( num ) ; i ++ ) { if ( num % i == 0 ) { if ( i == ( num / i ) ) result += i ; else result += ( i + num / i ) ; } } return ( result + 1 ) ; } static boolean isUntouchable ( int n ) { for ( int i = 1 ; i <= 2 * n ; i ++ ) { if ( divSum ( i ) == n ) return false ; } return true ; } public static void main ( String [ ] args ) { int n = 52 ; if ( isUntouchable ( n ) ) System . out . println ( " Yes " ) ; else System . out . println ( " No " ) ; } }


"Value of k | Java program to fin k - th element after append and insert middle operations ; Middle element of the sequence ; length of the resulting sequence . ; Updating the middle element of next sequence ; Moving to the left side of the middle element . ; Moving to the right side of the middle element . ; Driver code"
How can the above be solved in Java?

class GFG { static void findElement ( int n , int k ) { int ans = n ; int left = 1 ; int right = ( int ) ( Math . pow ( 2 , n ) - 1 ) ; while ( true ) { int mid = ( left + right ) / 2 ; if ( k == mid ) { System . out . println ( ans ) ; break ; } ans -- ; if ( k < mid ) { right = mid - 1 ; } else { left = mid + 1 ; } } } public static void main ( String [ ] args ) { int n = 4 , k = 8 ; findElement ( n , k ) ; } }


"Value of the series ( 1 ^ 3 + 2 ^ 3 + 3 ^ 3 + ... + n ^ 3 ) mod 4 for a given n | Java implementation of the approach ; function for obtaining the value of f ( n ) mod 4 ; Find the remainder of n when divided by 4 ; If n is of the form 4 k or 4 k + 3 ; If n is of the form 4 k + 1 or 4 k + 2 ; Driver code"
How can the above be solved in Java?

import java . io . * ; class GFG { static int fnMod ( int n ) { int rem = n % 4 ; if ( rem == 0 rem == 3 ) return 0 ; else if ( rem == 1 rem == 2 ) return 1 ; return 0 ; } public static void main ( String [ ] args ) { int n = 6 ; System . out . print ( fnMod ( n ) ) ; } }


"Value required to be added to N to obtain the sum of first M multiples of K | Java code of above approach ; Function to print the value to be added to N to obtain sum of first M multiples of K ; Store the sum of the first M multiples of K ; Store the value to be added to obtain N ; Driver code ; Input"
How can the above be solved in Java?

import java . util . * ; class GFG { static int printNumber ( int N , int K , int M ) { int sum = K * ( M * ( M + 1 ) / 2 ) ; return sum - N ; } public static void main ( String [ ] args ) { int N = 17 ; int K = 3 ; int M = 4 ; System . out . print ( printNumber ( N , K , M ) ) ; } }


"Value to be subtracted from array elements to make sum of all elements equals K | Java implementation of the approach ; Function to return the amount of wood collected if the cut is made at height m ; Function that returns Height at which cut should be made ; Sort the heights of the trees ; The minimum and the maximum cut that can be made ; Binary search to find the answer ; The amount of wood collected when cut is made at the mid ; If the current collected wood is equal to the required amount ; If it is more than the required amount then the cut needs to be made at a height higher than the current height ; Else made the cut at a lower height ; Driver code"
How can the above be solved in Java?

import java . util . Arrays ; class GFG { static int [ ] height = new int [ ] { 1 , 2 , 1 , 2 } ; public static int woodCollected ( int n , int m ) { int sum = 0 ; for ( int i = n - 1 ; i >= 0 ; i -- ) { if ( height [ i ] - m <= 0 ) break ; sum += ( height [ i ] - m ) ; } return sum ; } public static int collectKWood ( int n , int k ) { Arrays . sort ( height ) ; int low = 0 , high = height [ n - 1 ] ; while ( low <= high ) { int mid = low + ( ( high - low ) / 2 ) ; int collected = woodCollected ( n , mid ) ; if ( collected == k ) return mid ; if ( collected > k ) low = mid + 1 ; else high = mid - 1 ; } return - 1 ; } public static void main ( String [ ] args ) { int k = 2 ; int n = height . length ; System . out . print ( collectKWood ( n , k ) ) ; } }


"Vantieghems Theorem for Primality Test | Java code to verify Vantieghem 's Theorem ; Check if above condition is satisfied ; product of previous powers of 2 ; Driver code"
How can the above be solved in Java?

 import java . util . * ; class GFG { static void checkVantieghemsTheorem ( int limit ) { long prod = 1 ; for ( long n = 2 ; n < limit ; n ++ ) { if ( ( ( prod - n < 0 ? 0 : prod - n ) % ( ( 1 << n ) - 1 ) ) == 0 ) System . out . print ( n + " is prime
"); prod *= ( ( 1 << n ) - 1 ) ; } } public static void main ( String [ ] args ) { checkVantieghemsTheorem ( 10 ) ; } }