"Find if the Vacation can be taken or not | Java program to find if the Vacation can be taken or not ; Function to find if the Vacation is possible or not ; Find the required number of hours of study ; find the hours of study that can be done if the vacation is taken ; check if the required hours are less than or equal to the hours of study that can be done if the vacation is taken ; Driver Code"
How can the above be solved in Java?

 class GFG { static int isPossible ( int N , int S , int C , int H , int L , int T ) { int total_time_required = S * C * H ; int available_time_after_vacation = ( N - L ) * T ; if ( available_time_after_vacation >= total_time_required ) return 1 ; return 0 ; } public static void main ( String [ ] args ) { int N = 12 , S = 5 , C = 8 , H = 3 , L = 2 , T = 20 ; if ( isPossible ( N , S , C , H , L , T ) == 1 ) System . out . print ( " Yes " + "
"); else System . out . print ( " No " + "
"); N = 1 ; S = 2 ; C = 3 ; H = 4 ; L = 5 ; T = 6 ; if ( isPossible ( N , S , C , H , L , T ) == 1 ) System . out . print ( " Yes " + "
"); else System . out . print ( " No " + "
"); } }


"Find if the given number is present in the infinite sequence or not | Java implementation of the approach ; Function that returns true if the sequence will contain B ; Driver code"
How can the above be solved in Java?

class GFG { static boolean doesContainB ( int a , int b , int c ) { if ( a == b ) { return true ; } if ( ( b - a ) * c > 0 && ( b - a ) % c == 0 ) { return true ; } return false ; } public static void main ( String [ ] args ) { int a = 1 , b = 7 , c = 3 ; if ( doesContainB ( a , b , c ) ) { System . out . println ( " Yes " ) ; } else { System . out . println ( " No " ) ; } } }


"Find if the glass will be empty or not when the rate of drinking is given | Java implementation of the approach ; Function to return the time when the glass will be empty ; Check the condition when the glass will never be empty ; Find the time ; Driver code"
How can the above be solved in Java?

class GFG { static double pie = 3.1415926535897 ; static double findsolution ( double d , double h , double m , double n ) { double k = ( 4 * m ) / ( pie * d * d ) ; if ( n > k ) return - 1 ; double ans = ( h / ( k - n ) ) ; return ans ; } public static void main ( String [ ] args ) { double d = 1 , h = 1 , m = 1 , n = 1 ; System . out . printf ( " % .5f " , findsolution ( d , h , m , n ) ) ; } }


"Find if there exists a direction for ranges such that no two range intersect | Java implementation of the approach ; Structure to hold details of each interval ; Function that returns true if the assignment of directions is possible ; Sort the intervals based on velocity ; Test the condition for all intervals with same velocity ; If for any velocity , 3 or more intervals share a common point return false ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { static int MAX = 100001 ; static class interval { int l , r , v ; } static class Sort implements Comparator < interval > { public int compare ( interval a , interval b ) { return ( a . v < b . v ? 1 : 0 ) ; } } static boolean isPossible ( int range [ ] [ ] , int N ) { interval test [ ] = new interval [ N ] ; for ( int i = 0 ; i < N ; i ++ ) { test [ i ] = new interval ( ) ; test [ i ] . l = range [ i ] [ 0 ] ; test [ i ] . r = range [ i ] [ 1 ] ; test [ i ] . v = range [ i ] [ 2 ] ; } Arrays . sort ( test , new Sort ( ) ) ; for ( int i = 0 ; i < N ; i ++ ) { int count [ ] = new int [ MAX ] ; int current_velocity = test [ i ] . v ; int j = i ; while ( j < N && test [ j ] . v == current_velocity ) { for ( int k = test [ j ] . l ; k <= test [ j ] . r ; k ++ ) { count [ k ] ++ ; if ( count [ k ] >= 3 ) return false ; } j ++ ; } i = j - 1 ; } return true ; } public static void main ( String args [ ] ) { int range [ ] [ ] = { { 1 , 2 , 3 } , { 2 , 5 , 1 } , { 3 , 10 , 1 } , { 4 , 4 , 1 } , { 5 , 7 , 10 } } ; int n = range . length ; if ( isPossible ( range , n ) ) System . out . println ( " Yes " ) ; else System . out . println ( " No " ) ; } }


"Find if there exists multiple ways to draw line through ( x , y ) to cut rectangle in equal halfs | Java implementation of the approach ; Function that returns true if multiple lines are possible passing through ( x , y ) that divide the given rectangle into two equal parts ; If the point ( x , y ) is the centre of the rectangle ; Driver code"
How can the above be solved in Java?

class GFG { static boolean isPossible ( int w , int h , int x , int y ) { if ( x * 2 == w && y * 2 == h ) return true ; return false ; } public static void main ( String [ ] args ) { int w = 1 , h = 2 , x = 1 , y = 2 ; if ( isPossible ( w , h , x , y ) ) System . out . print ( " Yes " ) ; else System . out . print ( " No " ) ; } }


"Find if there is a pair in root to a leaf path with sum equals to root 's data | Java program to find if there is a pair in any root to leaf path with sum equals to root 's key. ; A binary tree node has data , pointer to left child and a pointer to right child ; utility that allocates a new node with the given data and null left and right pointers . ; Function to print root to leaf path which satisfies the condition ; Base condition ; Check if current node makes a pair with any of the existing elements in set . ; Insert current node in set ; If result returned by either left or right child is true , return true . ; Remove current node from hash table ; A wrapper over printPathUtil ( ) ; create an empty hash table ; Recursively check in left and right subtrees . ; 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 data ) { Node node = new Node ( ) ; node . data = data ; node . left = node . right = null ; return ( node ) ; } static boolean printPathUtil ( Node node , HashSet < Integer > s , int root_data ) { if ( node == null ) return false ; int rem = root_data - node . data ; if ( s . contains ( rem ) ) return true ; s . add ( node . data ) ; boolean res = printPathUtil ( node . left , s , root_data ) || printPathUtil ( node . right , s , root_data ) ; s . remove ( node . data ) ; return res ; } static boolean isPathSum ( Node root ) { HashSet < Integer > s = new HashSet < Integer > ( ) ; return printPathUtil ( root . left , s , root . data ) || printPathUtil ( root . right , s , root . data ) ; } public static void main ( String [ ] args ) { Node root = newnode ( 8 ) ; root . left = newnode ( 5 ) ; root . right = newnode ( 4 ) ; root . left . left = newnode ( 9 ) ; root . left . right = newnode ( 7 ) ; root . left . right . left = newnode ( 1 ) ; root . left . right . right = newnode ( 12 ) ; root . left . right . right . right = newnode ( 2 ) ; root . right . right = newnode ( 11 ) ; root . right . right . left = newnode ( 3 ) ; System . out . print ( isPathSum ( root ) == true ? " Yes " : " No " ) ; } }


"Find if there is a path between two vertices in a directed graph | Set 2 | Java program to find if there is a path between two vertices in a directed graph using Dynamic Programming ; Function to find if there is a path between two vertices in a directed graph ; mat matrix ; set mat [ i ] [ j ] = true if there is edge between i to j ; Check for all intermediate vertex ; If vertex is invalid ; If there is a path ; Driver code"
How can the above be solved in Java?

 import java . util . * ; class GFG { static final int X = 6 ; static final int Z = 2 ; static boolean existPath ( int V , int edges [ ] [ ] , int u , int v ) { boolean [ ] [ ] mat = new boolean [ V ] [ V ] ; for ( int i = 0 ; i < X ; i ++ ) mat [ edges [ i ] [ 0 ] ] [ edges [ i ] [ 1 ] ] = true ; for ( int k = 0 ; k < V ; k ++ ) { for ( int i = 0 ; i < V ; i ++ ) { for ( int j = 0 ; j < V ; j ++ ) { mat [ i ] [ j ] = mat [ i ] [ j ] || mat [ i ] [ k ] && mat [ k ] [ j ] ; } } } if ( u >= V v >= V ) { return false ; } if ( mat [ u ] [ v ] ) return true ; return false ; } public static void main ( String [ ] args ) { int V = 4 ; int edges [ ] [ ] = { { 0 , 2 } , { 0 , 1 } , { 1 , 2 } , { 2 , 3 } , { 2 , 0 } , { 3 , 3 } } ; int u = 1 , v = 3 ; if ( existPath ( V , edges , u , v ) ) System . out . print ( "Yes
"); else System . out . print ( "No
"); } }


"Find if two given Quadratic equations have common roots or not | Java Program to Find if two given quadratic equations have common roots or not ; Function to check if 2 quadratic equations have common roots or not . ; Driver code"
How can the above be solved in Java?

class GFG { static boolean checkSolution ( float a1 , float b1 , float c1 , float a2 , float b2 , float c2 ) { return ( ( a1 / a2 ) == ( b1 / b2 ) && ( b1 / b2 ) == ( c1 / c2 ) ) ; } public static void main ( String [ ] args ) { float a1 = 1 , b1 = - 5 , c1 = 6 ; float a2 = 2 , b2 = - 10 , c2 = 12 ; if ( checkSolution ( a1 , b1 , c1 , a2 , b2 , c2 ) ) System . out . println ( " Yes " ) ; else System . out . println ( " No " ) ; } }


"Find if two people ever meet after same number of jumps | java program to find any one of them can overtake the other ; function to find if any one of them can overtake the other ; Since starting points are always different , they will meet if following conditions are met . ( 1 ) Speeds are not same ( 2 ) Difference between speeds divide the total distance between initial points . ; Driver code"
How can the above be solved in Java?

import java . util . Arrays ; public class GFG { static boolean sackRace ( int p1 , int s1 , int p2 , int s2 ) { return ( ( s1 > s2 && ( p2 - p1 ) % ( s1 - s2 ) == 0 ) || ( s2 > s1 && ( p1 - p2 ) % ( s2 - s1 ) == 0 ) ) ; } public static void main ( String args [ ] ) { int p1 = 4 , s1 = 4 , p2 = 8 , s2 = 2 ; if ( sackRace ( p1 , s1 , p2 , s2 ) ) System . out . println ( " Yes " ) ; else System . out . println ( " No " ) ; } }


"Find index i such that prefix of S1 and suffix of S2 till i form a palindrome when concatenated | Java implementation of the above approach ; Function that returns true if the sub - String starting from index i and ending at index j is a palindrome ; Function to get the required index ; Start comparing the two Strings from both ends . ; Break from the loop at first mismatch ; If it is possible to concatenate the Strings to form palindrome , return index ; If remaining part for s2 is palindrome ; If remaining part for s1 is palindrome ; If not possible , return - 1 ; Driver Code"
How can the above be solved in Java?

class GFG { static boolean isPalindrome ( String s , int i , int j ) { while ( i < j ) { if ( s . charAt ( i ) != s . charAt ( j ) ) return false ; i ++ ; j -- ; } return true ; } static int getIndex ( String s1 , String s2 , int len ) { int i = 0 , j = len - 1 ; while ( i < j ) { if ( s1 . charAt ( i ) != s2 . charAt ( j ) ) { break ; } i ++ ; j -- ; } if ( i == j ) { return i - 1 ; } else if ( isPalindrome ( s2 , i , j ) ) return i - 1 ; else if ( isPalindrome ( s1 , i , j ) ) return j ; return - 1 ; } public static void main ( String args [ ] ) { String s1 = " abcdf " , s2 = " sfgba " ; int len = s1 . length ( ) ; System . out . println ( getIndex ( s1 , s2 , len ) ) ; } }


"Find index i such that prefix of S1 and suffix of S2 till i form a palindrome when concatenated | Java implementation of the approach ; Function that returns true if s is palindrome ; Function to return the required index ; Copy the ith character in S ; Copy all the character of string s2 in Temp ; Check whether the string is palindrome ; Driver code"
How can the above be solved in Java?

class GFG { static boolean isPalindrome ( String s ) { int i = 0 ; int j = s . length ( ) - 1 ; while ( i < j ) { if ( s . charAt ( i ) != s . charAt ( j ) ) return false ; i ++ ; j -- ; } return true ; } static int getIndex ( String S1 , String S2 , int n ) { String S = " " ; for ( int i = 0 ; i < n ; i ++ ) { S = S + S1 . charAt ( i ) ; String Temp = " " ; for ( int j = i + 1 ; j < n ; j ++ ) Temp += S2 . charAt ( j ) ; if ( isPalindrome ( S + Temp ) ) { return i ; } } return - 1 ; } public static void main ( String [ ] args ) { String S1 = " abcdf " , S2 = " sfgba " ; int n = S1 . length ( ) ; System . out . println ( getIndex ( S1 , S2 , n ) ) ; } }


"Find index of an extra element present in one sorted array | Java code for above approach ; Function to find Index ; Calculating extra element ; returns index of extra element ; function return sum of array elements ; function return index of given element ; Driver Code"
How can the above be solved in Java?

class GFG { static int find_extra_element_index ( int [ ] arrA , int [ ] arrB ) { int extra_element = sum ( arrA ) - sum ( arrB ) ; return indexOf ( arrA , extra_element ) ; } static int sum ( int [ ] arr ) { int sum = 0 ; for ( int i = 0 ; i < arr . length ; i ++ ) { sum += arr [ i ] ; } return sum ; } static int indexOf ( int [ ] arr , int element ) { for ( int i = 0 ; i < arr . length ; i ++ ) { if ( arr [ i ] == element ) { return i ; } } return - 1 ; } public static void main ( String [ ] args ) { int [ ] arrA = { 2 , 4 , 6 , 8 , 10 , 12 , 13 } ; int [ ] arrB = { 2 , 4 , 6 , 8 , 10 , 12 } ; System . out . println ( find_extra_element_index ( arrA , arrB ) ) ; } }


"Find index of an extra element present in one sorted array | Java program to find an extra element present in arr1 [ ] ; Returns index of extra element in arr1 [ ] . n is size of arr2 [ ] . Size of arr1 [ ] is n - 1. ; Driver Code ; Solve is passed both arrays"
How can the above be solved in Java?

class GFG { static int findExtra ( int arr1 [ ] , int arr2 [ ] , int n ) { for ( int i = 0 ; i < n ; i ++ ) if ( arr1 [ i ] != arr2 [ i ] ) return i ; return n ; } public static void main ( String [ ] args ) { int arr1 [ ] = { 2 , 4 , 6 , 8 , 10 , 12 , 13 } ; int arr2 [ ] = { 2 , 4 , 6 , 8 , 10 , 12 } ; int n = arr2 . length ; System . out . println ( findExtra ( arr1 , arr2 , n ) ) ; } }


"Find index of an extra element present in one sorted array | Java program to find an extra element present in arr1 [ ] ; Returns index of extra element in arr1 [ ] . n is size of arr2 [ ] . Size of arr1 [ ] is n - 1. ; Initialize result ; left and right are end points denoting the current range . ; If middle element is same of both arrays , it means that extra element is after mid so we update left to mid + 1 ; If middle element is different of the arrays , it means that the index we are searching for is either mid , or before mid . Hence we update right to mid - 1. ; when right is greater than left , our search is complete . ; Driver Code ; Solve is passed both arrays"
How can the above be solved in Java?

class GFG { static int findExtra ( int arr1 [ ] , int arr2 [ ] , int n ) { int index = n ; int left = 0 , right = n - 1 ; while ( left <= right ) { int mid = ( left + right ) / 2 ; if ( arr2 [ mid ] == arr1 [ mid ] ) left = mid + 1 ; else { index = mid ; right = mid - 1 ; } } return index ; } public static void main ( String [ ] args ) { int arr1 [ ] = { 2 , 4 , 6 , 8 , 10 , 12 , 13 } ; int arr2 [ ] = { 2 , 4 , 6 , 8 , 10 , 12 } ; int n = arr2 . length ; System . out . println ( findExtra ( arr1 , arr2 , n ) ) ; } }


"Find index of closing bracket for a given opening bracket in an expression | Java program to find index of closing bracket for given opening bracket . ; Function to find index of closing bracket for given opening bracket . ; If index given is invalid and is not an opening bracket . ; Stack to store opening brackets . ; Traverse through string starting from given index . ; If current character is an opening bracket push it in stack . ; If current character is a closing bracket , pop from stack . If stack is empty , then this closing bracket is required bracket . ; If no matching closing bracket is found . ; Driver Code ; should be 8 ; should be 7 ; should be 12 ; No matching bracket"
How can the above be solved in Java?

 import java . util . Stack ; class GFG { static void test ( String expression , int index ) { int i ; if ( expression . charAt ( index ) != ' [ ' ) { System . out . print ( expression + " , ▁ " + index + ": -1
"); return ; } Stack < Integer > st = new Stack < > ( ) ; for ( i = index ; i < expression . length ( ) ; i ++ ) { if ( expression . charAt ( i ) == ' [ ' ) { st . push ( ( int ) expression . charAt ( i ) ) ; } else if ( expression . charAt ( i ) == ' ] ' ) { st . pop ( ) ; if ( st . empty ( ) ) { System . out . print ( expression + " , ▁ " + index + " : ▁ " + i + "
"); return ; } } } System . out . print ( expression + " , ▁ " + index + ": -1
"); } public static void main ( String [ ] args ) { test ( " [ ABC [ 23 ] ] [89 ] " , 0 ) ; test ( " [ ABC [ 23 ] ] [89 ] " , 4 ) ; test ( " [ ABC [ 23 ] ] [89 ] " , 9 ) ; test ( " [ ABC [ 23 ] ] [89 ] " , 1 ) ; } }


"Find index of first occurrence when an unsorted array is sorted | Java program to find index of first occurrence of x when array is sorted . ; Driver main"
How can the above be solved in Java?

public class GFG { static int findFirst ( int arr [ ] , int n , int x ) { int count = 0 ; boolean isX = false ; for ( int i = 0 ; i < n ; i ++ ) { if ( arr [ i ] == x ) { isX = true ; } else if ( arr [ i ] < x ) { count ++ ; } } return ( isX == false ) ? - 1 : count ; } public static void main ( String [ ] args ) { int x = 20 , arr [ ] = { 10 , 30 , 20 , 50 , 20 } ; int n = arr . length ; System . out . println ( findFirst ( arr , n , x ) ) ; } }


"Find index of first occurrence when an unsorted array is sorted | Java program to find index of first occurrence of x when array is sorted . ; lower_bound returns iterator pointing to first element that does not compare less to x . ; If x is not present return - 1. ;  ; Driver Code"
How can the above be solved in Java?

import java . util . * ; class GFG { static int findFirst ( int arr [ ] , int n , int x ) { Arrays . sort ( arr ) ; int ptr = lowerBound ( arr , 0 , n , x ) ; return ( arr [ ptr ] != x ) ? - 1 : ( ptr ) ; } static int lowerBound ( int [ ] a , int low , int high , int element ) { while ( low < high ) { int middle = low + ( high - low ) / 2 ; if ( element > a [ middle ] ) low = middle + 1 ; else high = middle ; } return low ; } public static void main ( String [ ] args ) { int x = 20 , arr [ ] = { 10 , 30 , 20 , 50 , 20 } ; int n = arr . length ; System . out . println ( findFirst ( arr , n , x ) ) ; } }


"Find index of the element differing in parity with all other array elements | Java program for the above approach ; Function to print the element which differs in parity ; Stores the count of odd and even array elements encountered ; Stores the indices of the last odd and even array elements encountered ; Traverse the array ; If array element is even ; Otherwise ; If only one odd element is present in the array ; If only one even element is present in the array ; Driver Code ; Given array ; Size of the array"
How can the above be solved in Java?

import java . util . * ; class GFG { static void oddOneOut ( int arr [ ] , int N ) { int odd = 0 , even = 0 ; int lastOdd = 0 , lastEven = 0 ; for ( int i = 0 ; i < N ; i ++ ) { if ( arr [ i ] % 2 == 0 ) { even ++ ; lastEven = i ; } else { odd ++ ; lastOdd = i ; } } if ( odd == 1 ) { System . out . println ( lastOdd ) ; } else { System . out . println ( lastEven ) ; } } public static void main ( String args [ ] ) { int arr [ ] = { 2 , 4 , 7 , 8 , 10 } ; int N = arr . length ; oddOneOut ( arr , N ) ; } }


"Find indices of all local maxima and local minima in an Array | Java program for the above approach ; Function to find all the local maxima and minima in the given array arr [ ] ; Empty vector to store points of local maxima and minima ; Checking whether the first point is local maxima or minima or none ; Iterating over all points to check local maxima and local minima ; Condition for local minima ; Condition for local maxima ; Checking whether the last point is local maxima or minima or none ; Print all the local maxima and local minima indexes stored ; Driver code ; Given array arr [ ] ; Function call"
How can the above be solved in Java?

import java . util . * ; class GFG { public static void findLocalMaximaMinima ( int n , int [ ] arr ) { Vector < Integer > mx = new Vector < Integer > ( ) ; Vector < Integer > mn = new Vector < Integer > ( ) ; if ( arr [ 0 ] > arr [ 1 ] ) mx . add ( 0 ) ; else if ( arr [ 0 ] < arr [ 1 ] ) mn . add ( 0 ) ; for ( int i = 1 ; i < n - 1 ; i ++ ) { if ( ( arr [ i - 1 ] > arr [ i ] ) && ( arr [ i ] < arr [ i + 1 ] ) ) mn . add ( i ) ; else if ( ( arr [ i - 1 ] < arr [ i ] ) && ( arr [ i ] > arr [ i + 1 ] ) ) mx . add ( i ) ; } if ( arr [ n - 1 ] > arr [ n - 2 ] ) mx . add ( n - 1 ) ; else if ( arr [ n - 1 ] < arr [ n - 2 ] ) mn . add ( n - 1 ) ; if ( mx . size ( ) > 0 ) { System . out . print ( " Points ▁ of ▁ Local ▁ " + " maxima ▁ are ▁ : ▁ " ) ; for ( Integer a : mx ) System . out . print ( a + " ▁ " ) ; System . out . println ( ) ; } else System . out . println ( " There ▁ are ▁ no ▁ points ▁ " + " of ▁ Local ▁ Maxima ▁ " ) ; if ( mn . size ( ) > 0 ) { System . out . print ( " Points ▁ of ▁ Local ▁ " + " minima ▁ are ▁ : ▁ " ) ; for ( Integer a : mn ) System . out . print ( a + " ▁ " ) ; System . out . println ( ) ; } else System . out . println ( " There ▁ are ▁ no ▁ points ▁ of ▁ " + " Local ▁ Maxima ▁ " ) ; } public static void main ( String [ ] args ) { int N = 9 ; int arr [ ] = { 10 , 20 , 15 , 14 , 13 , 25 , 5 , 4 , 3 } ; findLocalMaximaMinima ( N , arr ) ; } }


"Find indices of all occurrence of one string in other | Java program to find indices of all occurrences of one String in other . ; Driver code"
How can the above be solved in Java?

class GFG { static void printIndex ( String str , String s ) { boolean flag = false ; for ( int i = 0 ; i < str . length ( ) - s . length ( ) + 1 ; i ++ ) { if ( str . substring ( i , i + s . length ( ) ) . equals ( s ) ) { System . out . print ( i + " ▁ " ) ; flag = true ; } } if ( flag == false ) { System . out . println ( " NONE " ) ; } } public static void main ( String [ ] args ) { String str1 = " GeeksforGeeks " ; String str2 = " Geeks " ; printIndex ( str1 , str2 ) ; } }


"Find initial integral solution of Linear Diophantine equation if finite solution exists | Java program for the above approach ; Function to implement the extended euclid algorithm ; Base Case ; Recursively find the gcd ; Function to print the solutions of the given equations ax + by = c ; Condition for infinite solutions ; Condition for no solutions exist ; Condition for no solutions exist ; Print the solution ; Driver Code ; Given coefficients ; Function Call"
How can the above be solved in Java?

 class GFG { static int x , y ; static int gcd_extend ( int a , int b ) { if ( b == 0 ) { x = 1 ; y = 0 ; return a ; } else { int g = gcd_extend ( b , a % b ) ; int x1 = x , y1 = y ; x = y1 ; y = x1 - ( a / b ) * y1 ; return g ; } } static void print_solution ( int a , int b , int c ) { if ( a == 0 && b == 0 ) { if ( c == 0 ) { System . out . print ( " Infinite ▁ Solutions ▁ " + " Exist " + "
"); } else { System . out . print ( " No ▁ Solution ▁ exists " + "
"); } } int gcd = gcd_extend ( a , b ) ; if ( c % gcd != 0 ) { System . out . print ( " No ▁ Solution ▁ exists " + "
"); } else { System . out . print ( " x ▁ = ▁ " + x * ( c / gcd ) + " , ▁ y ▁ = ▁ " + y * ( c / gcd ) + "
"); } } public static void main ( String [ ] args ) { int a , b , c ; a = 4 ; b = 18 ; c = 10 ; print_solution ( a , b , c ) ; } }


"Find initial sequence that produces a given Array by cyclic increments upto index P | Java program to implement the above approach ; Function to generate and return the required initial arrangement ; Store the minimum element in the array ; Store the number of increments ; Subtract mi - 1 from every index ; Start from the last index which had been incremented ; Stores the index chosen to distribute its element ; Traverse the array cyclically and find the index whose element was distributed ; If any index has its value reduced to 0 ; Index whose element was distributed ; Store the number of increments at the starting index ; Print the original array ; Driver Code"
How can the above be solved in Java?

import java . util . * ; class GFG { static void findArray ( int [ ] a , int n , int P ) { int mi = Arrays . stream ( a ) . min ( ) . getAsInt ( ) ; int ctr = 0 ; mi = Math . max ( 0 , mi - 1 ) ; for ( int i = 0 ; i < n ; i ++ ) { a [ i ] -= mi ; ctr += mi ; } int i = P - 1 ; int start = - 1 ; while ( true ) { if ( a [ i ] == 0 ) { start = i ; break ; } a [ i ] -= 1 ; ctr += 1 ; i = ( i - 1 + n ) % n ; } a [ start ] = ctr ; for ( i = 0 ; i < n ; i ++ ) { System . out . print ( a [ i ] + " , ▁ " ) ; } } public static void main ( String [ ] args ) { int N = 5 ; int P = 2 ; int arr [ ] = { 3 , 2 , 0 , 2 , 7 } ; findArray ( arr , N , P ) ; } }


"Find instances at end of time frame after auto scaling | Java program for above approach ; Function to find the number of instances after compintion ; Traverse the array , arr [ ] ; If current element is less than 25 ; Divide instances by 2 ; If the current element is greater than 60 ; Double the instances ; Print the instances at the end of the traversal ; Driver Code ; Function Call"
How can the above be solved in Java?

class GFG { public static void finalInstances ( int instances , int [ ] arr ) { int i = 0 ; while ( i < arr . length ) { if ( arr [ i ] < 25 && instances > 1 ) { instances = ( instances / 2 ) ; i = i + 10 ; } else if ( arr [ i ] > 60 && instances <= Math . pow ( 10 , 8 ) ) { instances = instances * 2 ; i = i + 10 ; } i = i + 1 ; } System . out . println ( instances ) ; } public static void main ( String args [ ] ) { int instances = 2 ; int [ ] arr = { 25 , 23 , 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 , 76 , 80 } ; finalInstances ( instances , arr ) ; } }


"Find integers that divides maximum number of elements of the array | Java implementation of the approach ; Function to print the integers that divide the maximum number of elements from the array ; Initialize two lists to store rank and factors ; Start from 2 till the maximum element in arr ; Initialize a variable to count the number of elements it is a factor of ; Maximum rank in the rank list ; Print all the elements with rank m ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { static void maximumFactor ( int [ ] arr ) { int [ ] rank = new int [ Arrays . stream ( arr ) . max ( ) . getAsInt ( ) + 1 ] ; int [ ] factors = new int [ Arrays . stream ( arr ) . max ( ) . getAsInt ( ) + 1 ] ; int g = 0 ; for ( int i = 2 ; i <= Arrays . stream ( arr ) . max ( ) . getAsInt ( ) ; i ++ ) { int count = 0 ; for ( int j = 0 ; j < arr . length ; j ++ ) if ( arr [ j ] % i == 0 ) count += 1 ; rank [ g ] = count ; factors [ g ] = i ; g ++ ; } int m = Arrays . stream ( rank ) . max ( ) . getAsInt ( ) ; for ( int i = 0 ; i < rank . length ; i ++ ) { if ( rank [ i ] == m ) System . out . print ( factors [ i ] + " ▁ " ) ; } } public static void main ( String [ ] args ) { int [ ] arr = { 120 , 15 , 24 , 63 , 18 } ; maximumFactor ( arr ) ; } }


"Find integral points with minimum distance from given set of integers using BFS | Java implementation of above approach ; Function to find points at minimum distance ; Hash to store points that are encountered ; Queue to store initial set of points ; List to store integral points ; Using bfs to visit nearest points from already visited points ; Get first element from queue ; Check if ( x - 1 ) is not encountered so far ; Update hash with this new element ; Insert ( x - 1 ) into queue ; Push ( x - 1 ) as new element ; Decrement counter by 1 ; Check if ( x + 1 ) is not encountered so far ; Update hash with this new element ; Insert ( x + 1 ) into queue ; Push ( x + 1 ) as new element ; Decrement counter by 1 ; Print result array ; Driver code"
How can the above be solved in Java?

import java . util . HashMap ; import java . util . LinkedList ; import java . util . Map ; import java . util . Queue ; class Geeks { static void minDistancePoints ( int A [ ] , int K , int n ) { Map < Integer , Boolean > m = new HashMap < Integer , Boolean > ( ) ; Queue < Integer > q = new LinkedList < Integer > ( ) ; for ( int i = 0 ; i < n ; ++ i ) { m . put ( A [ i ] , true ) ; q . add ( A [ i ] ) ; } LinkedList < Integer > ans = new LinkedList < Integer > ( ) ; while ( K > 0 ) { int x = q . poll ( ) ; if ( ! m . containsKey ( x - 1 ) && K > 0 ) { m . put ( x - 1 , true ) ; q . add ( x - 1 ) ; ans . add ( x - 1 ) ; K -- ; } if ( ! m . containsKey ( x + 1 ) && K > 0 ) { m . put ( x + 1 , true ) ; q . add ( x + 1 ) ; ans . add ( x + 1 ) ; K -- ; } } for ( Integer i : ans ) System . out . print ( i + " ▁ " ) ; } public static void main ( String [ ] args ) { int A [ ] = new int [ ] { - 1 , 4 , 6 } ; int K = 3 ; int n = A . length ; minDistancePoints ( A , K , n ) ; } }


"Find interior angles for each side of a given Cyclic Quadrilateral | Java program for the above approach ; Function to find the interior angles of the cyclic quadrilateral ; Stores the numerator and the denominator to find angle A ; Stores the numerator and the denominator to find angle B ; Stores the numerator and the denominator to find angle C : ; Stores the numerator and the denominator to find angle D : ; Driver Code"
How can the above be solved in Java?

class GFG { static void findAngles ( double a , double b , double c , double d ) { double numerator = a * a + d * d - b * b - c * c ; double denominator = 2 * ( a * b + c * d ) ; double x = numerator / denominator ; System . out . println ( " A : ▁ " + Math . round ( ( ( Math . acos ( x ) * 180 ) / 3.141592 ) * 100.0 ) / 100.0 + " ▁ degrees " ) ; numerator = a * a + b * b - c * c - d * d ; x = numerator / denominator ; System . out . println ( " B : ▁ " + Math . round ( ( ( Math . acos ( x ) * 180 ) / 3.141592 ) * 100.0 ) / 100.0 + " ▁ degrees " ) ; numerator = c * c + b * b - a * a - d * d ; x = numerator / denominator ; System . out . println ( " C : ▁ " + Math . round ( ( ( Math . acos ( x ) * 180 ) / 3.141592 ) * 100.0 ) / 100.0 + " ▁ degrees " ) ; numerator = d * d + c * c - a * a - b * b ; x = numerator / denominator ; System . out . println ( " D : ▁ " + Math . round ( ( ( Math . acos ( x ) * 180 ) / 3.141592 ) * 100.0 ) / 100.0 + " ▁ degrees " ) ; } public static void main ( String [ ] args ) { double A = 10 , B = 15 , C = 20 , D = 25 ; findAngles ( A , B , C , D ) ; } }


"Find iâ €™ th index character in a binary string obtained after n iterations | Set 2 | Java program to find ith Index character in a binary string obtained after n iterations ; Function to find the i - th character ; distance between two consecutive elements after N iterations ; binary representation of M ; kth digit will be derived from root for sure ; Check whether there is need to flip root or not ; Driver Code"
How can the above be solved in Java?

import java . io . * ; class GFG { static void KthCharacter ( int m , int n , int k ) { int distance = ( int ) Math . pow ( 2 , n ) ; int Block_number = k / distance ; int remaining = k % distance ; int s [ ] = new int [ 32 ] ; int x = 0 ; for ( ; m > 0 ; x ++ ) { s [ x ] = m % 2 ; m = m / 2 ; } int root = s [ x - 1 - Block_number ] ; if ( remaining == 0 ) { System . out . println ( root ) ; return ; } Boolean flip = true ; while ( remaining > 1 ) { if ( ( remaining & 1 ) > 0 ) { flip = ! flip ; } remaining = remaining >> 1 ; } if ( flip ) { System . out . println ( ( root > 0 ) ? 0 : 1 ) ; } else { System . out . println ( root ) ; } } public static void main ( String [ ] args ) { int m = 5 , k = 5 , n = 3 ; KthCharacter ( m , n , k ) ; } }


"Find k 'th character of decrypted string | Set 1 | Java program to find K 'th character in decrypted string ; Function to find K 'th character in  Encoded String ; expand string variable is used to store final string after decompressing string str ; String temp = " " ; Current substring int freq = 0 ; Count of current substring ; read characters until you find a number or end of string ; push character in temp ; read number for how many times string temp will be repeated in decompressed string ; generating frequency of temp ; now append string temp into expand equal to its frequency ; this condition is to handle the case when string str is ended with alphabets not with numeric value ; Driver program to test the string"
How can the above be solved in Java?

public class GFG { static char encodedChar ( String str , int k ) { String expand = " " ; for ( int i = 0 ; i < str . length ( ) ; ) { while ( i < str . length ( ) && str . charAt ( i ) >= ' a ' && str . charAt ( i ) <= ' z ' ) { temp += str . charAt ( i ) ; i ++ ; } while ( i < str . length ( ) && str . charAt ( i ) >= '1' && str . charAt ( i ) <= '9' ) { freq = freq * 10 + str . charAt ( i ) - '0' ; i ++ ; } for ( int j = 1 ; j <= freq ; j ++ ) expand += temp ; } if ( freq == 0 ) expand += temp ; return expand . charAt ( k - 1 ) ; } public static void main ( String args [ ] ) { String str = " ab4c12ed3" ; int k = 21 ; System . out . println ( encodedChar ( str , k ) ) ; } }


"Find k numbers which are powers of 2 and have sum N | Set 1 | Java program to find k numbers that are power of 2 and have sum equal to N ; function to print numbers ; Count the number of set bits ; Not - possible condition ; Stores the number ; Get the set bits ; Iterate till we get K elements ; Get the topmost element ; Push the elements / 2 into priority queue ; Print all elements ; Driver Code"
How can the above be solved in Java?

import java . io . * ; import java . util . * ; class GFG { static void printNum ( int n , int k ) { String str = Integer . toBinaryString ( n ) ; int x = 0 ; for ( int i = 0 ; i < str . length ( ) ; i ++ ) if ( str . charAt ( i ) == '1' ) x ++ ; if ( k < x k > n ) { System . out . println ( " - 1" ) ; return ; } PriorityQueue < Integer > pq = new PriorityQueue < > ( Comparator . reverseOrder ( ) ) ; int two = 1 ; while ( n > 0 ) { if ( ( n & 1 ) == 1 ) pq . add ( two ) ; two *= 2 ; n = n >> 1 ; } while ( pq . size ( ) < k ) { int el = pq . poll ( ) ; pq . add ( el / 2 ) ; pq . add ( el / 2 ) ; } int ind = 0 ; while ( ind < k ) { System . out . print ( pq . poll ( ) + " ▁ " ) ; ind ++ ; } } public static void main ( String [ ] args ) { int n = 9 , k = 4 ; printNum ( n , k ) ; } }


"Find k pairs with smallest sums in two arrays | Java code to print first k pairs with least sum from two arrays . ; Function to find k pairs with least sum such that one elemennt of a pair is from arr1 [ ] and other element is from arr2 [ ] ; Stores current index in arr2 [ ] for every element of arr1 [ ] . Initially all values are considered 0. Here current index is the index before which all elements are considered as part of output . ; Initialize current pair sum as infinite ; To pick next pair , traverse for all elements of arr1 [ ] , for every element , find corresponding current element in arr2 [ ] and pick minimum of all formed pairs . ; Check if current element of arr1 [ ] plus element of array2 to be used gives minimum sum ; Update index that gives minimum ; update minimum sum ; Driver code"
How can the above be solved in Java?

import java . io . * ; class KSmallestPair { static void kSmallestPair ( int arr1 [ ] , int n1 , int arr2 [ ] , int n2 , int k ) { if ( k > n1 * n2 ) { System . out . print ( " k ▁ pairs ▁ don ' t ▁ exist " ) ; return ; } int index2 [ ] = new int [ n1 ] ; while ( k > 0 ) { int min_sum = Integer . MAX_VALUE ; int min_index = 0 ; for ( int i1 = 0 ; i1 < n1 ; i1 ++ ) { if ( index2 [ i1 ] < n2 && arr1 [ i1 ] + arr2 [ index2 [ i1 ] ] < min_sum ) { min_index = i1 ; min_sum = arr1 [ i1 ] + arr2 [ index2 [ i1 ] ] ; } } System . out . print ( " ( " + arr1 [ min_index ] + " , ▁ " + arr2 [ index2 [ min_index ] ] + " ) ▁ " ) ; index2 [ min_index ] ++ ; k -- ; } } public static void main ( String [ ] args ) { int arr1 [ ] = { 1 , 3 , 11 } ; int n1 = arr1 . length ; int arr2 [ ] = { 2 , 4 , 8 } ; int n2 = arr2 . length ; int k = 4 ; kSmallestPair ( arr1 , n1 , arr2 , n2 , k ) ; } }


"Find k pairs with smallest sums in two arrays | Set 2 | Java program to print the k smallest pairs | Set 2 ; Function to print the K smallest pairs ; if k is greater than total pairs ; _pair _one keeps track of ' first ' in a1 and ' second ' in a2 in _two , _two . first keeps track of element in the a2 [ ] and _two . second in a1 [ ] ; Repeat the above process till all K pairs are printed ; when both the pointers are pointing to the same elements ( point 3 ) ; updates according to step 1 ; see point 2 ; updates opposite to step 1 ; updates according to rule 1 ; see point 2 ; updates opposite to rule 1 ; see point 2 ; else update as necessary ( point 1 ) ; updating according to rule 1 ; see point 2 ; updating according to rule 1 ; see point 2 ; updating according to rule 1 ; see point 2 ; updating according to rule 1 ; see point 2 ; Driver Code"
How can the above be solved in Java?

 import java . util . * ; class GFG { static class _pair { int first , second ; } ; static void printKPairs ( int a1 [ ] , int a2 [ ] , int size1 , int size2 , int k ) { if ( k > ( size2 * size1 ) ) { System . out . print ( "k pairs don't exist
"); return ; } _pair _one = new _pair ( ) ; _pair _two = new _pair ( ) ; _one . first = _one . second = _two . first = _two . second = 0 ; int cnt = 0 ; while ( cnt < k ) { if ( _one . first == _two . second && _two . first == _one . second ) { if ( a1 [ _one . first ] < a2 [ _one . second ] ) { System . out . print ( " [ " + a1 [ _one . first ] + " , ▁ " + a2 [ _one . second ] + " ] ▁ " ) ; _one . second = ( _one . second + 1 ) % size2 ; if ( _one . second == 0 ) _one . first = ( _one . first + 1 ) % size1 ; _two . second = ( _two . second + 1 ) % size2 ; if ( _two . second == 0 ) _two . first = ( _two . first + 1 ) % size2 ; } else { System . out . print ( " [ " + a2 [ _one . second ] + " , ▁ " + a1 [ _one . first ] + " ] ▁ " ) ; _one . first = ( _one . first + 1 ) % size1 ; if ( _one . first == 0 ) _one . second = ( _one . second + 1 ) % size2 ; _two . first = ( _two . first + 1 ) % size2 ; if ( _two . first == 0 ) _two . second = ( _two . second + 1 ) % size1 ; } } else if ( a1 [ _one . first ] + a2 [ _one . second ] <= a2 [ _two . first ] + a1 [ _two . second ] ) { if ( a1 [ _one . first ] < a2 [ _one . second ] ) { System . out . print ( " [ " + a1 [ _one . first ] + " , ▁ " + a2 [ _one . second ] + " ] ▁ " ) ; _one . second = ( ( _one . second + 1 ) % size2 ) ; if ( _one . second == 0 ) _one . first = ( _one . first + 1 ) % size1 ; } else { System . out . print ( " [ " + a2 [ _one . second ] + " , ▁ " + a1 [ _one . first ] + " ] ▁ " ) ; _one . first = ( ( _one . first + 1 ) % size1 ) ; if ( _one . first == 0 ) _one . second = ( _one . second + 1 ) % size2 ; } } else if ( a1 [ _one . first ] + a2 [ _one . second ] > a2 [ _two . first ] + a1 [ _two . second ] ) { if ( a2 [ _two . first ] < a1 [ _two . second ] ) { System . out . print ( " [ " + a2 [ _two . first ]...


"Find k | A simple inorder traversal based Java program to find k - th smallest element in a BST . ; A BST node ; Recursive function to insert an key into BST ; Function to find k 'th largest element in BST  Here count denotes the number  of nodes processed so far ; base case ; search in left subtree ; if k 'th smallest is found in left subtree, return it ; if current element is k 'th smallest, return it ; else search in right subtree ; Function to find k 'th largest element in BST ; maintain an index to count number of nodes processed so far ; Driver code"
How can the above be solved in Java?

import java . io . * ; class Node { int data ; Node left , right ; Node ( int x ) { data = x ; left = right = null ; } } class GFG { static int count = 0 ; public static Node insert ( Node root , int x ) { if ( root == null ) return new Node ( x ) ; if ( x < root . data ) root . left = insert ( root . left , x ) ; else if ( x > root . data ) root . right = insert ( root . right , x ) ; return root ; } public static Node kthSmallest ( Node root , int k ) { if ( root == null ) return null ; Node left = kthSmallest ( root . left , k ) ; if ( left != null ) return left ; count ++ ; if ( count == k ) return root ; return kthSmallest ( root . right , k ) ; } public static void printKthSmallest ( Node root , int k ) { count = 0 ; Node res = kthSmallest ( root , k ) ; if ( res == null ) System . out . println ( " There ▁ are ▁ less ▁ " + " than ▁ k ▁ nodes ▁ in ▁ the ▁ BST " ) ; else System . out . println ( " K - th ▁ Smallest " + " ▁ Element ▁ is ▁ " + res . data ) ; } public static void main ( String [ ] args ) { Node root = null ; int keys [ ] = { 20 , 8 , 22 , 4 , 12 , 10 , 14 } ; for ( int x : keys ) root = insert ( root , x ) ; int k = 3 ; printKthSmallest ( root , k ) ; } }


"Find k | A simple inorder traversal based Java program to find k - th smallest element in a BST . ; A BST node ; Recursive function to insert an key into BST ; If a node is inserted in left subtree , then lCount of this node is increased . For simplicity , we are assuming that all keys ( tried to be inserted ) are distinct . ; Function to find k 'th largest element in BST  Here count denotes the number of  nodes processed so far ; base case ; else search in right subtree ; main function"
How can the above be solved in Java?

import java . io . * ; import java . util . * ; class Node { int data ; Node left , right ; int lCount ; Node ( int x ) { data = x ; left = right = null ; lCount = 0 ; } } class Gfg { public static Node insert ( Node root , int x ) { if ( root == null ) return new Node ( x ) ; if ( x < root . data ) { root . left = insert ( root . left , x ) ; root . lCount ++ ; } else if ( x > root . data ) root . right = insert ( root . right , x ) ; return root ; } public static Node kthSmallest ( Node root , int k ) { if ( root == null ) return null ; int count = root . lCount + 1 ; if ( count == k ) return root ; if ( count > k ) return kthSmallest ( root . left , k ) ; return kthSmallest ( root . right , k - count ) ; } public static void main ( String args [ ] ) { Node root = null ; int keys [ ] = { 20 , 8 , 22 , 4 , 12 , 10 , 14 } ; for ( int x : keys ) root = insert ( root , x ) ; int k = 4 ; Node res = kthSmallest ( root , k ) ; if ( res == null ) System . out . println ( " There ▁ are ▁ less ▁ " + " than ▁ k ▁ nodes ▁ in ▁ the ▁ BST " ) ; else System . out . println ( " K - th ▁ Smallest " + " ▁ Element ▁ is ▁ " + res . data ) ; } }


"Find k | Java implementation to solve k queries for given n ranges ; Structure to store the start and end point ; Comparison function for sorting ; Function to find Kth smallest number in a Vector of merged intervals ; Traverse merged . get ( ) o find Kth smallest element using Linear search . ; To combined both type of ranges , overlapping as well as non - overlapping . ; Sorting intervals according to start time ; Merging all intervals into merged ; To check if starting point of next range is lying between the previous range and ending point of next range is greater than the Ending point of previous range then update ending point of previous range by ending point of next range . ; If starting point of next range is greater than the ending point of previous range then store next range in merged . get ( . ) if ( curr . s > prev . e ) ; Driver code ; Merge all intervals into merged . get ( ) ) ; Processing all queries on merged intervals"
How can the above be solved in Java?

import java . util . * ; class GFG { static class Interval { int s ; int e ; Interval ( int a , int b ) { s = a ; e = b ; } } ; static class Sortby implements Comparator < Interval > { public int compare ( Interval a , Interval b ) { return a . s - b . s ; } } static int kthSmallestNum ( Vector < Interval > merged , int k ) { int n = merged . size ( ) ; for ( int j = 0 ; j < n ; j ++ ) { if ( k <= Math . abs ( merged . get ( j ) . e - merged . get ( j ) . s + 1 ) ) return ( merged . get ( j ) . s + k - 1 ) ; k = k - Math . abs ( merged . get ( j ) . e - merged . get ( j ) . s + 1 ) ; } if ( k != 0 ) return - 1 ; return 0 ; } static Vector < Interval > mergeIntervals ( Vector < Interval > merged , Interval arr [ ] , int n ) { Arrays . sort ( arr , new Sortby ( ) ) ; merged . add ( arr [ 0 ] ) ; for ( int i = 1 ; i < n ; i ++ ) { Interval prev = merged . get ( merged . size ( ) - 1 ) ; Interval curr = arr [ i ] ; if ( ( curr . s >= prev . s && curr . s <= prev . e ) && ( curr . e > prev . e ) ) merged . get ( merged . size ( ) - 1 ) . e = curr . e ; else { merged . add ( curr ) ; } } return merged ; } public static void main ( String args [ ] ) { Interval arr [ ] = { new Interval ( 2 , 6 ) , new Interval ( 4 , 7 ) } ; int n = arr . length ; int query [ ] = { 5 , 8 } ; int q = query . length ; Vector < Interval > merged = new Vector < Interval > ( ) ; merged = mergeIntervals ( merged , arr , n ) ; for ( int i = 0 ; i < q ; i ++ ) System . out . println ( kthSmallestNum ( merged , query [ i ] ) ) ; } }


"Find k | Java program to find K - Cores of a graph ; This class represents a undirected graph using adjacency list representation ; No . of vertices ; Pointer to an array containing adjacency lists ; function to add an edge to graph ; A recursive function to print DFS starting from v . It returns true if degree of v after processing is less than k else false It also updates degree of adjacent if degree of v is less than k . And if degree of a processed adjacent becomes less than k , then it reduces of degree of v also , ; Mark the current node as visited and print it ; Recur for all the vertices adjacent to this vertex ; degree of v is less than k , then degree of adjacent must be reduced ; If adjacent is not processed , process it ; If degree of adjacent after processing becomes less than k , then reduce degree of v also . ; Return true if degree of v is less than k ; Prints k cores of an undirected graph ; INITIALIZATION Mark all the vertices as not visited and not processed . ; Store degrees of all vertices ; DFS traversal to update degrees of all vertices . ; PRINTING K CORES ; Only considering those vertices which have degree >= K after BFS ; Traverse adjacency list of v and print only those adjacent which have vDegree >= k after BFS . ; Driver Code ; Create a graph given in the above diagram"
How can the above be solved in Java?

import java . util . * ; class GFG { static class Graph { int V ; Vector < Integer > [ ] adj ; @ SuppressWarnings ( " unchecked " ) Graph ( int V ) { this . V = V ; this . adj = new Vector [ V ] ; for ( int i = 0 ; i < V ; i ++ ) adj [ i ] = new Vector < > ( ) ; } void addEdge ( int u , int v ) { this . adj [ u ] . add ( v ) ; this . adj [ v ] . add ( u ) ; } boolean DFSUtil ( int v , boolean [ ] visited , int [ ] vDegree , int k ) { visited [ v ] = true ; for ( int i : adj [ v ] ) { if ( vDegree [ v ] < k ) vDegree [ i ] -- ; if ( ! visited [ i ] ) { DFSUtil ( i , visited , vDegree , k ) ; } } return ( vDegree [ v ] < k ) ; } void printKCores ( int k ) { boolean [ ] visited = new boolean [ V ] ; boolean [ ] processed = new boolean [ V ] ; Arrays . fill ( visited , false ) ; Arrays . fill ( processed , false ) ; int mindeg = Integer . MAX_VALUE ; int startvertex = 0 ; int [ ] vDegree = new int [ V ] ; for ( int i = 0 ; i < V ; i ++ ) { vDegree [ i ] = adj [ i ] . size ( ) ; if ( vDegree [ i ] < mindeg ) { mindeg = vDegree [ i ] ; startvertex = i ; } } DFSUtil ( startvertex , visited , vDegree , k ) ; for ( int i = 0 ; i < V ; i ++ ) if ( ! visited [ i ] ) DFSUtil ( i , visited , vDegree , k ) ; System . out . println ( " K - Cores ▁ : ▁ " ) ; for ( int v = 0 ; v < V ; v ++ ) { if ( vDegree [ v ] >= k ) { System . out . printf ( " [ % d ] ", v); for ( int i : adj [ v ] ) if ( vDegree [ i ] >= k ) System . out . printf ( " ▁ - > ▁ % d " , i ) ; } } } } public static void main ( String [ ] args ) { int k = 3 ; Graph g1 = new Graph ( 9 ) ; g1 . addEdge ( 0 , 1 ) ; g1 . addEdge ( 0 , 2 ) ; g1 . addEdge ( 1 , 2 ) ; g1 . addEdge ( 1 , 5 ) ; g1 . addEdge ( 2 , 3 ) ; g1 . addEdge ( 2 , 4 ) ; g1 . addEdge ( 2 , 5 ) ; g1 . addEdge ( 2 , 6 ) ; g1 . addEdge ( 3 , 4 ) ; g1 . addEdge ( 3 , 6 ) ; g1 . addEdge ( 3 , 7 ) ; g1 . addEdge ( 4 , 6 ) ; g1 . addEdge ( 4 , 7 ) ; g1 . addEdge ( 5 , 6 ) ; g1 . addEdge ( 5 , 8 ) ; g1 . addEdge ( 6 , 7 ) ; g1 . addEdge ( 6 , 8 ) ; g1 . printKCores ( k ) ; System . out . println ( ) ;...


"Find kth smallest number in range [ 1 , n ] when all the odd numbers are deleted | Java implementation of the approach ; Function to return the kth smallest element from the range [ 1 , n ] after removing all the odd elements ; Driver code"
How can the above be solved in Java?

class GFG { static int kthSmallest ( int n , int k ) { return ( 2 * k ) ; } public static void main ( String args [ ] ) { int n = 8 , k = 4 ; System . out . print ( kthSmallest ( n , k ) ) ; } }


"Find larger of x ^ y and y ^ x | Java program to print greater of x ^ y and y ^ x ; Driver Code"
How can the above be solved in Java?

import java . io . * ; class GFG { static void printGreater ( int x , int y ) { double X = y * Math . log ( x ) ; double Y = x * Math . log ( y ) ; if ( Math . abs ( X - Y ) < 1e-9 ) { System . out . println ( " Equal " ) ; } else if ( X > Y ) { System . out . println ( x + " ^ " + y ) ; } else { System . out . println ( y + " ^ " + x ) ; } } public static void main ( String [ ] args ) { int x = 5 , y = 8 ; printGreater ( x , y ) ; } }


"Find largest factor of N such that N / F is less than K | Java program for the above approach ; Function to find the largest factor of N which is less than or equal to K ; Initialise the variable to store the largest factor of N <= K ; Loop to find all factors of N ; Check if j is a factor of N or not ; Check if j <= K If yes , then store the larger value between ans and j in ans ; Check if N / j <= K If yes , then store the larger value between ans and j in ans ; Since max value is always stored in ans , the maximum value divisible by N less than or equal to K will be returned . ; Driver Code ; Given N and K ; Function call"
How can the above be solved in Java?

import java . util . * ; class GFG { static int solve ( int n , int k ) { int ans = 0 ; for ( int j = 1 ; j * j <= n ; j ++ ) { if ( n % j == 0 ) { if ( j <= k ) { ans = Math . max ( ans , j ) ; } if ( n / j <= k ) { ans = Math . max ( ans , n / j ) ; } } } return ans ; } public static void main ( String [ ] args ) { int N = 8 , K = 7 ; System . out . print ( ( N / solve ( N , K ) ) ) ; } }


"Find largest factor of N such that N / F is less than K | Java program for the above approach ; Function to find the value of X ; Loop to check all the numbers divisible by N that yield minimum N / i value ; Print the value of packages ; Driver code ; Given N and K ; Function call"
How can the above be solved in Java?

import java . util . Arrays ; class GFG { static void findMaxValue ( int N , int K ) { int packages ; int maxi = 1 ; for ( int i = 1 ; i <= K ; i ++ ) { if ( N % i == 0 ) maxi = Math . max ( maxi , i ) ; } packages = N / maxi ; System . out . println ( packages ) ; } public static void main ( String [ ] args ) { int N = 8 , K = 7 ; findMaxValue ( N , K ) ; } }


"Find largest prime factor of a number | Java Program to find largest prime factor of number ; function to find largest prime factor ; Initialize the maximum prime factor variable with the lowest one ; Print the number of 2 s that divide n ; equivalent to n /= 2 ; n must be odd at this point ; now we have to iterate only for integers who does not have prime factor 2 and 3 ; This condition is to handle the case when n is a prime number greater than 4 ; Driver code"
How can the above be solved in Java?

import java . io . * ; import java . util . * ; class GFG { static long maxPrimeFactors ( long n ) { long maxPrime = - 1 ; while ( n % 2 == 0 ) { maxPrime = 2 ; n >>= 1 ; } while ( n % 3 == 0 ) { maxPrime = 3 ; n = n / 3 ; } for ( int i = 5 ; i <= Math . sqrt ( n ) ; i += 6 ) { while ( n % i == 0 ) { maxPrime = i ; n = n / i ; } while ( n % ( i + 2 ) == 0 ) { maxPrime = i + 2 ; n = n / ( i + 2 ) ; } } if ( n > 4 ) maxPrime = n ; return maxPrime ; } public static void main ( String [ ] args ) { Long n = 15l ; System . out . println ( maxPrimeFactors ( n ) ) ; n = 25698751364526l ; System . out . println ( maxPrimeFactors ( n ) ) ; } }


"Find largest subtree having identical left and right subtrees | Java program to find the largest subtree having identical left and right subtree ; A binary tree node has data , pointer to left child and a pointer to right child ; Helper function that allocates a new node with the given data and null left and right pointers . ; Sets maxSize to size of largest subtree with identical left and right . maxSize is set with size of the maximum sized subtree . It returns size of subtree rooted with current node . This size is used to keep track of maximum size . ; string to store structure of left and right subtrees ; traverse left subtree and finds its size ; traverse right subtree and finds its size ; if left and right subtrees are similar update maximum subtree if needed ( Note that left subtree may have a bigger value than right and vice versa ) ; append left subtree data ; append current node data ; append right subtree data ; function to find the largest subtree having identical left and right subtree ; Driver program to test above functions ; Let us construct the following Tree 50 / \ 10 60 / \ / \ 5 20 70 70 / \ / \ 65 80 65 80"
How can the above be solved in Java?

class GFG { static class Node { int data ; Node left , right ; } ; static Node newNode ( int data ) { Node node = new Node ( ) ; node . data = data ; node . left = node . right = null ; return ( node ) ; } static class string { String str ; } static int maxSize ; static Node maxNode ; static class pair { int first ; String second ; pair ( int a , String b ) { first = a ; second = b ; } } static pair largestSubtreeUtil ( Node root , String str ) { if ( root == null ) return new pair ( 0 , str ) ; String left = " " , right = " " ; pair ls1 = largestSubtreeUtil ( root . left , left ) ; left = ls1 . second ; int ls = ls1 . first ; pair rs1 = largestSubtreeUtil ( root . right , right ) ; right = rs1 . second ; int rs = rs1 . first ; int size = ls + rs + 1 ; if ( left . equals ( right ) ) { if ( size > maxSize ) { maxSize = size ; maxNode = root ; } } str += " | " + left + " | " ; str += " | " + root . data + " | " ; str += " | " + right + " | " ; return new pair ( size , str ) ; } static int largestSubtree ( Node node ) { maxSize = 0 ; largestSubtreeUtil ( node , " " ) ; return maxSize ; } public static void main ( String args [ ] ) { Node root = newNode ( 50 ) ; root . left = newNode ( 10 ) ; root . right = newNode ( 60 ) ; root . left . left = newNode ( 5 ) ; root . left . right = newNode ( 20 ) ; root . right . left = newNode ( 70 ) ; root . right . left . left = newNode ( 65 ) ; root . right . left . right = newNode ( 80 ) ; root . right . right = newNode ( 70 ) ; root . right . right . left = newNode ( 65 ) ; root . right . right . right = newNode ( 80 ) ; maxNode = null ; maxSize = largestSubtree ( root ) ; System . out . println ( " Largest ▁ Subtree ▁ is ▁ rooted ▁ at ▁ node ▁ " + maxNode . data + " and its size is " + maxSize); } }


"Find largest word in dictionary by deleting some characters of given string | Java program to find largest word in Dictionary by deleting some characters of given String ; Returns true if str1 [ ] is a subsequence of str2 [ ] . m is length of str1 and n is length of str2 ; Traverse str2 and str1 , and compare current character of str2 with first unmatched char of str1 , if matched then move ahead in str1 ; If all characters of str1 were found in str2 ; Returns the longest String in dictionary which is a subsequence of str . ; Traverse through all words of dictionary ; If current word is subsequence of str and is largest such word so far . ; Return longest String ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { static boolean isSubSequence ( String str1 , String str2 ) { int m = str1 . length ( ) , n = str2 . length ( ) ; for ( int i = 0 ; i < n && j < m ; i ++ ) { if ( str1 . charAt ( j ) == str2 . charAt ( i ) ) { j ++ ; } } return ( j == m ) ; } static String findLongestString ( Vector < String > dict , String str ) { String result = " " ; int length = 0 ; for ( String word : dict ) { if ( length < word . length ( ) && isSubSequence ( word , str ) ) { result = word ; length = word . length ( ) ; } } return result ; } public static void main ( String [ ] args ) { String [ ] arr = { " ale " , " apple " , " monkey " , " plea " } ; Vector dict = new Vector ( Arrays . asList ( arr ) ) ; String str = " abpcplea " ; System . out . println ( findLongestString ( dict , str ) ) ; } }


"Find last 2 survivors in N persons standing in a circle after killing next to immediate neighbour | Java implementation of the approach ; Node for a Linked List ; Function to find the last 2 survivors ; Total is the count of alive people ; Initiating the list of n people ; Total != 2 is terminating condition because at last only two - person will remain alive ; Del represent next person to be deleted or killed ; Last two person to survive ( in any order ) ; Driver code"
How can the above be solved in Java?

class GFG { static class Node { int val ; Node next ; Node ( int _val ) { val = _val ; next = null ; } } ; static void getLastTwoPerson ( int n ) { int total = n ; Node head = new Node ( 1 ) ; Node temp = head ; for ( int i = 2 ; i <= n ; i ++ ) { temp . next = new Node ( i ) ; temp = temp . next ; } temp . next = head ; temp = head ; Node del ; while ( total != 2 ) { del = temp . next . next ; temp . next . next = temp . next . next . next ; temp = temp . next ; del = null ; System . gc ( ) ; total -= 1 ; } System . out . print ( temp . val + " ▁ " + temp . next . val ) ; } public static void main ( String [ ] args ) { int n = 2 ; getLastTwoPerson ( n ) ; } }


"Find last digit in factorial | Java program to find last digit in factorial n . ; Explicitly handle all numbers less than or equal to 4 ; For all numbers greater than 4 the last digit is 0 ; Driver code"
How can the above be solved in Java?

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


"Find last five digits of a given five digit number raised to power five | Java program to find last five digits of a five digit number raised to power five ; Function to find the last five digits of a five digit number raised to power five ; Driver code"
How can the above be solved in Java?

class GfG { static void lastFiveDigits ( int n ) { n = ( n / 10000 ) * 10000 + ( ( n / 100 ) % 10 ) * 1000 + ( n % 10 ) * 100 + ( ( n / 10 ) % 10 ) * 10 + ( n / 1000 ) % 10 ; int ans = 1 ; for ( int i = 0 ; i < 5 ; i ++ ) { ans *= n ; ans %= 100000 ; } System . out . println ( ans ) ; } public static void main ( String [ ] args ) { int n = 12345 ; lastFiveDigits ( n ) ; } }


"Find last index of a character in a string | Java code to find last index character x in given string . ; Returns last index of x if it is present . Else returns - 1. ; Traverse from right ; Driver code"
How can the above be solved in Java?

import java . io . * ; class GFG { static int findLastIndex ( String str , Character x ) { for ( int i = str . length ( ) - 1 ; i >= 0 ; i -- ) if ( str . charAt ( i ) == x ) return i ; return - 1 ; } public static void main ( String [ ] args ) { String str = " geeksforgeeks " ; Character x = ' e ' ; int index = findLastIndex ( str , x ) ; if ( index == - 1 ) System . out . println ( " Character ▁ not ▁ found " ) ; else System . out . println ( " Last ▁ index ▁ is ▁ " + index ) ; } }


"Find last index of a character in a string | Java program to find last index of character x in given string . ; Returns last index of x if it is present Else returns - 1. ; Driver code ; String in which char is to be found ; char whose index is to be found"
How can the above be solved in Java?

import java . io . * ; class GFG { static int findLastIndex ( String str , Character x ) { int index = - 1 ; for ( int i = 0 ; i < str . length ( ) ; i ++ ) if ( str . charAt ( i ) == x ) index = i ; return index ; } public static void main ( String [ ] args ) { String str = " geeksforgeeks " ; Character x = ' e ' ; int index = findLastIndex ( str , x ) ; if ( index == - 1 ) System . out . println ( " Character ▁ not ▁ found " ) ; else System . out . println ( " Last ▁ index ▁ is ▁ " + index ) ; } }


"Find last two digits of sum of N factorials | Java program to find the unit place digit of the first N natural numbers factorials ; Function to find the unit ' s ▁ and ▁ ten ' s place digit ; Let us write for cases when N is smaller than or equal to 10. ; We know following ( 1 ! + 2 ! + 3 ! + 4 ! ... + 10 ! ) % 100 = 13 else ( N >= 10 ) ; Driver code"
How can the above be solved in Java?

public class AAA { static int get_last_two_digit ( long N ) { if ( N <= 10 ) { long ans = 0 , fac = 1 ; for ( int i = 1 ; i <= N ; i ++ ) { fac = fac * i ; ans += fac ; } return ( int ) ans % 100 ; } return 13 ; } public static void main ( String [ ] args ) { long N = 1 ; for ( N = 1 ; N <= 10 ; N ++ ) System . out . println ( " For ▁ N ▁ = ▁ " + N + " ▁ : ▁ " + get_last_two_digit ( N ) ) ; } }


"Find least non | Java program to find the least non - overlapping number from a given set intervals ; Function to find the smallest non - overlapping number ; Sort the intervals based on their starting value ; Check if any missing value exist ; Finally print the missing value ; Driver code"
How can the above be solved in Java?

import java . util . * ; import java . io . * ; class GFG { static class Pair implements Comparable < Pair > { int start , end ; Pair ( int s , int e ) { start = s ; end = e ; } public int compareTo ( Pair p ) { return this . start - p . start ; } } static void findMissing ( ArrayList < Pair > interval ) { Collections . sort ( interval ) ; int mx = 0 ; for ( int i = 0 ; i < interval . size ( ) ; ++ i ) { if ( interval . get ( i ) . start > mx ) { System . out . println ( mx ) ; return ; } else mx = Math . max ( mx , interval . get ( i ) . end + 1 ) ; } System . out . println ( mx ) ; } public static void main ( String [ ] args ) { ArrayList < Pair > interval = new ArrayList < > ( ) ; interval . add ( new Pair ( 0 , 14 ) ) ; interval . add ( new Pair ( 86 , 108 ) ) ; interval . add ( new Pair ( 22 , 30 ) ) ; interval . add ( new Pair ( 5 , 17 ) ) ; findMissing ( interval ) ; } }


"Find least non | Java program to find the least non - overlapping number from a given set intervals ; function to find the smallest non - overlapping number ; create a visited array ; find the first missing value ; Driver function"
How can the above be solved in Java?

 class GFG { static int MAX = ( int ) ( 1e5 + 5 ) ; static class pair { int first , second ; public pair ( int first , int second ) { this . first = first ; this . second = second ; } } static void find_missing ( pair [ ] interval ) { int [ ] vis = new int [ MAX ] ; for ( int i = 0 ; i < interval . length ; ++ i ) { int start = interval [ i ] . first ; int end = interval [ i ] . second ; vis [ start ] ++ ; vis [ end + 1 ] -- ; } for ( int i = 1 ; i < MAX ; i ++ ) { vis [ i ] += vis [ i - 1 ] ; if ( vis [ i ] == 0 ) { System . out . print ( i + "
"); return ; } } } public static void main ( String [ ] args ) { pair [ ] interval = { new pair ( 0 , 14 ) , new pair ( 86 , 108 ) , new pair ( 22 , 30 ) , new pair ( 5 , 17 ) } ; find_missing ( interval ) ; } }


"Find length of Diagonal of Hexagon | Java Program to find the diagonal of the hexagon ; Function to find the diagonal of the hexagon ; side cannot be negative ; diagonal of the hexagon ; Driver code"
How can the above be solved in Java?

import java . io . * ; class GFG { static float hexadiagonal ( float a ) { if ( a < 0 ) return - 1 ; return 2 * a ; } public static void main ( String [ ] args ) { float a = 4 ; System . out . print ( hexadiagonal ( a ) ) ; } }


"Find length of longest subsequence of one string which is substring of another string | Base Case ; if the last char of both Strings are equal ; if the last char of both Strings are not equal ; Driver code ; as minimum length can be 0 only . ; traversing for every length of Y ."
How can the above be solved in Java?

import java . util . * ; class GFG { static int maxSubsequenceSubString ( String X , String Y , int n , int m ) { if ( n == 0 m == 0 ) return 0 ; if ( X . charAt ( n - 1 ) == Y . charAt ( m - 1 ) ) { return 1 + maxSubsequenceSubString ( X , Y , n - 1 , m - 1 ) ; } else { return maxSubsequenceSubString ( X , Y , n - 1 , m ) ; } } public static void main ( String [ ] args ) { String X = " abcd " ; String Y = " bacdbdcd " ; int n = X . length ( ) , m = Y . length ( ) ; int maximum_length = 0 ; for ( int i = 0 ; i <= m ; i ++ ) { int temp_ans = maxSubsequenceSubString ( X , Y , n , i ) ; if ( temp_ans > maximum_length ) maximum_length = temp_ans ; } System . out . print ( " Length ▁ for ▁ maximum ▁ possible ▁ Subsequence ▁ of ▁ String ▁ X ▁ which ▁ is ▁ SubString ▁ of ▁ Y - > " + maximum_length ) ; } }


"Find length of longest subsequence of one string which is substring of another string | Java program to find maximum length of subsequence of a string X such it is substring in another string Y . ; Return the maximum size of substring of X which is substring in Y . ; Initialize the dp [ ] [ ] to 0. ; Calculating value for each element . ; If alphabet of string X and Y are equal make dp [ i ] [ j ] = 1 + dp [ i - 1 ] [ j - 1 ] ; Else copy the previous value in the row i . e dp [ i - 1 ] [ j - 1 ] ; Finding the maximum length . ; Driver Method"
How can the above be solved in Java?

public class GFG { static final int MAX = 1000 ; static int maxSubsequenceSubstring ( char x [ ] , char y [ ] , int n , int m ) { int dp [ ] [ ] = new int [ MAX ] [ MAX ] ; for ( int i = 0 ; i <= m ; i ++ ) for ( int j = 0 ; j <= n ; j ++ ) dp [ i ] [ j ] = 0 ; for ( int i = 1 ; i <= m ; i ++ ) { for ( int j = 1 ; j <= n ; j ++ ) { if ( x [ j - 1 ] == y [ i - 1 ] ) dp [ i ] [ j ] = 1 + dp [ i - 1 ] [ j - 1 ] ; else dp [ i ] [ j ] = dp [ i ] [ j - 1 ] ; } } int ans = 0 ; for ( int i = 1 ; i <= m ; i ++ ) ans = Math . max ( ans , dp [ i ] [ n ] ) ; return ans ; } public static void main ( String [ ] args ) { char x [ ] = " ABCD " . toCharArray ( ) ; char y [ ] = " BACDBDCD " . toCharArray ( ) ; int n = x . length , m = y . length ; System . out . println ( maxSubsequenceSubstring ( x , y , n , m ) ) ; } }


"Find length of longest substring with at most K normal characters | Java implementation to Find length of longest subString with at most K normal characters ; Function to find maximum length of normal subStrings ; keeps count of normal characters ; indexes of subString ; maintain length of longest subString with at most K normal characters ; get position of character ; check if current character is normal ; check if normal characters count exceeds K ; update answer with subString length ; get position of character ; check if character is normal then decrement count ; Driver code ; initialise the String"
How can the above be solved in Java?

class GFG { static int maxNormalSubString ( char [ ] P , char [ ] Q , int K , int N ) { if ( K == 0 ) return 0 ; int count = 0 ; int left = 0 , right = 0 ; int ans = 0 ; while ( right < N ) { while ( right < N && count <= K ) { int pos = P [ right ] - ' a ' ; if ( Q [ pos ] == '0' ) { if ( count + 1 > K ) break ; else count ++ ; } right ++ ; if ( count <= K ) ans = Math . max ( ans , right - left ) ; } while ( left < right ) { int pos = P [ left ] - ' a ' ; left ++ ; if ( Q [ pos ] == '0' ) count -- ; if ( count < K ) break ; } } return ans ; } public static void main ( String [ ] args ) { String P = " giraffe " , Q = "01111001111111111011111111" ; int K = 2 ; int N = P . length ( ) ; System . out . print ( maxNormalSubString ( P . toCharArray ( ) , Q . toCharArray ( ) , K , N ) ) ; } }


"Find length of period in decimal value of 1 / n | Java program to find length of period of 1 / n without using map or hash ; Function to find length of period in 1 / n ; Find the ( n + 1 ) th remainder after decimal point in value of 1 / n ; Store ( n + 1 ) th remainder ; Count the number of remainders before next occurrence of ( n + 1 ) ' th ▁ remainder ▁ ' d ' ; Driver code"
How can the above be solved in Java?

class GFG { static int getPeriod ( int n ) { int rem = 1 ; for ( int i = 1 ; i <= n + 1 ; i ++ ) rem = ( 10 * rem ) % n ; int d = rem ; int count = 0 ; do { rem = ( 10 * rem ) % n ; count ++ ; } while ( rem != d ) ; return count ; } public static void main ( String [ ] args ) { System . out . println ( getPeriod ( 3 ) ) ; System . out . println ( getPeriod ( 7 ) ) ; } }


"Find length of the largest region in Boolean Matrix | Java program to find the length of the largest region in boolean 2D - matrix ; A function to check if a given cell ( row , col ) can be included in DFS ; row number is in range , column number is in range and value is 1 and not yet visited ; A utility function to do DFS for a 2D boolean matrix . It only considers the 8 neighbours as adjacent vertices ; These arrays are used to get row and column numbers of 8 neighbours of a given cell ; Mark this cell as visited ; Recur for all connected neighbours ; increment region length by one ; The main function that returns largest length region of a given boolean 2D matrix ; Make a boolean array to mark visited cells . Initially all cells are unvisited ; Initialize result as 0 and traverse through the all cells of given matrix ; If a cell with value 1 is not ; visited yet , then new region found ; maximum region ; Driver code ; Function call"
How can the above be solved in Java?

import java . io . * ; import java . util . * ; class GFG { static int ROW , COL , count ; static boolean isSafe ( int [ ] [ ] M , int row , int col , boolean [ ] [ ] visited ) { return ( ( row >= 0 ) && ( row < ROW ) && ( col >= 0 ) && ( col < COL ) && ( M [ row ] [ col ] == 1 && ! visited [ row ] [ col ] ) ) ; } static void DFS ( int [ ] [ ] M , int row , int col , boolean [ ] [ ] visited ) { int [ ] rowNbr = { - 1 , - 1 , - 1 , 0 , 0 , 1 , 1 , 1 } ; int [ ] colNbr = { - 1 , 0 , 1 , - 1 , 1 , - 1 , 0 , 1 } ; visited [ row ] [ col ] = true ; for ( int k = 0 ; k < 8 ; k ++ ) { if ( isSafe ( M , row + rowNbr [ k ] , col + colNbr [ k ] , visited ) ) { count ++ ; DFS ( M , row + rowNbr [ k ] , col + colNbr [ k ] , visited ) ; } } } static int largestRegion ( int [ ] [ ] M ) { boolean [ ] [ ] visited = new boolean [ ROW ] [ COL ] ; int result = 0 ; for ( int i = 0 ; i < ROW ; i ++ ) { for ( int j = 0 ; j < COL ; j ++ ) { if ( M [ i ] [ j ] == 1 && ! visited [ i ] [ j ] ) { count = 1 ; DFS ( M , i , j , visited ) ; result = Math . max ( result , count ) ; } } } return result ; } public static void main ( String args [ ] ) { int M [ ] [ ] = { { 0 , 0 , 1 , 1 , 0 } , { 1 , 0 , 1 , 1 , 0 } , { 0 , 1 , 0 , 0 , 0 } , { 0 , 0 , 0 , 0 , 1 } } ; ROW = 4 ; COL = 5 ; System . out . println ( largestRegion ( M ) ) ; } }


"Find length of the longest consecutive path from a given starting character | Java program to find the longest consecutive path ; tool matrices to recur for adjacent cells . ; dp [ i ] [ j ] Stores length of longest consecutive path starting at arr [ i ] [ j ] . ; check whether mat [ i ] [ j ] is a valid cell or not . ; Check whether current character is adjacent to previous character ( character processed in parent call ) or not . ; i , j are the indices of the current cell and prev is the character processed in the parent call . . also mat [ i ] [ j ] is our current character . ; If this cell is not valid or current character is not adjacent to previous one ( e . g . d is not adjacent to b ) or if this cell is already included in the path than return 0. ; If this subproblem is already solved , return the answer ; Initialize answer ; recur for paths with different adjacent cells and store the length of longest path . ; save the answer and return ; Returns length of the longest path with all characters consecutive to each other . This function first initializes dp array that is used to store results of subproblems , then it calls recursive DFS based function getLenUtil ( ) to find max length path ; check for each possible starting point ; recur for all eight adjacent cells ; Driver program"
How can the above be solved in Java?

class path { static int x [ ] = { 0 , 1 , 1 , - 1 , 1 , 0 , - 1 , - 1 } ; static int y [ ] = { 1 , 0 , 1 , 1 , - 1 , - 1 , 0 , - 1 } ; static int R = 3 ; static int C = 3 ; static int dp [ ] [ ] = new int [ R ] [ C ] ; static boolean isvalid ( int i , int j ) { if ( i < 0 j < 0 i >= R j >= C ) return false ; return true ; } static boolean isadjacent ( char prev , char curr ) { return ( ( curr - prev ) == 1 ) ; } static int getLenUtil ( char mat [ ] [ ] , int i , int j , char prev ) { if ( ! isvalid ( i , j ) || ! isadjacent ( prev , mat [ i ] [ j ] ) ) return 0 ; if ( dp [ i ] [ j ] != - 1 ) return dp [ i ] [ j ] ; int ans = 0 ; for ( int k = 0 ; k < 8 ; k ++ ) ans = Math . max ( ans , 1 + getLenUtil ( mat , i + x [ k ] , j + y [ k ] , mat [ i ] [ j ] ) ) ; return dp [ i ] [ j ] = ans ; } static int getLen ( char mat [ ] [ ] , char s ) { for ( int i = 0 ; i < R ; ++ i ) for ( int j = 0 ; j < C ; ++ j ) dp [ i ] [ j ] = - 1 ; int ans = 0 ; for ( int i = 0 ; i < R ; i ++ ) { for ( int j = 0 ; j < C ; j ++ ) { if ( mat [ i ] [ j ] == s ) { for ( int k = 0 ; k < 8 ; k ++ ) ans = Math . max ( ans , 1 + getLenUtil ( mat , i + x [ k ] , j + y [ k ] , s ) ) ; } } } return ans ; } public static void main ( String args [ ] ) { char mat [ ] [ ] = { { ' a ' , ' c ' , ' d ' } , { ' h ' , ' b ' , ' a ' } , { ' i ' , ' g ' , ' f ' } } ; System . out . println ( getLen ( mat , ' a ' ) ) ; System . out . println ( getLen ( mat , ' e ' ) ) ; System . out . println ( getLen ( mat , ' b ' ) ) ; System . out . println ( getLen ( mat , ' f ' ) ) ; } }


"Find letter 's position in Alphabet using Bit operation | Java implementation of the approach ; Function to calculate the position of characters ; Performing AND operation with number 31 ; Driver code"
How can the above be solved in Java?

public class GFG { public static final int NUM = 31 ; static void positions ( String str , int n ) { for ( int i = 0 ; i < n ; i ++ ) { System . out . print ( ( str . charAt ( i ) & NUM ) + " ▁ " ) ; } } public static void main ( String [ ] args ) { String str = " Geeks " ; int n = str . length ( ) ; positions ( str , n ) ; } }


"Find lexicographically smallest string in at most one swaps | Java implementation of the above approach ; Function to return the lexicographically smallest String that can be formed by swapping at most one character . The characters might not necessarily be adjacent . ; Store last occurrence of every character ; Set - 1 as default for every character . ; Character index to fill in the last occurrence array ; If this is true then this character is being visited for the first time from the last Thus last occurrence of this character is stored in this index ; Character to replace ; Find the last occurrence of this character . ; Swap this with the last occurrence ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { static String findSmallest ( char [ ] s ) { int len = s . length ; int [ ] loccur = new int [ 26 ] ; Arrays . fill ( loccur , - 1 ) ; for ( int i = len - 1 ; i >= 0 ; -- i ) { int chI = s [ i ] - ' a ' ; if ( loccur [ chI ] == - 1 ) { loccur [ chI ] = i ; } } char [ ] sorted_s = s ; Arrays . sort ( sorted_s ) ; for ( int i = 0 ; i < len ; ++ i ) { if ( s [ i ] != sorted_s [ i ] ) { int chI = sorted_s [ i ] - ' a ' ; int last_occ = loccur [ chI ] ; char temp = s [ last_occ ] ; s [ last_occ ] = s [ i ] ; s [ i ] = temp ; break ; } } return String . valueOf ( s ) ; } public static void main ( String [ ] args ) { String s = " geeks " ; System . out . print ( findSmallest ( s . toCharArray ( ) ) ) ; } }


"Find longest bitonic sequence such that increasing and decreasing parts are from two different arrays | Java to find largest bitonic sequence such that ; utility Binary search ; function to find LIS in reverse form ; Add boundary case , when array n is zero Depend on smart pointers ; Integer len = 1 ; it will always point to empty location ; new smallest value ; arr [ i ] wants to extend largest subsequence ; arr [ i ] wants to be a potential candidate of future subsequence It will replace ceil value in tailIndices ; put LIS into vector ; function for finding longest bitonic seq ; find LIS of array 1 in reverse form ; reverse res to get LIS of first array ; reverse array2 and find its LIS ; print result ; Driver Code"
How can the above be solved in Java?

import java . util . * ; class GFG { static Vector < Integer > res = new Vector < > ( ) ; static Integer GetCeilIndex ( Integer [ ] arr , Integer [ ] T , Integer l , Integer r , Integer key ) { while ( r - l > 1 ) { Integer m = l + ( r - l ) / 2 ; if ( arr [ T [ m ] ] >= key ) r = m ; else l = m ; } return r ; } static void LIS ( Integer [ ] arr , Integer n ) { Integer [ ] tailIndices = new Integer [ n ] ; Integer [ ] prevIndices = new Integer [ n ] ; for ( Integer i = 1 ; i < n ; i ++ ) { if ( arr [ i ] < arr [ tailIndices [ 0 ] ] ) tailIndices [ 0 ] = i ; else if ( arr [ i ] > arr [ tailIndices [ len - 1 ] ] ) { prevIndices [ i ] = tailIndices [ len - 1 ] ; tailIndices [ len ++ ] = i ; } else { Integer pos = GetCeilIndex ( arr , tailIndices , - 1 , len - 1 , arr [ i ] ) ; prevIndices [ i ] = tailIndices [ pos - 1 ] ; tailIndices [ pos ] = i ; } } for ( Integer i = tailIndices [ len - 1 ] ; i >= 0 ; i = prevIndices [ i ] ) res . add ( arr [ i ] ) ; } static void longestBitonic ( Integer [ ] arr1 , Integer n1 , Integer [ ] arr2 , Integer n2 ) { LIS ( arr1 , n1 ) ; Collections . reverse ( res ) ; Collections . reverse ( Arrays . asList ( arr2 ) ) ; LIS ( arr2 , n2 ) ; for ( Integer i = 0 ; i < res . size ( ) ; i ++ ) System . out . print ( res . elementAt ( i ) + " ▁ " ) ; } public static void main ( String [ ] args ) { Integer [ ] arr1 = { 1 , 2 , 4 , 3 , 2 } ; Integer [ ] arr2 = { 8 , 6 , 4 , 7 , 8 , 9 } ; Integer n1 = arr1 . length ; Integer n2 = arr2 . length ; longestBitonic ( arr1 , n1 , arr2 , n2 ) ; } }


"Find lost element from a duplicated array | Java program to find missing element from one array such that it has all elements of other array except one . Elements in two arrays can be in any order . ; This function mainly does XOR of all elements of arr1 [ ] and arr2 [ ] ; Do XOR of all element ; Driver Code"
How can the above be solved in Java?

import java . io . * ; class Missing { void findMissing ( int arr1 [ ] , int arr2 [ ] , int M , int N ) { if ( M != N - 1 && N != M - 1 ) { System . out . println ( " Invalid ▁ Input " ) ; return ; } int res = 0 ; for ( int i = 0 ; i < M ; i ++ ) res = res ^ arr1 [ i ] ; for ( int i = 0 ; i < N ; i ++ ) res = res ^ arr2 [ i ] ; System . out . println ( " Missing ▁ element ▁ is ▁ " + res ) ; } public static void main ( String args [ ] ) { Missing obj = new Missing ( ) ; int arr1 [ ] = { 4 , 1 , 5 , 9 , 7 } ; int arr2 [ ] = { 7 , 5 , 9 , 4 } ; int M = arr1 . length ; int N = arr2 . length ; obj . findMissing ( arr1 , arr2 , M , N ) ; } }


"Find lost element from a duplicated array | Java program to find missing element from same arrays ( except one missing element ) ; Function to find missing element based on binary search approach . arr1 [ ] is of larger size and N is size of it . arr1 [ ] and arr2 [ ] are assumed to be in same order . ; special case , for only element which is missing in second array ; special case , for first element missing ; Initialize current corner points ; loop until lo < hi ; If element at mid indices are equal then go to right subarray ; if lo , hi becomes contiguous , break ; missing element will be at hi index of bigger array ; This function mainly does basic error checking and calls findMissingUtil ; Driver Code"
How can the above be solved in Java?

 import java . io . * ; class MissingNumber { int findMissingUtil ( int arr1 [ ] , int arr2 [ ] , int N ) { if ( N == 1 ) return arr1 [ 0 ] ; if ( arr1 [ 0 ] != arr2 [ 0 ] ) return arr1 [ 0 ] ; int lo = 0 , hi = N - 1 ; while ( lo < hi ) { int mid = ( lo + hi ) / 2 ; if ( arr1 [ mid ] == arr2 [ mid ] ) lo = mid ; else hi = mid ; if ( lo == hi - 1 ) break ; } return arr1 [ hi ] ; } void findMissing ( int arr1 [ ] , int arr2 [ ] , int M , int N ) { if ( N == M - 1 ) System . out . println ( " Missing ▁ Element ▁ is ▁ " + findMissingUtil ( arr1 , arr2 , M ) + "
"); else if ( M == N - 1 ) System . out . println ( " Missing ▁ Element ▁ is ▁ " + findMissingUtil ( arr2 , arr1 , N ) + "
"); else System . out . println ( " Invalid ▁ Input " ) ; } public static void main ( String args [ ] ) { MissingNumber obj = new MissingNumber ( ) ; int arr1 [ ] = { 1 , 4 , 5 , 7 , 9 } ; int arr2 [ ] = { 4 , 5 , 7 , 9 } ; int M = arr1 . length ; int N = arr2 . length ; obj . findMissing ( arr1 , arr2 , M , N ) ; } }


"Find m | Java program to find m - th summation . ; Function to return mth summation ; base case ; Driver code"
How can the above be solved in Java?

class GFG { static int SUM ( int n , int m ) { if ( m == 1 ) return ( n * ( n + 1 ) / 2 ) ; int sum = SUM ( n , m - 1 ) ; return ( sum * ( sum + 1 ) / 2 ) ; } public static void main ( String [ ] args ) { int n = 5 ; int m = 3 ; System . out . println ( " SUM ( " + n + " , ▁ " + m + " ) : ▁ " + SUM ( n , m ) ) ; } }


"Find maximum ( or minimum ) in Binary Tree | A binary tree node ; Constructor that allocates a new node with the given data and NULL left and right pointers . ; Returns the max value in a binary tree ; Base case ; Return maximum of 3 values : 1 ) Root 's data 2) Max in Left Subtree 3) Max in right subtree ; Driver code ; Function call"
How can the above be solved in Java?

class Node { int data ; Node left , right ; public Node ( int data ) { this . data = data ; left = right = null ; } } class BinaryTree { Node root ; static int findMax ( Node node ) { if ( node == null ) return Integer . MIN_VALUE ; int res = node . data ; int lres = findMax ( node . left ) ; int rres = findMax ( node . right ) ; if ( lres > res ) res = lres ; if ( rres > res ) res = rres ; return res ; } public static void main ( String args [ ] ) { BinaryTree tree = new BinaryTree ( ) ; tree . root = new Node ( 2 ) ; tree . root . left = new Node ( 7 ) ; tree . root . right = new Node ( 5 ) ; tree . root . left . right = new Node ( 6 ) ; tree . root . left . right . left = new Node ( 1 ) ; tree . root . left . right . right = new Node ( 11 ) ; tree . root . right . right = new Node ( 9 ) ; tree . root . right . right . left = new Node ( 4 ) ; System . out . println ( " Maximum ▁ element ▁ is ▁ " + tree . findMax ( tree . root ) ) ; } }


"Find maximum ( or minimum ) in Binary Tree | Returns the min value in a binary tree"
How can the above be solved in Java?

static int findMin ( Node node ) { if ( node == null ) return Integer . MAX_VALUE ; int res = node . data ; int lres = findMin ( node . left ) ; int rres = findMin ( node . right ) ; if ( lres < res ) res = lres ; if ( rres < res ) res = rres ; return res ; }


"Find maximum GCD value from root to leaf in a Binary tree | Java program for the above approach ; Initialise to update the maximum gcd value from all the path ; Node structure ; Left & right child of the node ; Initialize constructor ; Function to find gcd of a and b ; Function to find the gcd of a path ; Function to find the maximum value of gcd from root to leaf in a Binary tree ; Check if root is not null ; Find the maximum gcd of path value and store in global maxm variable ; Traverse left of binary tree ; Traverse right of the binary tree ; Driver Code ; Given Tree ; Function call ; Print the maximum AND value"
How can the above be solved in Java?

 import java . util . * ; class GFG { static int maxm = 0 ; static class Node { int val ; Node left , right ; Node ( int x ) { val = x ; left = null ; right = null ; } } ; static int gcd ( int a , int b ) { if ( b == 0 ) return a ; return gcd ( b , a % b ) ; } static int find_gcd ( Vector < Integer > arr ) { if ( arr . size ( ) == 1 ) return arr . get ( 0 ) ; int g = arr . get ( 0 ) ; for ( int i = 1 ; i < arr . size ( ) ; i ++ ) { g = gcd ( g , arr . get ( 1 ) ) ; } return g ; } static void maxm_gcd ( Node root , Vector < Integer > ans ) { if ( root == null ) return ; if ( root . left == null && root . right == null ) { ans . add ( root . val ) ; maxm = Math . max ( find_gcd ( ans ) , maxm ) ; return ; } ans . add ( root . val ) ; maxm_gcd ( root . left , ans ) ; maxm_gcd ( root . right , ans ) ; } public static void main ( String [ ] args ) { Node root = new Node ( 15 ) ; root . left = new Node ( 3 ) ; root . right = new Node ( 7 ) ; root . left . left = new Node ( 15 ) ; root . left . right = new Node ( 1 ) ; root . right . left = new Node ( 31 ) ; root . right . right = new Node ( 9 ) ; maxm_gcd ( root , new Vector < > ( ) ) ; System . out . print ( maxm + "
"); } }


"Find maximum N such that the sum of square of first N natural numbers is not more than X | Java implementation of the approach ; Function to return the sum of the squares of first N natural numbers ; Function to return the maximum N such that the sum of the squares of first N natural numbers is not more than X ; Driver code"
How can the above be solved in Java?

class GFG { static long squareSum ( long N ) { long sum = ( long ) ( N * ( N + 1 ) * ( 2 * N + 1 ) ) / 6 ; return sum ; } static long findMaxN ( long X ) { long low = 1 , high = 100000 ; int N = 0 ; while ( low <= high ) { long mid = ( high + low ) / 2 ; if ( squareSum ( mid ) <= X ) { N = ( int ) mid ; low = mid + 1 ; } else high = mid - 1 ; } return N ; } public static void main ( String [ ] args ) { long X = 25 ; System . out . println ( findMaxN ( X ) ) ; } }


"Find maximum N such that the sum of square of first N natural numbers is not more than X | Java implementation of the approach ; Function to return the sum of the squares of first N natural numbers ; Function to return the maximum N such that the sum of the squares of first N natural numbers is not more than X ; Iterate through the maxvalue of N and find the ith position ; If the condition fails then return the i - 1 i . e sum of squares till i - 1 ; Driver code"
How can the above be solved in Java?

class GFG { static long squareSum ( long N ) { long sum = ( long ) ( N * ( N + 1 ) * ( 2 * N + 1 ) ) / 6 ; return sum ; } static long findMaxN ( long X ) { long N = ( long ) Math . sqrt ( X ) ; for ( long i = 1 ; i <= N ; i ++ ) { if ( squareSum ( i ) > X ) return i - 1 ; } return - 1 ; } public static void main ( String [ ] args ) { long X = 25 ; System . out . println ( findMaxN ( X ) ) ; } }


"Find maximum among x ^ ( y ^ 2 ) or y ^ ( x ^ 2 ) where x and y are given | Java program to find the greater value ; Function to find maximum ; Case 1 ; Case 2 ; Driver Code"
How can the above be solved in Java?

import java . io . * ; class GFG { static boolean findGreater ( int x , int y ) { if ( x > y ) { return false ; } else { return true ; } } public static void main ( String [ ] args ) { int x = 4 ; int y = 9 ; if ( findGreater ( x , y ) ) System . out . println ( "1" ) ; else System . out . println ( "2" ) ; } }


"Find maximum and minimum distance between magnets | Java program for max and min distance ; Function for finding distance between pivots ; Function for minimum distance ; Function for maximum distance ; Driver Code"
How can the above be solved in Java?

import java . io . * ; class GFG { static int pivotDis ( int x0 , int y0 , int x1 , int y1 ) { return ( int ) Math . sqrt ( ( x1 - x0 ) * ( x1 - x0 ) + ( y1 - y0 ) * ( y1 - y0 ) ) ; } static int minDis ( int D , int r1 , int r2 ) { return Math . max ( ( D - r1 - r2 ) , 0 ) ; } static int maxDis ( int D , int r1 , int r2 ) { return D + r1 + r2 ; } public static void main ( String [ ] args ) { int x0 = 0 , y0 = 0 , x1 = 8 , y1 = 0 , r1 = 4 , r2 = 5 ; int D = pivotDis ( x0 , y0 , x1 , y1 ) ; System . out . print ( " Distance ▁ while ▁ " + " repulsion ▁ = ▁ " + maxDis ( D , r1 , r2 ) ) ; System . out . print ( " Distance while " + " attraction ▁ = ▁ " + minDis ( D , r1 , r2 ) ) ; } }


"Find maximum distance between any city and station | Java program to calculate the maximum distance between any city and its nearest station ; Function to calculate the maximum distance between any city and its nearest station ; Initialize boolean list ; Assign True to cities containing station ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { static int findMaxDistance ( int numOfCities , int station [ ] , int n ) { boolean hasStation [ ] = new boolean [ numOfCities + 1 ] ; for ( int city = 0 ; city < n ; city ++ ) { hasStation [ station [ city ] ] = true ; } int dist = 0 ; int maxDist = Integer . MAX_VALUE ; for ( int i = 0 ; i < n ; i ++ ) { maxDist = Math . min ( station [ i ] , maxDist ) ; } for ( int city = 0 ; city < numOfCities ; city ++ ) { if ( hasStation [ city ] == true ) { maxDist = Math . max ( ( dist + 1 ) / 2 , maxDist ) ; dist = 0 ; } else dist += 1 ; } return Math . max ( maxDist , dist ) ; } public static void main ( String args [ ] ) { int numOfCities = 6 ; int station [ ] = { 3 , 1 } ; int n = station . length ; System . out . println ( " Max ▁ Distance : " + findMaxDistance ( numOfCities , station , n ) ) ; } }


"Find maximum height pyramid from the given array of objects | Java program to find maximum height pyramid from the given object width . ; Returns maximum number of pyramidcal levels n boxes of given widths . ; Sort objects in increasing order of widths ; Total width of previous level and total number of objects in previous level ; Number of object in current level . ; Width of current level . ; Picking the object . So increase current width and number of object . ; If current width and number of object are greater than previous . ; Update previous width , number of object on previous level . ; Reset width of current level , number of object on current level . ; Increment number of level . ; Driver Program"
How can the above be solved in Java?

import java . io . * ; import java . util . Arrays ; class GFG { static int maxLevel ( int [ ] boxes , int n ) { Arrays . sort ( boxes ) ; int prev_width = boxes [ 0 ] ; int prev_count = 1 ; int curr_count = 0 ; int curr_width = 0 ; for ( int i = 1 ; i < n ; i ++ ) { curr_width += boxes [ i ] ; curr_count += 1 ; if ( curr_width > prev_width && curr_count > prev_count ) { prev_width = curr_width ; prev_count = curr_count ; curr_count = 0 ; curr_width = 0 ; ans ++ ; } } return ans ; } static public void main ( String [ ] args ) { int [ ] boxes = { 10 , 20 , 30 , 50 , 60 , 70 } ; int n = boxes . length ; System . out . println ( maxLevel ( boxes , n ) ) ; } }


"Find maximum height to cut all chocolates horizontally such that at least K amount remains | Java program for the above approach ; Function to find the sum of remaining chocolate after making the horizontal cut at height mid ; Stores the sum of chocolates ; Traverse the array arr [ ] ; If the height is at least mid ; Return the possible sum ; Function to find the maximum horizontal cut made to all the chocolates such that the sum of the remaining element is at least K ; Ranges of Binary Search ; Perform the Binary Search ; Find the sum of removed after making cut at height mid ; If the chocolate removed is same as the chocolate needed then return the height ; If the chocolate removed is less than chocolate needed then shift to the left range ; Otherwise , shift to the right range ; Return the possible cut ; Driver Code"
How can the above be solved in Java?

import java . util . * ; import java . util . Arrays ; class GFG { static int cal ( int arr [ ] , int mid ) { int chocolate = 0 ; for ( int i = 0 ; i < arr . length ; i ++ ) { if ( arr [ i ] >= mid ) chocolate += arr [ i ] - mid ; } return chocolate ; } static int maximumCut ( int arr [ ] , int K ) { int low = 0 ; int high = Arrays . stream ( arr ) . max ( ) . getAsInt ( ) ; while ( low <= high ) { int mid = ( low + high ) / 2 ; int chocolate = cal ( arr , mid ) ; if ( chocolate == K ) return mid ; else if ( chocolate < K ) high = mid - 1 ; else { low = mid + 1 ; if ( mid > high ) high = mid ; } } return high ; } public static void main ( String [ ] args ) { int K = 7 ; int arr [ ] = { 15 , 20 , 8 , 17 } ; System . out . println ( maximumCut ( arr , K ) ) ; } }


"Find maximum length Snake sequence | Java program to find maximum length Snake sequence and print it ; Function to find maximum length Snake sequence path ( i , j ) corresponds to tail of the snake ; Function to find maximum length Snake sequence ; table to store results of subproblems ; stores maximum length of Snake sequence ; store coordinates to snake 's tail ; fill the table in bottom - up fashion ; do except for ( 0 , 0 ) cell ; look above ; look left ; find maximum length Snake sequence path ; Driver code"
How can the above be solved in Java?

 import java . util . * ; class GFG { static int M = 4 ; static int N = 4 ; static class Point { int x , y ; public Point ( int x , int y ) { this . x = x ; this . y = y ; } } ; static List < Point > findPath ( int grid [ ] [ ] , int mat [ ] [ ] , int i , int j ) { List < Point > path = new LinkedList < > ( ) ; Point pt = new Point ( i , j ) ; path . add ( 0 , pt ) ; while ( grid [ i ] [ j ] != 0 ) { if ( i > 0 && grid [ i ] [ j ] - 1 == grid [ i - 1 ] [ j ] ) { pt = new Point ( i - 1 , j ) ; path . add ( 0 , pt ) ; i -- ; } else if ( j > 0 && grid [ i ] [ j ] - 1 == grid [ i ] [ j - 1 ] ) { pt = new Point ( i , j - 1 ) ; path . add ( 0 , pt ) ; j -- ; } } return path ; } static void findSnakeSequence ( int mat [ ] [ ] ) { int [ ] [ ] lookup = new int [ M ] [ N ] ; int max_len = 0 ; int max_row = 0 ; int max_col = 0 ; for ( int i = 0 ; i < M ; i ++ ) { for ( int j = 0 ; j < N ; j ++ ) { if ( i != 0 j != 0 ) { if ( i > 0 && Math . abs ( mat [ i - 1 ] [ j ] - mat [ i ] [ j ] ) == 1 ) { lookup [ i ] [ j ] = Math . max ( lookup [ i ] [ j ] , lookup [ i - 1 ] [ j ] + 1 ) ; if ( max_len < lookup [ i ] [ j ] ) { max_len = lookup [ i ] [ j ] ; max_row = i ; max_col = j ; } } if ( j > 0 && Math . abs ( mat [ i ] [ j - 1 ] - mat [ i ] [ j ] ) == 1 ) { lookup [ i ] [ j ] = Math . max ( lookup [ i ] [ j ] , lookup [ i ] [ j - 1 ] + 1 ) ; if ( max_len < lookup [ i ] [ j ] ) { max_len = lookup [ i ] [ j ] ; max_row = i ; max_col = j ; } } } } } System . out . print ( " Maximum ▁ length ▁ of ▁ Snake ▁ " + " sequence ▁ is : ▁ " + max_len + "
"); List < Point > path = findPath ( lookup , mat , max_row , max_col ) ; System . out . print ( " Snake ▁ sequence ▁ is : " ) ; for ( Point it : path ) System . out . print ( " " ▁ + ▁ mat [ it . x ] [ it . y ] ▁ + ▁ " ( " ▁ + ▁ it . x ▁ + ▁ " , " ▁ + ▁ it . y ▁ + ▁ " ) "); } public static void main ( String [ ] args ) { int mat [ ] [ ] = { { 9 , 6 , 5 , 2 } , { 8 , 7 , 6 , 5 } , { 7 , 3 , 1 , 6 } , { 1 , 1 , 1 , 7 } } ; findSnakeSequence ( mat ) ; } }


"Find maximum number of edge disjoint paths between two vertices | Java program to find maximum number of edge disjoint paths ; Number of vertices in given graph ; Returns true if there is a path from source ' s ' to sink ' t ' in residual graph . Also fills parent [ ] to store the path ; Create a visited array and mark all vertices as not visited ; Create a queue , enqueue source vertex and mark source vertex as visited ; Standard BFS Loop ; If we reached sink in BFS starting from source , then return true , else false ; Returns tne maximum number of edge - disjoint paths from s to t . This function is copy of goo . gl / wtQ4Ks forFulkerson ( ) discussed at http : ; Create a residual graph and fill the residual graph with given capacities in the original graph as residual capacities in residual graph Residual graph where rGraph [ i ] [ j ] indicates residual capacity of edge from i to j ( if there is an edge . If rGraph [ i ] [ j ] is 0 , then there is not ) ; This array is filled by BFS and to store path ; There is no flow initially ; Augment the flow while there is path from source to sink ; Find minimum residual capacity of the edges along the path filled by BFS . Or we can say find the maximum flow through the path found . ; update residual capacities of the edges and reverse edges along the path ; Add path flow to overall flow ; Return the overall flow ( max_flow is equal to maximum number of edge - disjoint paths ) ; Driver Code ; Let us create a graph shown in the above example"
How can the above be solved in Java?

import java . util . * ; class GFG { static int V = 8 ; static boolean bfs ( int rGraph [ ] [ ] , int s , int t , int parent [ ] ) { boolean [ ] visited = new boolean [ V ] ; Queue < Integer > q = new LinkedList < > ( ) ; q . add ( s ) ; visited [ s ] = true ; parent [ s ] = - 1 ; while ( ! q . isEmpty ( ) ) { int u = q . peek ( ) ; q . remove ( ) ; for ( int v = 0 ; v < V ; v ++ ) { if ( visited [ v ] == false && rGraph [ u ] [ v ] > 0 ) { q . add ( v ) ; parent [ v ] = u ; visited [ v ] = true ; } } } return ( visited [ t ] == true ) ; } static int findDisjointPaths ( int graph [ ] [ ] , int s , int t ) { int u , v ; int [ ] [ ] rGraph = new int [ V ] [ V ] ; for ( u = 0 ; u < V ; u ++ ) for ( v = 0 ; v < V ; v ++ ) rGraph [ u ] [ v ] = graph [ u ] [ v ] ; int [ ] parent = new int [ V ] ; int max_flow = 0 ; while ( bfs ( rGraph , s , t , parent ) ) { int path_flow = Integer . MAX_VALUE ; for ( v = t ; v != s ; v = parent [ v ] ) { u = parent [ v ] ; path_flow = Math . min ( path_flow , rGraph [ u ] [ v ] ) ; } for ( v = t ; v != s ; v = parent [ v ] ) { u = parent [ v ] ; rGraph [ u ] [ v ] -= path_flow ; rGraph [ v ] [ u ] += path_flow ; } max_flow += path_flow ; } return max_flow ; } public static void main ( String [ ] args ) { int graph [ ] [ ] = { { 0 , 1 , 1 , 1 , 0 , 0 , 0 , 0 } , { 0 , 0 , 1 , 0 , 0 , 0 , 0 , 0 } , { 0 , 0 , 0 , 1 , 0 , 0 , 1 , 0 } , { 0 , 0 , 0 , 0 , 0 , 0 , 1 , 0 } , { 0 , 0 , 1 , 0 , 0 , 0 , 0 , 1 } , { 0 , 1 , 0 , 0 , 0 , 0 , 0 , 1 } , { 0 , 0 , 0 , 0 , 0 , 1 , 0 , 1 } , { 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 } } ; int s = 0 ; int t = 7 ; System . out . println ( " There ▁ can ▁ be ▁ maximum ▁ " + findDisjointPaths ( graph , s , t ) + " ▁ edge - disjoint ▁ paths ▁ from ▁ " + s + " ▁ to ▁ " + t ) ; } }


"Find maximum number that can be formed using digits of a given number | Java program to print the maximum number from the set of digits of a given number ; Function to print the maximum number ; hashed array to store count of digits ; Converting given number to string ; Updating the count array ; result is to store the final number ; Traversing the count array to calculate the maximum number ; return the result ; Driver program to test above function"
How can the above be solved in Java?

public class GFG { static int printMaxNum ( int num ) { int count [ ] = new int [ 10 ] ; String str = Integer . toString ( num ) ; for ( int i = 0 ; i < str . length ( ) ; i ++ ) count [ str . charAt ( i ) - '0' ] ++ ; int result = 0 , multiplier = 1 ; for ( int i = 0 ; i <= 9 ; i ++ ) { while ( count [ i ] > 0 ) { result = result + ( i * multiplier ) ; count [ i ] -- ; multiplier = multiplier * 10 ; } } return result ; } public static void main ( String [ ] args ) { int num = 38293367 ; System . out . println ( printMaxNum ( num ) ) ; } }