"Find coordinates of the triangle given midpoint of each side | Java program to find coordinate of the triangle given midpoint of each side ; Return after solving the equations and finding the vertices coordinate . ; Finding sum of all three coordinate . ; Solving the equation . ; Finds vertices of a triangles from given middle vertices . ; Find X coordinates of vertices . ; Find Y coordinates of vertices . ; Output the solution . ; Driver code"
How can the above be solved in Java?

import java . util . Vector ; class GFG { static final int N = 3 ; static Vector < Integer > solve ( int v [ ] ) { Vector < Integer > res = new Vector < Integer > ( ) ; int all3 = v [ 0 ] + v [ 1 ] + v [ 2 ] ; res . add ( all3 - v [ 1 ] * 2 ) ; res . add ( all3 - v [ 2 ] * 2 ) ; res . add ( all3 - v [ 0 ] * 2 ) ; return res ; } static void findVertex ( int xmid [ ] , int ymid [ ] ) { Vector < Integer > V1 = solve ( xmid ) ; Vector < Integer > V2 = solve ( ymid ) ; for ( int i = 0 ; i < 3 ; i ++ ) { System . out . println ( V1 . get ( i ) + " ▁ " + V2 . get ( i ) ) ; } } public static void main ( String [ ] args ) { int xmid [ ] = { 5 , 4 , 5 } ; int ymid [ ] = { 3 , 4 , 5 } ; findVertex ( xmid , ymid ) ; } }


"Find cost price from given selling price and profit or loss percentage | Java implementation to find Cost price ; Function to calculate cost price with profit ; required formula to calculate CP with profit ; Function to calculate cost price with loss ; required formula to calculate CP with loss ; Driver code"
How can the above be solved in Java?

import java . util . * ; class solution { static float CPwithProfit ( int sellingPrice , int profit ) { float costPrice ; costPrice = ( sellingPrice * 100 ) / ( 100 + profit ) ; return costPrice ; } static float CPwithLoss ( int sellingPrice , int loss ) { float costPrice ; costPrice = ( sellingPrice * 100 ) / ( 100 - loss ) ; return costPrice ; } public static void main ( String args [ ] ) { int SP , profit , loss ; SP = 1020 ; profit = 20 ; System . out . println ( " Cost ▁ Price ▁ = ▁ " + CPwithProfit ( SP , profit ) ) ; SP = 900 ; loss = 10 ; System . out . println ( " Cost ▁ Price ▁ = ▁ " + CPwithLoss ( SP , loss ) ) ; SP = 42039 ; profit = 8 ; System . out . println ( " Cost ▁ Price ▁ = ▁ " + CPwithProfit ( SP , profit ) ) ; } }


"Find count of digits in a number that divide the number | Java program to count number of digits that divides the number . ; Return the number of digits that divides the number . ; Fetching each digit of the number ; Checking if digit is greater than 0 and can divides n . ; Driver method"
How can the above be solved in Java?

class Test { static int countDigit ( int n ) { int temp = n , count = 0 ; while ( temp != 0 ) { int d = temp % 10 ; temp /= 10 ; if ( d > 0 && n % d == 0 ) count ++ ; } return count ; } public static void main ( String args [ ] ) { int n = 1012 ; System . out . println ( countDigit ( n ) ) ; } }


"Find count of numbers from 0 to n which satisfies the given equation for a value K | Java implementation to find the total count of all the numbers from 0 to n which satisfies the given equation for a value K ; Function to find the values ; Calculate the LCM ; Calculate the multiples of lcm ; Find the values which satisfies the given condition ; Subtract the extra values ; Return the final result ; Driver code"
How can the above be solved in Java?

 class GFG { static int findAns ( int a , int b , int n ) { int lcm = ( a * b ) / __gcd ( a , b ) ; int multiples = ( n / lcm ) + 1 ; int answer = Math . max ( a , b ) * multiples ; int lastvalue = lcm * ( n / lcm ) + Math . max ( a , b ) ; if ( lastvalue > n ) answer = answer - ( lastvalue - n - 1 ) ; return answer ; } static int __gcd ( int a , int b ) { return b == 0 ? a : __gcd ( b , a % b ) ; } public static void main ( String [ ] args ) { int a = 1 , b = 13 , n = 500 ; System . out . print ( findAns ( a , b , n ) + "
"); } }


"Find cubic root of a number | Java program to find cubic root of a number using Binary Search ; Returns the absolute value of n - mid * mid * mid ; Returns cube root of a no n ; Set start and end for binary search ; Set precision ; If error is less than e then mid is our answer so return mid ; If mid * mid * mid is greater than n set end = mid ; If mid * mid * mid is less than n set start = mid ; Driver program to test above function"
How can the above be solved in Java?

import java . io . * ; class GFG { static double diff ( double n , double mid ) { if ( n > ( mid * mid * mid ) ) return ( n - ( mid * mid * mid ) ) ; else return ( ( mid * mid * mid ) - n ) ; } static double cubicRoot ( double n ) { double start = 0 , end = n ; double e = 0.0000001 ; while ( true ) { double mid = ( start + end ) / 2 ; double error = diff ( n , mid ) ; if ( error <= e ) return mid ; if ( ( mid * mid * mid ) > n ) end = mid ; else start = mid ; } } public static void main ( String [ ] args ) { double n = 3 ; System . out . println ( " Cube ▁ root ▁ of ▁ " + n + " ▁ is ▁ " + cubicRoot ( n ) ) ; } }


"Find depth of the deepest odd level leaf node | A binary tree node ; A recursive function to find depth of the deepest odd level leaf ; Base Case ; If this node is a leaf and its level is odd , return its level ; If not leaf , return the maximum value from left and right subtrees ; Main function which calculates the depth of deepest odd level leaf . This function mainly uses depthOfOddLeafUtil ( ) ; Driver Code"
How can the above be solved in Java?

class Node { int data ; Node left , right ; Node ( int item ) { data = item ; left = right = null ; } } class BinaryTree { Node root ; int depthOfOddLeafUtil ( Node node , int level ) { if ( node == null ) return 0 ; if ( node . left == null && node . right == null && ( level & 1 ) != 0 ) return level ; return Math . max ( depthOfOddLeafUtil ( node . left , level + 1 ) , depthOfOddLeafUtil ( node . right , level + 1 ) ) ; } int depthOfOddLeaf ( Node node ) { int level = 1 , depth = 0 ; return depthOfOddLeafUtil ( node , level ) ; } public static void main ( String args [ ] ) { int k = 45 ; 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 . right . left = new Node ( 5 ) ; tree . root . right . right = new Node ( 6 ) ; tree . root . right . left . right = new Node ( 7 ) ; tree . root . right . right . right = new Node ( 8 ) ; tree . root . right . left . right . left = new Node ( 9 ) ; tree . root . right . right . right . right = new Node ( 10 ) ; tree . root . right . right . right . right . left = new Node ( 11 ) ; System . out . println ( tree . depthOfOddLeaf ( tree . root ) + " ▁ is ▁ the ▁ required ▁ depth " ) ; } }


"Find depth of the deepest odd level leaf node | Java program to find depth of the deepest odd level leaf node of binary tree ; tree node ; returns a new tree Node ; return max odd number depth of leaf node ; create a queue for level order traversal ; traverse until the queue is empty ; traverse for complete level ; check if the node is leaf node and level is odd if level is odd , then update result ; check for left child ; check for right child ; Driver Code ; construct a tree"
How can the above be solved in Java?

import java . util . * ; class GFG { static class Node { int data ; Node left , right ; } ; static Node newNode ( int data ) { Node temp = new Node ( ) ; temp . data = data ; temp . left = temp . right = null ; return temp ; } static int maxOddLevelDepth ( Node root ) { if ( root == null ) return 0 ; Queue < Node > q = new LinkedList < > ( ) ; q . add ( root ) ; int result = Integer . MAX_VALUE ; int level = 0 ; while ( ! q . isEmpty ( ) ) { int size = q . size ( ) ; level += 1 ; while ( size > 0 ) { Node temp = q . peek ( ) ; q . remove ( ) ; if ( temp . left == null && temp . right == null && ( level % 2 != 0 ) ) { result = level ; } if ( temp . left != null ) { q . add ( temp . left ) ; } if ( temp . right != null ) { q . add ( temp . right ) ; } size -= 1 ; } } return result ; } public static void main ( String [ ] args ) { Node root = newNode ( 1 ) ; root . left = newNode ( 2 ) ; root . right = newNode ( 3 ) ; root . left . left = newNode ( 4 ) ; root . right . left = newNode ( 5 ) ; root . right . right = newNode ( 6 ) ; root . right . left . right = newNode ( 7 ) ; root . right . right . right = newNode ( 8 ) ; root . right . left . right . left = newNode ( 9 ) ; root . right . right . right . right = newNode ( 10 ) ; root . right . right . right . right . left = newNode ( 11 ) ; int result = maxOddLevelDepth ( root ) ; if ( result == Integer . MAX_VALUE ) System . out . println ( " No ▁ leaf ▁ node ▁ at ▁ odd ▁ level " ) ; else { System . out . print ( result ) ; System . out . println ( " ▁ is ▁ the ▁ required ▁ depth ▁ " ) ; } } }


"Find determinant of matrix generated by array rotation | Java program for finding determinant of generated matrix ; Function to calculate determinant ; Driver code"
How can the above be solved in Java?

import java . util . * ; import java . lang . * ; class GFG { static int N = 3 ; static double calcDeterminant ( int arr [ ] ) { double determinant = 0 ; for ( int i = 0 ; i < N ; i ++ ) { determinant += Math . pow ( arr [ i ] , 3 ) ; } determinant -= 3 * arr [ 0 ] * arr [ 1 ] * arr [ 2 ] ; return determinant ; } static public void main ( String args [ ] ) { int [ ] arr = { 4 , 5 , 3 } ; System . out . println ( calcDeterminant ( arr ) ) ; } }


"Find difference between sums of two diagonals | JAVA Code for Find difference between sums of two diagonals ; Initialize sums of diagonals ; Absolute difference of the sums across the diagonals ; Driver program to test above function"
How can the above be solved in Java?

class GFG { public static int difference ( int arr [ ] [ ] , int n ) { int d1 = 0 , d2 = 0 ; for ( int i = 0 ; i < n ; i ++ ) { d1 += arr [ i ] [ i ] ; d2 += arr [ i ] [ n - i - 1 ] ; } return Math . abs ( d1 - d2 ) ; } public static void main ( String [ ] args ) { int n = 3 ; int arr [ ] [ ] = { { 11 , 2 , 4 } , { 4 , 5 , 6 } , { 10 , 8 , - 12 } } ; System . out . print ( difference ( arr , n ) ) ; } }


"Find difference between sums of two diagonals | JAVA Code for Find difference between sums of two diagonals ; Initialize sums of diagonals ; finding sum of primary diagonal ; finding sum of secondary diagonal ; Absolute difference of the sums across the diagonals ; Driver program to test above function"
How can the above be solved in Java?

class GFG { public static int difference ( int arr [ ] [ ] , int n ) { int d1 = 0 , d2 = 0 ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = 0 ; j < n ; j ++ ) { if ( i == j ) d1 += arr [ i ] [ j ] ; if ( i == n - j - 1 ) d2 += arr [ i ] [ j ] ; } } return Math . abs ( d1 - d2 ) ; } public static void main ( String [ ] args ) { int n = 3 ; int arr [ ] [ ] = { { 11 , 2 , 4 } , { 4 , 5 , 6 } , { 10 , 8 , - 12 } } ; System . out . print ( difference ( arr , n ) ) ; } }


"Find distance between two nodes in the given Binary tree for Q queries | Java program to find distance between two nodes using LCA ; log2 ( MAX ) ; Array to store the level of each node ; Vector to store tree ; Pre - Processing to calculate values of lca [ ] [ ] , dist [ ] [ ] ; Using recursion formula to calculate the values of lca [ ] [ ] ; Storing the level of each node ; Using recursion formula to calculate the values of lca [ ] [ ] and dist [ ] [ ] ; Function to find the distance between given nodes u and v ; The node which is present farthest from the root node is taken as v . If u is farther from root node then swap the two ; Finding the ancestor of v which is at same level as u ; Adding distance of node v till its 2 ^ i - th ancestor ; If u is the ancestor of v then u is the LCA of u and v ; Finding the node closest to the root which is not the common ancestor of u and v i . e . a node x such that x is not the common ancestor of u and v but lca [ x ] [ 0 ] is ; Adding the distance of v and u to its 2 ^ i - th ancestor ; Adding the distance of u and v to its first ancestor ; Driver Code ; Number of nodes ; Add edges with their cost ; Initialising lca and dist values with - 1 and 0 respectively ; Perform DFS ; Query 1 : { 1 , 3 } ; Query 2 : { 2 , 3 } ; Query 3 : { 3 , 5 }"
How can the above be solved in Java?

import java . io . * ; import java . util . * ; class GFG { static final int MAX = 1000 ; static final int log = 10 ; static int [ ] level = new int [ MAX ] ; static int [ ] [ ] lca = new int [ MAX ] [ log ] ; static int [ ] [ ] dist = new int [ MAX ] [ log ] ; @ SuppressWarnings ( " unchecked " ) static List < List < int [ ] > > graph = new ArrayList ( ) ; static void addEdge ( int u , int v , int cost ) { graph . get ( u ) . add ( new int [ ] { v , cost } ) ; graph . get ( v ) . add ( new int [ ] { u , cost } ) ; } static void dfs ( int node , int parent , int h , int cost ) { lca [ node ] [ 0 ] = parent ; level [ node ] = h ; if ( parent != - 1 ) { dist [ node ] [ 0 ] = cost ; } for ( int i = 1 ; i < log ; i ++ ) { if ( lca [ node ] [ i - 1 ] != - 1 ) { lca [ node ] [ i ] = lca [ lca [ node ] [ i - 1 ] ] [ i - 1 ] ; dist [ node ] [ i ] = dist [ node ] [ i - 1 ] + dist [ lca [ node ] [ i - 1 ] ] [ i - 1 ] ; } } for ( int [ ] i : graph . get ( node ) ) { if ( i [ 0 ] == parent ) continue ; dfs ( i [ 0 ] , node , h + 1 , i [ 1 ] ) ; } } static void findDistance ( int u , int v ) { int ans = 0 ; if ( level [ u ] > level [ v ] ) { int temp = u ; u = v ; v = temp ; } for ( int i = log - 1 ; i >= 0 ; i -- ) { if ( lca [ v ] [ i ] != - 1 && level [ lca [ v ] [ i ] ] >= level [ u ] ) { ans += dist [ v ] [ i ] ; v = lca [ v ] [ i ] ; } } if ( v == u ) { System . out . println ( ans ) ; } else { for ( int i = log - 1 ; i >= 0 ; i -- ) { if ( lca [ v ] [ i ] != lca [ u ] [ i ] ) { ans += dist [ u ] [ i ] + dist [ v ] [ i ] ; v = lca [ v ] [ i ] ; u = lca [ u ] [ i ] ; } } ans += dist [ u ] [ 0 ] + dist [ v ] [ 0 ] ; System . out . println ( ans ) ; } } public static void main ( String [ ] args ) { int n = 5 ; for ( int i = 0 ; i < MAX ; i ++ ) { graph . add ( new ArrayList < int [ ] > ( ) ) ; } addEdge ( 1 , 2 , 2 ) ; addEdge ( 1 , 3 , 3 ) ; addEdge ( 2 , 4 , 5 ) ; addEdge ( 2 , 5 , 7 ) ; for ( int i = 1 ; i <= n ; i ++ ) { for ( int j = 0 ; j < log ; j ++ ) { lca [ i ] [ j ] = - 1 ; dist [ i ] [ j ] = 0 ; } } dfs ( 1...


"Find distance from root to given node in a binary tree | Java program to find distance of a given node from root . ; A Binary Tree Node ; A utility function to create a new Binary Tree Node ; Returns - 1 if x doesn 't exist in tree. Else returns distance of x from root ; Base case ; Initialize distance ; Check if x is present at root or in left subtree or right subtree . ; Driver Program to test above functions"
How can the above be solved in Java?

import java . util . * ; class GfG { static class Node { int data ; Node left , right ; } static Node newNode ( int item ) { Node temp = new Node ( ) ; temp . data = item ; temp . left = null ; temp . right = null ; return temp ; } static int findDistance ( Node root , int x ) { if ( root == null ) return - 1 ; int dist = - 1 ; if ( ( root . data == x ) || ( dist = findDistance ( root . left , x ) ) >= 0 || ( dist = findDistance ( root . right , x ) ) >= 0 ) return dist + 1 ; return dist ; } public static void main ( String [ ] args ) { Node root = newNode ( 5 ) ; root . left = newNode ( 10 ) ; root . right = newNode ( 15 ) ; root . left . left = newNode ( 20 ) ; root . left . right = newNode ( 25 ) ; root . left . right . right = newNode ( 45 ) ; root . right . left = newNode ( 30 ) ; root . right . right = newNode ( 35 ) ; System . out . println ( findDistance ( root , 45 ) ) ; } }


"Find distinct characters in distinct substrings of a string | Java implementation of the approach ; Function to return the count of distinct characters in all the distinct sub - strings of the given string ; To store all the sub - strings ; To store the current sub - string ; To store the characters of the current sub - string ; If current sub - string hasn 't  been stored before ; Insert it into the set ; Update the count of distinct characters ; Driver code"
How can the above be solved in Java?

import java . util . HashSet ; class geeks { public static int countTotalDistinct ( String str ) { int cnt = 0 ; HashSet < String > items = new HashSet < > ( ) ; for ( int i = 0 ; i < str . length ( ) ; ++ i ) { String temp = " " ; HashSet < Character > ans = new HashSet < > ( ) ; for ( int j = i ; j < str . length ( ) ; ++ j ) { temp = temp + str . charAt ( j ) ; ans . add ( str . charAt ( j ) ) ; if ( ! items . contains ( temp ) ) { items . add ( temp ) ; cnt += ans . size ( ) ; } } } return cnt ; } public static void main ( String [ ] args ) { String str = " ABCA " ; System . out . println ( countTotalDistinct ( str ) ) ; } }


"Find distinct integers for a triplet with given product | Java implementation of the approach ; Function to find the required triplets ; To store the factors ; Find factors in Math . sqrt ( x ) time ; Choose a factor ; Choose another factor ; These conditions need to be met for a valid triplet ; Print the valid triplet ; Triplet found ; Triplet not found ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { static void findTriplets ( int x ) { Vector < Integer > fact = new Vector < Integer > ( ) ; HashSet < Integer > factors = new HashSet < Integer > ( ) ; for ( int i = 2 ; i <= Math . sqrt ( x ) ; i ++ ) { if ( x % i == 0 ) { fact . add ( i ) ; if ( x / i != i ) fact . add ( x / i ) ; factors . add ( i ) ; factors . add ( x / i ) ; } } boolean found = false ; int k = fact . size ( ) ; for ( int i = 0 ; i < k ; i ++ ) { int a = fact . get ( i ) ; for ( int j = 0 ; j < k ; j ++ ) { int b = fact . get ( j ) ; if ( ( a != b ) && ( x % ( a * b ) == 0 ) && ( x / ( a * b ) != a ) && ( x / ( a * b ) != b ) && ( x / ( a * b ) != 1 ) ) { System . out . print ( a + " ▁ " + b + " ▁ " + ( x / ( a * b ) ) ) ; found = true ; break ; } } if ( found ) break ; } if ( ! found ) System . out . print ( " - 1" ) ; } public static void main ( String [ ] args ) { int x = 105 ; findTriplets ( x ) ; } }


"Find duplicate in an array in O ( n ) and by using O ( 1 ) extra space | Java code to find the repeated elements in the array where every other is present once ; Function to find duplicate ; Find the intersection point of the slow and fast . ; Find the " entrance " to the cycle . ; Driver Code"
How can the above be solved in Java?

import java . util . * ; class GFG { public static int findDuplicate ( int [ ] arr ) { int slow = arr [ 0 ] ; int fast = arr [ 0 ] ; do { slow = arr [ slow ] ; fast = arr [ arr [ fast ] ] ; } while ( slow != fast ) ; int ptr1 = arr [ 0 ] ; int ptr2 = slow ; while ( ptr1 != ptr2 ) { ptr1 = arr [ ptr1 ] ; ptr2 = arr [ ptr2 ] ; } return ptr1 ; } public static void main ( String [ ] args ) { int [ ] arr = { 1 , 3 , 2 , 1 } ; System . out . println ( " " + findDuplicate ( arr ) ) ; System . exit ( 0 ) ; } }


"Find duplicates in a given array when elements are not limited to a range | Java implementation of the above approach ; Function to find the Duplicates , if duplicate occurs 2 times or more than 2 times in array so , it will print duplicate value only once at output ; initialize ifPresent as false ; ArrayList to store the output ; checking if element is present in the ArrayList or not if present then break ; if element is not present in the ArrayList then add it to ArrayList and make ifPresent at true ; if duplicates is present then print ArrayList ; Driver Code"
How can the above be solved in Java?

import java . util . ArrayList ; public class GFG { static void findDuplicates ( int arr [ ] , int len ) { boolean ifPresent = false ; ArrayList < Integer > al = new ArrayList < Integer > ( ) ; for ( int i = 0 ; i < len - 1 ; i ++ ) { for ( int j = i + 1 ; j < len ; j ++ ) { if ( arr [ i ] == arr [ j ] ) { if ( al . contains ( arr [ i ] ) ) { break ; } else { al . add ( arr [ i ] ) ; ifPresent = true ; } } } } if ( ifPresent == true ) { System . out . print ( al + " ▁ " ) ; } else { System . out . print ( " No ▁ duplicates ▁ present ▁ in ▁ arrays " ) ; } } public static void main ( String [ ] args ) { int arr [ ] = { 12 , 11 , 40 , 12 , 5 , 6 , 5 , 12 , 11 } ; int n = arr . length ; findDuplicates ( arr , n ) ; } }


"Find element at given index after a number of rotations | Java code to rotate an array and answer the index query ; Function to compute the element at given index ; Range [ left ... right ] ; Rotation will not have any effect ; Returning new element ; Driver ; No . of rotations ; Ranges according to 0 - based indexing"
How can the above be solved in Java?

import java . util . * ; class GFG { static int findElement ( int [ ] arr , int [ ] [ ] ranges , int rotations , int index ) { for ( int i = rotations - 1 ; i >= 0 ; i -- ) { int left = ranges [ i ] [ 0 ] ; int right = ranges [ i ] [ 1 ] ; if ( left <= index && right >= index ) { if ( index == left ) index = right ; else index -- ; } } return arr [ index ] ; } public static void main ( String [ ] args ) { int [ ] arr = { 1 , 2 , 3 , 4 , 5 } ; int rotations = 2 ; int [ ] [ ] ranges = { { 0 , 2 } , { 0 , 3 } } ; int index = 1 ; System . out . println ( findElement ( arr , ranges , rotations , index ) ) ; } }


"Find element in a sorted array whose frequency is greater than or equal to n / 2. | Java code to find majority element in a sorted array ; Driver Code"
How can the above be solved in Java?

public class Test { public static int findMajority ( int arr [ ] , int n ) { return arr [ n / 2 ] ; } public static void main ( String args [ ] ) { int arr [ ] = { 1 , 2 , 2 , 3 } ; int n = arr . length ; System . out . println ( findMajority ( arr , n ) ) ; } }


"Find element in array that divides all array elements | JAVA program to find such number in the array that all array elements are divisible by it ; Returns GCD of two numbers ; Function to return the desired number if exists ; Find GCD of array ; Check if GCD is present in array ; Driver Code"
How can the above be solved in Java?

import java . io . * ; class GFG { static int gcd ( int a , int b ) { if ( a == 0 ) return b ; return gcd ( b % a , a ) ; } static int findNumber ( int arr [ ] , int n ) { int ans = arr [ 0 ] ; for ( int i = 0 ; i < n ; i ++ ) ans = gcd ( ans , arr [ i ] ) ; for ( int i = 0 ; i < n ; i ++ ) if ( arr [ i ] == ans ) return ans ; return - 1 ; } public static void main ( String args [ ] ) { int arr [ ] = { 2 , 2 , 4 } ; int n = arr . length ; System . out . println ( findNumber ( arr , n ) ) ; } }


"Find element using minimum segments in Seven Segment Display | Java program to find minimum number of segments required ; Precomputed values of segment used by digit 0 to 9. ; Return the number of segments used by x . ; Finding sum of the segment used by each digit of a number . ; Initialising the minimum segment and minimum number index . ; Finding and comparing segment used by each number arr [ i ] . ; If arr [ i ] used less segment then update minimum segment and minimum number . ; Driver program"
How can the above be solved in Java?

import java . io . * ; class GFG { static int [ ] seg = { 6 , 2 , 5 , 5 , 4 , 5 , 6 , 3 , 7 , 6 } ; static int computeSegment ( int x ) { if ( x == 0 ) return seg [ 0 ] ; int count = 0 ; while ( x > 0 ) { count += seg [ x % 10 ] ; x /= 10 ; } return count ; } static int elementMinSegment ( int [ ] arr , int n ) { int minseg = computeSegment ( arr [ 0 ] ) ; int minindex = 0 ; for ( int i = 1 ; i < n ; i ++ ) { int temp = computeSegment ( arr [ i ] ) ; if ( temp < minseg ) { minseg = temp ; minindex = i ; } } return arr [ minindex ] ; } static public void main ( String [ ] args ) { int [ ] arr = { 489 , 206 , 745 , 123 , 756 } ; int n = arr . length ; System . out . println ( elementMinSegment ( arr , n ) ) ; } }


"Find element with the maximum set bits in an array | Java implementation of the approach ; Function to return the element from the array which has the maximum set bits ; To store the required element and the maximum set bits so far ; Count of set bits in the current element ; Update the max ; Driver code"
How can the above be solved in Java?

class GFG { static int maxBitElement ( int arr [ ] , int n ) { int num = 0 , max = - 1 ; for ( int i = 0 ; i < n ; i ++ ) { int cnt = Integer . bitCount ( arr [ i ] ) ; if ( cnt > max ) { max = cnt ; num = arr [ i ] ; } } return num ; } public static void main ( String [ ] args ) { int arr [ ] = { 3 , 2 , 4 , 7 , 1 , 10 , 5 , 8 , 9 , 6 } ; int n = arr . length ; System . out . print ( maxBitElement ( arr , n ) ) ; } }


"Find elements in a given range having at least one odd divisor | Java program to print all numbers with least one odd factor in the given range ; Function to prints all numbers with at least one odd divisor ; Check if the number is not a power of two ; Driver Code"
How can the above be solved in Java?

class GFG { static int printOddFactorNumber ( int n , int m ) { for ( int i = n ; i <= m ; i ++ ) { if ( ( i > 0 ) && ( ( i & ( i - 1 ) ) != 0 ) ) System . out . print ( i + " ▁ " ) ; } return 0 ; } public static void main ( String [ ] args ) { int N = 2 , M = 10 ; printOddFactorNumber ( N , M ) ; } }


"Find elements larger than half of the elements in an array | Java program to find elements that are larger than half of the elements in array ; Prints elements larger than n / 2 element ; Sort the array in ascending order ; Print last ceil ( n / 2 ) elements ; Driver program"
How can the above be solved in Java?

import java . util . * ; class Gfg { static void findLarger ( int arr [ ] , int n ) { Arrays . sort ( arr ) ; for ( int i = n - 1 ; i >= n / 2 ; i -- ) System . out . print ( arr [ i ] + " ▁ " ) ; } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 3 , 6 , 1 , 0 , 9 } ; int n = arr . length ; findLarger ( arr , n ) ; } }


"Find elements larger than half of the elements in an array | Set 2 | Java program for the above approach ; Function to find the element that are larger than half of elements of the array ; Find the value of mid ; Stores the maximum element ; Stores the frequency of each array element ; Traverse the array in the reverse order ; Decrement the value of count [ i ] and mid ; Print the current element ; Check if the value of mid is equal to 0 ; Driver Code"
How can the above be solved in Java?

import java . util . * ; class GFG { static void findLarger ( int arr [ ] , int n ) { int mid = ( n + 1 ) / 2 ; int mx = Arrays . stream ( arr ) . max ( ) . getAsInt ( ) ; int count [ ] = new int [ mx + 1 ] ; for ( int i = 0 ; i < mx + 1 ; i ++ ) { count [ i ] = 0 ; } for ( int i = 0 ; i < n ; i ++ ) { count [ arr [ i ] ] ++ ; } for ( int i = mx ; i >= 0 ; i -- ) { while ( count [ i ] > 0 ) { count [ i ] -- ; mid -- ; System . out . print ( i + " ▁ " ) ; if ( mid == 0 ) break ; } if ( mid == 0 ) break ; } } public static void main ( String [ ] args ) { int arr [ ] = { 10 , 4 , 2 , 8 , 9 } ; int N = arr . length ; findLarger ( arr , N ) ; } }


"Find elements of array using XOR of consecutive elements | Java program to find the array elements using XOR of consecutive elements ; Function to find the array elements using XOR of consecutive elements ; array to store the original elements ; first element a i . e elements [ 0 ] = a ; To get the next elements we have to calculate xor of previous elements with given xor of 2 consecutive elements . e . g . if a ^ b = k1 so to get b xor a both side . b = k1 ^ a ; Printing the original array elements ; Driver Code"
How can the above be solved in Java?

import java . io . * ; class GFG { static void getElements ( int a , int arr [ ] , int n ) { int elements [ ] = new int [ n + 1 ] ; elements [ 0 ] = a ; for ( int i = 0 ; i < n ; i ++ ) { elements [ i + 1 ] = arr [ i ] ^ elements [ i ] ; } for ( int i = 0 ; i < n + 1 ; i ++ ) System . out . print ( elements [ i ] + " ▁ " ) ; } public static void main ( String [ ] args ) { int arr [ ] = { 13 , 2 , 6 , 1 } ; int n = arr . length ; int a = 5 ; getElements ( a , arr , n ) ; } }


"Find elements which are present in first array and not in second | Java efficient program to find elements which are not present in second array ; Function for finding elements which are there in a [ ] but not in b [ ] . ; Store all elements of second array in a hash table ; Print all elements of first array that are not present in hash table ; Driver code"
How can the above be solved in Java?

import java . util . HashSet ; import java . util . Set ; public class GfG { static void findMissing ( int a [ ] , int b [ ] , int n , int m ) { HashSet < Integer > s = new HashSet < > ( ) ; for ( int i = 0 ; i < m ; i ++ ) s . add ( b [ i ] ) ; for ( int i = 0 ; i < n ; i ++ ) if ( ! s . contains ( a [ i ] ) ) System . out . print ( a [ i ] + " ▁ " ) ; } public static void main ( String [ ] args ) { int a [ ] = { 1 , 2 , 6 , 3 , 4 , 5 } ; int b [ ] = { 2 , 4 , 3 , 1 , 0 } ; int n = a . length ; int m = b . length ; findMissing ( a , b , n , m ) ; } }


"Find elements which are present in first array and not in second | Java simple program to find elements which are not present in second array ; Function for finding elements which are there in a [ ] but not in b [ ] . ; Driver Code"
How can the above be solved in Java?

class GFG { static void findMissing ( int a [ ] , int b [ ] , int n , int m ) { for ( int i = 0 ; i < n ; i ++ ) { int j ; for ( j = 0 ; j < m ; j ++ ) if ( a [ i ] == b [ j ] ) break ; if ( j == m ) System . out . print ( a [ i ] + " ▁ " ) ; } } public static void main ( String [ ] args ) { int a [ ] = { 1 , 2 , 6 , 3 , 4 , 5 } ; int b [ ] = { 2 , 4 , 3 , 1 , 0 } ; int n = a . length ; int m = b . length ; findMissing ( a , b , n , m ) ; } }


"Find even occurring elements in an array of limited range | Java Program to find the even occurring elements in given array ; Function to find the even occurring elements in given array ; do for each element of array ; left - shift 1 by value of current element ; Toggle the bit everytime element gets repeated ; Traverse array again and use _xor to find even occurring elements ; left - shift 1 by value of current element ; Each 0 in _xor represents an even occurrence ; print the even occurring numbers ; set bit as 1 to avoid printing duplicates ; Driver code"
How can the above be solved in Java?

class GFG { static void printRepeatingEven ( int arr [ ] , int n ) { long _xor = 0L ; long pos ; for ( int i = 0 ; i < n ; ++ i ) { pos = 1 << arr [ i ] ; _xor ^= pos ; } for ( int i = 0 ; i < n ; ++ i ) { pos = 1 << arr [ i ] ; if ( ! ( ( pos & _xor ) != 0 ) ) { System . out . print ( arr [ i ] + " ▁ " ) ; _xor ^= pos ; } } } public static void main ( String args [ ] ) { int arr [ ] = { 9 , 12 , 23 , 10 , 12 , 12 , 15 , 23 , 14 , 12 , 15 } ; int n = arr . length ; printRepeatingEven ( arr , n ) ; } }


"Find farthest node from each node in Tree | Java implementation to find the farthest node from each vertex of the tree ; Adjacency list to store edges ; Add edge between U and V in tree ; Edge from U to V ; Edge from V to U ; DFS to find the first End Node of diameter ; Calculating level of nodes ; Go in opposite direction of parent ; Function to clear the levels of the nodes ; Set all value of lvl [ ] to 0 for next dfs ; Set maximum with 0 ; DFS will calculate second end of the diameter ; Calculating level of nodes ; Store the node with maximum depth from end1 ; Go in opposite direction of parent ; Function to find the distance of the farthest distant node ; Storing distance from end1 to node u ; Function to find the distance of nodes from second end of diameter ; Storing distance from end2 to node u ; Joining Edge between two nodes of the tree ; Find the one end of the diameter of tree ; Find the other end of the diameter of tree ; Find the distance to each node from end1 ; Find the distance to each node from end2 ; Comparing distance between the two ends of diameter ; Driver Code ; Function call"
How can the above be solved in Java?

import java . util . * ; class GFG { static int N = 10000 ; @ SuppressWarnings ( " unchecked " ) static Vector < Integer > [ ] adj = new Vector [ N ] ; static int [ ] lvl = new int [ N ] , dist1 = new int [ N ] , dist2 = new int [ N ] ; static void AddEdge ( int u , int v ) { adj [ u ] . add ( v ) ; adj [ v ] . add ( u ) ; } static int end1 , end2 , maxi ; static void findFirstEnd ( int u , int p ) { lvl [ u ] = 1 + lvl [ p ] ; if ( lvl [ u ] > maxi ) { maxi = lvl [ u ] ; end1 = u ; } for ( int i = 0 ; i < adj [ u ] . size ( ) ; i ++ ) { if ( adj [ u ] . elementAt ( i ) != p ) { findFirstEnd ( adj [ u ] . elementAt ( i ) , u ) ; } } } static void clear ( int n ) { for ( int i = 0 ; i <= n ; i ++ ) { lvl [ i ] = 0 ; } maxi = 0 ; dist1 [ 0 ] = dist2 [ 0 ] = - 1 ; } static void findSecondEnd ( int u , int p ) { lvl [ u ] = 1 + lvl [ p ] ; if ( lvl [ u ] > maxi ) { maxi = lvl [ u ] ; end2 = u ; } for ( int i = 0 ; i < adj [ u ] . size ( ) ; i ++ ) { if ( adj [ u ] . elementAt ( i ) != p ) { findSecondEnd ( adj [ u ] . elementAt ( i ) , u ) ; } } } static void findDistancefromFirst ( int u , int p ) { dist1 [ u ] = 1 + dist1 [ p ] ; for ( int i = 0 ; i < adj [ u ] . size ( ) ; i ++ ) { if ( adj [ u ] . elementAt ( i ) != p ) { findDistancefromFirst ( adj [ u ] . elementAt ( i ) , u ) ; } } } static void findDistancefromSecond ( int u , int p ) { dist2 [ u ] = 1 + dist2 [ p ] ; for ( int i = 0 ; i < adj [ u ] . size ( ) ; i ++ ) { if ( adj [ u ] . elementAt ( i ) != p ) { findDistancefromSecond ( adj [ u ] . elementAt ( i ) , u ) ; } } } static void findNodes ( ) { int n = 5 ; AddEdge ( 1 , 2 ) ; AddEdge ( 1 , 3 ) ; AddEdge ( 3 , 4 ) ; AddEdge ( 3 , 5 ) ; findFirstEnd ( 1 , 0 ) ; clear ( n ) ; findSecondEnd ( end1 , 0 ) ; findDistancefromFirst ( end1 , 0 ) ; findDistancefromSecond ( end2 , 0 ) ; for ( int i = 1 ; i <= n ; i ++ ) { int x = dist1 [ i ] ; int y = dist2 [ i ] ; if ( x >= y ) { System . out . print ( end1 + " ▁ " ) ; } else { System . out . print ( end2 + " ▁ " ) ; } } } public static void main ( String...


"Find final value if we double after every successful search in array | Java program to find value if we double the value after every successful search ; Function to Find the value of k ; Search for k . After every successful search , double k . ; Driver Code"
How can the above be solved in Java?

class GFG { static int findValue ( int arr [ ] , int n , int k ) { for ( int i = 0 ; i < n ; i ++ ) if ( arr [ i ] == k ) k *= 2 ; return k ; } public static void main ( String [ ] args ) { int arr [ ] = { 2 , 3 , 4 , 10 , 8 , 1 } , k = 2 ; int n = arr . length ; System . out . print ( findValue ( arr , n , k ) ) ; } }


"Find first and last digits of a number | Java Program to find first and last digits of a number ; Find the first digit ; Remove last digit from number till only one digit is left ; return the first digit ; Find the last digit ; return the last digit ; driver function"
How can the above be solved in Java?

import java . util . * ; import java . lang . * ; public class GfG { public static int firstDigit ( int n ) { while ( n >= 10 ) n /= 10 ; return n ; } public static int lastDigit ( int n ) { return ( n % 10 ) ; } public static void main ( String argc [ ] ) { int n = 98562 ; System . out . println ( firstDigit ( n ) + " ▁ " + lastDigit ( n ) ) ; } }


"Find first and last digits of a number | Java program to find first and last digits of a number ; Find the first digit ; Find total number of digits - 1 ; Find first digit ; Return first digit ; Find the last digit ; return the last digit ; Driver program"
How can the above be solved in Java?

import java . math . * ; class GFG { static int firstDigit ( int n ) { int digits = ( int ) ( Math . log10 ( n ) ) ; n = ( int ) ( n / ( int ) ( Math . pow ( 10 , digits ) ) ) ; return n ; } static int lastDigit ( int n ) { return ( n % 10 ) ; } public static void main ( String args [ ] ) { int n = 98562 ; System . out . println ( firstDigit ( n ) + " ▁ " + lastDigit ( n ) ) ; } }


"Find first k natural numbers missing in given array | Java code for the above approach ; Program to print first k missing number ; Creating a hashmap ; Iterate over array ; Iterate to find missing element ; Driver Code"
How can the above be solved in Java?

import java . io . * ; import java . util . HashMap ; class GFG { static void printmissingk ( int arr [ ] , int n , int k ) { HashMap < Integer , Integer > d = new HashMap < > ( ) ; for ( int i = 0 ; i < n ; i ++ ) d . put ( arr [ i ] , arr [ i ] ) ; int cnt = 1 ; int fl = 0 ; for ( int i = 0 ; i < ( n + k ) ; i ++ ) { if ( ! d . containsKey ( cnt ) ) { fl += 1 ; System . out . print ( cnt + " ▁ " ) ; if ( fl == k ) break ; } cnt += 1 ; } } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 4 , 3 } ; int n = arr . length ; int k = 3 ; printmissingk ( arr , n , k ) ; } }


"Find first k natural numbers missing in given array | Java program to find missing k numbers in an array . ; Prints first k natural numbers in arr [ 0. . n - 1 ] ; Find first positive number ; Now find missing numbers between array elements ; Find missing numbers after maximum . ; Driver code"
How can the above be solved in Java?

import java . util . Arrays ; class GFG { static void printKMissing ( int [ ] arr , int n , int k ) { Arrays . sort ( arr ) ; int i = 0 ; while ( i < n && arr [ i ] <= 0 ) i ++ ; int count = 0 , curr = 1 ; while ( count < k && i < n ) { if ( arr [ i ] != curr ) { System . out . print ( curr + " ▁ " ) ; count ++ ; } else i ++ ; curr ++ ; } while ( count < k ) { System . out . print ( curr + " ▁ " ) ; curr ++ ; count ++ ; } } public static void main ( String [ ] args ) { int [ ] arr = { 2 , 3 , 4 } ; int n = arr . length ; int k = 3 ; printKMissing ( arr , n , k ) ; } }


"Find first non matching leaves in two binary trees | Java program to find first leaves that are not same . ; Tree node ; Utility method to create a new node ; Prints the first non - matching leaf node in two trees if it exists , else prints nothing . ; If any of the tree is empty ; Create two stacks for preorder traversals ; If traversal of one tree is over and other tree still has nodes . ; Do iterative traversal of first tree and find first lead node in it as " temp1" ; pushing right childfirst so that left child comes first while popping . ; Do iterative traversal of second tree and find first lead node in it as " temp2" ; If we found leaves in both trees ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GfG { static class Node { int data ; Node left , right ; } static Node newNode ( int x ) { Node temp = new Node ( ) ; temp . data = x ; temp . left = null ; temp . right = null ; return temp ; } static boolean isLeaf ( Node t ) { return ( ( t . left == null ) && ( t . right == null ) ) ; } static void findFirstUnmatch ( Node root1 , Node root2 ) { if ( root1 == null root2 == null ) return ; Stack < Node > s1 = new Stack < Node > ( ) ; Stack < Node > s2 = new Stack < Node > ( ) ; s1 . push ( root1 ) ; s2 . push ( root2 ) ; while ( ! s1 . isEmpty ( ) || ! s2 . isEmpty ( ) ) { if ( s1 . isEmpty ( ) || s2 . isEmpty ( ) ) return ; Node temp1 = s1 . peek ( ) ; s1 . pop ( ) ; while ( temp1 != null && isLeaf ( temp1 ) != true ) { s1 . push ( temp1 . right ) ; s1 . push ( temp1 . left ) ; temp1 = s1 . peek ( ) ; s1 . pop ( ) ; } Node temp2 = s2 . peek ( ) ; s2 . pop ( ) ; while ( temp2 != null && isLeaf ( temp2 ) != true ) { s2 . push ( temp2 . right ) ; s2 . push ( temp2 . left ) ; temp2 = s2 . peek ( ) ; s2 . pop ( ) ; } if ( temp1 != null && temp2 != null ) { if ( temp1 . data != temp2 . data ) { System . out . println ( temp1 . data + " ▁ " + temp2 . data ) ; return ; } } } } public static void main ( String [ ] args ) { Node root1 = newNode ( 5 ) ; root1 . left = newNode ( 2 ) ; root1 . right = newNode ( 7 ) ; root1 . left . left = newNode ( 10 ) ; root1 . left . right = newNode ( 11 ) ; Node root2 = newNode ( 6 ) ; root2 . left = newNode ( 10 ) ; root2 . right = newNode ( 15 ) ; findFirstUnmatch ( root1 , root2 ) ; } }


"Find first non | Java implementation to find the first non - repeating element of the string using Linked List ; Function to find the first non - repeating element of the given string using Linked List ; Driver Code ; Function Call"
How can the above be solved in Java?

import java . util . LinkedList ; public class FirstNonRepeatingElement { static void firstNonRepElement ( String str ) { LinkedList < Character > list = new LinkedList < Character > ( ) ; list . add ( str . charAt ( 0 ) ) ; for ( int i = 1 ; i < str . length ( ) ; i ++ ) { if ( list . contains ( str . charAt ( i ) ) ) list . remove ( list . indexOf ( str . charAt ( i ) ) ) ; else list . add ( str . charAt ( i ) ) ; } System . out . println ( list . get ( 0 ) ) ; } public static void main ( String [ ] args ) { String str = " geeksforgeeks " ; firstNonRepElement ( str ) ; } }


"Find first undeleted integer from K to N in given unconnected Graph after performing Q queries | Java program for the above approach ; Function to perform th Get operation of disjoint set union ; Function to perform the union operation of dijoint set union ; Update the graph [ a ] as b ; Function to perform given queries on set of vertices initially not connected ; Stores the vertices ; Mark every vertices rightmost vertex as i ; Traverse the queries array ; Check if it is first type of the givan query ; Get the parent of a ; Print the answer for the second query ; Driver Code"
How can the above be solved in Java?

class GFG { public static int Get ( int [ ] graph , int a ) { return graph [ a ] = ( graph [ a ] == a ? a : Get ( graph , graph [ a ] ) ) ; } public static void Union ( int [ ] graph , int a , int b ) { a = Get ( graph , a ) ; b = Get ( graph , b ) ; graph [ a ] = b ; } public static void Queries ( int [ ] [ ] queries , int N , int M ) { int [ ] graph = new int [ N + 2 ] ; for ( int i = 1 ; i <= N + 1 ; i ++ ) { graph [ i ] = i ; } for ( int [ ] query : queries ) { if ( query [ 0 ] == 1 ) { Union ( graph , query [ 1 ] , query [ 1 ] + 1 ) ; } else { int a = Get ( graph , query [ 1 ] ) ; if ( a == N + 1 ) System . out . print ( - 1 ) ; else System . out . print ( graph [ a ] + " ▁ " ) ; } } } public static void main ( String args [ ] ) { int N = 5 ; int [ ] [ ] queries = { { 2 , 1 } , { 1 , 1 } , { 2 , 1 } , { 2 , 3 } } ; int Q = queries . length ; Queries ( queries , N , Q ) ; } }


"Find four elements a , b , c and d in an array such that a + b = c + d | Java Program to find four different elements a , b , c and d of array such that a + b = c + d ; Class to represent a pair ; function to find a , b , c , d such that ( a + b ) = ( c + d ) ; Create an empty Hash to store mapping from sum to pair indexes ; Traverse through all possible pairs of arr [ ] ; If sum of current pair is not in hash , then store it and continue to next pair ; Testing program"
How can the above be solved in Java?

import java . io . * ; import java . util . * ; class ArrayElements { class pair { int first , second ; pair ( int f , int s ) { first = f ; second = s ; } } ; boolean findPairs ( int arr [ ] ) { HashMap < Integer , pair > map = new HashMap < Integer , pair > ( ) ; int n = arr . length ; for ( int i = 0 ; i < n ; ++ i ) { for ( int j = i + 1 ; j < n ; ++ j ) { int sum = arr [ i ] + arr [ j ] ; if ( ! map . containsKey ( sum ) ) map . put ( sum , new pair ( i , j ) ) ; else { pair p = map . get ( sum ) ; System . out . println ( " ( " + arr [ p . first ] + " , ▁ " + arr [ p . second ] + " ) ▁ and ▁ ( " + arr [ i ] + " , ▁ " + arr [ j ] + " ) " ) ; return true ; } } } return false ; } public static void main ( String args [ ] ) { int arr [ ] = { 3 , 4 , 7 , 1 , 2 , 9 , 8 } ; ArrayElements a = new ArrayElements ( ) ; a . findPairs ( arr ) ; } }


"Find four elements that sum to a given value | Set 1 ( n ^ 3 solution ) |  ; A naive solution to print all combination of 4 elements in A [ ] with sum equal to X ; Fix the first element and find other three ; Fix the second element and find other two ; Fix the third element and find the fourth ; find the fourth ; Driver program to test above functions"
How can the above be solved in Java?

class FindFourElements { void findFourElements ( int A [ ] , int n , int X ) { for ( int i = 0 ; i < n - 3 ; i ++ ) { for ( int j = i + 1 ; j < n - 2 ; j ++ ) { for ( int k = j + 1 ; k < n - 1 ; k ++ ) { for ( int l = k + 1 ; l < n ; l ++ ) { if ( A [ i ] + A [ j ] + A [ k ] + A [ l ] == X ) System . out . print ( A [ i ] + " ▁ " + A [ j ] + " ▁ " + A [ k ] + " ▁ " + A [ l ] ) ; } } } } } public static void main ( String [ ] args ) { FindFourElements findfour = new FindFourElements ( ) ; int A [ ] = { 10 , 20 , 30 , 40 , 1 , 2 } ; int n = A . length ; int X = 91 ; findfour . findFourElements ( A , n , X ) ; } }


"Find four elements that sum to a given value | Set 2 | A hashing based Java program to find if there are four elements with given sum . ; The function finds four elements with given sum X ; Store sums of all pairs in a hash table ; Traverse through all pairs and search for X - ( current pair sum ) . ; If X - sum is present in hash table , ; Making sure that all elements are distinct array elements and an element is not considered more than once . ; Driver Code ; Function call"
How can the above be solved in Java?

import java . util . HashMap ; class GFG { static class pair { int first , second ; public pair ( int first , int second ) { this . first = first ; this . second = second ; } } static void findFourElements ( int arr [ ] , int n , int X ) { HashMap < Integer , pair > mp = new HashMap < Integer , pair > ( ) ; for ( int i = 0 ; i < n - 1 ; i ++ ) for ( int j = i + 1 ; j < n ; j ++ ) mp . put ( arr [ i ] + arr [ j ] , new pair ( i , j ) ) ; for ( int i = 0 ; i < n - 1 ; i ++ ) { for ( int j = i + 1 ; j < n ; j ++ ) { int sum = arr [ i ] + arr [ j ] ; if ( mp . containsKey ( X - sum ) ) { pair p = mp . get ( X - sum ) ; if ( p . first != i && p . first != j && p . second != i && p . second != j ) { System . out . print ( arr [ i ] + " , ▁ " + arr [ j ] + " , ▁ " + arr [ p . first ] + " , ▁ " + arr [ p . second ] ) ; return ; } } } } } public static void main ( String [ ] args ) { int arr [ ] = { 10 , 20 , 30 , 40 , 1 , 2 } ; int n = arr . length ; int X = 91 ; findFourElements ( arr , n , X ) ; } }


"Find four elements that sum to a given value | Set 2 | Java program to find four elements with the given sum ; Function to find 4 elements that add up to given sum ; Iterate from 0 to temp . length ; Iterate from 0 to arr . length ; Iterate from i + 1 to arr . length ; Store curr_sum = arr [ i ] + arr [ j ] ; Check if X - curr_sum if present in map ; Store pair having map value X - curr_sum ; Print the output ; Program for two Sum ; to store indices of two sum pair ; Driver Code ; Function call"
How can the above be solved in Java?

import java . util . * ; class fourElementWithSum { public static void fourSum ( int X , int [ ] arr , Map < Integer , pair > map ) { int [ ] temp = new int [ arr . length ] ; for ( int i = 0 ; i < temp . length ; i ++ ) temp [ i ] = 0 ; for ( int i = 0 ; i < arr . length - 1 ; i ++ ) { for ( int j = i + 1 ; j < arr . length ; j ++ ) { int curr_sum = arr [ i ] + arr [ j ] ; if ( map . containsKey ( X - curr_sum ) ) { pair p = map . get ( X - curr_sum ) ; if ( p . first != i && p . sec != i && p . first != j && p . sec != j && temp [ p . first ] == 0 && temp [ p . sec ] == 0 && temp [ i ] == 0 && temp [ j ] == 0 ) { System . out . printf ( " % d , % d , % d , % d " , arr [ i ] , arr [ j ] , arr [ p . first ] , arr [ p . sec ] ) ; temp [ p . sec ] = 1 ; temp [ i ] = 1 ; temp [ j ] = 1 ; break ; } } } } } public static Map < Integer , pair > twoSum ( int [ ] nums ) { Map < Integer , pair > map = new HashMap < > ( ) ; for ( int i = 0 ; i < nums . length - 1 ; i ++ ) { for ( int j = i + 1 ; j < nums . length ; j ++ ) { map . put ( nums [ i ] + nums [ j ] , new pair ( i , j ) ) ; } } return map ; } public static class pair { int first , sec ; public pair ( int first , int sec ) { this . first = first ; this . sec = sec ; } } public static void main ( String args [ ] ) { int [ ] arr = { 10 , 20 , 30 , 40 , 1 , 2 } ; int n = arr . length ; int X = 91 ; Map < Integer , pair > map = twoSum ( arr ) ; fourSum ( X , arr , map ) ; } }


"Find four factors of N with maximum product and sum equal to N | Set 3 | Java implementation of above approach ; Function to find primes ; Corner cases ; This is checked so that we can skip middle five numbers in below loop ; Function to find factors ; run a loop upto square root of that number ; if the n is perfect square ; otherwise push it 's two divisors ; sort the divisors ; Function to find max product ; To store factors of ' n ' ; find factors ; if it is divisible by 4. ; if it is prime ; otherwise answer will be possible ; include last third factor ; nested loop to find other two factors ; Driver code ; function call"
How can the above be solved in Java?

import java . util . * ; import java . lang . * ; import java . io . * ; 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 Vector < Vector < Integer > > v = new Vector < Vector < Integer > > ( ) ; static void factors ( int N ) { for ( int i = 2 ; i < N ; i ++ ) { for ( int j = 1 ; j * j <= i ; j ++ ) { if ( i % j == 0 ) { if ( i / j == j ) v . get ( i ) . add ( j ) ; else { v . get ( i ) . add ( j ) ; v . get ( i ) . add ( i / j ) ; } } } Collections . sort ( v . get ( i ) ) ; } } static int product ( int n ) { v . clear ( ) ; for ( int i = 0 ; i < n + 100 ; i ++ ) v . add ( new Vector < Integer > ( ) ) ; factors ( n + 100 ) ; if ( n % 4 == 0 ) { int x = n / 4 ; x *= x ; return x * x ; } else { if ( isPrime ( n ) ) return - 1 ; else { int ans = - 1 ; if ( v . get ( n ) . size ( ) > 2 ) { int fac = v . get ( n ) . get ( v . get ( n ) . size ( ) - 3 ) ; for ( int i = v . get ( n ) . size ( ) - 1 ; i >= 0 ; i -- ) { for ( int j = v . get ( n ) . size ( ) - 1 ; j >= 0 ; j -- ) { if ( ( fac * 2 ) + ( v . get ( n ) . get ( j ) + v . get ( n ) . get ( i ) ) == n ) ans = Math . max ( ans , fac * fac * v . get ( n ) . get ( j ) * v . get ( n ) . get ( i ) ) ; } } return ans ; } } } return 0 ; } public static void main ( String args [ ] ) { int n = 24 ; System . out . println ( product ( n ) ) ; } }


"Find four factors of N with maximum product and sum equal to N | Set | Java program to find four factors of N with maximum product and sum equal to N ; Function to find factors and to print those four factors ; push all the factors in the container ; number of factors ; Initial maximum ; hash - array to mark the pairs ; form all the pair sums ; if the pair sum is less than n ; push in another container ; mark the sum with the elements formed ; mark in the map that v . get ( i ) + v . get ( j ) is present ; new size of all the pair sums ; iterate for all pair sum ; the required part ; if the required part is also present in pair sum ; find the elements with which the first pair is formed ; find the elements with which the second pair is formed ; check for previous maximum ; Driver code"
How can the above be solved in Java?

import java . util . * ; import java . lang . * ; import java . io . * ; class GFG { static void findfactors ( int n ) { HashMap < Integer , Integer > mpp = new HashMap < > ( ) ; Vector < Integer > v = new Vector < Integer > ( ) , v1 = new Vector < Integer > ( ) ; for ( int i = 1 ; i <= ( int ) Math . sqrt ( n ) ; i ++ ) { if ( n % i == 0 ) { v . add ( i ) ; if ( i != ( n / i ) && i != 1 ) v . add ( n / i ) ; } } int s = v . size ( ) ; int maxi = - 1 ; int mp1_first [ ] = new int [ n + 5 ] , mp1_second [ ] = new int [ n + 5 ] ; for ( int i = 0 ; i < s ; i ++ ) { for ( int j = i ; j < s ; j ++ ) { if ( v . get ( i ) + v . get ( j ) < n ) { v1 . add ( v . get ( i ) + v . get ( j ) ) ; mp1_first [ v . get ( i ) + v . get ( j ) ] = v . get ( i ) ; mp1_second [ v . get ( i ) + v . get ( j ) ] = v . get ( j ) ; mpp . put ( v . get ( i ) + v . get ( j ) , 1 ) ; } } } s = v1 . size ( ) ; for ( int i = 0 ; i < s ; i ++ ) { int el = n - ( v1 . get ( i ) ) ; if ( mpp . get ( el ) != null ) { int a = mp1_first [ v1 . get ( i ) ] ; int b = mp1_second [ v1 . get ( i ) ] ; int c = mp1_first [ n - v1 . get ( i ) ] ; int d = mp1_second [ n - v1 . get ( i ) ] ; maxi = Math . max ( a * b * c * d , maxi ) ; } } if ( maxi == - 1 ) System . out . println ( " Not ▁ Possible " ) ; else { System . out . println ( " The ▁ maximum ▁ product " + " ▁ is ▁ " + maxi ) ; } } public static void main ( String args [ ] ) { int n = 50 ; findfactors ( n ) ; } }


"Find frequency of each element in a limited range array in less than O ( n ) time | Java program to count number of occurrences of each element in the array ; It prints number of occurrences of each element in the array . ; HashMap to store frequencies ; traverse the array ; update the frequency ; traverse the hashmap ; Driver function"
How can the above be solved in Java?

import java . io . * ; import java . util . * ; class GFG { static void findFrequency ( int [ ] arr , int n ) { Map < Integer , Integer > mp = new HashMap < Integer , Integer > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( ! mp . containsKey ( arr [ i ] ) ) mp . put ( arr [ i ] , 0 ) ; mp . put ( arr [ i ] , mp . get ( arr [ i ] ) + 1 ) ; } for ( Map . Entry < Integer , Integer > kvp : mp . entrySet ( ) ) { System . out . println ( " Element ▁ " + kvp . getKey ( ) + " ▁ occurs ▁ " + kvp . getValue ( ) + " ▁ times " ) ; } } public static void main ( String [ ] args ) { int [ ] arr = { 1 , 1 , 1 , 2 , 3 , 3 , 5 , 5 , 8 , 8 , 8 , 9 , 9 , 10 } ; int n = arr . length ; findFrequency ( arr , n ) ; } }


"Find frequency of each element in a limited range array in less than O ( n ) time | Java program to count number of occurrences of each element in the array in O ( n ) time and O ( 1 ) space ; check if the current element is equal to previous element . ; reset the frequency ; print the last element and its frequency ; Driver code"
How can the above be solved in Java?

function void findFrequencies ( ele ) { var freq = 1 ; var idx = 1 ; var element = ele [ 0 ] ; while ( idx < ele . length ) { if ( ele [ idx - 1 ] == ele [ idx ] ) { freq ++ ; idx ++ ; } else { document . write ( element + " ▁ " + freq + " < br > " ) ; element = ele [ idx ] ; idx ++ ; freq = 1 ; } } document . write ( element + " ▁ " + freq + " < br > " ) ; } document . write ( " - - - frequencies ▁ in ▁ a ▁ sorted ▁ array - - - - " + " < br > " ) ; findFrequencies ( new Array ( 10 , 20 , 30 , 30 , 30 , 40 , 50 , 50 , 50 , 50 , 70 ) ) ;


"Find frequency of each element in a limited range array in less than O ( n ) time | Java program to count number of occurrences of each element in the array in less than O ( n ) time ; A recursive function to count number of occurrences for each element in the array without traversing the whole array ; If element at index low is equal to element at index high in the array ; increment the frequency of the element by count of elements between high and low ; Find mid and recurse for left and right subarray ; A wrapper over recursive function findFrequencyUtil ( ) . It print number of occurrences of each element in the array . ; create a empty vector to store frequencies and initialize it by 0. Size of vector is maximum value ( which is last value in sorted array ) plus 1. ; Fill the vector with frequency ; Print the frequencies ; Driver Code"
How can the above be solved in Java?

import java . util . * ; class GFG { static void findFrequencyUtil ( int arr [ ] , int low , int high , int [ ] freq ) { if ( arr [ low ] == arr [ high ] ) { freq [ arr [ low ] ] += high - low + 1 ; } else { int mid = ( low + high ) / 2 ; findFrequencyUtil ( arr , low , mid , freq ) ; findFrequencyUtil ( arr , mid + 1 , high , freq ) ; } } static void findFrequency ( int arr [ ] , int n ) { int [ ] freq = new int [ arr [ n - 1 ] + 1 ] ; findFrequencyUtil ( arr , 0 , n - 1 , freq ) ; for ( int i = 0 ; i <= arr [ n - 1 ] ; i ++ ) if ( freq [ i ] != 0 ) System . out . println ( " Element ▁ " + i + " ▁ occurs ▁ " + freq [ i ] + " ▁ times " ) ; } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 1 , 1 , 2 , 3 , 3 , 5 , 5 , 8 , 8 , 8 , 9 , 9 , 10 } ; int n = arr . length ; findFrequency ( arr , n ) ; } }


"Find gcd ( a ^ n , c ) where a , n and c can vary from 1 to 10 ^ 9 | Java program to find GCD of a ^ n and b . ; Iterative Function to calculate ( x ^ y ) % p in O ( log y ) ; x = x % p ; Update x if it is more than or equal to p ; If y is odd , multiply x with result ; y must be even now y = y >> 1 ; y = y / 2 ; Finds GCD of a and b ; Finds GCD of a ^ n and c ; check if c is a divisor of a ; First compute ( a ^ n ) % c ; Now simply return GCD of modulo power and c . ; Driver code"
How can the above be solved in Java?

class GFG { static long modPower ( long x , long y , long p ) { while ( y > 0 ) { if ( ( y & 1 ) > 0 ) res = ( res * x ) % p ; x = ( x * x ) % p ; } return res ; } static long gcd ( long a , long b ) { if ( b == 0 ) return a ; return gcd ( b , a % b ) ; } static long gcdPow ( long a , long n , long c ) { if ( a % c == 0 ) return c ; long modexpo = modPower ( a , n , c ) ; return gcd ( modexpo , c ) ; } public static void main ( String [ ] args ) { long a = 10248585 , n = 1000000 , c = 12564 ; System . out . println ( gcdPow ( a , n , c ) ) ; } }


"Find height of a special binary tree whose leaf nodes are connected | Java implementation to calculate height of a special tree whose leaf nodes forms a circular doubly linked list ; User defined node class ; Constructor to create a new tree node ; function to check if given node is a leaf node or node ; If given node ' s ▁ left ' s right is pointing to given node and its right ' s ▁ left ▁ is ▁ pointing ▁ to ▁ the ▁ node ▁ ▁ itself ▁ then ▁ it ' s a leaf ; Compute the height of a tree -- the number of Nodes along the longest path from the root node down to the farthest leaf node . ; if node is NULL , return 0 ; if node is a leaf node , return 1 ; compute the depth of each subtree and take maximum ; Driver code ; Given tree contains 3 leaf nodes ; create circular doubly linked list out of leaf nodes of the tree set next pointer of linked list ; set prev pointer of linked list ; calculate height of the tree"
How can the above be solved in Java?

import java . io . * ; import java . util . * ; class Node { int data ; Node left , right ; Node ( int key ) { data = key ; left = right = null ; } } class GFG { static boolean isLeaf ( Node node ) { return ( node . left != null && node . left . right == node && node . right != null && node . right . left == node ) ; } static int maxDepth ( Node node ) { if ( node == null ) return 0 ; if ( isLeaf ( node ) ) return 1 ; return 1 + Math . max ( maxDepth ( node . left ) , maxDepth ( node . right ) ) ; } public static void main ( String args [ ] ) { Node root = new Node ( 1 ) ; root . left = new Node ( 2 ) ; root . right = new Node ( 3 ) ; root . left . left = new Node ( 4 ) ; root . left . right = new Node ( 5 ) ; root . left . left . left = new Node ( 6 ) ; Node L1 = root . left . left . left ; Node L2 = root . left . right ; Node L3 = root . right ; L1 . right = L2 ; L2 . right = L3 ; L3 . right = L1 ; L3 . left = L2 ; L2 . left = L1 ; L1 . left = L3 ; System . out . println ( " Height ▁ of ▁ tree ▁ is ▁ " + maxDepth ( root ) ) ; } }


"Find i 'th Index character in a binary string obtained after n iterations | Java Program to find ith character in a binary String . ; Function to store binary Representation ; Function to find ith character ; Function to change decimal to binary ; Assign s1 String in s String ; Driver Code"
How can the above be solved in Java?

import java . io . * ; import java . util . Arrays ; class GFG { static String s = " " ; static String ReverseString ( String s ) { char [ ] arr = s . toCharArray ( ) ; for ( int i = 0 ; i < arr . length / 2 ; i ++ ) { char temp = arr [ i ] ; arr [ i ] = arr [ arr . length - i - 1 ] ; arr [ arr . length - i - 1 ] = temp ; } return new String ( arr ) ; } static void binary_conversion ( int m ) { while ( m != 0 ) { int tmp = m % 2 ; s += Integer . toString ( tmp ) ; m = ( int ) ( m / 2 ) ; } s = ReverseString ( s ) ; } static int find_character ( int n , int m , int i ) { binary_conversion ( m ) ; String s1 = " " ; for ( int x = 0 ; x < n ; x ++ ) { for ( int y = 0 ; y < s . length ( ) ; y ++ ) { if ( s . charAt ( y ) == '1' ) s1 += "10" ; else s1 += "01" ; } s = s1 ; s1 = " " ; } return s . charAt ( i ) - '0' ; } public static void main ( String args [ ] ) { int m = 5 , n = 2 , i = 8 ; System . out . print ( find_character ( n , m , i ) ) ; } }


"Find if a 2 | Java program to Find a 2 - D array is completely traversed or not by following the cell values ; Cell class constructor ; function which tells all cells are visited or not ; starting cell values ; if we get null before the end of loop then returns false . Because it means we didn 't traverse all the cells ; If found cycle then return false ; Update startx and starty values to next cell values ; finally if we reach our goal then returns true ; Driver program to test above function"
How can the above be solved in Java?

import java . io . * ; class Cell { int x ; int y ; Cell ( int x , int y ) { this . x = x ; this . y = y ; } } public class MoveCellPerCellValue { public boolean isAllCellTraversed ( Cell grid [ ] [ ] ) { boolean [ ] [ ] visited = new boolean [ grid . length ] [ grid [ 0 ] . length ] ; int total = grid . length * grid [ 0 ] . length ; int startx = grid [ 0 ] [ 0 ] . x ; int starty = grid [ 0 ] [ 0 ] . y ; for ( int i = 0 ; i < total - 2 ; i ++ ) { if ( grid [ startx ] [ starty ] == null ) return false ; if ( visited [ startx ] [ starty ] == true ) return false ; visited [ startx ] [ starty ] = true ; int x = grid [ startx ] [ starty ] . x ; int y = grid [ startx ] [ starty ] . y ; startx = x ; starty = y ; } if ( grid [ startx ] [ starty ] == null ) return true ; return false ; } public static void main ( String args [ ] ) { Cell cell [ ] [ ] = new Cell [ 3 ] [ 2 ] ; cell [ 0 ] [ 0 ] = new Cell ( 0 , 1 ) ; cell [ 0 ] [ 1 ] = new Cell ( 2 , 0 ) ; cell [ 1 ] [ 0 ] = null ; cell [ 1 ] [ 1 ] = new Cell ( 1 , 0 ) ; cell [ 2 ] [ 0 ] = new Cell ( 2 , 1 ) ; cell [ 2 ] [ 1 ] = new Cell ( 1 , 1 ) ; MoveCellPerCellValue mcp = new MoveCellPerCellValue ( ) ; System . out . println ( mcp . isAllCellTraversed ( cell ) ) ; } }


"Find if a binary matrix exists with given row and column sums | Java implementation of above approach ; Function to check if matrix exists ; Store sum of rowsums , max of row sum number of non zero row sums ; Store sum of column sums , max of column sum number of non zero column sums ; Check condition 1 , 2 , 3 ; Driver Code"
How can the above be solved in Java?

import java . util . * ; class GFG { static boolean matrix_exist ( int row [ ] , int column [ ] , int r , int c ) { int row_sum = 0 ; int column_sum = 0 ; int row_max = - 1 ; int column_max = - 1 ; int row_non_zero = 0 ; int column_non_zero = 0 ; for ( int i = 0 ; i < r ; i ++ ) { row_sum += row [ i ] ; row_max = Math . max ( row_max , row [ i ] ) ; if ( row [ i ] > 0 ) { row_non_zero ++ ; } } for ( int i = 0 ; i < c ; i ++ ) { column_sum += column [ i ] ; column_max = Math . max ( column_max , column [ i ] ) ; if ( column [ i ] > 0 ) { column_non_zero ++ ; } } if ( ( row_sum != column_sum ) || ( row_max > column_non_zero ) || ( column_max > row_non_zero ) ) { return false ; } return true ; } public static void main ( String [ ] args ) { int row [ ] = { 2 , 2 , 2 , 2 , 2 } ; int column [ ] = { 5 , 5 , 0 , 0 } ; int r = row . length ; int c = column . length ; if ( matrix_exist ( row , column , r , c ) ) System . out . println ( " Yes " ) ; else System . out . println ( " No " ) ; } }


"Find if a crest is present in the index range [ L , R ] of the given array | Java implementation of the approach ; Function that returns true if the array contains a crest in the index range [ L , R ] ; To keep track of elements which satisfy the Property ; Property is satisfied for the current element ; Cumulative Sum ; If a crest is present in the given index range ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { static boolean hasCrest ( int arr [ ] , int n , int L , int R ) { int [ ] present = new int [ n ] ; for ( int i = 0 ; i < n ; i ++ ) { present [ i ] = 0 ; } for ( int i = 1 ; i <= n - 2 ; i ++ ) { if ( ( arr [ i ] <= arr [ i + 1 ] ) && ( arr [ i ] <= arr [ i - 1 ] ) ) { present [ i ] = 1 ; } } for ( int i = 1 ; i < n ; i ++ ) { present [ i ] += present [ i - 1 ] ; } if ( present [ L ] == present [ R - 1 ] ) return true ; return false ; } public static void main ( String args [ ] ) { int arr [ ] = { 2 , 1 , 3 , 5 , 12 , 11 , 7 , 9 } ; int N = arr . length ; int L = 2 ; int R = 6 ; if ( hasCrest ( arr , N , L , R ) ) System . out . println ( " Yes " ) ; else System . out . println ( " No " ) ; } }


"Find if a degree sequence can form a simple graph | Havel | Java implementation of the approach ; Function that returns true if a simple graph exists ; Keep performing the operations until one of the stopping condition is met ; Sort the list in non - decreasing order ; Check if all the elements are equal to 0 ; Store the first element in a variable and delete it from the list ; Check if enough elements are present in the list ; Subtract first element from next v elements ; Check if negative element is encountered after subtraction ; Driver Code"
How can the above be solved in Java?

import java . util . * ; @ SuppressWarnings ( " unchecked " ) class GFG { static boolean graphExists ( ArrayList a , int n ) { while ( true ) { Collections . sort ( a , Collections . reverseOrder ( ) ) ; if ( ( int ) a . get ( 0 ) == 0 ) return true ; int v = ( int ) a . get ( 0 ) ; a . remove ( a . get ( 0 ) ) ; if ( v > a . size ( ) ) return false ; for ( int i = 0 ; i < v ; i ++ ) { a . set ( i , ( int ) a . get ( i ) - 1 ) ; if ( ( int ) a . get ( i ) < 0 ) return false ; } } } public static void main ( String [ ] args ) { ArrayList a = new ArrayList ( ) ; a . add ( 3 ) ; a . add ( 3 ) ; a . add ( 3 ) ; a . add ( 3 ) ; int n = a . size ( ) ; if ( graphExists ( a , n ) ) { System . out . print ( " Yes " ) ; } else { System . out . print ( " NO " ) ; } } }


"Find if a molecule can be formed from 3 atoms using their valence numbers | Java implementation of the above approach ; Function to check if it is possible ; Driver code"
How can the above be solved in Java?

import java . io . * ; class GFG { static void printPossible ( int a , int b , int c ) { if ( ( a + b + c ) % 2 != 0 a + b < c ) System . out . println ( " NO " ) ; else System . out . println ( " YES " ) ; } public static void main ( String [ ] args ) { int a = 2 , b = 4 , c = 2 ; printPossible ( a , b , c ) ; } }


"Find if a number is divisible by every number in a list | Java program which check is a number divided with every element in list or not ; Function which check is a number divided with every element in list or not ; driver program"
How can the above be solved in Java?

class GFG { static boolean findNoIsDivisibleOrNot ( int a [ ] , int n ) { for ( int i = 0 ; i < a . length ; i ++ ) { if ( a [ i ] % n != 0 ) return false ; } return true ; } public static void main ( String [ ] args ) { int a [ ] = { 14 , 12 , 4 , 18 } ; int n = 2 ; if ( findNoIsDivisibleOrNot ( a , n ) ) System . out . println ( " Yes " ) ; else System . out . println ( " No " ) ; } }


"Find if a number is part of AP whose first element and difference are given | Java program to check if x exist or not in the given AP . ; returns yes if exist else no . ; If difference is 0 , then x must be same as a . ; Else difference between x and a must be divisible by d . ; Driver code ."
How can the above be solved in Java?

class GFG { static boolean isMember ( int a , int d , int x ) { if ( d == 0 ) return ( x == a ) ; return ( ( x - a ) % d == 0 && ( x - a ) / d >= 0 ) ; } public static void main ( String args [ ] ) { int a = 1 , x = 7 , d = 3 ; if ( isMember ( a , d , x ) ) System . out . println ( " Yes " ) ; else System . out . println ( " No " ) ; } }


"Find if a point lies inside , outside or on the circumcircle of three points A , B , C | Java program to find the points which lies inside , outside or on the circle ; Structure Pointer to store x and y coordinates ; Function to find the line given two points ; Function which converts the input line to its perpendicular bisector . It also inputs the points whose mid - point lies o on the bisector ; Find the mid point ; x coordinates ; y coordinates ; c = - bx + ay ; Assign the coefficient of a and b ; Returns the intersection point of two lines ; Find determinant ; Returns the intersection point of two lines ; Find determinant ; Function to find the point lies inside , outside or on the circle ; Store the coordinates radius of circumcircle ; Line PQ is represented as ax + by = c ; Line QR is represented as ex + fy = g ; Converting lines PQ and QR to perpendicular bisectors . After this , L = ax + by = c M = ex + fy = g ; The point of intersection of L and M gives r as the circumcenter ; Length of radius ; Distance between radius and the given point D ; Condition for point lies inside circumcircle ; Condition for point lies on circumcircle ; Condition for point lies outside circumcircle ; Driver Code ; Given Points ; Function call to find the point lies inside , outside or on the circle"
How can the above be solved in Java?

class GFG { static class point { double x , y ; public point ( ) { } public point ( double x , double y ) { this . x = x ; this . y = y ; } } ; static void lineFromPoints ( point P , point Q , double a , double b , double c ) { a = Q . y - P . y ; b = P . x - Q . x ; c = a * ( P . x ) + b * ( P . y ) ; } static void perpenBisectorFromLine ( point P , point Q , double a , double b , double c ) { point mid_point = new point ( ) ; mid_point . x = ( P . x + Q . x ) / 2 ; mid_point . y = ( P . y + Q . y ) / 2 ; c = - b * ( mid_point . x ) + a * ( mid_point . y ) ; double temp = a ; a = - b ; b = temp ; } static double LineInterX ( double a1 , double b1 , double c1 , double a2 , double b2 , double c2 ) { double determ = a1 * b2 - a2 * b1 ; double x = ( b2 * c1 - b1 * c2 ) ; x /= determ ; return x ; } static double LineInterY ( double a1 , double b1 , double c1 , double a2 , double b2 , double c2 ) { double determ = a1 * b2 - a2 * b1 ; double y = ( a1 * c2 - a2 * c1 ) ; y /= determ ; return y ; } static void findPosition ( point P , point Q , point R , point D ) { point r = new point ( ) ; double a = 0 , b = 0 , c = 0 ; lineFromPoints ( P , Q , a , b , c ) ; double e = 0 , f = 0 , g = 0 ; lineFromPoints ( Q , R , e , f , g ) ; perpenBisectorFromLine ( P , Q , a , b , c ) ; perpenBisectorFromLine ( Q , R , e , f , g ) ; r . x = LineInterX ( a , b , c , e , f , g ) ; r . y = LineInterY ( a , b , c , e , f , g ) ; double q = ( r . x - P . x ) * ( r . x - P . x ) + ( r . y - P . y ) * ( r . y - P . y ) ; double dis = ( r . x - D . x ) * ( r . x - D . x ) + ( r . y - D . y ) * ( r . y - D . y ) ; if ( dis < q ) { System . out . print ( " Point ▁ ( " + D . x + " , ▁ " + D . y + " ) ▁ is ▁ inside ▁ " + " the ▁ circumcircle " ) ; } else if ( dis == q ) { System . out . print ( " Point ▁ ( " + D . x + " , ▁ " + D . y + " ) ▁ lies ▁ on ▁ the ▁ " + " circumcircle " ) ; } else { System . out . print ( " Point ▁ ( " + D . x + " , ▁ " + D . y + " ) ▁ lies ▁ outside " + " ▁ the ▁ circumcircle " ) ; } } public static void main (...


"Find if a string starts and ends with another given string | Java program to find if a given corner string is present at corners . ; If length of corner string is more , it cannot be present at corners . ; Return true if corner string is present at both corners of given string . ; Driver Code"
How can the above be solved in Java?

import java . io . * ; class GFG { static boolean isCornerPresent ( String str , String corner ) { int n = str . length ( ) ; int cl = corner . length ( ) ; if ( n < cl ) return false ; return ( str . substring ( 0 , cl ) . equals ( corner ) && str . substring ( n - cl , n ) . equals ( corner ) ) ; } public static void main ( String [ ] args ) { String str = " geeksforgeeks " ; String corner = " geeks " ; if ( isCornerPresent ( str , corner ) ) System . out . println ( " Yes " ) ; else System . out . println ( " No " ) ; } }


"Find if an array contains a string with one mismatch | Java program to find if given string is present with one mismatch . ; If the array is empty ; If sizes are same ; If first mismatch ; Second mismatch ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { static boolean check ( Vector < String > list , String s ) { int n = ( int ) list . size ( ) ; if ( n == 0 ) { return false ; } for ( int i = 0 ; i < n ; i ++ ) { if ( list . get ( i ) . length ( ) != s . length ( ) ) { continue ; } boolean diff = false ; for ( int j = 0 ; j < ( int ) list . get ( i ) . length ( ) ; j ++ ) { if ( list . get ( i ) . charAt ( j ) != s . charAt ( j ) ) { if ( ! diff ) { diff = true ; } else { diff = false ; break ; } } } if ( diff ) { return true ; } } return false ; } public static void main ( String [ ] args ) { Vector < String > s = new Vector < > ( ) ; s . add ( " bana " ) ; s . add ( " apple " ) ; s . add ( " banacb " ) ; s . add ( " bonanza " ) ; s . add ( " banamf " ) ; System . out . println ( check ( s , " banana " ) == true ? 1 : 0 ) ; } }


"Find if an expression has duplicate parenthesis or not | Java program to find duplicate parenthesis in a balanced expression ; Function to find duplicate parenthesis in a balanced expression ; create a stack of characters ; Iterate through the given expression ; if current character is close parenthesis ' ) ' ; pop character from the stack ; stores the number of characters between a closing and opening parenthesis if this count is less than or equal to 1 then the brackets are redundant else not ; push open parenthesis ' ( ' , operators and operands to stack ; No duplicates found ; Driver code ; input balanced expression"
How can the above be solved in Java?

import java . util . Stack ; public class GFG { static boolean findDuplicateparenthesis ( String s ) { Stack < Character > Stack = new Stack < > ( ) ; char [ ] str = s . toCharArray ( ) ; for ( char ch : str ) { if ( ch == ' ) ' ) { char top = Stack . peek ( ) ; Stack . pop ( ) ; int elementsInside = 0 ; while ( top != ' ( ' ) { elementsInside ++ ; top = Stack . peek ( ) ; Stack . pop ( ) ; } if ( elementsInside < 1 ) { return true ; } } else { Stack . push ( ch ) ; } } return false ; } public static void main ( String [ ] args ) { String str = " ( ( ( a + ( b ) ) + ( c + d ) ) ) " ; if ( findDuplicateparenthesis ( str ) ) { System . out . println ( " Duplicate ▁ Found ▁ " ) ; } else { System . out . println ( " No ▁ Duplicates ▁ Found ▁ " ) ; } } }


"Find if array can be sorted by swaps limited to multiples of k |  ; CheckSort function To check if array can be sorted ; sortarr is sorted array of arr ; If k = 1 then ( always possible to sort ) swapping can easily give sorted array ; Comparing sortarray with array ; Element at index j must be in j = i + l * k form where i = 0 , 1 , 2 , 3. . . where l = 0 , 1 , 2 , 3 , . . n - 1 ; If element is present then swapped ; If element of sorted array does not found in its sequence then flag remain zero that means arr can not be sort after swapping ; If flag is 0 Not possible else Possible ; Driver code ; Size of step ; Array initialized ; Length of arr ; Calling function"
How can the above be solved in Java?

import java . util . * ; class GFG { public static void CheckSort ( Vector < Integer > arr , int k , int n ) { Vector < Integer > sortarr = new Vector < Integer > ( ) ; for ( int i = 0 ; i < arr . size ( ) ; i ++ ) { sortarr . add ( arr . get ( i ) ) ; } Collections . sort ( sortarr ) ; if ( k == 1 ) System . out . println ( " yes " ) ; else { int flag = 0 ; for ( int i = 0 ; i < n ; i ++ ) { flag = 0 ; for ( int j = i ; j < n ; j += k ) { if ( sortarr . get ( i ) == arr . get ( j ) ) { Collections . swap ( arr , i , j ) ; flag = 1 ; break ; } if ( j + k >= n ) break ; } if ( flag == 0 ) break ; } if ( flag == 0 ) System . out . println ( " Not ▁ possible ▁ to ▁ sort " ) ; else System . out . println ( " Possible ▁ to ▁ sort " ) ; } } public static void main ( String [ ] args ) { int k = 3 ; Vector < Integer > arr = new Vector < Integer > ( ) ; arr . add ( 1 ) ; arr . add ( 5 ) ; arr . add ( 6 ) ; arr . add ( 9 ) ; arr . add ( 2 ) ; arr . add ( 3 ) ; arr . add ( 5 ) ; arr . add ( 9 ) ; int n = arr . size ( ) ; CheckSort ( arr , k , n ) ; } }


"Find if given matrix is Toeplitz or not | JAVA program to check whether given matrix is a Toeplitz matrix or not ; row = number of rows col = number of columns ; HashMap to store key , value pairs ; if key value exists in the hashmap , ; we check whether the current value stored in this key matches to element at current index or not . If not , return false ; else we put key , value pair in hashmap ; Driver Code ; Function call"
How can the above be solved in Java?

import java . util . * ; class GFG { static boolean isToeplitz ( int [ ] [ ] matrix ) { int row = matrix . length ; int col = matrix [ 0 ] . length ; HashMap < Integer , Integer > map = new HashMap < Integer , Integer > ( ) ; for ( int i = 0 ; i < row ; i ++ ) { for ( int j = 0 ; j < col ; j ++ ) { int key = i - j ; if ( map . containsKey ( key ) ) { if ( map . get ( key ) != matrix [ i ] [ j ] ) return false ; } else { map . put ( i - j , matrix [ i ] [ j ] ) ; } } } return true ; } public static void main ( String [ ] args ) { int [ ] [ ] matrix = { { 12 , 23 , - 32 } , { - 20 , 12 , 23 } , { 56 , - 20 , 12 } , { 38 , 56 , - 20 } } ; String result = ( isToeplitz ( matrix ) ) ? " Yes " : " No " ; System . out . println ( result ) ; } }


"Find if given matrix is Toeplitz or not | Java program to check whether given matrix is a Toeplitz matrix or not ; Function to check if all elements present in descending diagonal starting from position ( i , j ) in the matrix are all same or not ; mismatch found ; we only reach here when all elements in given diagonal are same ; Function to check whether given matrix is a Toeplitz matrix or not ; do for each element in first row ; check descending diagonal starting from position ( 0 , j ) in the matrix ; do for each element in first column ; check descending diagonal starting from position ( i , 0 ) in the matrix ; we only reach here when each descending diagonal from left to right is same ; Driver code ; Function call"
How can the above be solved in Java?

import java . io . * ; class GFG { public static int N = 5 ; public static int M = 4 ; static boolean checkDiagonal ( int mat [ ] [ ] , int i , int j ) { int res = mat [ i ] [ j ] ; while ( ++ i < N && ++ j < M ) { if ( mat [ i ] [ j ] != res ) return false ; } return true ; } static boolean isToepliz ( int mat [ ] [ ] ) { for ( int i = 0 ; i < M ; i ++ ) { if ( ! checkDiagonal ( mat , 0 , i ) ) return false ; } for ( int i = 1 ; i < N ; i ++ ) { if ( ! checkDiagonal ( mat , i , 0 ) ) return false ; } return true ; } public static void main ( String [ ] args ) { int mat [ ] [ ] = { { 6 , 7 , 8 , 9 } , { 4 , 6 , 7 , 8 } , { 1 , 4 , 6 , 7 } , { 0 , 1 , 4 , 6 } , { 2 , 0 , 1 , 4 } } ; if ( isToepliz ( mat ) ) System . out . println ( " Matrix ▁ is ▁ a ▁ Toepliz ▁ " ) ; else System . out . println ( " Matrix ▁ is ▁ not ▁ a ▁ Toepliz ▁ " ) ; } }


"Find if given number is sum of first n natural numbers | Java program for above implementation ; Function to find no . of elements to be added from 1 to get n ; Start adding numbers from 1 ; If sum becomes equal to s return n ; Drivers code"
How can the above be solved in Java?

class GFG { static int findS ( int s ) { int sum = 0 ; for ( int n = 1 ; sum < s ; n ++ ) { sum += n ; if ( sum == s ) return n ; } return - 1 ; } public static void main ( String [ ] args ) { int s = 15 ; int n = findS ( s ) ; if ( n == - 1 ) System . out . println ( " - 1" ) ; else System . out . println ( n ) ; } }


"Find if given number is sum of first n natural numbers | Java program of the above approach ; Function to check if the s is the sum of first N natural number ; Solution of Quadratic Equation ; Condition to check if the solution is a integer ; Driver code ; Function call"
How can the above be solved in Java?

import java . util . * ; class GFG { public static int isvalid ( int s ) { double k = ( - 1.0 + Math . sqrt ( 1 + 8 * s ) ) / 2 ; if ( Math . ceil ( k ) == Math . floor ( k ) ) return ( int ) k ; else return - 1 ; } public static void main ( String [ ] args ) { int s = 15 ; System . out . print ( isvalid ( s ) ) ; } }


"Find if given number is sum of first n natural numbers | java program for finding s such that sum from 1 to s equals to n ; Function to find no . of elements to be added to get s ; Apply Binary search ; Find mid ; find sum of 1 to mid natural numbers using formula ; If sum is equal to n return mid ; If greater than n do r = mid - 1 ; else do l = mid + 1 ; If not possible , return - 1 ; Drivers code"
How can the above be solved in Java?

import java . io . * ; public class GFG { static int findS ( int s ) { int l = 1 , r = ( s / 2 ) + 1 ; while ( l <= r ) { int mid = ( l + r ) / 2 ; int sum = mid * ( mid + 1 ) / 2 ; if ( sum == s ) return mid ; else if ( sum > s ) r = mid - 1 ; else l = mid + 1 ; } return - 1 ; } static public void main ( String [ ] args ) { int s = 15 ; int n = findS ( s ) ; if ( n == - 1 ) System . out . println ( " - 1" ) ; else System . out . println ( n ) ; } }


"Find if it 's possible to rotate the page by an angle or not. | java program to find if its possible to rotate page or not ; function to find if it 's possible  to rotate page or not ; Calculating distance b / w points ; If distance is not equal ; If the points are in same line ; Driver method ; Points a , b , and c"
How can the above be solved in Java?

import java . util . Arrays ; class GFG { static void possibleOrNot ( long a1 , long a2 , long b1 , long b2 , long c1 , long c2 ) { long dis1 = ( long ) Math . pow ( b1 - a1 , 2 ) + ( long ) Math . pow ( b2 - a2 , 2 ) ; long dis2 = ( long ) Math . pow ( c1 - b1 , 2 ) + ( long ) Math . pow ( c2 - b2 , 2 ) ; if ( dis1 != dis2 ) System . out . print ( " No " ) ; else if ( b1 == ( ( a1 + c1 ) / 2.0 ) && b2 == ( ( a2 + c2 ) / 2.0 ) ) System . out . print ( " No " ) ; else System . out . print ( " Yes " ) ; } public static void main ( String [ ] args ) { long a1 = 1 , a2 = 0 , b1 = 2 , b2 = 0 , c1 = 3 , c2 = 0 ; possibleOrNot ( a1 , a2 , b1 , b2 , c1 , c2 ) ; } }


"Find if it is possible to choose subarray that it contains exactly K even integers | Java program to check if it is possible to choose a subarray that contains exactly K even integers ; Function to check if it is possible to choose a subarray that contains exactly K even integers ; Variable to store the count of even numbers ; If we have to select 0 even numbers but there is all odd numbers in the array ; If the count of even numbers is greater than or equal to K then we can select a subarray with exactly K even integers ; If the count of even numbers is less than K then we cannot select any subarray with exactly K even integers ; Driver Code"
How can the above be solved in Java?

import java . util . * ; class GFG { static void isPossible ( int [ ] A , int n , int k ) { int countOfTwo = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( A [ i ] % 2 == 0 ) { countOfTwo ++ ; } } if ( k == 0 && countOfTwo == n ) System . out . print ( " NO " ) ; else if ( countOfTwo >= k ) { System . out . print ( " YES " ) ; } else System . out . print ( " No " ) ; } public static void main ( String [ ] args ) { int [ ] arr = { 1 , 2 , 4 , 5 } ; int K = 2 ; int n = arr . length ; isPossible ( arr , n , K ) ; } }


"Find if it is possible to get a ratio from given ranges of costs and quantities | Java program to find if it is possible to get the ratio r ; Returns true if it is possible to get ratio r from given cost and quantity ranges . ; Calculating cost corresponding to value of i ; Driver Code"
How can the above be solved in Java?

import java . io . * ; class Ratio { static boolean isRatioPossible ( int lowCost , int upCost , int lowQuant , int upQuant , int r ) { for ( int i = lowQuant ; i <= upQuant ; i ++ ) { int ans = i * r ; if ( lowCost <= ans && ans <= upCost ) return true ; } return false ; } public static void main ( String args [ ] ) { int lowCost = 14 , upCost = 30 , lowQuant = 5 , upQuant = 12 , r = 9 ; if ( isRatioPossible ( lowCost , upCost , lowQuant , upQuant , r ) ) System . out . println ( " Yes " ) ; else System . out . println ( " No " ) ; } }


"Find if it is possible to make a binary string which contanins given number of "0" , "1" , "01" and "10" as sub sequences | Java implementation of the approach ; Function that returns true if it is possible to make a binary string consisting of l 0 ' s , ▁ m ▁ 1' s , x "01" sub - sequences and y "10" sub - sequences ; Driver code"
How can the above be solved in Java?

class sol { static boolean isPossible ( int l , int m , int x , int y ) { if ( l * m == x + y ) return true ; return false ; } public static void main ( String args [ ] ) { int l = 3 , m = 2 , x = 4 , y = 2 ; if ( isPossible ( l , m , x , y ) ) System . out . print ( " Yes " ) ; else System . out . print ( " No " ) ; } }


"Find if k bookings possible with given arrival and departure times | Java code implementation of the above approach ; Driver Code"
How can the above be solved in Java?

import java . util . * ; class GFG { static String areBookingsPossible ( int [ ] A , int [ ] B , int K ) { Arrays . sort ( A ) ; Arrays . sort ( B ) ; for ( int i = 0 ; i < A . length ; i ++ ) { if ( i + K < A . length && A [ i + K ] < B [ i ] ) { return " No " ; } } return " Yes " ; } public static void main ( String [ ] s ) { int [ ] arrival = { 1 , 2 , 3 } ; int [ ] departure = { 2 , 3 , 4 } ; int K = 1 ; System . out . print ( areBookingsPossible ( arrival , departure , K ) ) ; } }


"Find if n can be written as product of k numbers | Java program to find if it is possible to write a number n as product of exactly k positive numbers greater than 1. ; Prints k factors of n if n can be written as multiple of k numbers . Else prints - 1. ; A vector to store all prime factors of n ; Insert all 2 's in list ; n must be odd at this point So we skip one element ( i = i + 2 ) ; This is to handle when n > 2 and n is prime ; If size ( P ) < k , k factors are not possible ; printing first k - 1 factors ; calculating and printing product of rest of numbers ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { static void kFactors ( int n , int k ) { ArrayList < Integer > P = new ArrayList < Integer > ( ) ; while ( n % 2 == 0 ) { P . add ( 2 ) ; n /= 2 ; } for ( int i = 3 ; i * i <= n ; i = i + 2 ) { while ( n % i == 0 ) { n = n / i ; P . add ( i ) ; } } if ( n > 2 ) P . add ( n ) ; if ( P . size ( ) < k ) { System . out . println ( " - 1" ) ; return ; } for ( int i = 0 ; i < k - 1 ; i ++ ) System . out . print ( P . get ( i ) + " , ▁ " ) ; int product = 1 ; for ( int i = k - 1 ; i < P . size ( ) ; i ++ ) product = product * P . get ( i ) ; System . out . println ( product ) ; } public static void main ( String [ ] args ) { int n = 54 , k = 3 ; kFactors ( n , k ) ; } }


"Find if nCr is divisible by the given prime | Java Implementation of above approach ; Function to return the highest power of p that divides n ! implementing Legendre Formula ; Return the highest power of p which divides n ! ; Function to return N digits number which is divisible by D ; Find the highest powers of p that divide n ! , r ! and ( n - r ) ! ; If nCr is divisible by p ; Driver code"
How can the above be solved in Java?

import java . io . * ; class GFG { static int getfactor ( int n , int p ) { int pw = 0 ; while ( n != 0 ) { n /= p ; pw += n ; } return pw ; } static int isDivisible ( int n , int r , int p ) { int x1 = getfactor ( n , p ) ; int x2 = getfactor ( r , p ) ; int x3 = getfactor ( n - r , p ) ; if ( x1 > x2 + x3 ) return 1 ; return 0 ; } public static void main ( String [ ] args ) { int n = 7 , r = 2 , p = 7 ; if ( isDivisible ( n , r , p ) == 1 ) System . out . print ( " Yes " ) ; else System . out . print ( " No " ) ; } }


"Find if path length is even or odd between given Tree nodes for Q queries | Java program for the above approach ; Stores the input tree ; Stores the set number of all nodes ; Function to add an edge in the tree ; Function to convert the given tree into a bipartite graph using BFS ; Set the set number to - 1 for all node of the given tree ; Stores the current node during the BFS traversal of the tree ; Initialize the set number of 1 st node and enqueue it ; BFS traversal of the given tree ; Current node ; Traverse over all neighbours of the current node ; If the set is not assigned ; Assign set number to node u ; Function to find if the path length between node A and B is even or odd ; If the set number of both nodes is same , path length is odd else even ; Driver Code ; Function to convert tree into bipartite"
How can the above be solved in Java?

import java . io . * ; import java . util . * ; class GFG { @ SuppressWarnings ( " unchecked " ) static Vector < Integer > [ ] adj = new Vector [ 100000 ] ; static Vector < Integer > setNum = new Vector < Integer > ( 100000 ) ; static void addEdge ( int a1 , int a2 ) { adj [ a1 ] . add ( a2 ) ; adj [ a2 ] . add ( a1 ) ; } static void toBipartite ( int N ) { for ( int i = 0 ; i < 100000 ; i ++ ) setNum . add ( - 1 ) ; Queue < Integer > q = new LinkedList < > ( ) ; q . add ( 0 ) ; setNum . set ( 0 , 0 ) ; while ( ! q . isEmpty ( ) ) { int v = q . peek ( ) ; q . remove ( ) ; for ( int u : adj [ v ] ) { if ( setNum . get ( u ) == - 1 ) { setNum . set ( u , setNum . get ( v ) ^ 1 ) ; q . add ( u ) ; } } } } static void pathLengthQuery ( int A , int B ) { if ( setNum . get ( A ) == setNum . get ( B ) ) { System . out . println ( " Odd " ) ; } else { System . out . println ( " Even " ) ; } } public static void main ( String [ ] args ) { for ( int i = 0 ; i < 100000 ; i ++ ) adj [ i ] = new Vector < Integer > ( ) ; int N = 7 ; addEdge ( 0 , 1 ) ; addEdge ( 0 , 2 ) ; addEdge ( 1 , 3 ) ; addEdge ( 3 , 4 ) ; addEdge ( 3 , 5 ) ; addEdge ( 2 , 6 ) ; toBipartite ( N ) ; pathLengthQuery ( 4 , 2 ) ; pathLengthQuery ( 0 , 4 ) ; } }


"Find if possible to visit every nodes in given Graph exactly once based on given conditions | Java program for the above approach ; Function to find print path ; If a [ 0 ] is 1 ; Printing path ; Seeking for a [ i ] = 0 and a [ i + 1 ] = 1 ; Printing path ; If a [ N - 1 ] = 0 ; Driver Code ; Given Input ; Function Call"
How can the above be solved in Java?

import java . io . * ; class GFG { static void findpath ( int N , int a [ ] ) { if ( a [ 0 ] == 1 ) { System . out . print ( ( N + 1 ) + " ▁ " ) ; for ( int i = 1 ; i <= N ; i ++ ) System . out . print ( ( i ) + " ▁ " ) ; return ; } for ( int i = 0 ; i < N - 1 ; i ++ ) { if ( a [ i ] == 0 && a [ i + 1 ] == 1 ) { for ( int j = 1 ; j <= i ; j ++ ) System . out . print ( ( j ) + " ▁ " ) ; System . out . print ( ( N + 1 ) + " ▁ " ) ; for ( int j = i + 1 ; j <= N ; j ++ ) System . out . print ( ( j ) + " ▁ " ) ; return ; } } for ( int i = 1 ; i <= N ; i ++ ) System . out . print ( ( i ) + " ▁ " ) ; System . out . print ( ( N + 1 ) + " ▁ " ) ; } public static void main ( String [ ] args ) { int N = 3 , arr [ ] = { 0 , 1 , 0 } ; findpath ( N , arr ) ; } }


import java . io . * ; class GFG { static void findpath ( int N , int a [ ] ) { if ( a [ 0 ] == 1 ) { System . out . print ( ( N + 1 ) + " ▁ " ) ; for ( int i = 1 ; i <= N ; i ++ ) System . out . print ( ( i ) + " ▁ " ) ; return ; } for ( int i = 0 ; i < N - 1 ; i ++ ) { if ( a [ i ] == 0 && a [ i + 1 ] == 1 ) { for ( int j = 1 ; j <= i ; j ++ ) System . out . print ( ( j ) + " ▁ " ) ; System . out . print ( ( N + 1 ) + " ▁ " ) ; for ( int j = i + 1 ; j <= N ; j ++ ) System . out . print ( ( j ) + " ▁ " ) ; return ; } } for ( int i = 1 ; i <= N ; i ++ ) System . out . print ( ( i ) + " ▁ " ) ; System . out . print ( ( N + 1 ) + " ▁ " ) ; } public static void main ( String [ ] args ) { int N = 3 , arr [ ] = { 0 , 1 , 0 } ; int N = 3 , arr [ ] = { 0 , 1 , 0 } ; findpath ( N , arr ) ; } }


"Find if string is K | A Naive recursive Java program to find if given string is K - Palindrome or not ; find if given string is K - Palindrome or not ; If first string is empty , the only option is to remove all characters of second string ; If second string is empty , the only option is to remove all characters of first string ; If last characters of two strings are same , ignore last characters and get count for remaining strings . ; If last characters are not same , 1. Remove last char from str1 and recur for m - 1 and n 2. Remove last char from str2 and recur for m and n - 1 Take minimum of above two operations return 1 + Math . min ( isKPalRec ( str1 , str2 , m - 1 , n ) , Remove from str1 isKPalRec ( str1 , str2 , m , n - 1 ) ) ; Remove from str2 ; Returns true if str is k palindrome . ; Swap values of left and right ; Driver code"
How can the above be solved in Java?

class GFG { static int isKPalRec ( String str1 , String str2 , int m , int n ) { if ( m == 0 ) { return n ; } if ( n == 0 ) { return m ; } if ( str1 . charAt ( m - 1 ) == str2 . charAt ( n - 1 ) ) { return isKPalRec ( str1 , str2 , m - 1 , n - 1 ) ; } } static boolean isKPal ( String str , int k ) { String revStr = str ; revStr = reverse ( revStr ) ; int len = str . length ( ) ; return ( isKPalRec ( str , revStr , len , len ) <= k * 2 ) ; } static String reverse ( String input ) { char [ ] temparray = input . toCharArray ( ) ; int left , right = 0 ; right = temparray . length - 1 ; for ( left = 0 ; left < right ; left ++ , right -- ) { char temp = temparray [ left ] ; temparray [ left ] = temparray [ right ] ; temparray [ right ] = temp ; } return String . valueOf ( temparray ) ; } public static void main ( String [ ] args ) { String str = " acdcb " ; int k = 2 ; if ( isKPal ( str , k ) ) { System . out . println ( " Yes " ) ; } else { System . out . println ( " No " ) ; } } }


"Find if string is K | Java program to find if String is K - Palindrome or not using all characters exactly once ; When size of String is less than k ; When size of String is equal to k ; When size of String is greater than k to store the frequencies of the characters ; To store the count of characters whose number of occurrences is odd . ; Iterating over the map ; Driver code"
How can the above be solved in Java?

 import java . util . * ; class GFG { static void iskPalindromesPossible ( String s , int k ) { if ( s . length ( ) < k ) { System . out . print ( " Not ▁ Possible " + "
"); return ; } if ( s . length ( ) == k ) { System . out . print ( " Possible " + "
"); return ; } HashMap < Character , Integer > freq = new HashMap < Character , Integer > ( ) ; for ( int i = 0 ; i < s . length ( ) ; i ++ ) if ( freq . containsKey ( s . charAt ( i ) ) ) { freq . put ( s . charAt ( i ) , freq . get ( s . charAt ( i ) ) + 1 ) ; } else { freq . put ( s . charAt ( i ) , 1 ) ; } int count = 0 ; for ( Map . Entry < Character , Integer > it : freq . entrySet ( ) ) { if ( it . getValue ( ) % 2 == 1 ) count ++ ; } if ( count > k ) System . out . print ( " No " + "
"); else System . out . print ( " Yes " + "
"); } public static void main ( String [ ] args ) { String str = " poor " ; int K = 3 ; iskPalindromesPossible ( str , K ) ; str = " geeksforgeeks " ; K = 10 ; iskPalindromesPossible ( str , K ) ; } }


"Find if string is K | Java program to find if given String is K - Palindrome or not ; Returns length of LCS for X [ 0. . m - 1 ] , Y [ 0. . n - 1 ] ; Following steps build L [ m + 1 ] [ n + 1 ] in bottom up fashion . Note that L [ i ] [ j ] contains length of LCS of X [ 0. . i - 1 ] and Y [ 0. . j - 1 ] ; L [ m ] [ n ] contains length of LCS for X and Y ; find if given String is K - Palindrome or not ; Find reverse of String ; find longest palindromic subsequence of given String ; If the difference between longest palindromic subsequence and the original String is less than equal to k , then the String is k - palindrome ; Driver code"
How can the above be solved in Java?

class GFG { static int lcs ( String X , String Y , int m , int n ) { int L [ ] [ ] = new int [ m + 1 ] [ n + 1 ] ; for ( int i = 0 ; i <= m ; i ++ ) { for ( int j = 0 ; j <= n ; j ++ ) { if ( i == 0 j == 0 ) { L [ i ] [ j ] = 0 ; } else if ( X . charAt ( i - 1 ) == Y . charAt ( j - 1 ) ) { L [ i ] [ j ] = L [ i - 1 ] [ j - 1 ] + 1 ; } else { L [ i ] [ j ] = Math . max ( L [ i - 1 ] [ j ] , L [ i ] [ j - 1 ] ) ; } } } return L [ m ] [ n ] ; } static boolean isKPal ( String str , int k ) { int n = str . length ( ) ; StringBuilder revStr = new StringBuilder ( str ) ; revStr = revStr . reverse ( ) ; int lps = lcs ( str , revStr . toString ( ) , n , n ) ; return ( n - lps <= k ) ; } public static void main ( String [ ] args ) { String str = " abcdeca " ; int k = 2 ; if ( isKPal ( str , k ) ) { System . out . println ( " Yes " ) ; } else System . out . println ( " No " ) ; } }


"Find if string is K | Java program to find if given string is K - Palindrome or not ; find if given string is K - Palindrome or not ; Create a table to store results of subproblems ; Fill dp [ ] [ ] in bottom up manner ; If first string is empty , only option is to remove all characters of second string ; Min . operations = j ; If second string is empty , only option is to remove all characters of first string ; Min . operations = i ; If last characters are same , ignore last character and recur for remaining string ; If last character are different , remove it and find minimum ; Remove from str1 Remove from str2 ; Returns true if str is k palindrome . ;  ; Driver program"
How can the above be solved in Java?

class GFG { static int isKPalDP ( String str1 , String str2 , int m , int n ) { int dp [ ] [ ] = new int [ m + 1 ] [ n + 1 ] ; for ( int i = 0 ; i <= m ; i ++ ) { for ( int j = 0 ; j <= n ; j ++ ) { if ( i == 0 ) { dp [ i ] [ j ] = j ; } else if ( j == 0 ) { dp [ i ] [ j ] = i ; } else if ( str1 . charAt ( i - 1 ) == str2 . charAt ( j - 1 ) ) { dp [ i ] [ j ] = dp [ i - 1 ] [ j - 1 ] ; } else { dp [ i ] [ j ] = 1 + Math . min ( dp [ i - 1 ] [ j ] , dp [ i ] [ j - 1 ] ) ; } } } return dp [ m ] [ n ] ; } static boolean isKPal ( String str , int k ) { String revStr = str ; revStr = reverse ( revStr ) ; int len = str . length ( ) ; return ( isKPalDP ( str , revStr , len , len ) <= k * 2 ) ; } static String reverse ( String str ) { StringBuilder sb = new StringBuilder ( str ) ; sb . reverse ( ) ; return sb . toString ( ) ; } public static void main ( String [ ] args ) { String str = " acdcb " ; int k = 2 ; if ( isKPal ( str , k ) ) { System . out . println ( " Yes " ) ; } else { System . out . println ( " No " ) ; } } }