"Minimum length subarray containing all unique elements after Q operations | Java implementation to find the minimum size subarray containing all unique elements after processing the array for K queries of ranges ; Function to find minimum size subarray of all array elements ; Updating the array after processing each query ; Making it to 0 - indexing ; Prefix sum array concept is used to obtain the count array ; Iterating over the array to get the final array ; Variable to get count of all unique elements ; Hash to maintain perviously occurred elements ; Loop to find the all unique elements ; array to maintain counter of encountered elements ; variable to store answer ; Using two pointers approach ; Increment counter if occurred once ; when all unique elements are found ; update answer with minimum size ; decrement count of elements from left ; decrement counter ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { static int subarrayLength ( int A [ ] , int R [ ] [ ] , int N , int M ) { for ( int i = 0 ; i < M ; ++ i ) { int l = R [ i ] [ 0 ] , r = R [ i ] [ 1 ] + 1 ; l -- ; r -- ; A [ l ] ++ ; if ( r < N ) A [ r ] -- ; } for ( int i = 1 ; i < N ; ++ i ) { A [ i ] += A [ i - 1 ] ; } int count = 0 ; HashSet < Integer > s = new HashSet < Integer > ( ) ; for ( int i = 0 ; i < N ; ++ i ) { if ( ! s . contains ( A [ i ] ) ) count ++ ; s . add ( A [ i ] ) ; } int [ ] repeat = new int [ count + 1 ] ; int ans = N ; int counter = 0 , left = 0 , right = 0 ; while ( right < N ) { int cur_element = A [ right ] ; repeat [ cur_element ] += 1 ; if ( repeat [ cur_element ] == 1 ) ++ counter ; while ( counter == count ) { ans = Math . min ( ans , right - left + 1 ) ; cur_element = A [ left ] ; repeat [ cur_element ] -= 1 ; ++ left ; if ( repeat [ cur_element ] == 0 ) -- counter ; } ++ right ; } return ans ; } public static void main ( String [ ] args ) { int N = 8 , queries = 6 ; int Q [ ] [ ] = { { 1 , 4 } , { 3 , 4 } , { 4 , 5 } , { 5 , 5 } , { 7 , 8 } , { 8 , 8 } } ; int A [ ] = new int [ N ] ; System . out . print ( subarrayLength ( A , Q , N , queries ) ) ; } }


"Minimum length substring with exactly K distinct characters | Java program to find minimum length subString having exactly k distinct character . ; Function to find minimum length subString having exactly k distinct character . ; Starting index of sliding window . ; Ending index of sliding window . ; To store count of character . ; To store count of distinct character in current sliding window . ; To store length of current sliding window . ; To store minimum length . ; To store starting index of minimum length subString . ; Increment count of current character If this count is one then a new distinct character is found in sliding window . ; If number of distinct characters is is greater than k , then move starting point of sliding window forward , until count is k . ; Remove characters from the beginning of sliding window having count more than 1 to minimize length . ; Compare length with minimum length and update if required . ; Return minimum length subString . ; Driver code"
How can the above be solved in Java?

class GFG { static String findMinLenStr ( String str , int k ) { int n = str . length ( ) ; int st = 0 ; int end = 0 ; int cnt [ ] = new int [ 26 ] ; for ( int i = 0 ; i < 26 ; i ++ ) cnt [ i ] = 0 ; int distEle = 0 ; int currlen ; int minlen = n ; int startInd = - 1 ; while ( end < n ) { cnt [ str . charAt ( end ) - ' a ' ] ++ ; if ( cnt [ str . charAt ( end ) - ' a ' ] == 1 ) distEle ++ ; if ( distEle > k ) { while ( st < end && distEle > k ) { if ( cnt [ str . charAt ( st ) - ' a ' ] == 1 ) distEle -- ; cnt [ str . charAt ( st ) - ' a ' ] -- ; st ++ ; } } if ( distEle == k ) { while ( st < end && cnt [ str . charAt ( st ) - ' a ' ] > 1 ) { cnt [ str . charAt ( st ) - ' a ' ] -- ; st ++ ; } currlen = end - st + 1 ; if ( currlen < minlen ) { minlen = currlen ; startInd = st ; } } end ++ ; } return str . substring ( startInd , startInd + minlen ) ; } public static void main ( String args [ ] ) { String str = " efecfefd " ; int k = 4 ; System . out . println ( findMinLenStr ( str , k ) ) ; } }


"Minimum letters to be removed to make all occurrences of a given letter continuous | Java implementation of the above approach ; Function to find the minimum number of deletions required to make the occurrences of the given character K continuous ; Find the first occurrence of the given letter ; Iterate from the first occurrence till the end of the sequence ; Find the index from where the occurrence of the character is not continuous ; Update the answer with the number of elements between non - consecutive occurrences of the given letter ; Update the count for all letters which are not equal to the given letter ; Return the count ; Driver code ; Calling the function ; Calling the function"
How can the above be solved in Java?

 import java . util . * ; class GFG { static int noOfDeletions ( String str , char k ) { int ans = 0 , cnt = 0 , pos = 0 ; while ( pos < str . length ( ) && str . charAt ( pos ) != k ) { pos ++ ; } int i = pos ; while ( i < str . length ( ) ) { while ( i < str . length ( ) && str . charAt ( i ) == k ) { i = i + 1 ; } ans = ans + cnt ; cnt = 0 ; while ( i < str . length ( ) && str . charAt ( i ) != k ) { i = i + 1 ; cnt = cnt + 1 ; } } return ans ; } public static void main ( String [ ] args ) { String str1 = " ababababa " ; char k1 = ' a ' ; System . out . print ( noOfDeletions ( str1 , k1 ) + "
"); String str2 = " kprkkoinkopt " ; char k2 = ' k ' ; System . out . print ( noOfDeletions ( str2 , k2 ) + "
"); } }


"Minimum matches the team needs to win to qualify | Java implementation of the approach ; Function to return the minimum number of matches to win to qualify for next round ; Do a binary search to find ; Find mid element ; Check for condition to qualify for next round ; Driver Code"
How can the above be solved in Java?

import java . io . * ; class GFG { static int findMinimum ( int x , int y ) { int low = 0 , high = y ; while ( low <= high ) { int mid = ( low + high ) >> 1 ; if ( ( mid * 2 + ( y - mid ) ) >= x ) high = mid - 1 ; else low = mid + 1 ; } return low ; } public static void main ( String [ ] args ) { int x = 6 , y = 5 ; System . out . println ( findMinimum ( x , y ) ) ; } }


"Minimum minutes needed to make the time palindromic | Java program for the above approach ; Function to get the required minutes ; Storing hour and minute value in integral form ; Keep iterating till first digit hour becomes equal to second digit of minute and second digit of hour becomes equal to first digit of minute ; If mins is 60 , increase hour , and reinitilialized to 0 ; If hours is 60 , reinitialized to 0 ; Return the required time ; Driver code ; Given Time as a string ; Function Call"
How can the above be solved in Java?

class GFG { public static int get_palindrome_time ( String str ) { int hh , mm ; hh = ( str . charAt ( 0 ) - 48 ) * 10 + ( str . charAt ( 1 ) - 48 ) ; mm = ( str . charAt ( 3 ) - 48 ) * 10 + ( str . charAt ( 4 ) - 48 ) ; int requiredTime = 0 ; while ( hh % 10 != mm / 10 hh / 10 != mm % 10 ) { ++ mm ; if ( mm == 60 ) { mm = 0 ; ++ hh ; } if ( hh == 24 ) hh = 0 ; ++ requiredTime ; } return requiredTime ; } public static void main ( String [ ] args ) { String str = "05:39" ; System . out . println ( get_palindrome_time ( str ) ) ; } }


"Minimum move to end operations to make all strings equal | Java program to make all strings same using move to end operations . ; Returns minimum number of moves to end operations to make all strings same . ; Consider s [ i ] as target string and count rotations required to make all other strings same as str [ i ] . ; find function returns the index where we found arr [ i ] which is actually count of move - to - front operations . ; If any two strings are not rotations of each other , we can 't make them same. ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { static int minimunMoves ( String arr [ ] , int n ) { int ans = Integer . MAX_VALUE ; for ( int i = 0 ; i < n ; i ++ ) { int curr_count = 0 ; String tmp = " " ; for ( int j = 0 ; j < n ; j ++ ) { tmp = arr [ j ] + arr [ j ] ; int index = tmp . indexOf ( arr [ i ] ) ; if ( index == arr [ i ] . length ( ) ) return - 1 ; curr_count += index ; } ans = Math . min ( curr_count , ans ) ; } return ans ; } public static void main ( String args [ ] ) { String arr [ ] = { " xzzwo " , " zwoxz " , " zzwox " , " xzzwo " } ; int n = arr . length ; System . out . println ( minimunMoves ( arr , n ) ) ; } }


"Minimum moves required to come out of a grid safely | Java program to implement the above approach ; Structure of cell of the grid ; Stores size of the grid ; Function to find shortest distance between two cells of the grid ; Rows of the grid ; Column of the grid ; Stores possible move of the person ; Store possible cells visited by the person ; Store possible cells which are burning ; Traverse the grid ; If current cell is burning ; If person is in the current cell ; Stores shortest distance between two cells ; Check if a cell is visited by the person or not ; While pQ is not empty ; Update depth ; Popped all the cells from pQ and mark all adjacent cells of as visited ; Front element of the queue pQ ; Remove front element of the queue pQ ; If current cell is burning ; Find all adjacent cells ; Stores row number of adjacent cell ; Stores column number of adjacent cell ; Checks if current cell is valid ; Mark the cell as visited ; Enqueue the cell ; Checks the escape condition ; Burn all the adjacent cells of burning cells ; Front element of the queue fQ ; Delete front element of the queue fQ ; Find adjacent cells of burning cell ; Stores row number of adjacent cell ; Stores column number of adjacent cell ; Checks if current cell is valid ; Burn all the adjacent cells of current cell ; Function to check valid cells of the grid ; Checks for the border sides ; Driver Code ; Given grid"
How can the above be solved in Java?

import java . util . * ; import java . lang . * ; class GFG { static class pair { int x , y ; pair ( int x , int y ) { this . x = x ; this . y = y ; } } static int m , n ; static int minStep ( int [ ] [ ] mat ) { m = mat . length ; n = mat [ 0 ] . length ; int dx [ ] = { 1 , - 1 , 0 , 0 } ; int dy [ ] = { 0 , 0 , 1 , - 1 } ; Queue < pair > pQ = new LinkedList < > ( ) ; Queue < pair > fQ = new LinkedList < > ( ) ; for ( int i = 0 ; i < m ; i ++ ) for ( int j = 0 ; j < n ; j ++ ) { if ( mat [ i ] [ j ] == 2 ) fQ . add ( new pair ( i , j ) ) ; else if ( mat [ i ] [ j ] == 1 ) { if ( border ( i , j ) ) return 0 ; pQ . add ( new pair ( i , j ) ) ; } } int depth = 0 ; boolean [ ] [ ] visited = new boolean [ n ] [ m ] ; while ( ! pQ . isEmpty ( ) ) { depth ++ ; for ( int i = pQ . size ( ) ; i > 0 ; i -- ) { pair pos = pQ . peek ( ) ; pQ . remove ( ) ; if ( mat [ pos . x ] [ pos . y ] == 2 ) continue ; for ( int j = 0 ; j < 4 ; j ++ ) { int x = pos . x + dx [ j ] ; int y = pos . y + dy [ j ] ; if ( valid ( x , y ) && mat [ x ] [ y ] != 2 && ! visited [ x ] [ y ] ) { visited [ x ] [ y ] = true ; pQ . add ( new pair ( x , y ) ) ; if ( border ( x , y ) ) return depth ; } } } for ( int i = fQ . size ( ) ; i > 0 ; i -- ) { pair pos = fQ . peek ( ) ; fQ . remove ( ) ; for ( int j = 0 ; j < 4 ; j ++ ) { int x = pos . x + dx [ j ] ; int y = pos . y + dy [ j ] ; if ( valid ( x , y ) && mat [ x ] [ y ] != 2 ) { mat [ x ] [ y ] = 2 ; fQ . add ( new pair ( x , y ) ) ; } } } } return - 1 ; } static boolean valid ( int x , int y ) { return ( x >= 0 && x < m && y >= 0 && y < n ) ; } static boolean border ( int x , int y ) { return ( x == 0 x == m - 1 y == 0 y == n - 1 ) ; } public static void main ( String [ ] args ) { int [ ] [ ] grid = { { 0 , 0 , 0 , 0 } , { 2 , 0 , 0 , 0 } , { 2 , 1 , 0 , 0 } , { 2 , 2 , 0 , 0 } } ; System . out . println ( minStep ( grid ) ) ; } }


"Minimum moves required to type a word in QWERTY based keyboard | Java program for the above approach ; Function that calculates the moves required to print the current String ; row1 has qwertyuiop , row2 has asdfghjkl , and row3 has zxcvbnm Store the row number of each character ; String length ; Initialise move to 1 ; Traverse the String ; If current row number is not equal to previous row then increment the moves ; Return the moves ; Driver Code ; Given String str ; Function Call"
How can the above be solved in Java?

import java . util . * ; class GFG { static int numberMoves ( String s ) { int row [ ] = { 2 , 3 , 3 , 2 , 1 , 2 , 2 , 2 , 1 , 2 , 2 , 2 , 3 , 3 , 1 , 1 , 1 , 1 , 2 , 1 , 1 , 3 , 1 , 3 , 1 , 3 } ; int n = s . length ( ) ; int move = 1 ; for ( int i = 1 ; i < n ; i ++ ) { if ( row [ s . charAt ( i ) - ' a ' ] != row [ s . charAt ( i - 1 ) - ' a ' ] ) { move ++ ; } } return move ; } public static void main ( String [ ] args ) { String str = " geeksforgeeks " ; System . out . print ( numberMoves ( str ) ) ; } }


"Minimum moves taken to move coin of each cell to any one cell of Matrix | Java program to find the minimum number of moves taken to move the element of each cell to any one cell of the square matrix of odd length ; Function to find the minimum number of moves taken to move the element of each cell to any one cell of the square matrix of odd length ; Initializing count to 0 ; Number of layers that are around the centre element ; Iterating over ranger of layers ; Increase the value of count by 8 * k * k ; Driver code"
How can the above be solved in Java?

class GFG { public static int calculateMoves ( int n ) { int count = 0 ; int layers = n / 2 ; for ( int k = 1 ; k < layers + 1 ; k ++ ) { count += 8 * k * k ; } return count ; } public static void main ( String [ ] args ) { int N = 5 ; System . out . println ( calculateMoves ( N ) ) ; } }


"Minimum moves to make count of lowercase and uppercase letters equal | Java program for the above approach ; Function to calculate minimum number of moves required to convert the string ; Stores Count of upper and lower case characters ; Traverse the string S ; If current character is uppercase ; Increment count of Uppercase characters ; Otherwise , ; Increment count of Lowercase characters ; Stores minimum number of moves needed ; If there are more upper case characters ; Iterate until upper is greater than N / 2 ; Convert uppercase into lowercase until upper = N / 2 ; Increment the pointer ; If there are more lower case characters ; Iterate until lower is greater than N / 2 ; Convert lowercase into uppercase until lower = N / 2 ; Increment the pointer ; Print moves required ; Print resultant string ; Driver code ; Given string ; Function call"
How can the above be solved in Java?

class GFG { static void minimumTimeToConvertString ( String S , int N ) { int upper = 0 , lower = 0 ; for ( int i = 0 ; i < N ; i ++ ) { char c = S . charAt ( i ) ; if ( Character . isUpperCase ( c ) ) { upper ++ ; } else { lower ++ ; } } int moves = 0 ; if ( upper > N / 2 ) { int i = 0 ; while ( upper > N / 2 && i < N ) { if ( Character . isUpperCase ( S . charAt ( i ) ) ) { S = S . substring ( 0 , i ) + ( char ) ( S . charAt ( i ) + 32 ) + S . substring ( i + 1 ) ; moves ++ ; upper -- ; lower ++ ; } i ++ ; } } else if ( lower > N / 2 ) { int i = 0 ; while ( lower > N / 2 && i < N ) { if ( Character . isLowerCase ( S . charAt ( i ) ) ) { S = S . substring ( 0 , i ) + ( char ) ( S . charAt ( i ) - 32 ) + S . substring ( i + 1 ) ; moves ++ ; upper ++ ; lower -- ; } i ++ ; } } System . out . println ( moves ) ; System . out . println ( S ) ; } public static void main ( String [ ] args ) { String S = " AbcdEf " ; int N = S . length ( ) ; minimumTimeToConvertString ( S , N ) ; } }


"Minimum moves to reach from i to j in a cyclic string | Java implementation of the approach ; Function to return the count of steps required to move from i to j ; Starting from i + 1 ; Count of steps ; Current character ; If current character is different from previous ; Increment steps ; Update current character ; Return total steps ; Function to return the minimum number of steps required to reach j from i ; Swap the values so that i <= j ; Steps to go from i to j ( left to right ) ; While going from i to j ( right to left ) First go from i to 0 then from ( n - 1 ) to j ; If first and last character is different then it 'll add a step to stepsToLeft ; Return the minimum of two paths ; Driver code"
How can the above be solved in Java?

class GFG { static int getSteps ( String str , int i , int j , int n ) { int k = i + 1 ; int steps = 0 ; char ch = str . charAt ( i ) ; while ( k <= j ) { if ( str . charAt ( k ) != ch ) { steps ++ ; ch = str . charAt ( k ) ; } k ++ ; } return steps ; } static int getMinSteps ( String str , int i , int j , int n ) { if ( j < i ) { int temp = i ; i = j ; j = temp ; } int stepsToRight = getSteps ( str , i , j , n ) ; int stepsToLeft = getSteps ( str , 0 , i , n ) + getSteps ( str , j , n - 1 , n ) ; if ( str . charAt ( 0 ) != str . charAt ( n - 1 ) ) stepsToLeft ++ ; return Math . min ( stepsToLeft , stepsToRight ) ; } public static void main ( String [ ] args ) { String str = " SSNSS " ; int n = str . length ( ) ; int i = 0 , j = 3 ; System . out . println ( getMinSteps ( str , i , j , n ) ) ; } }


"Minimum moves to reach target on a infinite line | Set 2 | Java code to find minimum moves to reach target ; Function to find minimum steps to reach target ; Handling negatives by symmetry ; Keep moving while sum is smaller i . e calculating n ; case 1 : d is even ; d is odd ; Driver code ; Function call"
How can the above be solved in Java?

import java . lang . * ; class GFG { static int StepstoReachTarget ( int target ) { target = Math . abs ( target ) ; int n = ( int ) Math . ceil ( ( - 1.0 + ( int ) Math . sqrt ( 1 + 8.0 * target ) ) / 2 ) ; int sum = n * ( n + 1 ) / 2 ; if ( sum == target ) return n ; int d = sum - target ; if ( ( d & 1 ) == 0 ) return n ; else return n + ( ( n & 1 ) != 0 ? 2 : 1 ) ; } public static void main ( String [ ] arg ) { int target = 5 ; System . out . println ( StepstoReachTarget ( target ) ) ; } }


"Minimum multiplications with { 2 , 3 , 7 } to make two numbers equal | Java implementation of above approach ; Function to find powers of 2 , 3 and 7 in x ; To keep count of each divisor ; To store the result ; Count powers of 2 in x ; Count powers of 3 in x ; Count powers of 7 in x ; Remaining number which is not divisible by 2 , 3 or 7 ; Function to return the minimum number of given operations required to make a and b equal ; a = x * 2 ^ a1 * 3 ^ a2 * 7 ^ a3 va [ 0 ] = a1 va [ 1 ] = a2 va [ 2 ] = a3 va [ 3 ] = x ; Similarly for b ; If a and b cannot be made equal with the given operation . Note that va [ 3 ] and vb [ 3 ] contain remaining numbers after repeated divisions with 2 , 3 and 7. If remaining numbers are not same then we cannot make them equal . ; Minimum number of operations required ; Driver code"
How can the above be solved in Java?

import java . util . Vector ; class GFG { static Vector < Integer > Divisors ( int x ) { int c = 0 ; Vector < Integer > v = new Vector < Integer > ( ) ; while ( x % 2 == 0 ) { c ++ ; x /= 2 ; } v . add ( c ) ; c = 0 ; while ( x % 3 == 0 ) { c ++ ; x /= 3 ; } v . add ( c ) ; c = 0 ; while ( x % 7 == 0 ) { c ++ ; x /= 7 ; } v . add ( c ) ; v . add ( x ) ; return v ; } static int MinOperations ( int a , int b ) { Vector < Integer > va = Divisors ( a ) ; Vector < Integer > vb = Divisors ( b ) ; if ( va . get ( 3 ) != vb . get ( 3 ) ) { return - 1 ; } int minOperations = Math . abs ( va . get ( 0 ) - vb . get ( 0 ) ) + Math . abs ( va . get ( 1 ) - vb . get ( 1 ) ) + Math . abs ( va . get ( 2 ) - vb . get ( 2 ) ) ; return minOperations ; } public static void main ( String [ ] args ) { int a = 14 , b = 28 ; System . out . println ( MinOperations ( a , b ) ) ; } }


"Minimum no . of iterations to pass information to all nodes in the tree | Java program to find minimum number of iterations to pass information from root to all nodes in an n - ary tree ; No . of nodes ; Adjacency list containing list of children ; function to add a child w to v ; Main function to find the minimum iterations ; Base case : if height = 0 or 1 ; ; Start Post Order Traversal from Root ; A recursive function to used by getMinIter ( ) . This function mainly does postorder traversal and get minimum iteration of all children of parent node , sort them in decreasing order and then get minimum iteration of parent node 1. Get minItr ( B ) of all children ( B ) of a node ( A ) 2. Sort all minItr ( B ) in descending order 3. Get minItr of A based on all minItr ( B ) minItr ( A ) = child ( A ) -- >> child ( A ) is children count of node A For children B from i = 0 to child ( A ) minItr ( A ) = max ( minItr ( A ) , minItr ( B ) + i + 1 ) Base cases would be : If node is leaf , minItr = 0 If node 's height is 1, minItr = children count   ; Base case : Leaf node ; Driver Code ; TestCase1 ; TestCase2 ; TestCase3 ; TestCase4 ; TestCase 5 ; TestCase 6 ; TestCase 7 ; TestCase 8 ; TestCase 9"
How can the above be solved in Java?

import java . util . ArrayList ; import java . util . Arrays ; import java . util . Collections ; import java . util . Iterator ; import java . util . List ; class GFG { private static int N ; private static List < List < Integer > > adj ; GFG ( int N ) { this . N = N ; adj = new ArrayList < > ( N ) ; for ( int i = 0 ; i < N ; i ++ ) adj . add ( new ArrayList < > ( ) ) ; } void addChild ( int v , int w ) { adj . get ( v ) . add ( w ) ; } private int getMinIteration ( ) { if ( N == 0 N == 1 ) return 0 ; int [ ] mintItr = new int [ N ] ; getMinIterUtil ( 0 , mintItr ) ; return mintItr [ 0 ] ; } private void getMinIterUtil ( int u , int [ ] minItr ) { if ( adj . get ( u ) . size ( ) == 0 ) return ; minItr [ u ] = adj . get ( u ) . size ( ) ; Integer [ ] minItrTemp = new Integer [ minItr [ u ] ] ; int k = 0 ; Iterator itr = adj . get ( u ) . iterator ( ) ; while ( itr . hasNext ( ) ) { int currentChild = ( int ) itr . next ( ) ; getMinIterUtil ( currentChild , minItr ) ; minItrTemp [ k ++ ] = minItr [ currentChild ] ; } Arrays . sort ( minItrTemp , Collections . reverseOrder ( ) ) ; for ( k = 0 ; k < adj . get ( u ) . size ( ) ; k ++ ) { int temp = minItrTemp [ k ] + k + 1 ; minItr [ u ] = Math . max ( minItr [ u ] , temp ) ; } } public static void main ( String args [ ] ) { GFG testCase1 = new GFG ( 17 ) ; testCase1 . addChild ( 0 , 1 ) ; testCase1 . addChild ( 0 , 2 ) ; testCase1 . addChild ( 0 , 3 ) ; testCase1 . addChild ( 0 , 4 ) ; testCase1 . addChild ( 0 , 5 ) ; testCase1 . addChild ( 0 , 6 ) ; testCase1 . addChild ( 1 , 7 ) ; testCase1 . addChild ( 1 , 8 ) ; testCase1 . addChild ( 1 , 9 ) ; testCase1 . addChild ( 4 , 10 ) ; testCase1 . addChild ( 4 , 11 ) ; testCase1 . addChild ( 6 , 12 ) ; testCase1 . addChild ( 7 , 13 ) ; testCase1 . addChild ( 7 , 14 ) ; testCase1 . addChild ( 10 , 15 ) ; testCase1 . addChild ( 11 , 16 ) ; System . out . println ( " TestCase ▁ 1 ▁ - ▁ Minimum ▁ Iteration : ▁ " + testCase1 . getMinIteration ( ) ) ; GFG testCase2 = new GFG ( 3 ) ; testCase2 . addChild ( 0 , 1 ) ;...


"Minimum non | Java program for above approach ; Function to find minimum flips required to remove all 0 s from a given binary string ; Length of given string ; Stores the indices of previous 0 s ; Stores the minimum operations ; Traverse string to find minimum operations to obtain required string ; Current character ; If current character is '0' ; Update temp1 with current index , if both temp variables are empty ; Update temp2 with current index , if temp1 contains prev index but temp2 is empty ; If temp1 is not empty ; Reset temp1 to - 1 ; Increase ans ; If temp2 is not empty but temp1 is empty ; Reset temp2 to - 1 ; Increase ans ; If both temp variables are not empty ; Otherwise ; Return the answer ; Driver Code"
How can the above be solved in Java?

import java . util . * ; class GFG { static int minOperation ( String s ) { int n = s . length ( ) ; int temp1 = - 1 , temp2 = - 1 ; int ans = 0 ; for ( int i = 0 ; i < n ; i ++ ) { int curr = s . charAt ( i ) ; if ( curr == '0' ) { if ( temp1 == - 1 && temp2 == - 1 ) { temp1 = i ; } else if ( temp1 != - 1 && temp2 == - 1 && i - temp1 == 1 ) { temp2 = i ; } else if ( temp1 != - 1 ) { temp1 = - 1 ; ans ++ ; } else if ( temp1 == - 1 && temp2 != - 1 && i - temp2 != 1 ) { temp2 = - 1 ; ans ++ ; } } } if ( temp1 != - 1 && temp2 != - 1 ) { ans += 2 ; } else if ( temp1 != - 1 temp2 != - 1 ) { ans += 1 ; } return ans ; } public static void main ( String [ ] args ) { String s = "110010" ; System . out . println ( minOperation ( s ) ) ; } }


"Minimum number N such that total set bits of all numbers from 1 to N is at | Java implementation of the above approach ; Function to count sum of set bits of all numbers till N ; Function to find the minimum number ; Binary search for the lowest number ; Find mid number ; Check if it is atleast x ; Driver Code"
How can the above be solved in Java?

import java . util . * ; class solution { static int INF = 99999 ; static int size = 10 ; static int getSetBitsFromOneToN ( int N ) { int two = 2 , ans = 0 ; int n = N ; while ( n != 0 ) { ans += ( N / two ) * ( two >> 1 ) ; if ( ( N & ( two - 1 ) ) > ( two >> 1 ) - 1 ) ans += ( N & ( two - 1 ) ) - ( two >> 1 ) + 1 ; two <<= 1 ; n >>= 1 ; } return ans ; } static int findMinimum ( int x ) { int low = 0 , high = 100000 ; int ans = high ; while ( low <= high ) { int mid = ( low + high ) >> 1 ; if ( getSetBitsFromOneToN ( mid ) >= x ) { ans = Math . min ( ans , mid ) ; high = mid - 1 ; } else low = mid + 1 ; } return ans ; } public static void main ( String args [ ] ) { int x = 20 ; System . out . println ( findMinimum ( x ) ) ; } }


"Minimum number greater than the maximum of array which cannot be formed using the numbers in the array | Java implementation of the approach ; Function that returns the minimum number greater than maximum of the array that cannot be formed using the elements of the array ; Sort the given array ; Maximum number in the array ; table [ i ] will store the minimum number of elements from the array to form i ; Calculate the minimum number of elements from the array required to form the numbers from 1 to ( 2 * max ) ; If there exists a number greater than the maximum element of the array that can be formed using the numbers of array ; Driver code"
How can the above be solved in Java?

import java . util . Arrays ; class GFG { static int findNumber ( int arr [ ] , int n ) { Arrays . sort ( arr ) ; int max = arr [ n - 1 ] ; int table [ ] = new int [ ( 2 * max ) + 1 ] ; table [ 0 ] = 0 ; for ( int i = 1 ; i < ( 2 * max ) + 1 ; i ++ ) table [ i ] = Integer . MAX_VALUE ; int ans = - 1 ; for ( int i = 1 ; i < ( 2 * max ) + 1 ; i ++ ) { for ( int j = 0 ; j < n ; j ++ ) { if ( arr [ j ] <= i ) { int res = table [ i - arr [ j ] ] ; if ( res != Integer . MAX_VALUE && res + 1 < table [ i ] ) table [ i ] = res + 1 ; } } if ( i > arr [ n - 1 ] && table [ i ] == Integer . MAX_VALUE ) { ans = i ; break ; } } return ans ; } public static void main ( String [ ] args ) { int arr [ ] = { 6 , 7 , 15 } ; int n = arr . length ; System . out . println ( findNumber ( arr , n ) ) ; } }


"Minimum number of 1 's to be replaced in a binary array | Java program to find minimum number of 1 ' s ▁ to ▁ be ▁ replaced ▁ to ▁ 0' s ; Function to find minimum number of 1 ' s ▁ to ▁ be ▁ replaced ▁ to ▁ 0' s ; return final answer ; Driver Code"
How can the above be solved in Java?

import java . lang . * ; import java . util . * ; class GFG { static int minChanges ( int [ ] A , int n ) { int cnt = 0 ; for ( int i = 0 ; i < n - 2 ; ++ i ) { if ( ( i - 1 >= 0 ) && A [ i - 1 ] == 1 && A [ i + 1 ] == 1 && A [ i ] == 0 ) { A [ i + 1 ] = 0 ; cnt ++ ; } } return cnt ; } public static void main ( String args [ ] ) { int [ ] A = { 1 , 1 , 0 , 1 , 1 , 0 , 1 , 0 , 1 , 0 } ; int n = A . length ; System . out . print ( minChanges ( A , n ) ) ; } }


"Minimum number of 1 s present in a submatrix of given dimensions in a Binary Matrix | Java program for the above approach ; Function to count number of 1 s present in a sub matrix from ( start_i , start_j ) to ( end_i , end_j ) ; Stores the number of 1 s present in current submatrix ; Traverse the submatrix ; If mat [ x ] [ y ] is equal to 1 ; Increase count by 1 ; Return the total count of 1 s ; Function to find the minimum number of 1 s present in a sub - matrix of size A * B or B * A ; Stores the minimum count of 1 s ; Iterate i from 0 to N ; Iterate j from 0 to M ; If a valid sub matrix of size A * B from ( i , j ) is possible ; Count the number of 1 s present in the sub matrix of size A * B from ( i , j ) ; Update minimum if count is less than the current minimum ; If a valid sub matrix of size B * A from ( i , j ) is possible ; Count the number of 1 s in the sub matrix of size B * A from ( i , j ) ; Update minimum if count is less than the current minimum ; Return minimum as the final result ; Driver code ; Given Input ; Function call to find the minimum number of 1 s in a submatrix of size A * B or B * A"
How can the above be solved in Java?

class GFG { static int count1s ( int start_i , int start_j , int end_i , int end_j , int [ ] [ ] mat ) { int count = 0 ; for ( int x = start_i ; x < end_i ; x ++ ) { for ( int y = start_j ; y < end_j ; y ++ ) { if ( mat [ x ] [ y ] == 1 ) count ++ ; } } return count ; } static int findMinimumCount ( int N , int M , int A , int B , int [ ] [ ] mat ) { int minimum = ( int ) 1e9 ; for ( int i = 0 ; i < N ; i ++ ) { for ( int j = 0 ; j < M ; j ++ ) { if ( i + A <= N && j + B <= M ) { int count = count1s ( i , j , i + A , j + B , mat ) ; minimum = Math . min ( count , minimum ) ; } if ( i + B <= N && j + A <= M ) { int count = count1s ( i , j , i + B , j + A , mat ) ; minimum = Math . min ( count , minimum ) ; } } } return minimum ; } public static void main ( String [ ] args ) { int A = 2 , B = 2 ; int N = 3 , M = 4 ; int [ ] [ ] mat = { { 1 , 0 , 1 , 0 } , { 0 , 1 , 0 , 1 } , { 1 , 0 , 1 , 0 } } ; System . out . println ( findMinimumCount ( N , M , A , B , mat ) ) ; } }


"Minimum number of Appends needed to make a string palindrome | Java program to find minimum number of appends needed to make a string Palindrome ; Checking if the string is palindrome or not ; single character is always palindrome ; pointing to first character ; pointing to last character ; Recursive function to count number of appends ; Removing first character of string by incrementing base address pointer . ; Driver code"
How can the above be solved in Java?

 class GFG { static boolean isPalindrome ( char [ ] str ) { int len = str . length ; if ( len == 1 ) return true ; int ptr1 = 0 ; int ptr2 = len - 1 ; while ( ptr2 >= ptr1 ) { if ( str [ ptr1 ] != str [ ptr2 ] ) return false ; ptr1 ++ ; ptr2 -- ; } return true ; } static int noOfAppends ( String s ) { if ( isPalindrome ( s . toCharArray ( ) ) ) return 0 ; s = s . substring ( 1 ) ; return 1 + noOfAppends ( s ) ; } public static void main ( String arr [ ] ) { String s = " abede " ; System . out . printf ( "%d
", noOfAppends(s)); } }


"Minimum number of Apples to be collected from trees to guarantee M red apples | Java program for the above approach ; Function to minimum no . of apples ; If we get all required apple from South ; If we required trees at East and West ; If we doesn 't have enough  red apples ; Driver code ; No . of red apple for gift ; No . of red apple in each tree ; No . of tree in North ; No . of tree in South ; No . of tree in West ; No . of tree in East ; Function Call"
How can the above be solved in Java?

import java . io . * ; class GFG { static int minApples ( int M , int K , int N , int S , int W , int E ) { if ( M <= S * K ) return M ; else if ( M <= S * K + E + W ) return S * K + ( M - S * K ) * K ; else return - 1 ; } public static void main ( String [ ] args ) { int M = 10 ; int K = 15 ; int N = 0 ; int S = 1 ; int W = 0 ; int E = 0 ; int ans = minApples ( M , K , N , S , W , E ) ; System . out . println ( ans ) ; } }


"Minimum number of Binary strings to represent a Number | Java program to find the minimum number of binary Strings to represent a number ; Function to find the minimum number of binary Strings to represent a number ; Storing digits in correct order ; Find the maximum digit in the array ; Traverse for all the binary Strings ; If digit at jth position is greater than 0 then substitute 1 ;  ; Driver code"
How can the above be solved in Java?

 import java . util . * ; class GFG { static void minBinary ( int n ) { int [ ] digit = new int [ 10 ] ; int len = 0 ; while ( n > 0 ) { digit [ len ++ ] = n % 10 ; n /= 10 ; } digit = reverse ( digit , 0 , len - 1 ) ; int ans = 0 ; for ( int i = 0 ; i < len ; i ++ ) { ans = Math . max ( ans , digit [ i ] ) ; } System . out . print ( " Minimum ▁ Number ▁ of ▁ binary " + " ▁ Strings ▁ needed : ▁ " + ans + "
"); for ( int i = 1 ; i <= ans ; i ++ ) { int num = 0 ; for ( int j = 0 ; j < len ; j ++ ) { if ( digit [ j ] > 0 ) { num = num * 10 + 1 ; digit [ j ] -- ; } else { num *= 10 ; } } System . out . print ( num + " ▁ " ) ; } } static int [ ] reverse ( int str [ ] , int start , int end ) { int temp ; while ( start <= end ) { temp = str [ start ] ; str [ start ] = str [ end ] ; str [ end ] = temp ; start ++ ; end -- ; } return str ; } public static void main ( String [ ] args ) { int n = 564 ; minBinary ( n ) ; } }


"Minimum number of Bottles visible when a bottle can be enclosed inside another Bottle | Java code for the above approach ; Driver code ; Find the solution"
How can the above be solved in Java?

 import java . util . * ; class GFG { static void min_visible_bottles ( int [ ] arr , int n ) { HashMap < Integer , Integer > mp = new HashMap < Integer , Integer > ( ) ; int ans = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( mp . containsKey ( arr [ i ] ) ) { mp . put ( arr [ i ] , mp . get ( arr [ i ] ) + 1 ) ; } else { mp . put ( arr [ i ] , 1 ) ; } ans = Math . max ( ans , mp . get ( arr [ i ] ) ) ; } System . out . print ( " Minimum ▁ number ▁ of ▁ " + " Visible ▁ Bottles ▁ are : ▁ " + ans + "
"); } public static void main ( String [ ] args ) { int n = 8 ; int arr [ ] = { 1 , 1 , 2 , 3 , 4 , 5 , 5 , 4 } ; min_visible_bottles ( arr , n ) ; } }


"Minimum number of Circular obstacles required to obstruct the path in a Grid | Java program to find the minimum number of obstacles required ; Function to find the minimum number of obstacles required ; Find the minimum range required to put obstacles ; Sorting the radius ; If val is less than zero then we have find the number of obstacles required ; Driver code"
How can the above be solved in Java?

 import java . util . * ; class GFG { static int solve ( int n , int m , int obstacles , double range [ ] ) { double val = Math . min ( n , m ) ; Arrays . sort ( range ) ; int c = 1 ; for ( int i = obstacles - 1 ; i >= 0 ; i -- ) { range [ i ] = 2 * range [ i ] ; val -= range [ i ] ; if ( val <= 0 ) { return c ; } else { c ++ ; } } if ( val > 0 ) { return - 1 ; } return 0 ; } public static void main ( String [ ] args ) { int n = 4 , m = 5 , obstacles = 3 ; double range [ ] = { 1.0 , 1.25 , 1.15 } ; System . out . print ( solve ( n , m , obstacles , range ) + "
"); } }


"Minimum number of Cuboids required to form a Cube | Java program for the above approach ; Function to calculate and return LCM of a , b , and c ; Find GCD of a and b ; Find LCM of a and b ; LCM ( a , b , c ) = LCM ( LCM ( a , b ) , c ) ; Finding LCM of a , b , c ; return LCM ( a , b , c ) ; Function to find the minimum number of cuboids required to make the volume of a valid cube ; Find the LCM of L , B , H ; Volume of the cube ; Volume of the cuboid ; Minimum number cuboids required to form a cube ; Driver Code ; Given dimensions of cuboid ; Function Call"
How can the above be solved in Java?

import java . util . * ; class GFG { static int find_lcm ( int a , int b , int c ) { int g = __gcd ( a , b ) ; int LCM1 = ( a * b ) / g ; g = __gcd ( LCM1 , c ) ; int LCM = ( LCM1 * c ) / g ; return LCM ; } static void minimumCuboids ( int L , int B , int H ) { int lcm = find_lcm ( L , B , H ) ; int volume_cube = lcm * lcm * lcm ; int volume_cuboid = L * B * H ; System . out . print ( ( volume_cube / volume_cuboid ) ) ; } static int __gcd ( int a , int b ) { return b == 0 ? a : __gcd ( b , a % b ) ; } public static void main ( String [ ] args ) { int L = 1 , B = 1 , H = 2 ; minimumCuboids ( L , B , H ) ; } }


"Minimum number of Factorials whose sum is equal to N | Java program to find minimum number of factorials ; Array to calculate all factorials less than or equal to N Since there can be only 14 factorials till 10 ^ 10 Hence the maximum size of fact [ ] is 14 ; Store the actual size of fact [ ] ; Function to precompute factorials till N ; Precomputing factorials ; Function to find the minimum number of factorials whose sum represents N ; Precompute factorials ; Initialize result ; Traverse through all factorials ; Find factorials ; Print min count ; Print result ; Driver program"
How can the above be solved in Java?

 import java . util . * ; class GFG { static int [ ] fact = new int [ 14 ] ; static int size = 1 ; static void preCompute ( int N ) { fact [ 0 ] = 1 ; for ( int i = 1 ; fact [ i - 1 ] <= N ; i ++ ) { fact [ i ] = ( fact [ i - 1 ] * i ) ; size ++ ; } } static void findMin ( int N ) { preCompute ( N ) ; int originalN = N ; Vector < Integer > ans = new Vector < Integer > ( ) ; for ( int i = size - 1 ; i >= 0 ; i -- ) { while ( N >= fact [ i ] ) { N -= fact [ i ] ; ans . add ( fact [ i ] ) ; } } System . out . print ( ans . size ( ) + "
"); for ( int i = 0 ; i < ans . size ( ) ; i ++ ) System . out . print ( ans . get ( i ) + " ▁ " ) ; } public static void main ( String [ ] args ) { int n = 27 ; findMin ( n ) ; } }


"Minimum number of Fibonacci jumps to reach end | A Dynamic Programming based Java program to find minimum number of jumps to reach Destination ; Function that returns the min number of jump to reach the destination ; We consider only those Fibonacci numbers which are less than n , where we can consider fib [ 30 ] to be the upper bound as this will cross 10 ^ 5 ; DP [ i ] will be storing the minimum number of jumps required for the position i . So DP [ N + 1 ] will have the result we consider 0 as source and N + 1 as the destination ; Base case ( Steps to reach source is ) ; Initialize all table values as Infinite ; Go through each positions till destination . ; Calculate the minimum of that position if all the Fibonacci numbers are considered ; If the position is safe or the position is the destination then only we calculate the minimum otherwise the cost is MAX as default ; - 1 denotes if there is no path possible ; Driver Code"
How can the above be solved in Java?

import java . util . * ; import java . lang . * ; class GFG { public static int minJumps ( int arr [ ] , int N ) { int MAX = 1000000 ; int [ ] fib = new int [ 30 ] ; fib [ 0 ] = 0 ; fib [ 1 ] = 1 ; for ( int i = 2 ; i < 30 ; i ++ ) fib [ i ] = fib [ i - 1 ] + fib [ i - 2 ] ; int [ ] DP = new int [ N + 2 ] ; DP [ 0 ] = 0 ; for ( int i = 1 ; i <= N + 1 ; i ++ ) DP [ i ] = MAX ; for ( int i = 1 ; i <= N + 1 ; i ++ ) { for ( int j = 1 ; j < 30 ; j ++ ) { if ( ( i == N + 1 arr [ i - 1 ] == 1 ) && i - fib [ j ] >= 0 ) DP [ i ] = Math . min ( DP [ i ] , 1 + DP [ i - fib [ j ] ] ) ; } } if ( DP [ N + 1 ] != MAX ) return DP [ N + 1 ] ; else return - 1 ; } public static void main ( String [ ] args ) { int [ ] arr = new int [ ] { 0 , 0 , 0 , 1 , 1 , 0 , 1 , 0 , 0 , 0 , 0 } ; int n = 11 ; int ans = minJumps ( arr , n ) ; System . out . println ( ans ) ; } }


"Minimum number of Nodes to be removed such that no subtree has more than K nodes | Java program for the above approach ; Variables used to store data globally ; Adjacency list representation of tree ; Function to perform DFS Traversal ; Mark the node as true ; Traverse adjacency list of child node ; If already visited then omit the node ; Add number of nodes in subtree ; Increment the count ; Return the nodes ; Function to add edges in graph ; Function that finds the number of nodes to be removed such that every subtree has size at most K ; Function Call to find the number of nodes to remove ; Print Removed Nodes ; Driver Code ; Creating list for all nodes ; Insert of nodes in graph ; Required subtree size ; Function Call"
How can the above be solved in Java?

import java . util . * ; class GFG { static final int N = 20 ; static boolean visited [ ] = new boolean [ N ] ; static int K ; static int removals = 0 ; static ArrayList < Integer > removed_nodes = new ArrayList < > ( ) ; static ArrayList < ArrayList < Integer > > adj = new ArrayList < > ( ) ; static int dfs ( int s ) { visited [ s ] = true ; int nodes = 1 ; for ( Integer child : adj . get ( s ) ) { if ( visited [ child ] ) continue ; nodes += dfs ( child ) ; } if ( nodes > K ) { removals ++ ; removed_nodes . add ( s ) ; nodes = 0 ; } return nodes ; } static void addEdge ( int a , int b ) { adj . get ( a ) . add ( b ) ; adj . get ( b ) . add ( a ) ; } public static void findRemovedNodes ( int K ) { dfs ( 1 ) ; System . out . println ( " Number ▁ of ▁ nodes " + " ▁ removed : ▁ " + removals ) ; System . out . print ( " Removed ▁ Nodes : ▁ " ) ; for ( int node : removed_nodes ) System . out . print ( node + " ▁ " ) ; } public static void main ( String [ ] args ) { for ( int i = 0 ; i < N ; i ++ ) adj . add ( new ArrayList < > ( ) ) ; addEdge ( 1 , 2 ) ; addEdge ( 1 , 3 ) ; addEdge ( 2 , 4 ) ; addEdge ( 2 , 5 ) ; addEdge ( 3 , 6 ) ; K = 3 ; findRemovedNodes ( K ) ; } }


"Minimum number of Parentheses to be added to make it valid | Java Program to find minimum number of ' ( ' or ' ) ' must be added to make Parentheses string valid . ; Function to return required minimum number ; maintain balance of string ; It is guaranteed bal >= - 1 ; Driver code ; Function to print required answer"
How can the above be solved in Java?

public class GFG { static int minParentheses ( String p ) { int bal = 0 ; int ans = 0 ; for ( int i = 0 ; i < p . length ( ) ; ++ i ) { bal += p . charAt ( i ) == ' ( ' ? 1 : - 1 ; if ( bal == - 1 ) { ans += 1 ; bal += 1 ; } } return bal + ans ; } public static void main ( String args [ ] ) { String p = " ( ) ) " ; System . out . println ( minParentheses ( p ) ) ; } }


"Minimum number of Square Free Divisors | Java Program to find the minimum number of square free divisors ; Initializing MAX with SQRT ( 10 ^ 6 ) ; Create a boolean array " prime [ 0 . . n ] " and initialize all entries it as true . A value in prime [ i ] will finally be false if i is Not a prime , else true . ; If prime [ p ] is not changed , then it is a prime ; Update all multiples of p ; Print all prime numbers ; This function returns the minimum number of Square Free divisors ; Precomputing Prime Factors ; holds max of max power of all prime factors ; holds the max power of current prime factor ; If number itself is prime , it will be included as answer and thus minimum required answer is 1 ; Driver Code to test above functions"
How can the above be solved in Java?

import java . util . Vector ; public class GFG { static final int MAX = 1005 ; static void SieveOfEratosthenes ( Vector < Integer > primes ) { boolean prime [ ] = new boolean [ MAX ] ; for ( int i = 0 ; i < prime . length ; i ++ ) { prime [ i ] = true ; } for ( int p = 2 ; p * p < MAX ; p ++ ) { if ( prime [ p ] == true ) { for ( int i = p * 2 ; i < MAX ; i += p ) { prime [ i ] = false ; } } } for ( int p = 2 ; p < MAX ; p ++ ) { if ( prime [ p ] ) { primes . add ( primes . size ( ) , p ) ; } } } static int minimumSquareFreeDivisors ( int N ) { Vector < Integer > primes = new Vector < > ( ) ; SieveOfEratosthenes ( primes ) ; int max_count = 0 ; for ( int i = 0 ; i < primes . size ( ) && primes . get ( i ) * primes . get ( i ) <= N ; i ++ ) { if ( N % primes . get ( i ) == 0 ) { int tmp = 0 ; while ( N % primes . get ( i ) == 0 ) { tmp ++ ; N /= primes . get ( i ) ; } max_count = Math . max ( max_count , tmp ) ; } } if ( max_count == 0 ) { max_count = 1 ; } return max_count ; } public static void main ( String [ ] args ) { int N = 24 ; System . out . println ( " Minimum ▁ Number ▁ of ▁ Square ▁ Free ▁ Divisors ▁ is ▁ " + minimumSquareFreeDivisors ( N ) ) ; N = 6 ; System . out . println ( " Minimum ▁ Number ▁ of ▁ Square ▁ Free ▁ Divisors ▁ is ▁ " + minimumSquareFreeDivisors ( N ) ) ; } }


"Minimum number of alternate subsequences required to be removed to empty a Binary String | Java program for the above approach ; Function to find the minimum number of operations to empty a binary string ; Stores the resultant number of operations ; Stores the number of 0 s ; Stores the number of 1 s ; Traverse the given string ; To balance 0 with 1 if possible ; Increment the value of cn0 by 1 ; To balance 1 with 0 if possible ; Increment the value of cn1 ; Update the maximum number of unused 0 s and 1 s ; Print the resultant count ; Driver Code"
How can the above be solved in Java?

import java . util . * ; class GFG { static void minOpsToEmptyString ( String s ) { int ans = Integer . MIN_VALUE ; int cn0 = 0 ; int cn1 = 0 ; for ( int i = 0 ; i < s . length ( ) ; i ++ ) { if ( s . charAt ( i ) == '0' ) { if ( cn1 > 0 ) cn1 -- ; cn0 ++ ; } else { if ( cn0 > 0 ) cn0 -- ; cn1 ++ ; } ans = Math . max ( ans , Math . max ( cn0 , cn1 ) ) ; } System . out . print ( ans ) ; } public static void main ( String [ ] args ) { String S = "010101" ; minOpsToEmptyString ( S ) ; } }


"Minimum number of array elements from either ends required to be subtracted from X to reduce X to 0 | Java program to implement the above approach ; Function to count the minimum number of operations required to reduce x to 0 ; If sum of the array is less than x ; Stores the count of operations ; Two pointers to traverse the array ; Reduce x by the sum of the entire array ; Iterate until l reaches the front of the array ; If sum of elements from the front exceeds x ; Shift towards left ; If sum exceeds 0 ; Reduce x by elements from the right ; If x is reduced to 0 ; Update the minimum count of operations required ; Driver Code"
How can the above be solved in Java?

import java . util . * ; class GFG { static int minOperations ( int nums [ ] , int x ) { int sum = 0 ; for ( int i = 0 ; i < x ; i ++ ) sum += nums [ i ] ; if ( sum < x ) return - 1 ; int ans = Integer . MAX_VALUE ; int l = nums . length - 1 , r = nums . length ; x -= sum ; while ( l >= 0 ) { if ( x <= 0 ) { x += nums [ l ] ; l -= 1 ; } if ( x > 0 ) { r -= 1 ; x -= nums [ r ] ; } if ( x == 0 ) { ans = Math . min ( ans , ( l + 1 ) + ( nums . length - r ) ) ; } } if ( ans < Integer . MAX_VALUE ) return ans ; else return - 1 ; } public static void main ( String [ ] args ) { int [ ] nums = { 1 , 1 , 4 , 2 , 3 } ; int x = 5 ; System . out . println ( minOperations ( nums , x ) ) ; } }


"Minimum number of basic logic gates required to realize given Boolean expression | Java implementation of the above approach ; Function to count the total number of gates required to realize the boolean expression S ; Length of the string ; Stores the count of total gates ; Traverse the string ; AND , OR and NOT Gate ; Print the count of gates required ; Driver Code ; Input ; Function call to count the total number of gates required"
How can the above be solved in Java?

class GFG { static void numberOfGates ( String s ) { int N = s . length ( ) ; int ans = 0 ; for ( int i = 0 ; i < ( int ) s . length ( ) ; i ++ ) { if ( s . charAt ( i ) == ' . ' || s . charAt ( i ) == ' + ' || s . charAt ( i ) == '1' ) { ans ++ ; } } System . out . println ( ans ) ; } public static void main ( String [ ] args ) { String S = " ( 1 - A ) . B + C " ; numberOfGates ( S ) ; } }


"Minimum number of bits of array elements required to be flipped to make all array elements equal | Java program for the above approach ; Function to count minimum number of bits required to be flipped to make all array elements equal ; Stores the count of unset bits ; Stores the count of set bits ; Traverse the array ; Traverse the bit of arr [ i ] ; If current bit is set ; Increment fre1 [ j ] ; Otherwise ; Increment fre0 [ j ] ; Right shift x by 1 ; Stores the count of total moves ; Traverse the range [ 0 , 32 ] ; Update the value of ans ; Return the minimum number of flips required ; Driver Code"
How can the above be solved in Java?

import java . io . * ; import java . lang . * ; import java . util . * ; class GFG { static int makeEqual ( int arr [ ] , int n ) { int fre0 [ ] = new int [ 33 ] ; int fre1 [ ] = new int [ 33 ] ; for ( int i = 0 ; i < n ; i ++ ) { int x = arr [ i ] ; for ( int j = 0 ; j < 33 ; j ++ ) { if ( ( x & 1 ) != 0 ) { fre1 [ j ] += 1 ; } else { fre0 [ j ] += 1 ; } x = x >> 1 ; } } int ans = 0 ; for ( int i = 0 ; i < 33 ; i ++ ) { ans += Math . min ( fre0 [ i ] , fre1 [ i ] ) ; } return ans ; } public static void main ( String [ ] args ) { int arr [ ] = { 3 , 5 } ; int N = arr . length ; System . out . print ( makeEqual ( arr , N ) ) ; } }


"Minimum number of bits required to be flipped such that Bitwise OR of A and B is equal to C | Java program for the above approach ; Function to count the number of bit flips required on A and B such that Bitwise OR of A and B is C ; Stores the count of flipped bit ; Iterate over the range [ 0 , 32 ] ; Check if i - th bit of A is set ; Check if i - th bit of B is set or not ; Check if i - th bit of C is set or not ; If i - th bit of C is unset ; Check if i - th bit of A is set or not ; Check if i - th bit of B is set or not ; Check if i - th bit of C is set or not ; Check if i - th bit of both A and B is set ; Return the count of bits flipped ; Driver Code"
How can the above be solved in Java?

import java . io . * ; import java . lang . * ; import java . util . * ; class GFG { static int minimumFlips ( int A , int B , int C ) { int res = 0 ; for ( int i = 0 ; i < 32 ; i ++ ) { int x = 0 , y = 0 , z = 0 ; if ( ( A & ( 1 << i ) ) != 0 ) { x = 1 ; } if ( ( B & ( 1 << i ) ) != 0 ) { y = 1 ; } if ( ( C & ( 1 << i ) ) != 0 ) { z = 1 ; } if ( z == 0 ) { if ( x == 1 ) { res ++ ; } if ( y == 1 ) { res ++ ; } } if ( z == 1 ) { if ( x == 0 && y == 0 ) { res ++ ; } } } return res ; } public static void main ( String [ ] args ) { int A = 2 , B = 6 , C = 5 ; System . out . println ( minimumFlips ( A , B , C ) ) ; } }


"Minimum number of blocks required to form Hollow Rectangular Prism | Java Implementation to find the minimum no of blocks required to form hollow rectangular prism ; Function to display output ; Function to return minimum no of layers required to form the hollow prism ; Function to calculate no of blocks required for each layer ; No of blocks required for each row ; Check for no of layers is minimum ; Driver function ; Length , width , height of each block ; Side of one wall ; height of each wall"
How can the above be solved in Java?

import java . util . * ; class GFG { static void disp ( int row_no , int block ) { System . out . print ( row_no * block ) ; } static int row ( int ht , int h ) { return ht / h ; } static void calculate ( int l , int w , int h , int a , int ht ) { int no_block = ( 4 * a ) / l ; int row_no ; if ( h < w ) row_no = row ( ht , w ) ; else row_no = row ( ht , h ) ; disp ( row_no , no_block ) ; } public static void main ( String [ ] args ) { int l = 50 , w = 20 , h = 35 ; int a = 700 ; int ht = 140 ; calculate ( l , w , h , a , ht ) ; } }


"Minimum number of bombs | Java program to find number of bombings required to kill all aliens . ; function to print where to shoot ; no . of bombs required ; bomb all the even positions ; bomb all the odd positions ; bomb all the even positions again ; Driver code"
How can the above be solved in Java?

class GFG { static void print ( int n ) { System . out . println ( n + n / 2 ) ; for ( int i = 2 ; i <= n ; i += 2 ) System . out . print ( i + " ▁ " ) ; for ( int i = 1 ; i <= n ; i += 2 ) System . out . print ( i + " ▁ " ) ; for ( int i = 2 ; i <= n ; i += 2 ) System . out . print ( i + " ▁ " ) ; } public static void main ( String [ ] args ) { int n = 3 ; print ( n ) ; } }


"Minimum number of bricks that can be intersected | Java program for the above approach ; Function to find a line across a wall such that it intersects minimum number of bricks ; Declare a hashmap ; Store the maximum number of brick ending a point on x - axis ; Iterate over all the rows ; Initialize width as 0 ; Iterate over individual bricks ; Add the width of the current brick to the total width ; Increment number of bricks ending at this width position ; Update the variable , res ; Print the answer ; Driver code ; Given Input ; Function Call"
How can the above be solved in Java?

import java . util . ArrayList ; import java . util . Arrays ; import java . util . HashMap ; public class GFG { static void leastBricks ( ArrayList < ArrayList < Integer > > wall ) { HashMap < Integer , Integer > map = new HashMap < > ( ) ; int res = 0 ; for ( ArrayList < Integer > list : wall ) { int width = 0 ; for ( int i = 0 ; i < list . size ( ) - 1 ; i ++ ) { width += list . get ( i ) ; map . put ( width , map . getOrDefault ( width , 0 ) + 1 ) ; res = Math . max ( res , map . getOrDefault ( width , 0 ) ) ; } } System . out . println ( wall . size ( ) - res ) ; } public static void main ( String [ ] args ) { ArrayList < ArrayList < Integer > > arr = new ArrayList < > ( ) ; arr . add ( new ArrayList < > ( Arrays . asList ( 1 , 2 , 2 , 1 ) ) ) ; arr . add ( new ArrayList < > ( Arrays . asList ( 3 , 1 , 2 ) ) ) ; arr . add ( new ArrayList < > ( Arrays . asList ( 1 , 3 , 2 ) ) ) ; arr . add ( new ArrayList < > ( Arrays . asList ( 2 , 4 ) ) ) ; arr . add ( new ArrayList < > ( Arrays . asList ( 3 , 1 , 2 ) ) ) ; arr . add ( new ArrayList < > ( Arrays . asList ( 1 , 3 , 1 , 1 ) ) ) ; leastBricks ( arr ) ; } }


"Minimum number of candies required to distribute among children based on given conditions | Java program for the above approach ; Function to count the minimum number of candies that is to be distributed ; Stores total count of candies ; Stores the amount of candies allocated to a student ; If the value of N is 1 ; Initialize with 1 all array element ; Traverse the array arr [ ] ; If arr [ i + 1 ] is greater than arr [ i ] and ans [ i + 1 ] is at most ans [ i ] ; Assign ans [ i ] + 1 to ans [ i + 1 ] ; Iterate until i is atleast 0 ; If arr [ i ] is greater than arr [ i + 1 ] and ans [ i ] is at most ans [ i + 1 ] ; Assign ans [ i + 1 ] + 1 to ans [ i ] ; If arr [ i ] is equals arr [ i + 1 ] and ans [ i ] is less than ans [ i + 1 ] ; Assign ans [ i + 1 ] + 1 to ans [ i ] ; Increment the sum by ans [ i ] ; Return the resultant sum ; Driver Code"
How can the above be solved in Java?

import java . io . * ; class GFG { static int countCandies ( int arr [ ] , int n ) { int sum = 0 ; int [ ] ans = new int [ n ] ; if ( n == 1 ) { return 1 ; } for ( int i = 0 ; i < n ; i ++ ) ans [ i ] = 1 ; for ( int i = 0 ; i < n - 1 ; i ++ ) { if ( arr [ i + 1 ] > arr [ i ] && ans [ i + 1 ] <= ans [ i ] ) { ans [ i + 1 ] = ans [ i ] + 1 ; } } for ( int i = n - 2 ; i >= 0 ; i -- ) { if ( arr [ i ] > arr [ i + 1 ] && ans [ i ] <= ans [ i + 1 ] ) { ans [ i ] = ans [ i + 1 ] + 1 ; } else if ( arr [ i ] == arr [ i + 1 ] && ans [ i ] < ans [ i + 1 ] ) { ans [ i ] = ans [ i + 1 ] + 1 ; } sum += ans [ i ] ; } sum += ans [ n - 1 ] ; return sum ; } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 0 , 2 } ; int N = arr . length ; System . out . println ( countCandies ( arr , N ) ) ; } }


"Minimum number of chairs required to ensure that every worker is seated at any instant | Java program for the above approach ; Function to find the minimum number of chairs required to ensure that every worker is seated at any time ; Stores the number of chairs required ; Pointer to iterate ; Stores minimum number of chairs required ; Iterate over every character ; If character is ' E ' ; Increase the count ; Otherwise ; Update maximum value of count obtained at any given time ; Return mini ; Driver code ; Given String ; Function call to find the minimum number of chairs"
How can the above be solved in Java?

import java . io . * ; import java . util . * ; class GFG { static int findMinimumChairs ( String s ) { int count = 0 ; int i = 0 ; int mini = Integer . MIN_VALUE ; while ( i < s . length ( ) ) { if ( s . charAt ( i ) == ' E ' ) count ++ ; else count -- ; mini = Math . max ( count , mini ) ; i ++ ; } return mini ; } public static void main ( String [ ] args ) { String s = " EELEE " ; System . out . print ( findMinimumChairs ( s ) ) ; } }


"Minimum number of changes such that elements are first Negative and then Positive | Java implementation of the approach ; Function to return the count of minimum operations required ; To store the count of negative integers on the right of the current index ( inclusive ) ; Find the count of negative integers on the right ; If current element is negative ; To store the count of positive elements ; Find the positive integers on the left ; If current element is positive ; Update the answer ; Return the required answer ; Driver code"
How can the above be solved in Java?

class GFG { static int Minimum_Operations ( int [ ] a , int n ) { int [ ] np = new int [ n + 1 ] ; np [ n ] = 0 ; for ( int i = n - 1 ; i >= 0 ; i -- ) { np [ i ] = np [ i + 1 ] ; if ( a [ i ] <= 0 ) np [ i ] ++ ; } int pos = 0 ; int ans = n ; for ( int i = 0 ; i < n - 1 ; i ++ ) { if ( a [ i ] >= 0 ) pos ++ ; ans = Math . min ( ans , pos + np [ i + 1 ] ) ; } return ans ; } public static void main ( String args [ ] ) { int [ ] a = { - 1 , 0 , 1 , 2 } ; int n = a . length ; System . out . print ( Minimum_Operations ( a , n ) ) ; } }


"Minimum number of characters required to be added to a String such that all lowercase alphabets occurs as a subsequence in increasing order | Java program for the above approach ; Function to find the LCS of strings S and string T ; Base Case ; Already Calculated State ; If the characters are the same ; Otherwise ; Function to find the minimum number of characters that needs to be appended in the string to get all lowercase alphabets as a subsequences ; String containing all the characters ; Stores the result of overlapping subproblems ; Return the minimum characters required ; Driver Code"
How can the above be solved in Java?

import java . io . * ; class GFG { static int LCS ( String S , int N , String T , int M , int dp [ ] [ ] ) { if ( N == 0 M == 0 ) return 0 ; if ( dp [ N ] [ M ] != 0 ) return dp [ N ] [ M ] ; if ( S . charAt ( N - 1 ) == T . charAt ( M - 1 ) ) { return dp [ N ] [ M ] = 1 + LCS ( S , N - 1 , T , M - 1 , dp ) ; } return dp [ N ] [ M ] = Math . max ( LCS ( S , N - 1 , T , M , dp ) , LCS ( S , N , T , M - 1 , dp ) ) ; } static int minimumCharacter ( String S ) { String T = " abcdefghijklmnopqrstuvwxyz " ; int N = S . length ( ) , M = T . length ( ) ; int dp [ ] [ ] = new int [ N + 1 ] [ M + 1 ] ; return ( 26 - LCS ( S , N , T , M , dp ) ) ; } public static void main ( String [ ] args ) { String S = " abcdadc " ; System . out . println ( minimumCharacter ( S ) ) ; } }


"Minimum number of characters required to be removed such that every character occurs same number of times | Java program for the above approach ; Function to find minimum number of character removals required to make frequency of all distinct characters the same ; Stores the frequency of each character ; Traverse the string ; Stores the frequency of each charachter in sorted order ; Insert the frequency in multiset ; Stores the count of elements required to be removed ; Stores the size of multiset ; Traverse the multiset ; Update the ans ; Increment i by 1 ; Return ; Driver Code ; Input"
How can the above be solved in Java?

import java . io . * ; import java . lang . * ; import java . util . * ; class GFG { static int minimumDeletion ( String s , int n ) { HashMap < Character , Integer > countMap = new HashMap < > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { char ch = s . charAt ( i ) ; countMap . put ( ch , countMap . getOrDefault ( ch , 0 ) + 1 ) ; } ArrayList < Integer > countMultiset = new ArrayList < > ( countMap . values ( ) ) ; Collections . sort ( countMultiset ) ; int ans = Integer . MAX_VALUE ; int i = 0 ; int m = countMultiset . size ( ) ; for ( int j : countMultiset ) { ans = Math . min ( ans , n - ( m - i ) * j ) ; i ++ ; } return ans ; } public static void main ( String [ ] args ) { String S = " geeksforgeeks " ; int N = S . length ( ) ; System . out . println ( minimumDeletion ( S , N ) ) ; } }


"Minimum number of characters to be removed to make a binary string alternate | Java program to find minimum number of characters to be removed to make a string alternate . ; Returns count of minimum characters to be removed to make s alternate . ; if two alternating characters of string are same ; result ++ ; then need to delete a character ; Driver code"
How can the above be solved in Java?

import java . io . * ; public class GFG { static int countToMake0lternate ( String s ) { int result = 0 ; for ( int i = 0 ; i < ( s . length ( ) - 1 ) ; i ++ ) if ( s . charAt ( i ) == s . charAt ( i + 1 ) ) return result ; } static public void main ( String [ ] args ) { System . out . println ( countToMake0lternate ( "000111" ) ) ; System . out . println ( countToMake0lternate ( "11111" ) ) ; System . out . println ( countToMake0lternate ( "01010101" ) ) ; } }


"Minimum number of coins having value equal to powers of 2 required to obtain N | Java program for above approach ; Function to count of set bit in N ; Stores count of set bit in N ; Iterate over the range [ 0 , 31 ] ; If current bit is set ; Update result ; Driver Code"
How can the above be solved in Java?

public class Main { public static void count_setbit ( int N ) { int result = 0 ; for ( int i = 0 ; i < 32 ; i ++ ) { if ( ( ( 1 << i ) & N ) > 0 ) { result ++ ; } } System . out . println ( result ) ; } public static void main ( String [ ] args ) { int N = 43 ; count_setbit ( N ) ; } }


"Minimum number of coins needed to remove all the elements of the array based on given rules | Java implementation for the above approach ; Function to calculate minimum number of coins needed ; Consider the first element separately , add 1 to the total if it 's of type 1 ; Iterate from the second element ; If the current element is of type 2 then any Player can remove the element ; Second pointer to reach end of type 1 elements ; Increment j until arr [ j ] is equal to 1 and j is not out of bounds ; Number of type 1 elements in a continious chunk ; From next iteration i pointer will start from index of j ; Return the minimum count of coins ; Driver Code"
How can the above be solved in Java?

import java . io . * ; import java . util . * ; class GFG { static int minimumcoins ( int arr [ ] , int N ) { int coins = 0 ; int j = 0 ; if ( arr [ 0 ] == 1 ) coins ++ ; for ( int i = 1 ; i < N ; i ++ ) { if ( arr [ i ] == 2 ) continue ; j = i ; while ( j < N && arr [ j ] == 1 ) { j ++ ; } int x = ( j - i ) ; coins += x / 3 ; i = j - 1 ; } return coins ; } public static void main ( String [ ] args ) { int N = 8 ; int arr [ ] = { 1 , 2 , 1 , 1 , 2 , 1 , 1 , 1 } ; System . out . println ( minimumcoins ( arr , N ) ) ; } }


"Minimum number of coins that can generate all the values in the given range | Java implementation of the approach ; Function to return the count of minimum coins required ; To store the required sequence ; Creating list of the sum of all previous bit values including that bit value ; Driver Code"
How can the above be solved in Java?

import java . util . * ; class GFG { static int findCount ( int N ) { Vector list = new Vector ( ) ; int sum = 0 ; int i ; for ( i = 0 ; i < 20 ; i ++ ) { sum += Math . pow ( 2 , i ) ; list . add ( sum ) ; } for ( i = 0 ; i < 20 ; i ++ ) { if ( ( int ) list . get ( i ) >= N ) return ( list . indexOf ( list . get ( i ) ) + 1 ) ; } return 0 ; } public static void main ( String [ ] args ) { int N = 10 ; System . out . println ( findCount ( N ) ) ; } }


"Minimum number of coins that can generate all the values in the given range | Java program to find minimum number of coins ; Function to find minimum number of coins ; Driver code"
How can the above be solved in Java?

class GFG { static int findCount ( int n ) { return ( int ) ( Math . log ( n ) / Math . log ( 2 ) ) + 1 ; } public static void main ( String [ ] args ) { int N = 10 ; System . out . println ( findCount ( N ) ) ; } }


"Minimum number of colors required to color a Circular Array | Java implementation of above approach ; Function that finds minimum number of colors required ; To check that if all the elements are same or not ; To check if only one adjacent exist ; Traverse the array ; If adjacent elements found different means all are not same ; If two adjacent elements found to be same then make one_adjacent_same true ; If all elements are same then print 1 ; If total number of elements are even or there exist two adjacent elements that are same then print 2 ; Else 3 type of colors are required ; Driver Code ; Function call"
How can the above be solved in Java?

 import java . util . * ; class GFG { static void colorRequired ( int arr [ ] , int n ) { boolean all_same = true ; boolean one_adjacent_same = false ; for ( int i = 0 ; i < n - 1 ; i ++ ) { if ( arr [ i ] != arr [ i + 1 ] ) { all_same = false ; } if ( arr [ i ] == arr [ i + 1 ] ) { one_adjacent_same = true ; } } if ( all_same == true ) { System . out . print ( 1 + "
"); return ; } if ( n % 2 == 0 one_adjacent_same == true ) { System . out . print ( 2 + "
"); return ; } System . out . print ( 3 + "
"); } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 2 , 1 , 1 , 2 } ; int n = arr . length ; colorRequired ( arr , n ) ; } }


"Minimum number of consecutive sequences that can be formed in an array | Java program find the minimum number of consecutive sequences in an array ; Driver program ; function call to print required answer"
How can the above be solved in Java?

import java . util . Arrays ; import java . io . * ; class GFG { static int countSequences ( int arr [ ] , int n ) { int count = 1 ; Arrays . sort ( arr ) ; for ( int i = 0 ; i < n - 1 ; i ++ ) if ( arr [ i ] + 1 != arr [ i + 1 ] ) count ++ ; return count ; } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 7 , 3 , 5 , 10 } ; int n = arr . length ; System . out . println ( countSequences ( arr , n ) ) ; } }


"Minimum number of cubes whose sum equals to given number N | Java implementation of the approach ; Function to return the minimum number of cubes whose sum is k ; If k is less than the 2 ^ 3 ; Initialize with the maximum number of cubes required ; Driver code"
How can the above be solved in Java?

class GFG { static int MinOfCubed ( int k ) { if ( k < 8 ) return k ; int res = k ; for ( int i = 1 ; i <= k ; i ++ ) { if ( ( i * i * i ) > k ) return res ; res = Math . min ( res , MinOfCubed ( k - ( i * i * i ) ) + 1 ) ; } return res ; } public static void main ( String [ ] args ) { int num = 15 ; System . out . println ( MinOfCubed ( num ) ) ; } }


"Minimum number of cubes whose sum equals to given number N | Java implementation of the approach ; Function to return the minimum number of cubes whose sum is k ; While current perfect cube is less than current element ; If i is a perfect cube ; i = ( i - 1 ) + 1 ^ 3 ; Next perfect cube ; Re - initialization for next element ; Driver code"
How can the above be solved in Java?

class GFG { static int MinOfCubedDP ( int k ) { int [ ] DP = new int [ k + 1 ] ; int j = 1 , t = 1 ; DP [ 0 ] = 0 ; for ( int i = 1 ; i <= k ; i ++ ) { DP [ i ] = Integer . MAX_VALUE ; while ( j <= i ) { if ( j == i ) DP [ i ] = 1 ; else if ( DP [ i ] > DP [ i - j ] ) DP [ i ] = DP [ i - j ] + 1 ; t ++ ; j = t * t * t ; } t = j = 1 ; } return DP [ k ] ; } public static void main ( String [ ] args ) { int num = 15 ; System . out . println ( MinOfCubedDP ( num ) ) ; } }


"Minimum number of cuts required to make circle segments equal sized | Java program to find the minimum number of additional cuts required to make circle segments equal sized ; Recursive function to return gcd of two nos ; Function to find the minimum number of additional cuts required to make circle segments are equal sized ; Sort the array ; Initial gcd value ; Including the last segment ; Driver code"
How can the above be solved in Java?

import java . util . Arrays ; class GFG { static int findgcd ( int a , int b ) { if ( b == 0 ) return a ; return findgcd ( b , a % b ) ; } static int minimumCuts ( int a [ ] , int n ) { Arrays . sort ( a ) ; int gcd = a [ 1 ] - a [ 0 ] ; int s = gcd ; for ( int i = 2 ; i < n ; i ++ ) { gcd = findgcd ( gcd , a [ i ] - a [ i - 1 ] ) ; s += a [ i ] - a [ i - 1 ] ; } if ( 360 - s > 0 ) gcd = findgcd ( gcd , 360 - s ) ; return ( 360 / gcd ) - n ; } public static void main ( String [ ] args ) { int [ ] arr = new int [ ] { 30 , 60 , 180 } ; int n = arr . length ; System . out . println ( minimumCuts ( arr , n ) ) ; } }


"Minimum number of cuts required to pay salary from N length Gold Bar | JAVA Implementation to find the minimum number of cuts to pay the worker . ; Function to find the minimum number of cuts to pay the worker . ; Nearest Integer to the Log value of the number N ; Driver code ; Cuts Required in the Length of 15"
How can the above be solved in Java?

 class GFG { static int pay ( int n ) { int cuts = ( int ) ( Math . log ( n ) / Math . log ( 2 ) ) ; return cuts ; } public static void main ( String [ ] args ) { int n = 5 ; int cuts = pay ( n ) ; System . out . print ( cuts + "
"); n = 15 ; cuts = pay ( n ) ; System . out . print ( cuts ) ; } }


"Minimum number of days required to complete the work | Java program to find the minimum number days required ; pair class for number of days ; Function to find the minimum number days required ; initialising ans to least value possible ; sort by first i . e D ( i ) ; Calculate the minimum possible days ; return the answer ; Driver Code ; Number of works ; D1 [ i ] ; D2 [ i ]"
How can the above be solved in Java?

import java . util . * ; import java . lang . * ; import java . io . * ; class Pair { int x , y ; Pair ( int a , int b ) { this . x = a ; this . y = b ; } } class GFG { static int inf = Integer . MIN_VALUE ; public static int minimumDays ( int N , int D1 [ ] , int D2 [ ] ) { int ans = - inf ; ArrayList < Pair > list = new ArrayList < Pair > ( ) ; for ( int i = 0 ; i < N ; i ++ ) list . add ( new Pair ( D1 [ i ] , D2 [ i ] ) ) ; Collections . sort ( list , new Comparator < Pair > ( ) { @ Override public int compare ( Pair p1 , Pair p2 ) { return p1 . x - p2 . x ; } } ) ; for ( int i = 0 ; i < N ; i ++ ) { if ( list . get ( i ) . y >= ans ) ans = list . get ( i ) . y ; else ans = list . get ( i ) . x ; } return ans ; } public static void main ( String [ ] args ) { int N = 3 ; int D1 [ ] = new int [ ] { 6 , 5 , 4 } ; int D2 [ ] = new int [ ] { 1 , 2 , 3 } ; System . out . print ( minimumDays ( N , D1 , D2 ) ) ; } }


"Minimum number of days to debug all programs | Java program for the above approach ; Function to calculate the minimum work sessions ; Break condition ; All bits are set ; Check if already calculated ; Store the answer ; Check if ith bit is set or unset ; Including in current work session ; Including in next work session ; Resultant answer will be minimum of both ; Function to initialize DP array and solve the problem ; Initialize dp table with - 1 ; Resultant mask ; no . of minimum work sessions is even ; no . of minimum work sessions is odd ; Driver code"
How can the above be solved in Java?

import java . util . Arrays ; class GFG { public static int minSessions ( int [ ] codeTime , int [ ] [ ] dp , int ones , int n , int mask , int currTime , int WorkingSessionTime ) { if ( currTime > WorkingSessionTime ) return Integer . MAX_VALUE ; if ( mask == ones ) return 1 ; if ( dp [ mask ] [ currTime ] != - 1 ) return dp [ mask ] [ currTime ] ; int ans = Integer . MAX_VALUE ; for ( int i = 0 ; i < n ; i ++ ) { if ( ( mask & ( 1 << i ) ) == 0 ) { int inc = minSessions ( codeTime , dp , ones , n , mask | ( 1 << i ) , currTime + codeTime [ i ] , WorkingSessionTime ) ; int inc_next = 1 + minSessions ( codeTime , dp , ones , n , mask | ( 1 << i ) , codeTime [ i ] , WorkingSessionTime ) ; ans = Math . min ( ans , Math . min ( inc , inc_next ) ) ; } } return dp [ mask ] [ currTime ] = ans ; } public static int solve ( int [ ] codeTime , int n , int WorkingSessionTime ) { int [ ] [ ] dp = new int [ ( 1 << 14 ) ] [ ] ; for ( int i = 0 ; i < 1 << 14 ; i ++ ) { dp [ i ] = new int [ 15 ] ; Arrays . fill ( dp [ i ] , - 1 ) ; } int ones = ( 1 << n ) - 1 ; int ans = minSessions ( codeTime , dp , ones , n , 0 , 0 , WorkingSessionTime ) ; if ( WorkingSessionTime < 6 ) { if ( ans % 2 == 0 ) ans = ans / 2 ; else ans = ( ans / 2 ) + 1 ; } return ans ; } public static void main ( String args [ ] ) { int [ ] codeTime = { 1 , 2 , 3 , 1 , 1 , 3 } ; int n = codeTime . length ; int WorkingSessionTime = 4 ; System . out . println ( solve ( codeTime , n , WorkingSessionTime ) ) ; } }


"Minimum number of decrements by 1 required to reduce all elements of a circular array to 0 | Java program for the above approach ; Function to find minimum operation require to make all elements 0 ; Stores the maximum element and its position in the array ; Traverse the array ; Update the maximum element and its index ; Print the minimum number of operations required ; Driver Code"
How can the above be solved in Java?

import java . io . * ; class GFG { static void minimumOperations ( int arr [ ] , int N ) { int mx = 0 , pos = 0 ; for ( int i = 0 ; i < N ; i ++ ) { if ( arr [ i ] >= mx ) { mx = arr [ i ] ; pos = i ; } } System . out . println ( ( mx - 1 ) * N + pos + 1 ) ; } public static void main ( String [ ] args ) { int arr [ ] = { 2 , 0 , 2 } ; int N = arr . length ; minimumOperations ( arr , N ) ; } }


"Minimum number of deletions and insertions to transform one string into another | Dynamic Programming Java implementation to find minimum number of deletions and insertions ; Returns length of length common subsequence for str1 [ 0. . m - 1 ] , str2 [ 0. . n - 1 ] ; Following steps build L [ m + 1 ] [ n + 1 ] in bottom up fashion . Note that L [ i ] [ j ] contains length of LCS of str1 [ 0. . i - 1 ] and str2 [ 0. . j - 1 ] ; L [ m ] [ n ] contains length of LCS for X [ 0. . n - 1 ] and Y [ 0. . m - 1 ] ; function to find minimum number of deletions and insertions ; Driver code ; Function Call"
How can the above be solved in Java?

import java . io . * ; class GFG { static int lcs ( String str1 , String str2 , int m , int n ) { int L [ ] [ ] = new int [ m + 1 ] [ n + 1 ] ; int i , j ; for ( i = 0 ; i <= m ; i ++ ) { for ( j = 0 ; j <= n ; j ++ ) { if ( i == 0 j == 0 ) L [ i ] [ j ] = 0 ; else if ( str1 . charAt ( i - 1 ) == str2 . charAt ( j - 1 ) ) L [ i ] [ j ] = L [ i - 1 ] [ j - 1 ] + 1 ; else L [ i ] [ j ] = Math . max ( L [ i - 1 ] [ j ] , L [ i ] [ j - 1 ] ) ; } } return L [ m ] [ n ] ; } static void printMinDelAndInsert ( String str1 , String str2 ) { int m = str1 . length ( ) ; int n = str2 . length ( ) ; int len = lcs ( str1 , str2 , m , n ) ; System . out . println ( " Minimum ▁ number ▁ of ▁ " + " deletions ▁ = ▁ " ) ; System . out . println ( m - len ) ; System . out . println ( " Minimum ▁ number ▁ of ▁ " + " insertions ▁ = ▁ " ) ; System . out . println ( n - len ) ; } public static void main ( String [ ] args ) { String str1 = new String ( " heap " ) ; String str2 = new String ( " pea " ) ; printMinDelAndInsert ( str1 , str2 ) ; } }


"Minimum number of deletions so that no two consecutive are same | Java code to count minimum deletions required so that there are no consecutive characters left ; Function for counting deletions ; If two consecutive characters are the same , delete one of them . ; Driver code ; Function call to print answer"
How can the above be solved in Java?

import java . util . * ; class GFG { static int countDeletions ( String s ) { int ans = 0 ; char [ ] str = s . toCharArray ( ) ; for ( int i = 0 ; i < str . length - 1 ; i ++ ) if ( str [ i ] == str [ i + 1 ] ) ans ++ ; return ans ; } public static void main ( String [ ] args ) { String str = " AAABBB " ; System . out . println ( countDeletions ( str ) ) ; } }


"Minimum number of deletions to make a sorted sequence | Java implementation to find minimum number of deletions to make a sorted sequence ; lis ( ) returns the length of the longest increasing subsequence in arr [ ] of size n ; Initialize LIS values for all indexes ; Compute optimized LIS values in bottom up manner ; Pick resultimum of all LIS values ; function to calculate minimum number of deletions ; Find longest increasing subsequence ; After removing elements other than the lis , we get sorted sequence . ; Driver Code"
How can the above be solved in Java?

class GFG { static int lis ( int arr [ ] , int n ) { int result = 0 ; int [ ] lis = new int [ n ] ; for ( int i = 0 ; i < n ; i ++ ) lis [ i ] = 1 ; for ( int i = 1 ; i < n ; i ++ ) for ( int j = 0 ; j < i ; j ++ ) if ( arr [ i ] > arr [ j ] && lis [ i ] < lis [ j ] + 1 ) lis [ i ] = lis [ j ] + 1 ; for ( int i = 0 ; i < n ; i ++ ) if ( result < lis [ i ] ) result = lis [ i ] ; return result ; } static int minimumNumberOfDeletions ( int arr [ ] , int n ) { int len = lis ( arr , n ) ; return ( n - len ) ; } public static void main ( String [ ] args ) { int arr [ ] = { 30 , 40 , 2 , 5 , 1 , 7 , 45 , 50 , 8 } ; int n = arr . length ; System . out . println ( " Minimum ▁ number ▁ of " + " ▁ deletions ▁ = ▁ " + minimumNumberOfDeletions ( arr , n ) ) ; } }


"Minimum number of deletions to make a string palindrome | Function definition ; Base cases ; Checking the ndesired condition ; If yes increment the cunt ; If no ; Return the value form the table ; Else store the max tranforamtion from the subsequence ; Return the dp [ - 1 ] [ - 1 ] ; Driver code ; Initialize the array with - 1"
How can the above be solved in Java?

import java . util . * ; public class GFG { static int dp [ ] [ ] = new int [ 2000 ] [ 2000 ] ; public static int transformation ( String s1 , String s2 , int i , int j ) { if ( i >= s1 . length ( ) || j >= s2 . length ( ) ) { return 0 ; } if ( s1 . charAt ( i ) == s2 . charAt ( j ) ) { dp [ i ] [ j ] = 1 + transformation ( s1 , s2 , i + 1 , j + 1 ) ; } if ( dp [ i ] [ j ] != - 1 ) { return dp [ i ] [ j ] ; } else { dp [ i ] [ j ] = Math . max ( transformation ( s1 , s2 , i , j + i ) , transformation ( s1 , s2 , i + 1 , j ) ) ; } return dp [ s1 . length ( ) - 1 ] [ s2 . length ( ) - 1 ] ; } public static void main ( String [ ] args ) { String s1 = " geeksforgeeks " ; String s2 = " geeks " ; int i = 0 ; int j = 0 ; for ( int [ ] row : dp ) { Arrays . fill ( row , - 1 ) ; } System . out . println ( " MINIMUM ▁ NUMBER ▁ OF ▁ DELETIONS : ▁ " + ( s1 . length ( ) - transformation ( s1 , s2 , 0 , 0 ) ) ) ; System . out . println ( " MINIMUM ▁ NUMBER ▁ OF ▁ INSERTIONS : ▁ " + ( s2 . length ( ) - transformation ( s1 , s2 , 0 , 0 ) ) ) ; System . out . println ( " LCS ▁ LENGTH : ▁ " + transformation ( s1 , s2 , 0 , 0 ) ) ; } }


"Minimum number of deletions to make a string palindrome | Java implementation to find minimum number of deletions to make a string palindromic ; Returns the length of the longest palindromic subsequence in ' str ' ; Create a table to store results of subproblems ; Strings of length 1 are palindrome of length 1 ; Build the table . Note that the lower diagonal values of table are useless and not filled in the process . c1 is length of substring ; length of longest palindromic subsequence ; function to calculate minimum number of deletions ; Find longest palindromic subsequence ; After removing characters other than the lps , we get palindrome . ; Driver Code"
How can the above be solved in Java?

class GFG { static int lps ( String str ) { int n = str . length ( ) ; int L [ ] [ ] = new int [ n ] [ n ] ; for ( int i = 0 ; i < n ; i ++ ) L [ i ] [ i ] = 1 ; for ( int cl = 2 ; cl <= n ; cl ++ ) { for ( int i = 0 ; i < n - cl + 1 ; i ++ ) { int j = i + cl - 1 ; if ( str . charAt ( i ) == str . charAt ( j ) && cl == 2 ) L [ i ] [ j ] = 2 ; else if ( str . charAt ( i ) == str . charAt ( j ) ) L [ i ] [ j ] = L [ i + 1 ] [ j - 1 ] + 2 ; else L [ i ] [ j ] = Integer . max ( L [ i ] [ j - 1 ] , L [ i + 1 ] [ j ] ) ; } } return L [ 0 ] [ n - 1 ] ; } static int minimumNumberOfDeletions ( String str ) { int n = str . length ( ) ; int len = lps ( str ) ; return ( n - len ) ; } public static void main ( String [ ] args ) { String str = " geeksforgeeks " ; System . out . println ( " Minimum ▁ number ▁ " + " of ▁ deletions ▁ = ▁ " + minimumNumberOfDeletions ( str ) ) ; } }


"Minimum number of deletions to make a string palindrome | Java program for above approach ; Function to return minimum Element between two values ; Utility function for calculating Minimum element to delete ; Condition to compare characters ; Recursive function call ; Return value , increamenting by 1 ; Function to calculate the minimum Element required to delete for Making string pelindrom ; Utility function call ; Driver Code"
How can the above be solved in Java?

import java . io . * ; import java . util . * ; class GFG { public static int min ( int x , int y ) { return ( x < y ) ? x : y ; } public static int utility_fun_for_del ( String str , int i , int j ) { if ( i >= j ) return 0 ; if ( str . charAt ( i ) == str . charAt ( j ) ) { return utility_fun_for_del ( str , i + 1 , j - 1 ) ; } return 1 + Math . min ( utility_fun_for_del ( str , i + 1 , j ) , utility_fun_for_del ( str , i , j - 1 ) ) ; } public static int min_ele_del ( String str ) { return utility_fun_for_del ( str , 0 , str . length ( ) - 1 ) ; } public static void main ( String [ ] args ) { String str = " abefbac " ; System . out . println ( " Minimum ▁ element ▁ of ▁ deletions ▁ = ▁ " + min_ele_del ( str ) ) ; } }


"Minimum number of deletions to make a string palindrome | Set 2 | Java program to find minimum deletions to make palindrome . ; Find reverse of input string ; Create a DP table for storing edit distance of string and reverse . ; Find edit distance between input and revInput considering only delete operation . ; Go from bottom left to top right and find the minimum ; Driver Code"
How can the above be solved in Java?

import java . io . * ; import java . util . * ; class GFG { static int getLevenstein ( StringBuilder input ) { StringBuilder revInput = new StringBuilder ( input ) ; revInput = revInput . reverse ( ) ; int n = input . length ( ) ; int [ ] [ ] dp = new int [ n + 1 ] [ n + 1 ] ; for ( int i = 0 ; i <= n ; ++ i ) { dp [ 0 ] [ i ] = i ; dp [ i ] [ 0 ] = i ; } for ( int i = 1 ; i <= n ; ++ i ) { for ( int j = 1 ; j <= n ; ++ j ) { if ( input . charAt ( i - 1 ) == revInput . charAt ( j - 1 ) ) dp [ i ] [ j ] = dp [ i - 1 ] [ j - 1 ] ; else dp [ i ] [ j ] = 1 + Math . min ( dp [ i - 1 ] [ j ] , dp [ i ] [ j - 1 ] ) ; } } int res = Integer . MAX_VALUE ; for ( int i = n , j = 0 ; i >= 0 ; i -- , j ++ ) { res = Math . min ( res , dp [ i ] [ j ] ) ; if ( i < n ) res = Math . min ( res , dp [ i + 1 ] [ j ] ) ; if ( i > 0 ) res = Math . min ( res , dp [ i - 1 ] [ j ] ) ; } return res ; } public static void main ( String [ ] args ) { StringBuilder input = new StringBuilder ( " myfirstgeekarticle " ) ; System . out . println ( getLevenstein ( input ) ) ; } }


"Minimum number of digits required to be removed to make a number divisible by 4 | Java program for the above approach ; Function to count the minimum number of digits required to be removed to make a given number divisible by 4 ; Store the size of the string ; Stores the required result ; Check for every pair of digits if the number formed by them is divisible by 4 or not ; Store s [ i ] in a variable ; If it is divisible by 2 ; Store the number formed by s [ j ] and s [ i ] ; Check if it is divisible by 4 ; Store the number of digits required to be deleted ; Update ans ; If value of ans is unchanged , then check if any s [ i ] is divisible by 4 ; If true , update ans to n - 1 ; Print the result ; Driver Code"
How can the above be solved in Java?

import java . util . * ; class GFG { static void minimumDeletions ( String s ) { int n = s . length ( ) ; int ans = n ; for ( int i = n - 1 ; i >= 0 ; i -- ) { int t = s . charAt ( i ) - '0' ; if ( t % 2 == 0 ) { for ( int j = i - 1 ; j >= 0 ; j -- ) { int num = ( s . charAt ( j ) - '0' ) * 10 + t ; if ( num % 4 == 0 ) { int k1 = i - j - 1 ; int k2 = n - i - 1 ; ans = Math . min ( ans , k1 + k2 ) ; } } } } if ( ans == n ) { for ( int i = 0 ; i < n ; i ++ ) { int num = s . charAt ( i ) - '0' ; if ( num % 4 == 0 ) { ans = n - 1 ; } } } System . out . println ( ans ) ; } static public void main ( String [ ] args ) { String str = "12367" ; minimumDeletions ( str ) ; } }


"Minimum number of distinct elements after removing M items | Set 2 | Java program to implement the above approach ; Function to return minimum distinct character after M removals ; Count the occurences of number and store in count ; Count the occurences of the frequencies ; Take answer as total unique numbers and remove the frequency and subtract the answer ; Remove the minimum number of times ; Return the answer ; Driver code ; Initialize array ; Size of array ; Function call"
How can the above be solved in Java?

import java . util . * ; class GFG { static int distinctNumbers ( int arr [ ] , int m , int n ) { Map < Integer , Integer > count = new HashMap < Integer , Integer > ( ) ; for ( int i = 0 ; i < n ; i ++ ) count . put ( arr [ i ] , count . getOrDefault ( arr [ i ] , 0 ) + 1 ) ; int [ ] fre_arr = new int [ n + 1 ] ; for ( Integer it : count . values ( ) ) { fre_arr [ it ] ++ ; } int ans = count . size ( ) ; for ( int i = 1 ; i <= n ; i ++ ) { int temp = fre_arr [ i ] ; if ( temp == 0 ) continue ; int t = Math . min ( temp , m / i ) ; ans -= t ; m -= i * t ; } return ans ; } public static void main ( String [ ] args ) { int arr [ ] = { 2 , 4 , 1 , 5 , 3 , 5 , 1 , 3 } ; int n = arr . length ; int m = 2 ; System . out . println ( distinctNumbers ( arr , m , n ) ) ; } }


"Minimum number of distinct elements after removing m items | Java program for Minimum number of distinct elements after removing m items ; Function to find distintc id 's ; Store the occurrence of ids ; Start removing elements from the beginning ; Remove if current value is less than or equal to mi ; Return the remaining size ; Driver method to test above function"
How can the above be solved in Java?

import java . util . HashMap ; import java . util . Map ; import java . util . Map . Entry ; public class DistinctIds { static int distinctIds ( int arr [ ] , int n , int mi ) { Map < Integer , Integer > m = new HashMap < Integer , Integer > ( ) ; int count = 0 ; int size = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( m . containsKey ( arr [ i ] ) == false ) { m . put ( arr [ i ] , 1 ) ; size ++ ; } else m . put ( arr [ i ] , m . get ( arr [ i ] ) + 1 ) ; } for ( Entry < Integer , Integer > mp : m . entrySet ( ) ) { if ( mp . getKey ( ) <= mi ) { mi -= mp . getKey ( ) ; count ++ ; } else return size - count ; } return size - count ; } public static void main ( String [ ] args ) { int arr [ ] = { 2 , 3 , 1 , 2 , 3 , 3 } ; int m = 3 ; System . out . println ( distinctIds ( arr , arr . length , m ) ) ; } }


"Minimum number of distinct elements present in a K | Java program for the above approach ; Function to count the minimum number of distinct elements present in any subsequence of length K of the given array ; Stores the frequency of each array element ; Traverse the array ; Update frequency of array elements ; Store the required result ; Store the length of the required subsequence ; Store the frequencies in decreasing order ; Traverse the map ; Push the frequencies into the HashMap ; Sort the array in decreasing order ; Add the elements into the subsequence starting from one with highest frequency ; If length of subsequence is >= k ; Print the result ; Driver code ; Store the size of the array ; Function Call to count minimum number of distinct elmeents present in a K - length subsequence"
How can the above be solved in Java?

import java . util . * ; class GFG { static void findMinimumDistinct ( int A [ ] , int N , int K ) { Map < Integer , Integer > mp = new HashMap < > ( ) ; for ( int i = 0 ; i < N ; i ++ ) mp . put ( A [ i ] , mp . getOrDefault ( A [ i ] , 0 ) + 1 ) ; int count = 0 ; int len = 0 ; ArrayList < Integer > counts = new ArrayList < > ( ) ; for ( Map . Entry < Integer , Integer > i : mp . entrySet ( ) ) counts . add ( i . getValue ( ) ) ; Collections . sort ( counts , ( a , b ) -> b - a ) ; for ( int i = 0 ; i < counts . size ( ) ; i ++ ) { if ( len >= K ) break ; len += counts . get ( i ) ; count ++ ; } System . out . print ( count ) ; } public static void main ( String [ ] args ) { int A [ ] = { 3 , 1 , 3 , 2 , 3 , 4 , 5 , 4 } ; int K = 4 ; int N = A . length ; findMinimumDistinct ( A , N , K ) ; } }


"Minimum number of distinct powers of 2 required to express a given binary number | Java program to implement the above approach ; Function to return the minimum distinct powers of 2 required to express s ; Reverse the string to start from lower powers ; Check if the character is 1 ; Add in range provided range ; Initialize the counter ; Check if the character is not 0 ; Increment the counter ; Print the result ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { static void findMinimum ( String s ) { int n = s . length ( ) ; int [ ] x = new int [ n + 1 ] ; StringBuilder s2 = new StringBuilder ( s ) ; s2 . reverse ( ) ; String s3 = s2 . toString ( ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( s3 . charAt ( i ) == '1' ) { if ( x [ i ] == 1 ) { x [ i + 1 ] = 1 ; x [ i ] = 0 ; } else if ( 1 <= i && ( i & x [ i - 1 ] ) == 1 ) { x [ i + 1 ] = 1 ; x [ i - 1 ] = - 1 ; } else x [ i ] = 1 ; } } int c = 0 ; for ( int i = 0 ; i <= n ; i ++ ) { if ( x [ i ] != 0 ) c ++ ; } System . out . println ( c ) ; } public static void main ( String [ ] args ) { String str = "111" ; findMinimum ( str ) ; } }


"Minimum number of edges between two vertices of a Graph | Java program to find minimum edge between given two vertex of Graph ; Method for finding minimum no . of edge using BFS ; visited [ n ] for keeping track of visited node in BFS ; Initialize distances as 0 ; queue to do BFS . ; update distance for i ; method for addition of edge ; Driver method ; To store adjacency list of graph"
How can the above be solved in Java?

import java . util . LinkedList ; import java . util . Queue ; import java . util . Vector ; class Test { static int minEdgeBFS ( Vector < Integer > edges [ ] , int u , int v , int n ) { Vector < Boolean > visited = new Vector < Boolean > ( n ) ; for ( int i = 0 ; i < n ; i ++ ) { visited . addElement ( false ) ; } Vector < Integer > distance = new Vector < Integer > ( n ) ; for ( int i = 0 ; i < n ; i ++ ) { distance . addElement ( 0 ) ; } Queue < Integer > Q = new LinkedList < > ( ) ; distance . setElementAt ( 0 , u ) ; Q . add ( u ) ; visited . setElementAt ( true , u ) ; while ( ! Q . isEmpty ( ) ) { int x = Q . peek ( ) ; Q . poll ( ) ; for ( int i = 0 ; i < edges [ x ] . size ( ) ; i ++ ) { if ( visited . elementAt ( edges [ x ] . get ( i ) ) ) continue ; distance . setElementAt ( distance . get ( x ) + 1 , edges [ x ] . get ( i ) ) ; Q . add ( edges [ x ] . get ( i ) ) ; visited . setElementAt ( true , edges [ x ] . get ( i ) ) ; } } return distance . get ( v ) ; } static void addEdge ( Vector < Integer > edges [ ] , int u , int v ) { edges [ u ] . add ( v ) ; edges [ v ] . add ( u ) ; } public static void main ( String args [ ] ) { int n = 9 ; Vector < Integer > edges [ ] = new Vector [ 9 ] ; for ( int i = 0 ; i < edges . length ; i ++ ) { edges [ i ] = new Vector < > ( ) ; } addEdge ( edges , 0 , 1 ) ; addEdge ( edges , 0 , 7 ) ; addEdge ( edges , 1 , 7 ) ; addEdge ( edges , 1 , 2 ) ; addEdge ( edges , 2 , 3 ) ; addEdge ( edges , 2 , 5 ) ; addEdge ( edges , 2 , 8 ) ; addEdge ( edges , 3 , 4 ) ; addEdge ( edges , 3 , 5 ) ; addEdge ( edges , 4 , 5 ) ; addEdge ( edges , 5 , 6 ) ; addEdge ( edges , 6 , 7 ) ; addEdge ( edges , 7 , 8 ) ; int u = 0 ; int v = 5 ; System . out . println ( minEdgeBFS ( edges , u , v , n ) ) ; } }


"Minimum number of edges required to be removed from an Undirected Graph to make it acyclic | Java program to implement the above approach ; Stores the adjacency list ; Stores if a vertex is visited or not ; Function to perform DFS Traversal to count the number and size of all connected components ; Mark the current node as visited ; Traverse the adjacency list of the current node ; For every unvisited node ; Recursive DFS call ; Function to add undirected edge in the graph ; Function to calculate minimum number of edges to be removed ; Create Adjacency list ; Iterate over all the nodes ; Print the final count ; Driver Code"
How can the above be solved in Java?

 import java . util . * ; class GFG { @ SuppressWarnings ( " unchecked " ) static Vector < Integer > [ ] vec = new Vector [ 100001 ] ; static boolean [ ] vis = new boolean [ 100001 ] ; static int cc = 1 ; static void dfs ( int node ) { vis [ node ] = true ; for ( int x : vec [ node ] ) { if ( ! vis [ x ] ) { cc ++ ; dfs ( x ) ; } } } static void addEdge ( int u , int v ) { vec [ u ] . add ( v ) ; vec [ v ] . add ( u ) ; } static void minEdgeRemoved ( int N , int M , int Edges [ ] [ ] ) { for ( int i = 0 ; i < M ; i ++ ) { addEdge ( Edges [ i ] [ 0 ] , Edges [ i ] [ 1 ] ) ; } int k = 0 ; for ( int i = 1 ; i <= N ; i ++ ) { if ( ! vis [ i ] ) { cc = 1 ; dfs ( i ) ; k ++ ; } } System . out . print ( M - N + k + "
"); } public static void main ( String [ ] args ) { int N = 3 , M = 2 ; int Edges [ ] [ ] = { { 1 , 2 } , { 2 , 3 } } ; for ( int i = 0 ; i < vec . length ; i ++ ) vec [ i ] = new Vector < Integer > ( ) ; minEdgeRemoved ( N , M , Edges ) ; } }


"Minimum number of edges that need to be added to form a triangle | Java implementation of the approach ; Pair class ; Function to return the minimum number of edges that need to be added to the given graph such that it contains at least one triangle ; adj is the adjacency matrix such that adj [ i ] [ j ] = 1 when there is an edge between i and j ; As the graph is undirected so there will be an edge between ( i , j ) and ( j , i ) ; To store the required count of edges ; For every possible vertex triplet ; If the vertices form a triangle ; If no edges are present ; If only 1 edge is required ; Two edges are required ; Driver Code ; Number of nodes ; Storing the edges in a vector of pairs"
How can the above be solved in Java?

import java . io . * ; import java . util . * ; class Pair < V , E > { V first ; E second ; Pair ( V first , E second ) { this . first = first ; this . second = second ; } } class GFG { static int minEdges ( Vector < Pair < Integer , Integer > > v , int n ) { int [ ] [ ] adj = new int [ n + 1 ] [ n + 1 ] ; for ( int i = 0 ; i < v . size ( ) ; i ++ ) { adj [ v . elementAt ( i ) . first ] [ v . elementAt ( i ) . second ] = 1 ; adj [ v . elementAt ( i ) . second ] [ v . elementAt ( i ) . first ] = 1 ; } int edgesNeeded = 0 ; for ( int i = 1 ; i <= n ; i ++ ) { for ( int j = i + 1 ; j <= n ; j ++ ) { for ( int k = j + 1 ; k <= n ; k ++ ) { if ( adj [ i ] [ j ] == 1 && adj [ j ] [ k ] == 1 && adj [ k ] [ i ] == 1 ) return 0 ; if ( ! ( adj [ i ] [ j ] == 1 adj [ j ] [ k ] == 1 adj [ k ] [ i ] == 1 ) ) edgesNeeded = Math . min ( edgesNeeded , 3 ) ; else { if ( ( adj [ i ] [ j ] == 1 && adj [ j ] [ k ] == 1 ) || ( adj [ j ] [ k ] == 1 && adj [ k ] [ i ] == 1 ) || ( adj [ k ] [ i ] == 1 && adj [ i ] [ j ] == 1 ) ) { edgesNeeded = 1 ; } else edgesNeeded = Math . min ( edgesNeeded , 2 ) ; } } } } return edgesNeeded ; } public static void main ( String [ ] args ) { int n = 3 ; Vector < Pair < Integer , Integer > > v = new Vector < > ( Arrays . asList ( new Pair < > ( 1 , 2 ) , new Pair < > ( 1 , 3 ) ) ) ; System . out . println ( minEdges ( v , n ) ) ; } }


"Minimum number of elements that should be removed to make the array good | Java implementation of the approach ; Function to return the minimum number of elements that must be removed to make the given array good ; Count frequency of each element ; For each element check if there exists another element that makes a valid pair ; If does not exist then increment answer ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { static int minimumRemoval ( int n , int a [ ] ) { Map < Integer , Integer > c = new HashMap < > ( ) ; for ( int i = 0 ; i < n ; i ++ ) if ( c . containsKey ( a [ i ] ) ) { c . put ( a [ i ] , c . get ( a [ i ] ) + 1 ) ; } else { c . put ( a [ i ] , 1 ) ; } int ans = 0 ; for ( int i = 0 ; i < n ; i ++ ) { boolean ok = false ; for ( int j = 0 ; j < 31 ; j ++ ) { int x = ( 1 << j ) - a [ i ] ; if ( ( c . get ( x ) != null && ( c . get ( x ) > 1 ) ) || c . get ( x ) != null && ( c . get ( x ) == 1 && x != a [ i ] ) ) { ok = true ; break ; } } if ( ! ok ) ans ++ ; } return ans ; } public static void main ( String [ ] args ) { int a [ ] = { 4 , 7 , 1 , 5 , 4 , 9 } ; int n = a . length ; System . out . println ( minimumRemoval ( n , a ) ) ; } }


"Minimum number of elements to add to make median equals x | Java program to find minimum number of elements needs to add to the array so that its median equals x . ; Returns count of elements to be added to make median x . This function assumes that a [ ] has enough extra space . ; to sort the array in increasing order . ; Driver code"
How can the above be solved in Java?

import java . util . Arrays ; class GFG { static int minNumber ( int a [ ] , int n , int x ) { Arrays . sort ( a ) ; int k ; for ( k = 0 ; a [ ( n ) / 2 ] != x ; k ++ ) { a [ n ++ ] = x ; Arrays . sort ( a ) ; } return k ; } public static void main ( String [ ] args ) { int x = 10 ; int a [ ] = { 10 , 20 , 30 } ; int n = 3 ; System . out . println ( minNumber ( a , n - 1 , x ) ) ; } }


"Minimum number of elements to add to make median equals x | Java program to find minimum number of elements to add so that its median equals x . ; no . of elements equals to x , that is , e . ; no . of elements greater than x , that is , h . ; no . of elements smaller than x , that is , l . ; subtract the no . of elements that are equal to x . ; Driven Program"
How can the above be solved in Java?

import java . util . * ; import java . lang . * ; class GFG { public static int minNumber ( int a [ ] , int n , int x ) { int l = 0 , h = 0 , e = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( a [ i ] == x ) e ++ ; else if ( a [ i ] > x ) h ++ ; else if ( a [ i ] < x ) l ++ ; } int ans = 0 ; if ( l > h ) ans = l - h ; else if ( l < h ) ans = h - l - 1 ; return ans + 1 - e ; } public static void main ( String [ ] args ) { int x = 10 ; int a [ ] = { 10 , 20 , 30 } ; int n = a . length ; System . out . println ( minNumber ( a , n , x ) ) ; } }


"Minimum number of elements to be removed so that pairwise consecutive elements are same | Java implementation of the above approach ; Function to count the minimum number of elements to remove from a number so that pairwise two consecutive digits are same . ; initialize counting variable ; check if two consecutive digits are same ; Driver code"
How can the above be solved in Java?

class GFG { static int countConsecutive ( String s ) { int count = 0 ; for ( int i = 0 ; i < s . length ( ) ; i ++ ) { if ( s . charAt ( i ) == s . charAt ( i + 1 ) ) { i ++ ; } else { count ++ ; } } return count ; } public static void main ( String args [ ] ) { String str = "44522255" ; System . out . println ( countConsecutive ( str ) ) ; } }