"Minimum number of elements to be removed to make XOR maximum | Java implementation to find minimum number of elements to remove to get maximum XOR value ; First n in the below condition is for the case where n is 0 ; Function to find minimum number of elements to be removed . ; Driver code ; print minimum number of elements to be removed"
How can the above be solved in Java?

public class GFG { static int nextPowerOf2 ( int n ) { int count = 0 ; if ( n != 0 && ( n & ( n - 1 ) ) == 0 ) return n ; while ( n != 0 ) { n >>= 1 ; count += 1 ; } return 1 << count ; } static int removeElement ( int n ) { if ( n == 1 n == 2 ) return 0 ; int a = nextPowerOf2 ( n ) ; if ( n == a n == a - 1 ) return 1 ; else if ( n == a - 2 ) return 0 ; else if ( n % 2 == 0 ) return 1 ; else return 2 ; } public static void main ( String [ ] args ) { int n = 5 ; System . out . println ( removeElement ( n ) ) ; } }


"Minimum number of elements which are not part of Increasing or decreasing subsequence in array | Java program to return minimum number of elements which are not part of increasing or decreasing subsequences . ; Return minimum number of elements which is not part of any of the sequence . ; If already calculated , return value . ; If whole array is traversed . ; calculating by considering element as part of decreasing sequence . ; calculating by considering element as part of increasing sequence . ; If cannot be calculated for decreasing sequence . ; After considering once by decreasing sequence , now try for increasing sequence . ; If element cannot be part of any of the sequence . ; After considering element as part of increasing and decreasing sequence trying as not part of any of the sequence . ; Wrapper Function ; Adding two number at the end of array , so that increasing and decreasing sequence can be made . MAX - 2 index is assigned INT_MAX for decreasing sequence because next number of sequence must be less than it . Similarly , for Increasing sequence INT_MIN is assigned to MAX - 1 index . ; Driver Code"
How can the above be solved in Java?

import java . util . * ; class GFG { static int MAX = 102 ; static int countMin ( int arr [ ] , int dp [ ] [ ] [ ] , int n , int dec , int inc , int i ) { if ( dp [ dec ] [ inc ] [ i ] != - 1 ) return dp [ dec ] [ inc ] [ i ] ; if ( i == n ) return 0 ; if ( arr [ i ] < arr [ dec ] ) dp [ dec ] [ inc ] [ i ] = countMin ( arr , dp , n , i , inc , i + 1 ) ; if ( arr [ i ] > arr [ inc ] ) { if ( dp [ dec ] [ inc ] [ i ] == - 1 ) dp [ dec ] [ inc ] [ i ] = countMin ( arr , dp , n , dec , i , i + 1 ) ; else dp [ dec ] [ inc ] [ i ] = Math . min ( countMin ( arr , dp , n , dec , i , i + 1 ) , dp [ dec ] [ inc ] [ i ] ) ; } if ( dp [ dec ] [ inc ] [ i ] == - 1 ) dp [ dec ] [ inc ] [ i ] = 1 + countMin ( arr , dp , n , dec , inc , i + 1 ) ; else dp [ dec ] [ inc ] [ i ] = Math . min ( 1 + countMin ( arr , dp , n , dec , inc , i + 1 ) , dp [ dec ] [ inc ] [ i ] ) ; return dp [ dec ] [ inc ] [ i ] ; } static int wrapper ( int arr [ ] , int n ) { arr [ MAX - 2 ] = Integer . MAX_VALUE ; arr [ MAX - 1 ] = Integer . MIN_VALUE ; int [ ] [ ] [ ] dp = new int [ MAX ] [ MAX ] [ MAX ] ; for ( int i = 0 ; i < MAX ; i ++ ) { for ( int j = 0 ; j < MAX ; j ++ ) { for ( int l = 0 ; l < MAX ; l ++ ) dp [ i ] [ j ] [ l ] = - 1 ; } } return countMin ( arr , dp , n , MAX - 2 , MAX - 1 , 0 ) ; } public static void main ( String [ ] args ) { int n = 12 ; int [ ] arr = new int [ MAX ] ; arr [ 0 ] = 7 ; arr [ 1 ] = 8 ; arr [ 2 ] = 1 ; arr [ 3 ] = 2 ; arr [ 4 ] = 4 ; arr [ 5 ] = 6 ; arr [ 6 ] = 3 ; arr [ 7 ] = 5 ; arr [ 8 ] = 2 ; arr [ 9 ] = 1 ; arr [ 10 ] = 8 ; arr [ 11 ] = 7 ; System . out . println ( wrapper ( arr , n ) ) ; } }


"Minimum number of flipping adjacent bits required to make given Binary Strings equal | Java program for the above approach ; Function to find the minimum number of inversions required . ; Initializing the answer ; Iterate over the range ; If s1 [ i ] != s2 [ i ] , then inverse the characters at i snd ( i + 1 ) positions in s1 . ; Adding 1 to counter if characters are not same ; Driver Code"
How can the above be solved in Java?

 import java . util . * ; class GFG { static int find_Min_Inversion ( int n , char [ ] s1 , char [ ] s2 ) { int count = 0 ; for ( int i = 0 ; i < n - 1 ; i ++ ) { if ( s1 [ i ] != s2 [ i ] ) { if ( s1 [ i ] == '1' ) { s1 [ i ] = '0' ; } else { s1 [ i ] = '1' ; } if ( s1 [ i + 1 ] == '1' ) { s1 [ i + 1 ] = '0' ; } else { s1 [ i + 1 ] = '1' ; } count ++ ; } } if ( String . copyValueOf ( s1 ) . equals ( String . copyValueOf ( s2 ) ) ) { return count ; } return - 1 ; } public static void main ( String [ ] args ) { int n = 4 ; String s1 = "0101" ; String s2 = "1111" ; System . out . print ( find_Min_Inversion ( n , s1 . toCharArray ( ) , s2 . toCharArray ( ) ) + "
"); } }


"Minimum number of flips or swaps of adjacent characters required to make two strings equal | Java program for the above approach ; Function to count the minimum number of operations required to make strings A and B equal ; Stores all dp - states ; Update the value of A [ i ] ; Iterate over the range [ 1 , N ] ; If A [ i - 1 ] equals to B [ i - 1 ] ; Assign Dp [ i - 1 ] to Dp [ i ] ; Otherwise ; Update dp [ i ] ; If swapping is possible ; Update dp [ i ] ; Return the minimum number of steps required ; Driver code ; Given Input ; Function Call"
How can the above be solved in Java?

import java . io . * ; class GFG { static int countMinSteps ( String A , String B , int N ) { int [ ] dp = new int [ N + 1 ] ; for ( int i = 1 ; i <= N ; i ++ ) { dp [ i ] = 0 ; } for ( int i = 1 ; i <= N ; i ++ ) { if ( A . charAt ( i - 1 ) == B . charAt ( i - 1 ) ) { dp [ i ] = dp [ i - 1 ] ; } else { dp [ i ] = dp [ i - 1 ] + 1 ; } if ( i >= 2 && A . charAt ( i - 2 ) == B . charAt ( i - 1 ) && A . charAt ( i - 1 ) == B . charAt ( i - 2 ) ) { dp [ i ] = Math . min ( dp [ i ] , dp [ i - 2 ] + 1 ) ; } } return dp [ N ] ; } public static void main ( String [ ] args ) { String A = "0101" ; String B = "0011" ; int N = A . length ( ) ; System . out . println ( countMinSteps ( A , B , N ) ) ; } }


"Minimum number of flips required such that a Binary Matrix doesn 't contain any path from the top left to the bottom right consisting only of 0s | Java program for the above approach ; The four direction coordinates changes from the current cell ; Function that returns true if there exists any path from the top - left to the bottom - right cell of 0 s ; If the bottom - right cell is reached ; Update the cell to 1 ; Traverse in all four directions ; Find the new coordinates ; If the new cell is valid ; Recursively call DFS ; If path exists , then return true ; Return false , if there doesn 't  exists any such path ; Function to flip the minimum number of cells such that there doesn 't exists any such path from (0, 0) to (N - 1, M - 1) cell consisting of 0s ; Case 1 : If no such path exists already ; Case 2 : If there exists only one path ; Case 3 : If there exists two - path ; Driver code"
How can the above be solved in Java?

import java . io . * ; class GFG { static int [ ] [ ] direction = { { - 1 , 0 } , { 0 , 1 } , { 0 , - 1 } , { 1 , 0 } } ; static boolean dfs ( int matrix [ ] [ ] , int i , int j , int N , int M ) { if ( i == N - 1 && j == M - 1 ) { return true ; } matrix [ i ] [ j ] = 1 ; for ( int k = 0 ; k < 4 ; k ++ ) { int newX = i + direction [ k ] [ 0 ] ; int newY = j + direction [ k ] [ 1 ] ; if ( newX >= 0 && newX < N && newY >= 0 && newY < M && matrix [ newX ] [ newY ] == 0 ) { if ( dfs ( matrix , newX , newY , N , M ) ) { return true ; } } } return false ; } static int solve ( int [ ] [ ] matrix ) { int N = matrix . length ; int M = matrix [ 0 ] . length ; if ( ! dfs ( matrix , 0 , 0 , N , M ) ) { return 0 ; } if ( ! dfs ( matrix , 0 , 0 , N , M ) ) { return 1 ; } return 2 ; } public static void main ( String [ ] args ) { int [ ] [ ] mat = { { 0 , 1 , 0 , 0 } , { 0 , 1 , 0 , 0 } , { 0 , 0 , 0 , 0 } } ; System . out . println ( solve ( mat ) ) ; } }


"Minimum number of flips required such that the last cell of matrix can be reached from any other cell | Java program for the above approach ; Function to calculate the minimum number of flips required ; Dimensions of mat [ ] [ ] ; Initialize answer ; Count all ' D ' s in the last row ; Count all ' R ' s in the last column ; Print answer ; Driver Code ; Given matrix ; Function call ; Print answer"
How can the above be solved in Java?

import java . io . * ; class GFG { public static int countChanges ( char mat [ ] [ ] ) { int n = mat . length ; int m = mat [ 0 ] . length ; int ans = 0 ; for ( int j = 0 ; j < m - 1 ; j ++ ) { if ( mat [ n - 1 ] [ j ] != ' R ' ) ans ++ ; } for ( int i = 0 ; i < n - 1 ; i ++ ) { if ( mat [ i ] [ m - 1 ] != ' D ' ) ans ++ ; } return ans ; } public static void main ( String [ ] args ) { char arr [ ] [ ] = { { ' R ' , ' R ' , ' R ' , ' D ' } , { ' D ' , ' D ' , ' D ' , ' R ' } , { ' R ' , ' D ' , ' R ' , ' F ' } } ; int cnt = countChanges ( arr ) ; System . out . println ( cnt ) ; } }


"Minimum number of flips to make a Binary String increasing | Java program for the above approach ; ; Function to find the minimum number of flips required to make String increasing ; Length of s ; Total number of zero in s ; Stores count of 1 s till ith index ; stors the minimum count of flip ; Traverse the given String ; Update the value of res and count of 1 s ; Return the minimum number of flips ; Utility count ; Driver code ; Given String ; function call"
How can the above be solved in Java?

import java . util . * ; class GFG { static int minimumFlips ( String s ) { int n = s . length ( ) ; int cnt0 = count ( s , '0' ) ; int cnt1 = 0 ; int res = n - cnt0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( s . charAt ( i ) == '0' ) { cnt0 -= 1 ; } else if ( s . charAt ( i ) == '1' ) { res = Math . min ( res , cnt1 + cnt0 ) ; cnt1 ++ ; } } return res ; } private static int count ( String s , char c ) { int ans = 0 ; for ( char i : s . toCharArray ( ) ) if ( c == i ) ans ++ ; return ans ; } public static void main ( String [ ] args ) { String S = "000110" ; System . out . print ( minimumFlips ( S ) ) ; } }


"Minimum number of flips with rotation to make binary string alternating | Java program for the above approach ; Function that finds the minimum number of flips to make the binary string alternating if left circular rotation is allowed ; Initialize prefix arrays to store number of changes required to put 1 s at either even or odd position ; If i is odd ; Update the oddone and evenone count ; Else i is even ; Update the oddone and evenone count ; Initialize minimum flips ; Check if substring [ 0 , i ] is appended at end how many changes will be required ; Return minimum flips ; Driver Code ; Given String ; Length of given string ; Function call"
How can the above be solved in Java?

import java . util . * ; class GFG { static int MinimumFlips ( String s , int n ) { int [ ] a = new int [ n ] ; for ( int i = 0 ; i < n ; i ++ ) { a [ i ] = ( s . charAt ( i ) == '1' ? 1 : 0 ) ; } int [ ] oddone = new int [ n + 1 ] ; int [ ] evenone = new int [ n + 1 ] ; oddone [ 0 ] = 0 ; evenone [ 0 ] = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( i % 2 != 0 ) { oddone [ i + 1 ] = oddone [ i ] + ( a [ i ] == 1 ? 1 : 0 ) ; evenone [ i + 1 ] = evenone [ i ] + ( a [ i ] == 0 ? 1 : 0 ) ; } else { oddone [ i + 1 ] = oddone [ i ] + ( a [ i ] == 0 ? 1 : 0 ) ; evenone [ i + 1 ] = evenone [ i ] + ( a [ i ] == 1 ? 1 : 0 ) ; } } int minimum = Math . min ( oddone [ n ] , evenone [ n ] ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( n % 2 != 0 ) { minimum = Math . min ( minimum , oddone [ n ] - oddone [ i + 1 ] + evenone [ i + 1 ] ) ; minimum = Math . min ( minimum , evenone [ n ] - evenone [ i + 1 ] + oddone [ i + 1 ] ) ; } } return minimum ; } public static void main ( String [ ] args ) { String S = "000001100" ; int n = S . length ( ) ; System . out . print ( MinimumFlips ( S , n ) ) ; } }


"Minimum number of given moves required to make N divisible by 25 | Java implementation of the approach ; Function to return the minimum number of moves required to make n divisible by 25 ; Convert number into string ; To store required answer ; Length of the string ; To check all possible pairs ; Make a duplicate string ; Number of swaps required to place ith digit in last position ; Number of swaps required to place jth digit in 2 nd last position ; Find first non zero digit ; Place first non zero digit in the first position ; Convert string to number ; If this number is divisible by 25 then cur is one of the possible answer ; If not possible ; Driver code"
How can the above be solved in Java?

class GFG { static int minMoves ( int n ) { String s = Integer . toString ( n ) ; int ans = Integer . MAX_VALUE ; int len = s . length ( ) ; for ( int i = 0 ; i < len ; ++ i ) { for ( int j = 0 ; j < len ; ++ j ) { if ( i == j ) continue ; char t [ ] = s . toCharArray ( ) ; int cur = 0 ; for ( int k = i ; k < len - 1 ; ++ k ) { swap ( t , k , k + 1 ) ; ++ cur ; } for ( int k = j - ( ( j > i ) ? 1 : 0 ) ; k < len - 2 ; ++ k ) { swap ( t , k , k + 1 ) ; ++ cur ; } int pos = - 1 ; for ( int k = 0 ; k < len ; ++ k ) { if ( t [ k ] != '0' ) { pos = k ; break ; } } for ( int k = pos ; k > 0 ; -- k ) { swap ( t , k , k - 1 ) ; ++ cur ; } long nn = Integer . parseInt ( String . valueOf ( t ) ) ; if ( nn % 25 == 0 ) ans = Math . min ( ans , cur ) ; } } if ( ans == Integer . MAX_VALUE ) return - 1 ; return ans ; } static void swap ( char t [ ] , int i , int j ) { char temp = t [ i ] ; t [ i ] = t [ j ] ; t [ j ] = temp ; } public static void main ( String [ ] args ) { int n = 509201 ; System . out . println ( minMoves ( n ) ) ; } }


"Minimum number of given operation required to convert n to m | Java implementation of the approach ; Function to return the minimum operations required ; Counting all 2 s ; Counting all 3 s ; If q contained only 2 and 3 as the only prime factors then it must be 1 now ; Driver code"
How can the above be solved in Java?

class GfG { static int minOperations ( int n , int m ) { if ( m % n != 0 ) return - 1 ; int minOperations = 0 ; int q = m / n ; while ( q % 2 == 0 ) { q = q / 2 ; minOperations ++ ; } while ( q % 3 == 0 ) { q = q / 3 ; minOperations ++ ; } if ( q == 1 ) return minOperations ; return - 1 ; } public static void main ( String [ ] args ) { int n = 120 , m = 51840 ; System . out . println ( minOperations ( n , m ) ) ; } }


"Minimum number of given operations required to reduce a number to 2 | Java program for the above approach ; Function to find the minimum number of operations required to reduce n to 2 ; Initialize a dp array ; Handle the base case ; Iterate in the range [ 2 , n ] ; Check if i * 5 <= n ; Check if i + 3 <= n ; Return the result ; Driver code ; Given Input ; Function Call ; Print the result"
How can the above be solved in Java?

public class GFG { static int findMinOperations ( int n ) { int i = 0 ; int dp [ ] = new int [ n + 1 ] ; for ( i = 0 ; i < n + 1 ; i ++ ) { dp [ i ] = 999999 ; } dp [ 2 ] = 0 ; for ( i = 2 ; i < n + 1 ; i ++ ) { if ( i * 5 <= n ) { dp [ i * 5 ] = Math . min ( dp [ i * 5 ] , dp [ i ] + 1 ) ; } if ( i + 3 <= n ) { dp [ i + 3 ] = Math . min ( dp [ i + 3 ] , dp [ i ] + 1 ) ; } } return dp [ n ] ; } public static void main ( String [ ] args ) { int n = 28 ; int m = findMinOperations ( n ) ; if ( m != 9999 ) System . out . println ( m ) ; else System . out . println ( - 1 ) ; } }


"Minimum number of increment / decrement operations such that array contains all elements from 1 to N | Java implementation of the above approach ; Function to find the minimum operations ; Sort the given array ; Count operations by assigning a [ i ] = i + 1 ; Driver Code"
How can the above be solved in Java?

import java . util . * ; class solution { static long minimumMoves ( int a [ ] , int n ) { long operations = 0 ; Arrays . sort ( a ) ; for ( int i = 0 ; i < n ; i ++ ) operations += ( long ) Math . abs ( a [ i ] - ( i + 1 ) ) ; return operations ; } public static void main ( String args [ ] ) { int arr [ ] = { 5 , 3 , 2 } ; int n = arr . length ; System . out . print ( minimumMoves ( arr , n ) ) ; } }


"Minimum number of integers required such that each Segment contains at least one of them | Java program for the above approach ; Function to compute minimum number of points which cover all segments ; Sort the list of tuples by their second element . ; To store the solution ; Iterate over all the segments ; Get the start point of next segment ; Loop over all those segments whose start point is less than the end point of current segment ; Print the possibles values of M ; Driver code ; Starting points of segments ; Ending points of segments ; Insert ranges in points [ ] ; Function call"
How can the above be solved in Java?

import java . util . * ; class GFG { static void minPoints ( int [ ] [ ] points , int n ) { Arrays . sort ( points , ( a , b ) -> a [ 1 ] - b [ 1 ] ) ; ArrayList < Integer > coordinates = new ArrayList < > ( ) ; int i = 0 ; while ( i < n ) { int seg = points [ i ] [ 1 ] ; coordinates . add ( seg ) ; int p = i + 1 ; if ( p >= n ) break ; int arrived = points [ p ] [ 0 ] ; while ( seg >= arrived ) { p += 1 ; if ( p >= n ) break ; arrived = points [ p ] [ 0 ] ; } i = p ; } for ( Integer point : coordinates ) System . out . print ( point + " ▁ " ) ; } public static void main ( String [ ] args ) { int n = 4 ; int [ ] start = { 4 , 1 , 2 , 5 } ; int [ ] end = { 7 , 3 , 5 , 6 } ; int [ ] [ ] points = new int [ n ] [ 2 ] ; for ( int i = 0 ; i < n ; i ++ ) { points [ i ] [ 0 ] = start [ i ] ; points [ i ] [ 1 ] = end [ i ] ; } minPoints ( points , n ) ; } }


"Minimum number of jumps required to sort numbers placed on a number line | Java program for the above approach ; Function to find the minimum number of jumps required to sort the array ; Base Case ; Store the required result ; Stores the current position of elements and their respective maximum jump ; Used to check if a position is already taken by another element ; Stores the sorted array a [ ] ; Traverse the array w [ ] & update positions jumps array a [ ] ; Sort the array a [ ] ; Traverse the array a [ ] over the range [ 1 , N - 1 ] ; Store the index of current element and its just smaller element in array w [ ] ; Iterate until current element position is at most its just smaller element position ; Update the position of the current element ; Print the result ; Driver Code"
How can the above be solved in Java?

import java . util . * ; class GFG { static void minJumps ( int [ ] w , int [ ] l , int n ) { if ( n == 1 ) { System . out . print ( 0 ) ; return ; } int ans = 0 ; HashMap < Integer , Integer > pos = new HashMap < Integer , Integer > ( ) ; HashMap < Integer , Integer > jump = new HashMap < Integer , Integer > ( ) ; HashMap < Integer , Boolean > filled = new HashMap < Integer , Boolean > ( ) ; int [ ] a = new int [ n ] ; for ( int i = 0 ; i < n ; i ++ ) { if ( pos . containsKey ( w [ i ] ) ) pos . put ( w [ i ] , i ) ; else pos . put ( w [ i ] , i ) ; if ( filled . containsKey ( w [ i ] ) ) filled . put ( i , true ) ; else filled . put ( i , true ) ; if ( jump . containsKey ( w [ i ] ) ) jump . put ( w [ i ] , l [ i ] ) ; else jump . put ( w [ i ] , l [ i ] ) ; a [ i ] = w [ i ] ; } Arrays . sort ( a ) ; for ( int curr = 1 ; curr < n ; curr ++ ) { int currElementPos = pos . get ( a [ curr ] ) ; int prevElementPos = pos . get ( a [ curr - 1 ] ) ; if ( currElementPos > prevElementPos ) continue ; while ( currElementPos <= prevElementPos || filled . containsKey ( currElementPos ) && filled . containsKey ( currElementPos ) ) { currElementPos += jump . get ( a [ curr ] ) ; ans ++ ; } if ( pos . containsKey ( a [ curr ] ) ) pos . put ( a [ curr ] , currElementPos ) ; else pos . put ( a [ curr ] , currElementPos ) ; if ( filled . containsKey ( currElementPos ) ) filled . put ( currElementPos , true ) ; else filled . put ( currElementPos , true ) ; } System . out . print ( ans ) ; } public static void main ( String [ ] args ) { int [ ] W = { 2 , 1 , 4 , 3 } ; int [ ] L = { 4 , 1 , 2 , 4 } ; int N = W . length ; minJumps ( W , L , N ) ; } }


"Minimum number of jumps required to sort the given array in ascending order | Java program for the above approach ; Function to count minimum number of jumps required to sort the array ; Stores minimum number of jumps ; Stores distances of jumps ; Stores the array elements with their starting indices ; Push the pairs { arr [ i ] , i + 1 } into the vector of pairs vect ; Update vect ; Populate the array temp [ ] ; Update temp [ arr [ i ] ] ; Sort the vector in the ascending order ; Jump till the previous index <= current index ; Update vect [ i ] ; Increment the number of jumps ; Print the minimum number of jumps required ; Driver Code ; Input ; Size of the array"
How can the above be solved in Java?

import java . io . * ; import java . lang . * ; import java . util . * ; class GFG { static void minJumps ( int arr [ ] , int jump [ ] , int N ) { int jumps = 0 ; int temp [ ] = new int [ 1000 ] ; int vect [ ] [ ] = new int [ N ] [ 2 ] ; for ( int i = 0 ; i < N ; i ++ ) { vect [ i ] [ 0 ] = arr [ i ] ; vect [ i ] [ 1 ] = i + 1 ; } for ( int i = 0 ; i < N ; i ++ ) { temp [ arr [ i ] ] = jump [ i ] ; } Arrays . sort ( vect , ( a , b ) -> { if ( a [ 0 ] != b [ 0 ] ) return a [ 0 ] - b [ 0 ] ; return a [ 1 ] - b [ 1 ] ; } ) ; for ( int i = 1 ; i < N ; i ++ ) { while ( vect [ i ] [ 1 ] <= vect [ i - 1 ] [ 1 ] ) { vect [ i ] [ 0 ] = vect [ i ] [ 0 ] ; vect [ i ] [ 1 ] = vect [ i ] [ 1 ] + temp [ vect [ i ] [ 0 ] ] ; jumps ++ ; } } System . out . println ( jumps ) ; } public static void main ( String [ ] args ) { int arr [ ] = { 3 , 2 , 1 } ; int jump [ ] = { 1 , 1 , 1 } ; int N = arr . length ; minJumps ( arr , jump , N ) ; } }


"Minimum number of jumps to obtain an element of opposite parity | Java program for above approach ; Bfs for odd numbers are source ; Initialize queue ; Stores for each node , the nodes visited and their distances ; If parity is 0 -> odd Otherwise -> even ; Perform multi - source bfs ; Extract the front element of the queue ; Traverse nodes connected to the current node ; If u is not visited ; If element with opposite parity is obtained ; Store its distance from source in ans [ ] ; Push the current neighbour to the queue ; Function to find the minimum jumps required by each index to reach element of opposite parity ; Initialise Inverse Graph ; Stores the result for each index ; For the jumped index ; If the ind is valid then add reverse directed edge ; Multi - source bfs with odd numbers as source by passing 0 ; Multi - source bfs with even numbers as source by passing 1 ; Print the answer ; Driver function"
How can the above be solved in Java?

import java . util . * ; import java . lang . * ; class Gfg { static void bfs ( int n , int [ ] a , ArrayList < ArrayList < Integer > > invGr , int [ ] ans , int parity ) { Queue < Integer > q = new LinkedList < > ( ) ; int [ ] vis = new int [ n + 1 ] ; int [ ] dist = new int [ n + 1 ] ; for ( int i = 1 ; i <= n ; i ++ ) { if ( ( ( a [ i ] + parity ) & 1 ) != 0 ) { q . add ( i ) ; vis [ i ] = 1 ; } } while ( ! q . isEmpty ( ) ) { int v = q . peek ( ) ; q . poll ( ) ; for ( Integer u : invGr . get ( v ) ) { if ( vis [ u ] == 0 ) { dist [ u ] = dist [ v ] + 1 ; vis [ u ] = 1 ; if ( ( a [ u ] + parity ) % 2 == 0 ) { if ( ans [ u ] == - 1 ) ans [ u ] = dist [ u ] ; } q . add ( u ) ; } } } } static void minJumps ( int [ ] a , int [ ] jump , int n ) { ArrayList < ArrayList < Integer > > invGr = new ArrayList < > ( ) ; for ( int i = 0 ; i <= n ; i ++ ) invGr . add ( new ArrayList < Integer > ( ) ) ; int [ ] ans = new int [ n + 1 ] ; Arrays . fill ( ans , - 1 ) ; for ( int i = 1 ; i <= n ; i ++ ) { if ( i + jump [ i ] >= 1 && i + jump [ i ] <= n ) { invGr . get ( i + jump [ i ] ) . add ( i ) ; } if ( i - jump [ i ] >= 1 && i - jump [ i ] <= n ) { invGr . get ( i - jump [ i ] ) . add ( i ) ; } } bfs ( n , a , invGr , ans , 0 ) ; bfs ( n , a , invGr , ans , 1 ) ; for ( int i = 1 ; i <= n ; i ++ ) { System . out . print ( ans [ i ] + " ▁ " ) ; } } public static void main ( String [ ] args ) { int [ ] arr = { 0 , 4 , 2 , 5 , 2 , 1 } ; int [ ] jump = { 0 , 1 , 2 , 3 , 1 , 2 } ; int N = arr . length ; minJumps ( arr , jump , N - 1 ) ; } }


"Minimum number of jumps to reach end | Java program to find Minimum number of jumps to reach end ; Returns Minimum number of jumps to reach end ; jumps [ 0 ] will hold the result ; Minimum number of jumps needed to reach last element from last elements itself is always 0 ; Start from the second element , move from right to left and construct the jumps [ ] array where jumps [ i ] represents minimum number of jumps needed to reach arr [ m - 1 ] from arr [ i ] ; If arr [ i ] is 0 then arr [ n - 1 ] can 't be reached from here ; If we can direcly reach to the end point from here then jumps [ i ] is 1 ; Otherwise , to find out the minimum number of jumps needed to reach arr [ n - 1 ] , check all the points reachable from here and jumps [ ] value for those points ; initialize min value ; following loop checks with all reachable points and takes the minimum ; Handle overflow ; or Integer . MAX_VALUE ; Driver Code"
How can the above be solved in Java?

class GFG { static int minJumps ( int arr [ ] , int n ) { int [ ] jumps = new int [ n ] ; int min ; jumps [ n - 1 ] = 0 ; for ( int i = n - 2 ; i >= 0 ; i -- ) { if ( arr [ i ] == 0 ) jumps [ i ] = Integer . MAX_VALUE ; else if ( arr [ i ] >= n - i - 1 ) jumps [ i ] = 1 ; else { min = Integer . MAX_VALUE ; for ( int j = i + 1 ; j < n && j <= arr [ i ] + i ; j ++ ) { if ( min > jumps [ j ] ) min = jumps [ j ] ; } if ( min != Integer . MAX_VALUE ) jumps [ i ] = min + 1 ; else jumps [ i ] = min ; } } return jumps [ 0 ] ; } public static void main ( String [ ] args ) { int [ ] arr = { 1 , 3 , 6 , 1 , 0 , 9 } ; int size = arr . length ; System . out . println ( " Minimum ▁ number ▁ of " + " ▁ jumps ▁ to ▁ reach ▁ end ▁ is ▁ " + minJumps ( arr , size ) ) ; } }


"Minimum number of jumps to reach end | Java program to find Minimum number of jumps to reach end ; Returns minimum number of jumps to reach arr [ h ] from arr [ l ] ; Base case : when source and destination are same ; When nothing is reachable from the given source ; Traverse through all the points reachable from arr [ l ] . Recursively get the minimum number of jumps needed to reach arr [ h ] from these reachable points . ; Driver code"
How can the above be solved in Java?

import java . util . * ; import java . io . * ; class GFG { static int minJumps ( int arr [ ] , int l , int h ) { if ( h == l ) return 0 ; if ( arr [ l ] == 0 ) return Integer . MAX_VALUE ; int min = Integer . MAX_VALUE ; for ( int i = l + 1 ; i <= h && i <= l + arr [ l ] ; i ++ ) { int jumps = minJumps ( arr , i , h ) ; if ( jumps != Integer . MAX_VALUE && jumps + 1 < min ) min = jumps + 1 ; } return min ; } public static void main ( String args [ ] ) { int arr [ ] = { 1 , 3 , 6 , 3 , 2 , 3 , 6 , 8 , 9 , 5 } ; int n = arr . length ; System . out . print ( " Minimum ▁ number ▁ of ▁ jumps ▁ to ▁ reach ▁ end ▁ is ▁ " + minJumps ( arr , 0 , n - 1 ) ) ; } }


"Minimum number of leaves required to be removed from a Tree to satisfy the given condition | Java Program to find the minimum number of leaves to be deleted ; Stores the count of safe nodes ; Function to perform DFS on the Tree to obtain the count of vertices that are not required to be deleted ; Update cost to reach the vertex ; If the vertex does not satisfy the condition ; Otherwise ; Traverse its subtree ; Driver Code ; Stores the Tree ; Perform DFS ; Print the number of nodes to be deleted"
How can the above be solved in Java?

import java . util . * ; class GFG { static int cnt = 0 ; static void dfs ( int [ ] val , int [ ] cost , Vector < Integer > [ ] tr , int u , int s ) { s = s + cost [ u ] ; if ( s < 0 ) s = 0 ; if ( s > val [ u ] ) return ; cnt ++ ; for ( int i = 0 ; i < tr [ u ] . size ( ) ; i ++ ) { dfs ( val , cost , tr , tr [ u ] . get ( i ) , s ) ; } } public static void main ( String [ ] args ) { int n = 9 ; int val [ ] = { 88 , 22 , 83 , 14 , 95 , 91 , 98 , 53 , 11 } ; int cost [ ] = { - 1 , 24 , - 8 , 67 , 64 , 65 , 12 , - 80 , 8 } ; @ SuppressWarnings ( " unchecked " ) Vector < Integer > [ ] tr = new Vector [ n + 1 ] ; for ( int i = 0 ; i < tr . length ; i ++ ) tr [ i ] = new Vector < Integer > ( ) ; tr [ 0 ] . add ( 3 ) ; tr [ 0 ] . add ( 4 ) ; tr [ 4 ] . add ( 6 ) ; tr [ 6 ] . add ( 2 ) ; tr [ 2 ] . add ( 1 ) ; tr [ 2 ] . add ( 8 ) ; tr [ 8 ] . add ( 5 ) ; tr [ 5 ] . add ( 7 ) ; dfs ( val , cost , tr , 0 , 0 ) ; System . out . print ( n - cnt ) ; } }


"Minimum number of letters needed to make a total of n | Java implementation of the approach ; Function to return the minimum letters required to make a total of n ; Driver code"
How can the above be solved in Java?

class GFG { static int minLettersNeeded ( int n ) { if ( n % 26 == 0 ) return ( n / 26 ) ; else return ( ( n / 26 ) + 1 ) ; } public static void main ( String args [ ] ) { int n = 52 ; System . out . print ( minLettersNeeded ( n ) ) ; } }


"Minimum number of mails required to distribute all the questions | Java code to find the minimum number of mails ; Function returns the min no of mails required ; Using the formula derived above ; Driver Code ; no of questions ; no of students ; maximum no of questions a mail can hold ; Calling function"
How can the above be solved in Java?

 import java . io . * ; import java . util . * ; import java . lang . * ; class GFG { static double MinimumMail ( int n , int k , int x ) { double m = ( n - 1 ) + Math . ceil ( ( n - 1 ) * 1.0 / x ) * ( n - 1 ) + Math . ceil ( n * 1.0 / x ) * ( k - n ) ; return m ; } public static void main ( String [ ] args ) { int N = 4 ; int K = 9 ; int X = 2 ; System . out . print ( ( int ) MinimumMail ( N , K , X ) + "
"); } }


"Minimum number of moves required to reach the destination by the king in a chess board | Java program to Find the minimum number of moves required to reach the destination by the king in a chess board ; function to Find the minimum number of moves required to reach the destination by the king in a chess board ; minimum number of steps ; while the king is not in the same row or column as the destination ; Go up ; Go down ; Go left ; Go right ; Driver code"
How can the above be solved in Java?

import java . io . * ; class GFG { static void MinSteps ( int SourceX , int SourceY , int DestX , int DestY ) { System . out . println ( Math . max ( Math . abs ( SourceX - DestX ) , Math . abs ( SourceY - DestY ) ) ) ; while ( ( SourceX != DestX ) || ( SourceY != DestY ) ) { if ( SourceX < DestX ) { System . out . print ( ' U ' ) ; SourceX ++ ; } if ( SourceX > DestX ) { System . out . println ( ' D ' ) ; SourceX -- ; } if ( SourceY > DestY ) { System . out . print ( ' L ' ) ; SourceY -- ; } if ( SourceY < DestY ) { System . out . print ( ' R ' ) ; SourceY ++ ; } System . out . println ( ) ; } } public static void main ( String [ ] args ) { int sourceX = 4 , sourceY = 4 ; int destinationX = 7 , destinationY = 0 ; MinSteps ( sourceX , sourceY , destinationX , destinationY ) ; } }


"Minimum number of moves to make M and N equal by repeatedly adding any divisor of number to itself except 1 and the number | Java program for above approach ;  ; Function to find the minimum number of moves to make N and M equal . ; Array to maintain the numbers included . ; Pair of vertex , count ; Run bfs from N ; If we reached goal ; Iterate in the range ; If i is a factor of aux ; If i is less than M - aux and is not included earlier . ; If aux / i is less than M - aux and is not included earlier . ; Not possible ; Driver Code"
How can the above be solved in Java?

import java . util . * ; class GFG { static class pair < T , V > { T first ; V second ; } static pair < Integer , Integer > make_pair ( int f , int s ) { pair < Integer , Integer > p = new pair < > ( ) ; p . first = f ; p . second = s ; return p ; } static int countOperations ( int N , int M ) { boolean [ ] visited = new boolean [ 100001 ] ; Arrays . fill ( visited , false ) ; Queue < pair < Integer , Integer > > Q = new LinkedList < > ( ) ; Q . add ( make_pair ( N , 0 ) ) ; visited [ N ] = true ; while ( ! Q . isEmpty ( ) ) { int aux = Q . peek ( ) . first ; int cont = Q . peek ( ) . second ; Q . remove ( ) ; if ( aux == M ) return cont ; for ( int i = 2 ; i * i <= aux ; i ++ ) if ( aux % i == 0 ) { if ( aux + i <= M && ! visited [ aux + i ] ) { Q . add ( make_pair ( aux + i , cont + 1 ) ) ; visited [ aux + i ] = true ; } if ( aux + aux / i <= M && ! visited [ aux + aux / i ] ) { Q . add ( make_pair ( aux + aux / i , cont + 1 ) ) ; visited [ aux + aux / i ] = true ; } } } return - 1 ; } public static void main ( String [ ] args ) { int N = 4 , M = 24 ; System . out . println ( countOperations ( N , M ) ) ; } }


"Minimum number of moves to reach N starting from ( 1 , 1 ) | Java implementation of the approach ; Function to return the minimum number of moves required to reach the cell containing N starting from ( 1 , 1 ) ; To store the required answer ; For all possible values of divisors ; If i is a divisor of n ; Get the moves to reach n ; Return the required answer ; Driver code"
How can the above be solved in Java?

class GFG { static int min_moves ( int n ) { int ans = Integer . MAX_VALUE ; for ( int i = 1 ; i * i <= n ; i ++ ) { if ( n % i == 0 ) { ans = Math . min ( ans , i + n / i - 2 ) ; } } return ans ; } public static void main ( String [ ] args ) { int n = 10 ; System . out . println ( min_moves ( n ) ) ; } }


"Minimum number of operations on a binary string such that it gives 10 ^ A as remainder when divided by 10 ^ B | Java implementation of the approach ; Function to return the minimum number of operations on a binary string such that it gives 10 ^ A as remainder when divided by 10 ^ B ; Initialize result ; Loop through last b digits ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { static int findCount ( String s , int n , int a , int b ) { int res = 0 ; char [ ] s1 = s . toCharArray ( ) ; for ( int i = 0 ; i < b ; i ++ ) { if ( i == a ) { if ( s1 [ n - i - 1 ] != '1' ) res += 1 ; } else { if ( s1 [ n - i - 1 ] != '0' ) res += 1 ; } } return res ; } static public void main ( String [ ] args ) { String str = "1001011001" ; int N = str . length ( ) ; int A = 3 , B = 6 ; System . out . println ( findCount ( str , N , A , B ) ) ; } }


"Minimum number of operations required to delete all elements of the array | Java implementation of the above approach ; function to find minimum operations ; sort array ; prepare hash of array ; Driver program"
How can the above be solved in Java?

import java . util . * ; class Solution { static final int MAX = 10000 ; static int hashTable [ ] = new int [ MAX ] ; static int minOperations ( int arr [ ] , int n ) { Arrays . sort ( arr ) ; for ( int i = 0 ; i < n ; i ++ ) hashTable [ arr [ i ] ] ++ ; int res = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( hashTable [ arr [ i ] ] != 0 ) { for ( int j = i ; j < n ; j ++ ) if ( arr [ j ] % arr [ i ] == 0 ) hashTable [ arr [ j ] ] = 0 ; res ++ ; } } return res ; } public static void main ( String args [ ] ) { int arr [ ] = { 4 , 6 , 2 , 8 , 7 , 21 , 24 , 49 , 44 } ; int n = arr . length ; System . out . print ( minOperations ( arr , n ) ) ; } }


"Minimum number of operations required to make a permutation of first N natural numbers equal | Java program for the above approach ; Function to find the minimum number of operations required to make all array elements equal ; Store the count of operations required ; Increment by K - 1 , as the last element will be used again for the next K consecutive elements ; Increment count by 1 ; Return the result ; Driver Code ; Given Input"
How can the above be solved in Java?

import java . io . * ; class GFG { static int MinimumOperations ( int [ ] A , int N , int K ) { int Count = 0 ; int i = 0 ; while ( i < N - 1 ) { i = i + K - 1 ; Count ++ ; } return Count ; } public static void main ( String [ ] args ) { int [ ] A = { 5 , 4 , 3 , 1 , 2 } ; int K = 3 ; int N = A . length ; System . out . println ( MinimumOperations ( A , N , K ) ) ; } }


"Minimum number of operations required to make all elements of at least one row of given Matrix prime | Java program to implement the above approach ; Function to generate all prime numbers using Sieve of Eratosthenes ; Function to check if a number is prime or not ; prime [ i ] : Check if i is a prime number or not ; Initialize prime [ ] array to true ; Iterate over the range [ 2 , sqrt ( n ) ] ; If p is a prime number ; Mark all multiples of i to false ; Update i ; Function to find minimum operations to make all elements of at least one row of the matrix as prime numbers ; dp [ i ] : Stores minimum operations to get i prime numbers in a row ; Initialize dp [ ] array to ( n + 1 ) ; Traverse the array ; Stores count of prime numbers in a i - th row ; Iterate over the range [ ( 1 << m ) - 1 , 0 ] ; If a row exist which contains j prime numbers ; Update dp [ j bitmask ] ; Update dp [ bitmask ] ; Return minimum operations to get a row of the matrix with all prime numbers ; Function to count prime numbers in a row ; i - th bit of bitmask check if i - th column is a prime or not ; Traverse the array ; if a [ i ] is a prime number ; Update bitmask ; Driver Code ; Stores count of columns in the matrix ; Stores length ; Calculate all prime numbers in range [ 1 , max ] using sieve ; Function Call"
How can the above be solved in Java?

import java . io . * ; import java . util . * ; class GFG { private static boolean [ ] prime ; private static void sieve ( int n ) { prime = new boolean [ n + 1 ] ; Arrays . fill ( prime , true ) ; for ( int p = 2 ; p * p <= n ; p ++ ) { if ( prime [ p ] == true ) { for ( int i = p * p ; i <= n ; i += p ) prime [ i ] = false ; } } } private static int MinWays ( int [ ] [ ] a , int n , int m ) { int [ ] dp = new int [ 1 << m ] ; Arrays . fill ( dp , n + 1 ) ; for ( int i = 0 ; i < a . length ; i ++ ) { int bitmask = BitMask ( a [ i ] ) ; for ( int j = ( 1 << m ) - 1 ; j >= 0 ; j -- ) { if ( dp [ j ] != n + 1 ) { dp [ j bitmask ] = Math . min ( dp [ j bitmask ] , dp [ j ] + 1 ) ; } } dp [ bitmask ] = 1 ; } return ( dp [ ( 1 << m ) - 1 ] - 1 ) == ( n + 1 ) ? - 1 : ( dp [ ( 1 << m ) - 1 ] - 1 ) ; } private static int BitMask ( int [ ] a ) { int bitmask = 0 ; for ( int i = 0 ; i < a . length ; i ++ ) { if ( prime [ a [ i ] ] ) { bitmask |= ( 1 << i ) ; } } return bitmask ; } public static void main ( String [ ] args ) { int [ ] [ ] mat = { { 4 , 6 , 5 , 8 } , { 2 , 9 , 12 , 14 } , { 32 , 7 , 18 , 16 } , { 12 , 4 , 35 , 17 } } ; int m = mat [ 0 ] . length ; int n = mat . length ; int max = 10000 ; sieve ( max ) ; System . out . println ( MinWays ( mat , n , m ) ) ; } }


"Minimum number of operations required to make an array non | Java program for the above approach ; Function to count the minimum number of steps required to make arr non - decreasing ; Stores differences ; Stores the max number ; Traverse the array arr [ ] ; Update mx ; Update val ; Stores the result ; Iterate until 2 ^ res - 1 is less than val ; Return the answer ; Driver Code ; Given input ; Function call"
How can the above be solved in Java?

import java . io . * ; class GFG { static int countMinSteps ( int arr [ ] , int N ) { int val = 0 ; int mx = Integer . MIN_VALUE ; for ( int i = 0 ; i < N ; i ++ ) { int curr = arr [ i ] ; mx = Math . max ( mx , curr ) ; val = Math . max ( val , mx - curr ) ; } long res = 0 ; while ( ( 1 << res ) - 1 < val ) { ++ res ; } return ( int ) res ; } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 7 , 6 , 5 } ; int N = arr . length ; System . out . println ( countMinSteps ( arr , N ) ) ; } }


"Minimum number of operations required to make two strings equal | Java implementation to find the minimum number of operations to make two Strings equal ; Function to find out parent of an alphabet ; Function to merge two different alphabets ; Merge a and b using rank compression ; Function to find the minimum number of operations required ; Initializing parent to i and rank ( size ) to 1 ; We will store our answer in this vector ; Traversing Strings ; If they have different parents ; Find their respective parents and merge them ; Store this in our Answer vector ; Number of operations ; Driver Code ; Two Strings S1 and S2 ; Function call"
How can the above be solved in Java?

 import java . util . * ; class GFG { static final int MAX = 500001 ; static int [ ] parent = new int [ MAX ] ; static int [ ] Rank = new int [ MAX ] ; static class pair { char first , second ; public pair ( char first , char second ) { this . first = first ; this . second = second ; } } static int find ( int x ) { return parent [ x ] = parent [ x ] == x ? x : find ( parent [ x ] ) ; } static void merge ( int r1 , int r2 ) { if ( r1 != r2 ) { if ( Rank [ r1 ] > Rank [ r2 ] ) { parent [ r2 ] = r1 ; Rank [ r1 ] += Rank [ r2 ] ; } else { parent [ r1 ] = r2 ; Rank [ r2 ] += Rank [ r1 ] ; } } } static void minimumOperations ( String s1 , String s2 ) { for ( int i = 1 ; i <= 26 ; i ++ ) { parent [ i ] = i ; Rank [ i ] = 1 ; } Vector < pair > ans = new Vector < pair > ( ) ; for ( int i = 0 ; i < s1 . length ( ) ; i ++ ) { if ( s1 . charAt ( i ) != s2 . charAt ( i ) ) { if ( find ( s1 . charAt ( i ) - 96 ) != find ( s2 . charAt ( i ) - 96 ) ) { int x = find ( s1 . charAt ( i ) - 96 ) ; int y = find ( s2 . charAt ( i ) - 96 ) ; merge ( x , y ) ; ans . add ( new pair ( s1 . charAt ( i ) , s2 . charAt ( i ) ) ) ; } } } System . out . print ( ans . size ( ) + "
"); for ( int i = 0 ; i < ans . size ( ) ; i ++ ) System . out . print ( ans . get ( i ) . first + " - > " + ans . get ( i ) . second + "
"); } public static void main ( String [ ] args ) { String s1 , s2 ; s1 = " abb " ; s2 = " dad " ; minimumOperations ( s1 , s2 ) ; } }


"Minimum number of operations required to maximize the Binary String | Java program to implement the above approach ; Function to find the number of operations required ; Count of 1 's ; Count of 0 's upto (cnt1)-th index ; Return the answer ; Driver Code"
How can the above be solved in Java?

 class GFG { static int minOperation ( String s , int n ) { int cnt1 = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( s . charAt ( i ) == '1' ) cnt1 ++ ; } int cnt0 = 0 ; for ( int i = 0 ; i < cnt1 ; i ++ ) { if ( s . charAt ( i ) == '0' ) cnt0 ++ ; } return cnt0 ; } public static void main ( String [ ] args ) { int n = 8 ; String s = "01001011" ; int ans = minOperation ( s , n ) ; System . out . print ( ans + "
"); } }


"Minimum number of operations required to maximize the Binary String | Java program to implement the above approach ; Function to find the number of operations required ; Swap 0 ' s ▁ and ▁ 1' s ; 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 ) { int ans = 0 ; int i = 0 , j = n - 1 ; while ( i < j ) { if ( s . charAt ( i ) == '0' && s . charAt ( j ) == '1' ) { ans ++ ; i ++ ; j -- ; continue ; } if ( s . charAt ( i ) == '1' ) { i ++ ; } if ( s . charAt ( j ) == '0' ) { j -- ; } } return ans ; } public static void main ( String [ ] args ) { int n = 8 ; String s = "10100101" ; System . out . println ( minOperation ( s , n ) ) ; } }


"Minimum number of operations required to obtain a given Binary String | Java program to implement the above approach ; Function to find the minimum number of operations required to obtain the string s ; Iterate the string s ; If first occurrence of 1 is found ; Mark the index ; Base case : If no 1 occurred ; No operations required ; Stores the character for which last operation was performed ; Stores minimum number of operations ; Iterate from pos to n ; Check if s [ i ] is 0 ; Check if last operation was performed because of 1 ; Set last to 0 ; Check if last operation was performed because of 0 ; Set last to 1 ; Return the answer ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { static int minOperations ( String s ) { int n = s . length ( ) ; int pos = - 1 ; for ( int i = 0 ; i < s . length ( ) ; i ++ ) { if ( s . charAt ( i ) == '1' ) { pos = i ; break ; } } if ( pos == - 1 ) { return 0 ; } int last = 1 ; int ans = 1 ; for ( int i = pos + 1 ; i < n ; i ++ ) { if ( s . charAt ( i ) == '0' ) { if ( last == 1 ) { ans ++ ; last = 0 ; } } else { if ( last == 0 ) { ans ++ ; last = 1 ; } } } return ans ; } public static void main ( String [ ] args ) { String s = "10111" ; System . out . println ( minOperations ( s ) ) ; } }


"Minimum number of operations required to reduce N to 0 | Java Program to implement the above approach ; Function to find the minimum steps required to reduce n ; Base case ; Return answer based on parity of n ; Driver Code"
How can the above be solved in Java?

class GFG { static int downToZero ( int n ) { if ( n <= 3 ) return n ; return n % 2 == 0 ? 3 : 4 ; } public static void main ( String [ ] args ) { int n = 4 ; System . out . println ( downToZero ( n ) ) ; } }


"Minimum number of operations required to reduce N to 0 | Java program to implement the above approach ; Function to count the minimum steps required to reduce n ; Base case ; Allocate memory for storing intermediate results ; Store base values ; Stores square root of each number ; Compute square root ; Use rule 1 to find optimized answer ; Check if it perfectly divides n ; Use of rule 2 to find the optimized answer ; Store computed value ; Return answer ; Driver Code"
How can the above be solved in Java?

class GFG { static int downToZero ( int n ) { if ( n <= 3 ) return n ; int [ ] dp = new int [ n + 1 ] ; for ( int i = 0 ; i < n + 1 ; i ++ ) dp [ i ] = - 1 ; dp [ 0 ] = 0 ; dp [ 1 ] = 1 ; dp [ 2 ] = 2 ; dp [ 3 ] = 3 ; int sqr ; for ( int i = 4 ; i <= n ; i ++ ) { sqr = ( int ) Math . sqrt ( i ) ; int best = Integer . MAX_VALUE ; while ( sqr > 1 ) { if ( i % sqr == 0 ) { best = Math . min ( best , 1 + dp [ sqr ] ) ; } sqr -- ; } best = Math . min ( best , 1 + dp [ i - 1 ] ) ; dp [ i ] = best ; } return dp [ n ] ; } public static void main ( String [ ] args ) { int n = 4 ; System . out . print ( downToZero ( n ) ) ; } }


"Minimum number of operations required to reduce N to 1 | Java implementation of above approach ; Function that returns the minimum number of operations to be performed to reduce the number to 1 ; Base cases ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { public static int count_minimum_operations ( int n ) { if ( n == 2 ) { return 1 ; } else if ( n == 1 ) { return 0 ; } if ( n % 3 == 0 ) { return 1 + count_minimum_operations ( n / 3 ) ; } else if ( n % 3 == 1 ) { return 1 + count_minimum_operations ( n - 1 ) ; } else { return 1 + count_minimum_operations ( n + 1 ) ; } } public static void main ( String [ ] args ) { int n = 4 ; int ans = count_minimum_operations ( n ) ; System . out . println ( ans ) ; } }


"Minimum number of operations required to reduce N to 1 | Java implementation of above approach ; Function that returns the minimum number of operations to be performed to reduce the number to 1 ; To stores the total number of operations to be performed ; if n is divisible by 3 then reduce it to n / 3 ; if n modulo 3 is 1 decrement it by 1 ; if n modulo 3 is 2 then increment it by 1 ; update the counter ; Driver code"
How can the above be solved in Java?

class GFG { static int count_minimum_operations ( long n ) { int count = 0 ; while ( n > 1 ) { if ( n % 3 == 0 ) n /= 3 ; else if ( n % 3 == 1 ) n -- ; else { if ( n == 2 ) n -- ; else n ++ ; } count ++ ; } return count ; } public static void main ( String [ ] args ) { long n = 4 ; long ans = count_minimum_operations ( n ) ; System . out . println ( ans ) ; } }


"Minimum number of operations required to sum to binary string S | Java program to find the minimum number of operations required to sum to N ; Function to return the minimum operations required to sum to a number reprented by the binary string S ; Reverse the string to consider it from LSB to MSB ; initialise the dp table ; If S [ 0 ] = '0' , there is no need to perform any operation ; If S [ 0 ] = '1' , just perform a single operation ( i . e Add 2 ^ 0 ) ; Irrespective of the LSB , dp [ 0 ] [ 1 ] is always 1 as there is always the need of making the suffix of the binary string of the form "11 . . . . 1" as suggested by the definition of dp [ i ] [ 1 ] ; Transition from dp [ i - 1 ] [ 0 ] ; 1. Transition from dp [ i - 1 ] [ 1 ] by just doing 1 extra operation of subtracting 2 ^ i 2. Transition from dp [ i - 1 ] [ 0 ] by just doing 1 extra operation of subtracting 2 ^ ( i + 1 ) ; Transition from dp [ i - 1 ] [ 1 ] ; 1. Transition from dp [ i - 1 ] [ 1 ] by just doing 1 extra operation of adding 2 ^ ( i + 1 ) 2. Transition from dp [ i - 1 ] [ 0 ] by just doing 1 extra operation of adding 2 ^ i ; Swap values of left and right ; Driver Code"
How can the above be solved in Java?

class GFG { static int findMinOperations ( String S ) { S = reverse ( S ) ; int n = S . length ( ) ; int dp [ ] [ ] = new int [ n + 1 ] [ 2 ] ; if ( S . charAt ( 0 ) == '0' ) { dp [ 0 ] [ 0 ] = 0 ; } else { dp [ 0 ] [ 0 ] = 1 ; } dp [ 0 ] [ 1 ] = 1 ; for ( int i = 1 ; i < n ; i ++ ) { if ( S . charAt ( i ) == '0' ) { dp [ i ] [ 0 ] = dp [ i - 1 ] [ 0 ] ; dp [ i ] [ 1 ] = 1 + Math . min ( dp [ i - 1 ] [ 1 ] , dp [ i - 1 ] [ 0 ] ) ; } else { dp [ i ] [ 1 ] = dp [ i - 1 ] [ 1 ] ; dp [ i ] [ 0 ] = 1 + Math . min ( dp [ i - 1 ] [ 0 ] , dp [ i - 1 ] [ 1 ] ) ; } } return dp [ n - 1 ] [ 0 ] ; } static String reverse ( String input ) { char [ ] temparray = input . toCharArray ( ) ; int left , right = 0 ; right = temparray . length - 1 ; for ( left = 0 ; left < right ; left ++ , right -- ) { char temp = temparray [ left ] ; temparray [ left ] = temparray [ right ] ; temparray [ right ] = temp ; } return String . valueOf ( temparray ) ; } public static void main ( String [ ] args ) { String S = "100" ; System . out . println ( findMinOperations ( S ) ) ; S = "111" ; System . out . println ( findMinOperations ( S ) ) ; } }


"Minimum number of operations to convert a given sequence into a Geometric Progression | Java program to find minimum number of operations to convert a given sequence to an Geometric Progression ; Function to print the GP series ; Check for possibility ; Function for getting the Arithmetic Progression ; The array c describes all the given set of possible operations . ; Size of c ; candidate answer ; loop through all the permutations of the first two elements . ; a1 and a2 are the candidate first two elements of the possible GP . ; temp stores the current answer , including the modification of the first two elements . ; common ratio of the possible GP ; To check if the chosen set is valid , and id yes find the number of operations it takes . ; ai is value of a [ i ] according to the assumed first two elements a1 , a2 ith element of an GP = a1 * ( ( a2 - a1 ) ^ ( i - 1 ) ) ; Check for the " proposed " element to be only differing by one ; set the temporary ans ; to infinity and break ; update answer ; Calling function to print the sequence ; Driver Code ; array is 1 - indexed , with a [ 0 ] = 0 for the sake of simplicity ; Function to print the minimum operations and the sequence of elements"
How can the above be solved in Java?

 import java . util . * ; class GFG { static class pair { double first , second ; public pair ( double first , double second ) { this . first = first ; this . second = second ; } } static void construct ( int n , pair ans_pair ) { if ( ans_pair . first == - 1 ) { System . out . print ( " Not ▁ possible " ) ; return ; } double a1 = ans_pair . first ; double a2 = ans_pair . second ; double r = a2 / a1 ; System . out . print ( "The resultant sequence is:
"); for ( int i = 1 ; i <= n ; i ++ ) { int ai = ( int ) ( a1 * Math . pow ( r , i - 1 ) ) ; System . out . print ( ai + " ▁ " ) ; } } static void findMinimumOperations ( double [ ] a , int n ) { int ans = Integer . MAX_VALUE ; int c [ ] = { - 1 , 0 , 1 } ; int possibilities = 3 ; int pos1 = - 1 , pos2 = - 1 ; for ( int i = 0 ; i < possibilities ; i ++ ) { for ( int j = 0 ; j < possibilities ; j ++ ) { double a1 = a [ 1 ] + c [ i ] ; double a2 = a [ 2 ] + c [ j ] ; int temp = ( int ) ( Math . abs ( a1 - a [ 1 ] ) + Math . abs ( a2 - a [ 2 ] ) ) ; if ( a1 == 0 a2 == 0 ) continue ; double r = a2 / a1 ; for ( int pos = 3 ; pos <= n ; pos ++ ) { double ai = a1 * Math . pow ( r , pos - 1 ) ; if ( a [ pos ] == ai ) { continue ; } else if ( a [ pos ] + 1 == ai a [ pos ] - 1 == ai ) { temp ++ ; } else { temp = Integer . MAX_VALUE ; break ; } } if ( temp < ans ) { ans = temp ; pos1 = ( int ) a1 ; pos2 = ( int ) a2 ; } } } if ( ans == - 1 ) { System . out . print ( " - 1" ) ; return ; } System . out . print ( " Minimum ▁ Number ▁ of ▁ Operations ▁ are ▁ " + ans + "
"); pair ans_pair = new pair ( pos1 , pos2 ) ; construct ( n , ans_pair ) ; } public static void main ( String [ ] args ) { double a [ ] = { 0 , 7 , 20 , 49 , 125 } ; int n = a . length ; findMinimumOperations ( a , n - 1 ) ; } }


"Minimum number of operations to convert a given sequence into a Geometric Progression | Set 2 | Java program for the above approach ; Function to find minimum cost ; Sort the array ; Maximum possible common ratios ; Iterate over all possible common ratios ; Calculate operations required for the current common ratio ; Calculate minimum cost ; Driver Code ; Given N ; Given arr [ ] ; Function Calling"
How can the above be solved in Java?

 import java . util . * ; class GFG { static void minCost ( int arr [ ] , int n ) { if ( n == 1 ) { System . out . print ( 0 + "
"); return ; } Arrays . sort ( arr ) ; float raised = 1 / ( float ) ( n - 1 ) ; float temp = ( float ) Math . pow ( arr [ n - 1 ] , raised ) ; int r = ( int ) ( temp ) + 1 ; int i , j , min_cost = Integer . MAX_VALUE ; int common_ratio = 1 ; for ( j = 1 ; j <= r ; j ++ ) { int curr_cost = 0 , prod = 1 ; for ( i = 0 ; i < n ; i ++ ) { curr_cost += Math . abs ( arr [ i ] - prod ) ; prod *= j ; if ( curr_cost >= min_cost ) break ; } if ( i == n ) { min_cost = Math . min ( min_cost , curr_cost ) ; common_ratio = j ; } } System . out . print ( min_cost + " ▁ " ) ; System . out . print ( common_ratio + " ▁ " ) ; } public static void main ( String [ ] args ) { int N = 6 ; int arr [ ] = { 1 , 11 , 4 , 27 , 15 , 33 } ; minCost ( arr , N ) ; } }


"Minimum number of operations to convert array A to array B by adding an integer into a subarray | Java implementation to find the minimum number of operations in which the array A can be converted to another array B ; Function to find the minimum number of operations in which array A can be converted to array B ; Loop to iterate over the array ; if both elements are equal then move to next element ; Calculate the difference between two elements ; loop while the next pair of elements have same difference ; Increase the number of operations by 1 ; Print the number of operations required ; Driver Code"
How can the above be solved in Java?

class GFG { static void checkArray ( int a [ ] , int b [ ] , int n ) { int operations = 0 ; int i = 0 ; while ( i < n ) { if ( a [ i ] - b [ i ] == 0 ) { i ++ ; continue ; } int diff = a [ i ] - b [ i ] ; i ++ ; while ( i < n && a [ i ] - b [ i ] == diff ) { i ++ ; } operations ++ ; } System . out . println ( operations ) ; } public static void main ( String [ ] args ) { int a [ ] = { 3 , 7 , 1 , 4 , 1 , 2 } ; int b [ ] = { 3 , 7 , 3 , 6 , 3 , 2 } ; int size = a . length ; checkArray ( a , b , size ) ; } }


"Minimum number of palindromes required to express N as a sum | Set 2 | Java program to find the minimum number of palindromes required to express N as a sum ; A utility for creating palindrome ; checks if number of digits is odd or even if odd then neglect the last digit of input in finding reverse as in case of odd number of digits middle element occur once ; Creates palindrome by just appending reverse of number to itself ; Function to generate palindromes ; Run two times for odd and even length palindromes ; Creates palindrome numbers with first half as i . Value of j decides whether we need an odd length or even length palindrome . ; Swap values of left and right ; Function to find the minimum number of palindromes required to express N as a sum ; Checking if the number is a palindrome ; Checking if the number is a sum of two palindromes Getting the list of all palindromes upto N ; Sorting the list of palindromes ; The answer is three if the control reaches till this point ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { static int createPalindrome ( int input , int isOdd ) { int n = input ; int palin = input ; if ( isOdd % 2 == 1 ) { n /= 10 ; } while ( n > 0 ) { palin = palin * 10 + ( n % 10 ) ; n /= 10 ; } return palin ; } static Vector < Integer > generatePalindromes ( int N ) { Vector < Integer > palindromes = new Vector < > ( ) ; int number ; for ( int j = 0 ; j < 2 ; j ++ ) { int i = 1 ; while ( ( number = createPalindrome ( i ++ , j ) ) <= N ) { palindromes . add ( number ) ; } } return palindromes ; } static String reverse ( String input ) { char [ ] temparray = input . toCharArray ( ) ; int left , right = 0 ; right = temparray . length - 1 ; for ( left = 0 ; left < right ; left ++ , right -- ) { char temp = temparray [ left ] ; temparray [ left ] = temparray [ right ] ; temparray [ right ] = temp ; } return String . valueOf ( temparray ) ; } static int minimumNoOfPalindromes ( int N ) { String a = String . valueOf ( N ) ; String b = String . valueOf ( N ) ; b = reverse ( b ) ; if ( a . equals ( b ) ) { return 1 ; } Vector < Integer > palindromes = generatePalindromes ( N ) ; Collections . sort ( palindromes ) ; int l = 0 , r = palindromes . size ( ) - 1 ; while ( l < r ) { if ( palindromes . get ( l ) + palindromes . get ( r ) == N ) { return 2 ; } else if ( palindromes . get ( l ) + palindromes . get ( r ) < N ) { ++ l ; } else { -- r ; } } return 3 ; } public static void main ( String [ ] args ) { int N = 65 ; System . out . println ( minimumNoOfPalindromes ( N ) ) ; } }


"Minimum number of pigs required to find the poisonous bucket | Java program for the above approach ; Function to find the minimum number of pigs required to find the poisonous bucket ; Print the result ; Driver Code"
How can the above be solved in Java?

import java . io . * ; class GFG { static void poorPigs ( int buckets , int minutesToDie , int minutesToTest ) { System . out . print ( ( int ) Math . ceil ( Math . log ( buckets ) / Math . log ( ( minutesToTest / minutesToDie ) + 1 ) ) ) ; } public static void main ( String [ ] args ) { int N = 1000 , M = 15 , P = 60 ; poorPigs ( N , M , P ) ; } }


"Minimum number of power terms with sum equal to n | Java program to calculate minimum numberof powers of x to make sum equal to n . ; Return minimum power terms of x required ; if x is 1 , return n since any power of 1 is 1 only . ; Consider n = a * x + b where a = n / x and b = n % x . ; Update count of powers for 1 's added ; Repeat the process for reduced n ; Driver code"
How can the above be solved in Java?

class GFG { static int minPower ( int n , int x ) { if ( x == 1 ) return n ; int ans = 0 ; while ( n > 0 ) { ans += ( n % x ) ; n /= x ; } return ans ; } public static void main ( String [ ] args ) { int n = 5 , x = 3 ; System . out . println ( minPower ( n , x ) ) ; } }


"Minimum number of primes required such that their sum is equal to N | Java program for the above approach ; Function to check if n is prime ; Function to count the minimum prime required for given sum N ; Case 1 : ; Case 2 : ; Case 3 : ; Case 3 a : ; Case 3 b : ; Driver Code ; Function Call"
How can the above be solved in Java?

 class GFG { static boolean isPrime ( int n ) { for ( int i = 2 ; i * i <= n ; i ++ ) { if ( n % i == 0 ) { return false ; } } return true ; } static void printMinCountPrime ( int N ) { int minCount ; if ( isPrime ( N ) ) { minCount = 1 ; } else if ( N % 2 == 0 ) { minCount = 2 ; } else { if ( isPrime ( N - 2 ) ) { minCount = 2 ; } else { minCount = 3 ; } } System . out . print ( minCount + "
"); } public static void main ( String [ ] args ) { int N = 100 ; printMinCountPrime ( N ) ; } }


"Minimum number of removals required such that no subsequence of length 2 occurs more than once | Java program for the above approach ; Function to remove the minimum count of characters from the string such that no subsequence of length 2 repeats ; Initialize the final string ; Stores if any character occurs in the final string or not ; Store the index of the last character added in the string ; Traverse the string ; Add all the unique characters ; Check if S [ 0 ] appears in the range [ pos + 1 , N - 1 ] ; If the characters are the same ; Print the resultant string ; Driver code"
How can the above be solved in Java?

import java . io . * ; class GFG { static void RemoveCharacters ( String s ) { String ans = " " ; int [ ] c = new int [ 26 ] ; for ( int i = 0 ; i < 26 ; i ++ ) c [ i ] = 0 ; int pos = 0 ; for ( int i = 0 ; i < s . length ( ) ; i ++ ) { if ( c [ ( int ) s . charAt ( i ) - 97 ] == 0 ) { c [ ( int ) s . charAt ( i ) - 97 ] = 1 ; pos = i ; ans += s . charAt ( i ) ; } } for ( int i = pos + 1 ; i < s . length ( ) ; i ++ ) { if ( s . charAt ( i ) == s . charAt ( 0 ) ) { ans += s . charAt ( i ) ; break ; } } System . out . println ( ans ) ; } public static void main ( String [ ] args ) { String S = " abcaadbcd " ; RemoveCharacters ( S ) ; } }


"Minimum number of replacement done of substring "01" with "110" to remove it completely | Java program for the above approach ; Function to find the minimum number of replacement of "01" with "110" s . t . S doesn 't contain substring "10" ; Stores the number of operations performed ; Stores the resultant count of substrings ; Traverse the string S from end ; If the current character is 0 ; If the current character is 1 ; Print the result ; Driver Code"
How can the above be solved in Java?

import java . io . * ; class GFG { public static void minimumOperations ( String S , int N ) { int ans = 0 ; int cntOne = 0 ; for ( int i = N - 1 ; i >= 0 ; i -- ) { if ( S . charAt ( i ) == '0' ) { ans += cntOne ; cntOne *= 2 ; } else cntOne ++ ; } System . out . println ( ans ) ; } public static void main ( String [ ] args ) { String S = "001" ; int N = S . length ( ) ; minimumOperations ( S , N ) ; } }


"Minimum number of replacements to make the binary string alternating | Set 2 | Java implementation of the approach ; Function to return the minimum number of characters of the given binary string to be replaced to make the string alternating ; If there is 1 at even index positions ; If there is 0 at odd index positions ; Driver code"
How can the above be solved in Java?

class GFG { static int minReplacement ( String s , int len ) { int ans = 0 ; for ( int i = 0 ; i < len ; i ++ ) { if ( i % 2 == 0 && s . charAt ( i ) == '1' ) ans ++ ; if ( i % 2 == 1 && s . charAt ( i ) == '0' ) ans ++ ; } return Math . min ( ans , len - ans ) ; } public static void main ( String args [ ] ) { String s = "1100" ; int len = s . length ( ) ; System . out . print ( minReplacement ( s , len ) ) ; } }


"Minimum number of sets with numbers less than Y | Java program to find the minimum number sets with consecutive numbers and less than Y ; Function to find the minimum number of shets ; Variable to count the number of sets ; Iterate in the string ; Add the number to string ; Mark that we got a number ; else Every time it exceeds ; Check if previous was anytime less than Y ; Current number ; Check for current number ; Check for last added number ; Driver Code"
How can the above be solved in Java?

import java . util . * ; class solution { static int minimumSets ( String s , int y ) { int cnt = 0 ; int num = 0 ; int l = s . length ( ) ; boolean f = false ; for ( int i = 0 ; i < l ; i ++ ) { num = num * 10 + ( s . charAt ( i ) - '0' ) ; if ( num <= y ) f = true ; { if ( f ) cnt += 1 ; num = s . charAt ( i ) - '0' ; f = false ; if ( num <= y ) f = true ; else num = 0 ; } } if ( f == true ) cnt += 1 ; return cnt ; } public static void main ( String args [ ] ) { String s = "1234" ; int y = 30 ; System . out . println ( minimumSets ( s , y ) ) ; } }


"Minimum number of single digit primes required whose sum is equal to N | Java program to find the minimum number of single digit prime numbers required which when summed equals to a given number N . ; function to check if i - th index is valid or not ; function to find the minimum number of single digit prime numbers required which when summed up equals to a given number N . ; Not possible ; Driver Code"
How can the above be solved in Java?

class Geeks { static boolean check ( int i , int val ) { if ( i - val < 0 ) return false ; else return true ; } static double MinimumPrimes ( int n ) { double [ ] dp ; dp = new double [ n + 1 ] ; for ( int i = 1 ; i <= n ; i ++ ) dp [ i ] = 1e9 ; dp [ 0 ] = dp [ 2 ] = dp [ 3 ] = dp [ 5 ] = dp [ 7 ] = 1 ; for ( int i = 1 ; i <= n ; i ++ ) { if ( check ( i , 2 ) ) dp [ i ] = Math . min ( dp [ i ] , 1 + dp [ i - 2 ] ) ; if ( check ( i , 3 ) ) dp [ i ] = Math . min ( dp [ i ] , 1 + dp [ i - 3 ] ) ; if ( check ( i , 5 ) ) dp [ i ] = Math . min ( dp [ i ] , 1 + dp [ i - 5 ] ) ; if ( check ( i , 7 ) ) dp [ i ] = Math . min ( dp [ i ] , 1 + dp [ i - 7 ] ) ; } if ( dp [ n ] == ( 1e9 ) ) return - 1 ; else return dp [ n ] ; } public static void main ( String args [ ] ) { int n = 12 ; int minimal = ( int ) MinimumPrimes ( n ) ; if ( minimal != - 1 ) System . out . println ( " Minimum ▁ number ▁ of ▁ single ▁ " + " digit ▁ primes ▁ required : ▁ " + minimal ) ; else System . out . println ( " Not ▁ Possible " ) ; } }


"Minimum number of socks required to picked to have at least K pairs of the same color | Java program for the above approach ; Function to count the minimum number of socks to be picked ; Stores the total count of pairs of socks ; Find the total count of pairs ; If K is greater than pairs ; Otherwise ; Driver Code"
How can the above be solved in Java?

import java . io . * ; class GFG { public static int findMin ( int [ ] arr , int N , int k ) { int pairs = 0 ; for ( int i = 0 ; i < N ; i ++ ) { pairs += arr [ i ] / 2 ; } if ( k > pairs ) return - 1 ; else return 2 * k + N - 1 ; } public static void main ( String [ ] args ) { int [ ] arr = { 4 , 5 , 6 } ; int K = 3 ; int N = arr . length ; System . out . println ( findMin ( arr , N , K ) ) ; } }


"Minimum number of square tiles required to fill the rectangular floor | Java implementation of above approach ; Function to find the number of tiles ; if breadth is divisible by side of square ; tiles required is N / s ; one more tile required ; if length is divisible by side of square ; tiles required is M / s ; one more tile required ; Driver Code ; input length and breadth of rectangle and side of square"
How can the above be solved in Java?

import java . util . * ; import java . lang . * ; import java . io . * ; class GFG { static int solve ( int M , int N , int s ) { if ( N % s == 0 ) { N = N / s ; } else { N = ( N / s ) + 1 ; } if ( M % s == 0 ) { M = M / s ; } else { M = ( M / s ) + 1 ; } return M * N ; } public static void main ( String args [ ] ) { int N = 12 , M = 13 , s = 4 ; System . out . println ( solve ( M , N , s ) ) ; } }


"Minimum number of square tiles required to fill the rectangular floor | Java implementation of above approach ; Function to find the number of tiles ; no of tiles ; Driver Code ; input length and breadth of rectangle and side of square"
How can the above be solved in Java?

class GFG { static int solve ( double M , double N , double s ) { int ans = ( ( int ) ( Math . ceil ( M / s ) ) * ( int ) ( Math . ceil ( N / s ) ) ) ; return ans ; } public static void main ( String [ ] args ) { double N = 12 , M = 13 , s = 4 ; System . out . println ( solve ( M , N , s ) ) ; } }


"Minimum number of squares whose sum equals to a given number N | Set | Java program for the above approach ; Function that returns true if N is a perfect square ; Function that returns true check if N is sum of three squares ; Factor out the powers of 4 ; N is NOT of the form 4 ^ a * ( 8 b + 7 ) ; Function that finds the minimum number of square whose sum is N ; If N is perfect square ; If N is sum of 2 perfect squares ; If N is sum of 3 perfect squares ; Otherwise , N is the sum of 4 perfect squares ; Driver code ; Given number ; Function call"
How can the above be solved in Java?

import java . util . * ; class GFG { static boolean isPerfectSquare ( int N ) { int floorSqrt = ( int ) Math . sqrt ( N ) ; return ( N == floorSqrt * floorSqrt ) ; } static boolean legendreFunction ( int N ) { while ( N % 4 == 0 ) N /= 4 ; if ( N % 8 != 7 ) return true ; else return false ; } static int minSquares ( int N ) { if ( isPerfectSquare ( N ) ) return 1 ; for ( int i = 1 ; i * i < N ; i ++ ) { if ( isPerfectSquare ( N - i * i ) ) return 2 ; } if ( legendreFunction ( N ) ) return 3 ; return 4 ; } public static void main ( String [ ] args ) { int N = 123 ; System . out . print ( minSquares ( N ) ) ; } }


"Minimum number of squares whose sum equals to given number N | set 2 | Java program to represent N as the sum of minimum square numbers . ; Function for finding minimum square numbers ; A [ i ] of array arr store minimum count of square number to get i ; sqrNum [ i ] store last square number to get i ; Initialize ; Find minimum count of square number for all value 1 to n ; In worst case it will be arr [ i - 1 ] + 1 we use all combination of a [ i - 1 ] and add 1 ; Check for all square number less or equal to i ; if it gives less count then update it ; Vector v stores optimum square number whose sum give N ; Driver code ; Calling function ; Printing vector"
How can the above be solved in Java?

import java . util . * ; class GFG { static Vector < Integer > minSqrNum ( int n ) { int [ ] arr = new int [ n + 1 ] ; int k = 0 ; int [ ] sqrNum = new int [ n + 1 ] ; Vector < Integer > v = new Vector < > ( ) ; arr [ 0 ] = 0 ; sqrNum [ 0 ] = 0 ; for ( int i = 1 ; i <= n ; i ++ ) { arr [ i ] = arr [ i - 1 ] + 1 ; sqrNum [ i ] = 1 ; k = 1 ; while ( k * k <= i ) { if ( arr [ i ] > arr [ i - k * k ] + 1 ) { arr [ i ] = arr [ i - k * k ] + 1 ; sqrNum [ i ] = k * k ; } k ++ ; } } while ( n > 0 ) { v . add ( sqrNum [ n ] ) ; n -= sqrNum [ n ] ; } return v ; } public static void main ( String [ ] args ) { int n = 10 ; Vector < Integer > v ; v = minSqrNum ( n ) ; for ( int i = 0 ; i < v . size ( ) ; i ++ ) { System . out . print ( v . elementAt ( i ) ) ; if ( i + 1 != v . size ( ) ) System . out . print ( " ▁ + ▁ " ) ; } } }


"Minimum number of squares whose sum equals to given number n | A dynamic programming based JAVA program to find minimum number of squares whose sum is equal to a given number ; Returns count of minimum squares that sum to n ; We need to add a check here for n . If user enters 0 or 1 or 2 the below array creation will go OutOfBounds . ; Create a dynamic programming table to store sq ; getMinSquares table for base case entries ; getMinSquares rest of the table using recursive formula ; max value is i as i can always be represented as 1 * 1 + 1 * 1 + ... ; Go through all smaller numbers to to recursively find minimum ; Store result and free dp [ ] ; Driver Code"
How can the above be solved in Java?

class squares { static int getMinSquares ( int n ) { if ( n <= 3 ) return n ; int dp [ ] = new int [ n + 1 ] ; dp [ 0 ] = 0 ; dp [ 1 ] = 1 ; dp [ 2 ] = 2 ; dp [ 3 ] = 3 ; for ( int i = 4 ; i <= n ; i ++ ) { dp [ i ] = i ; for ( int x = 1 ; x <= Math . ceil ( Math . sqrt ( i ) ) ; x ++ ) { int temp = x * x ; if ( temp > i ) break ; else dp [ i ] = Math . min ( dp [ i ] , 1 + dp [ i - temp ] ) ; } } int res = dp [ n ] ; return res ; } public static void main ( String args [ ] ) { System . out . println ( getMinSquares ( 6 ) ) ; } }


"Minimum number of squares whose sum equals to given number n | A naive recursive JAVA program to find minimum number of squares whose sum is equal to a given number ; Returns count of minimum squares that sum to n ; base cases ; getMinSquares rest of the table using recursive formula Maximum squares required is ; n ( 1 * 1 + 1 * 1 + . . ) Go through all smaller numbers to recursively find minimum ; Driver code"
How can the above be solved in Java?

class squares { static int getMinSquares ( int n ) { if ( n <= 3 ) return n ; int res = n ; for ( int x = 1 ; x <= n ; x ++ ) { int temp = x * x ; if ( temp > n ) break ; else res = Math . min ( res , 1 + getMinSquares ( n - temp ) ) ; } return res ; } public static void main ( String args [ ] ) { System . out . println ( getMinSquares ( 6 ) ) ; } }


"Minimum number of squares whose sum equals to given number n | Java program for the above approach ; Function to count minimum squares that sum to n ; Creating visited vector of size n + 1 ; Queue of pair to store node and number of steps ; Initially ans variable is initialized with inf ; Push starting node with 0 0 indicate current number of step to reach n ; Mark starting node visited ; If node reaches its destination 0 update it with answer ; Loop for all possible path from 1 to i * i <= current node ( p . first ) ; If we are standing at some node then next node it can jump to will be current node - ( some square less than or equal n ) ; Check if it is valid and not visited yet ; Mark visited ; Push it it Queue ; Return ans to calling function ; Driver code"
How can the above be solved in Java?

import java . util . * ; import java . awt . Point ; class GFG { public static int numSquares ( int n ) { int visited [ ] = new int [ n + 1 ] ; Queue < Point > q = new LinkedList < > ( ) ; int ans = Integer . MAX_VALUE ; q . add ( new Point ( n , 0 ) ) ; visited [ n ] = 1 ; while ( q . size ( ) != 0 ) { Point p = q . peek ( ) ; q . poll ( ) ; if ( p . x == 0 ) ans = Math . min ( ans , p . y ) ; for ( int i = 1 ; i * i <= p . x ; i ++ ) { int path = ( p . x - ( i * i ) ) ; if ( path >= 0 && ( visited [ path ] == 0 path == 0 ) ) { visited [ path ] = 1 ; q . add ( new Point ( path , p . y + 1 ) ) ; } } } return ans ; } public static void main ( String [ ] args ) { System . out . println ( numSquares ( 12 ) ) ; } }


"Minimum number of steps required to obtain the given Array by the given operations | Java Program to implement the above approach ; Function to calculate the minimum steps to obtain the desired array ; Initialize variable ; Iterate over the array arr [ ] ; Check if i > 0 ; Update the answer ; Return the result ; Driver Code"
How can the above be solved in Java?

import java . util . * ; class GFG { static int min_operation ( int a [ ] , int n ) { int ans = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( i > 0 ) ans += Math . abs ( a [ i ] - a [ i - 1 ] ) ; else ans += Math . abs ( a [ i ] ) ; } return ans ; } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 2 , 3 , 4 } ; int n = arr . length ; System . out . print ( min_operation ( arr , n ) ) ; } }


"Minimum number of steps required to place all 1 s at a single index | Java program for the above approach ; Function to print minimum steps required to shift all 1 s to a single index in a binary array ; Size of array ; Used to store cumulative sum ; Initialize count ; Traverse the array in forward direction ; Steps needed to store all previous ones to ith index ; Count number of 1 s present till i - th index ; Initialize count ; Traverse the array in backward direction ; Steps needed to store all 1 s to the right of i at current index ; Count number of 1 s present after i - th index ; Print the number of steps required ; Driver code"
How can the above be solved in Java?

import java . util . * ; import java . lang . * ; class GFG { static void minsteps ( int [ ] A ) { int n = A . length ; int [ ] left = new int [ n ] ; Arrays . fill ( left , 0 ) ; int [ ] right = new int [ n ] ; Arrays . fill ( right , 0 ) ; int [ ] res = new int [ n ] ; Arrays . fill ( res , 0 ) ; int count = A [ 0 ] ; for ( int i = 1 ; i < n ; i ++ ) { left [ i ] = left [ i - 1 ] + count ; count += A [ i ] ; } count = A [ n - 1 ] ; for ( int i = n - 2 ; i >= 0 ; i -- ) { right [ i ] = right [ i + 1 ] + count ; count += A [ i ] ; } for ( int i = 0 ; i < n ; i ++ ) { res [ i ] = left [ i ] + right [ i ] ; System . out . print ( res [ i ] + " ▁ " ) ; } System . out . println ( ) ; } public static void main ( String [ ] args ) { int [ ] A = { 1 , 0 , 1 , 0 } ; minsteps ( A ) ; } }


"Minimum number of sub | Java implementation of the approach ; Function that returns true if n is a power of 5 ; Function to return the decimal value of binary equivalent ; Function to return the minimum cuts required ; Alongocating memory for dp [ ] array ; From length 1 to n ; If previous character is '0' then ignore to avoid number with leading 0 s . ; Ignore s [ j ] = '0' starting numbers ; Number formed from s [ j ... . i ] ; Check for power of 5 ; Assigning min value to get min cut possible ; ( n + 1 ) to check if all the Strings are traversed and no divisible by 5 is obtained like 000000 ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { static boolean ispower ( long n ) { if ( n < 125 ) { return ( n == 1 n == 5 n == 25 ) ; } if ( n % 125 != 0 ) { return false ; } else { return ispower ( n / 125 ) ; } } static long number ( String s , int i , int j ) { long ans = 0 ; for ( int x = i ; x < j ; x ++ ) { ans = ans * 2 + ( s . charAt ( x ) - '0' ) ; } return ans ; } static int minCuts ( String s , int n ) { int [ ] dp = new int [ n + 1 ] ; Arrays . fill ( dp , n + 1 ) ; dp [ 0 ] = 0 ; for ( int i = 1 ; i <= n ; i ++ ) { if ( s . charAt ( i - 1 ) == '0' ) { continue ; } for ( int j = 0 ; j < i ; j ++ ) { if ( s . charAt ( j ) == '0' ) { continue ; } long num = number ( s , j , i ) ; if ( ! ispower ( num ) ) { continue ; } dp [ i ] = Math . min ( dp [ i ] , dp [ j ] + 1 ) ; } } return ( ( dp [ n ] < n + 1 ) ? dp [ n ] : - 1 ) ; } public static void main ( String [ ] args ) { String s = "101101101" ; int n = s . length ( ) ; System . out . println ( minCuts ( s , n ) ) ; } }


"Minimum number of subsequences required to convert one string to another using Greedy Algorithm | Java implementation for minimum number of subsequences required to convert one String to another ; Function to find the minimum number of subsequences required to convert one String to another S2 == A and S1 == B ; At least 1 subsequence is required Even in best case , when A is same as B ; size of B ; size of A ; Create an 2D array next [ ] [ ] of size 26 * sizeOfB to store the next occurrence of a character ( ' a ' to ' z ' ) as an index [ 0 , sizeOfA - 1 ] ; Array Initialization with infinite ; Loop to Store the values of index ; If the value of next [ i ] [ j ] is infinite then update it with next [ i ] [ j + 1 ] ; Greedy algorithm to obtain the maximum possible subsequence of B to cover the remaining String of A using next subsequence ; Loop to iterate over the String A ; Condition to check if the character is not present in the String B ; Condition to check if there is an element in B matching with character A [ i ] on or next to B [ pos ] given by next [ A [ i ] - ' a ' ] [ pos ] ; Condition to check if reached at the end of B or no such element exists on or next to A [ pos ] , thus increment number by one and reinitialise pos to zero ; Driver Code"
How can the above be solved in Java?

class GFG { static int findMinimumSubsequences ( String A , String B ) { int numberOfSubsequences = 1 ; int sizeOfB = B . length ( ) ; int sizeOfA = A . length ( ) ; int inf = 1000000 ; int [ ] [ ] next = new int [ 26 ] [ sizeOfB ] ; for ( int i = 0 ; i < 26 ; i ++ ) { for ( int j = 0 ; j < sizeOfB ; j ++ ) { next [ i ] [ j ] = inf ; } } for ( int i = 0 ; i < sizeOfB ; i ++ ) { next [ B . charAt ( i ) - ' a ' ] [ i ] = i ; } for ( int i = 0 ; i < 26 ; i ++ ) { for ( int j = sizeOfB - 2 ; j >= 0 ; j -- ) { if ( next [ i ] [ j ] == inf ) { next [ i ] [ j ] = next [ i ] [ j + 1 ] ; } } } int pos = 0 ; int i = 0 ; while ( i < sizeOfA ) { if ( pos == 0 && next [ A . charAt ( i ) - ' a ' ] [ pos ] == inf ) { numberOfSubsequences = - 1 ; break ; } else if ( pos < sizeOfB && next [ A . charAt ( i ) - ' a ' ] [ pos ] < inf ) { int nextIndex = next [ A . charAt ( i ) - ' a ' ] [ pos ] + 1 ; pos = nextIndex ; i ++ ; } else { numberOfSubsequences ++ ; pos = 0 ; } } return numberOfSubsequences ; } public static void main ( String [ ] args ) { String A = " aacbe " ; String B = " aceab " ; System . out . print ( findMinimumSubsequences ( A , B ) ) ; } }


"Minimum number of subtract operation to make an array decreasing | Java program to make an array decreasing ; Function to count minimum no of operation ; Count how many times we have to subtract . ; Check an additional subtraction is required or not . ; Modify the value of arr [ i ] ; Count total no of subtraction ; driver function"
How can the above be solved in Java?

import java . util . * ; import java . lang . * ; public class GfG { public static int min_noOf_operation ( int arr [ ] , int n , int k ) { int noOfSubtraction ; int res = 0 ; for ( int i = 1 ; i < n ; i ++ ) { noOfSubtraction = 0 ; if ( arr [ i ] > arr [ i - 1 ] ) { noOfSubtraction = ( arr [ i ] - arr [ i - 1 ] ) / k ; if ( ( arr [ i ] - arr [ i - 1 ] ) % k != 0 ) noOfSubtraction ++ ; arr [ i ] = arr [ i ] - k * noOfSubtraction ; } res = res + noOfSubtraction ; } return res ; } public static void main ( String argc [ ] ) { int arr = { 1 , 1 , 2 , 3 } ; int N = 4 ; int k = 5 ; System . out . println ( min_noOf_operation ( arr , N , k ) ) ; } }


"Minimum number of sum and modulo operations using given numbers to reach target | Java implementation of the above approach ; Function to find the minimum moves to reach K from N ; Initialization of dp vector ; dp [ i ] = minimum pushes required to reach i ; Traversing through the buttons ; Iterating through all the positions ; If not visited ; Next status of lock ; Advance to next state ; Return the final dp [ target ] ; Driver function ; Given Input ; Function Call"
How can the above be solved in Java?

class GFG { static int minPushes ( int N , int K , int [ ] arr ) { int [ ] dp = new int [ 100000 ] ; for ( int i = 0 ; i < dp . length ; i ++ ) dp [ i ] = - 1 ; dp [ N ] = 0 ; for ( int i = 0 ; i < arr . length ; i ++ ) { for ( int xx = 0 ; xx < 100000 ; xx ++ ) { int x = xx ; if ( dp [ x ] == - 1 ) continue ; int next = ( x + arr [ i ] ) % 100000 ; while ( dp [ next ] == - 1 dp [ next ] > dp [ x ] + 1 ) { dp [ next ] = dp [ x ] + 1 ; x = next ; next = ( next + arr [ i ] ) % 100000 ; } } } return dp [ K ] ; } public static void main ( String [ ] args ) { int N = 99880 , K = 89 ; int [ ] arr = { 100 , 3 } ; System . out . print ( minPushes ( N , K , arr ) ) ; } }


"Minimum number of swaps required for arranging pairs adjacent to each other | Java program to find minimum number of swaps required so that all pairs become adjacent . ; This function updates indexes of elements ' a ' and ' b ' ; This function returns minimum number of swaps required to arrange all elements of arr [ i . . n ] become arranged ; If all pairs procesed so no swapping needed return 0 ; If current pair is valid so DO NOT DISTURB this pair and move ahead . ; Swap pair of arr [ i ] with arr [ i + 1 ] and recursively compute minimum swap required if this move is made . ; Backtrack to previous configuration . Also restore the previous indices , of one and two ; Now swap arr [ i ] with pair of arr [ i + 1 ] and recursively compute minimum swaps required for the subproblem after this move ; Backtrack to previous configuration . Also restore the previous indices , of one and two ; Return minimum of two cases ; Returns minimum swaps required ; To store indices of array elements ; Store index of each element in array index ; Call the recursive function ; Driver code ; For simplicity , it is assumed that arr [ 0 ] is not used . The elements from index 1 to n are only valid elements ; if ( a , b ) is pair than we have assigned elements in array such that pairs [ a ] = b and pairs [ b ] = a ; Number of pairs n is half of total elements ; If there are n elements in array , then there are n pairs"
How can the above be solved in Java?

class GFG { static void updateindex ( int index [ ] , int a , int ai , int b , int bi ) { index [ a ] = ai ; index [ b ] = bi ; } static int minSwapsUtil ( int arr [ ] , int pairs [ ] , int index [ ] , int i , int n ) { if ( i > n ) return 0 ; if ( pairs [ arr [ i ] ] == arr [ i + 1 ] ) return minSwapsUtil ( arr , pairs , index , i + 2 , n ) ; int one = arr [ i + 1 ] ; int indextwo = i + 1 ; int indexone = index [ pairs [ arr [ i ] ] ] ; int two = arr [ index [ pairs [ arr [ i ] ] ] ] ; arr [ i + 1 ] = arr [ i + 1 ] ^ arr [ indexone ] ^ ( arr [ indexone ] = arr [ i + 1 ] ) ; updateindex ( index , one , indexone , two , indextwo ) ; int a = minSwapsUtil ( arr , pairs , index , i + 2 , n ) ; arr [ i + 1 ] = arr [ i + 1 ] ^ arr [ indexone ] ^ ( arr [ indexone ] = arr [ i + 1 ] ) ; updateindex ( index , one , indextwo , two , indexone ) ; one = arr [ i ] ; indexone = index [ pairs [ arr [ i + 1 ] ] ] ; two = arr [ index [ pairs [ arr [ i + 1 ] ] ] ] ; indextwo = i ; arr [ i ] = arr [ i ] ^ arr [ indexone ] ^ ( arr [ indexone ] = arr [ i ] ) ; updateindex ( index , one , indexone , two , indextwo ) ; int b = minSwapsUtil ( arr , pairs , index , i + 2 , n ) ; arr [ i ] = arr [ i ] ^ arr [ indexone ] ^ ( arr [ indexone ] = arr [ i ] ) ; updateindex ( index , one , indextwo , two , indexone ) ; return 1 + Math . min ( a , b ) ; } static int minSwaps ( int n , int pairs [ ] , int arr [ ] ) { int index [ ] = new int [ 2 * n + 1 ] ; for ( int i = 1 ; i <= 2 * n ; i ++ ) index [ arr [ i ] ] = i ; return minSwapsUtil ( arr , pairs , index , 1 , 2 * n ) ; } public static void main ( String [ ] args ) { int arr [ ] = { 0 , 3 , 5 , 6 , 4 , 1 , 2 } ; int pairs [ ] = { 0 , 3 , 6 , 1 , 5 , 4 , 2 } ; int m = pairs . length ; int n = m / 2 ; System . out . print ( " Min ▁ swaps ▁ required ▁ is ▁ " + minSwaps ( n , pairs , arr ) ) ; } }


"Minimum number of swaps required such that a given substring consists of exactly K 1 s | Java program for the above approach ; Function to find the minimum number of swaps required such that the substring { s [ l ] , . . , s [ r ] } consists of exactly k 1 s ; Store the size of the string ; Store the total number of 1 s and 0 s in the entire string ; Traverse the string S to find the frequency of 1 and 0 ; Store the number of 1 s and 0 s in the substring s [ l , r ] ; Traverse the substring S [ l , r ] to find the frequency of 1 s and 0 s in it ; Store the count of 1 s and 0 s outside substring s [ l , r ] ; Check if the sum of the substring is at most K ; Store number of 1 s required ; Check if there are enough 1 s remaining to be swapped ; If the count of 1 s in the substring exceeds k ; Store the number of 0 s required ; Check if there are enough 0 s remaining to be swapped ; In all other cases , print - 1 ; Driver Code"
How can the above be solved in Java?

import java . io . * ; import java . util . * ; class GFG { static int minimumSwaps ( String s , int l , int r , int k ) { int n = s . length ( ) ; int tot_ones = 0 , tot_zeros = 0 ; for ( int i = 0 ; i < s . length ( ) ; i ++ ) { if ( s . charAt ( i ) == '1' ) tot_ones ++ ; else tot_zeros ++ ; } int ones = 0 , zeros = 0 , sum = 0 ; for ( int i = l - 1 ; i < r ; i ++ ) { if ( s . charAt ( i ) == '1' ) { ones ++ ; sum ++ ; } else zeros ++ ; } int rem_ones = tot_ones - ones ; int rem_zeros = tot_zeros - zeros ; if ( k >= sum ) { int rem = k - sum ; if ( zeros >= rem && rem_ones >= rem ) return rem ; } else if ( k < sum ) { int rem = sum - k ; if ( ones >= rem && rem_zeros >= rem ) return rem ; } return - 1 ; } public static void main ( String [ ] args ) { String S = "110011111000101" ; int L = 5 , R = 8 , K = 2 ; System . out . println ( minimumSwaps ( S , L , R , K ) ) ; } }


"Minimum number of swaps required to make a number divisible by 60 | Java program to find minimum number of swap operations required ; Function that print minimum number of swap operations required ; Condition if more than one zero exist ; Condition if zero_exist ; Computing total sum of all digits ; Condition if zero does not exist or the sum is not divisible by 3 ; Condition to find a digit that is multiple of 2 other than one zero ; Condition if multiple of 2 do not exist ; Condition for zero swaps means the number is already is divisible by 60 ; Condition for only one swap ; Otherwise 2 swaps required ; Driver Code"
How can the above be solved in Java?

class GFG { static void MinimumSwapOperations ( String s ) { boolean zero_exist = false ; boolean multiple_of_2 = false ; int sum = 0 ; int index_of_zero = 0 ; boolean more_zero = false ; for ( int i = 0 ; i < s . length ( ) ; i ++ ) { int val = s . charAt ( i ) - '0' ; if ( zero_exist == true ) more_zero = true ; if ( val == 0 ) { zero_exist = true ; index_of_zero = i ; } sum += val ; } if ( zero_exist == false sum % 3 != 0 ) { System . out . println ( " - 1" ) ; return ; } for ( int i = 0 ; i < s . length ( ) ; i ++ ) { int val = s . charAt ( i ) - '0' ; if ( val % 2 == 0 && i != index_of_zero ) multiple_of_2 = true ; } if ( multiple_of_2 == false ) { System . out . println ( " - 1" ) ; return ; } int last_val = s . charAt ( s . length ( ) - 1 ) - '0' ; int second_last_val = s . charAt ( s . length ( ) - 2 ) - '0' ; if ( last_val == 0 && second_last_val % 2 == 0 ) System . out . println ( 0 ) ; else if ( ( last_val == 0 && second_last_val % 2 != 0 ) || ( last_val % 2 == 0 && second_last_val == 0 ) ) System . out . println ( 1 ) ; else if ( more_zero == true && ( last_val == 0 && second_last_val % 2 != 0 ) ) System . out . println ( 1 ) ; else System . out . println ( 2 ) ; } public static void main ( String [ ] args ) { String N = "20" ; MinimumSwapOperations ( N ) ; } }


"Minimum number of swaps required to make parity of array elements same as their indices | Java program for the above approach ; Function to count the minimum number of swaps required to make the parity of array elements same as their indices ; Stores count of even and odd array elements ; Traverse the array ; Check if indices and array elements are not of the same parity ; If index is even ; Update even ; Update odd ; Condition for not possible ; Otherwise ; Driver Code"
How can the above be solved in Java?

import java . io . * ; import java . lang . * ; import java . util . * ; class GFG { static void minimumSwaps ( int arr [ ] , int N ) { int even = 0 , odd = 0 ; for ( int i = 0 ; i < N ; i ++ ) { if ( arr [ i ] % 2 != i % 2 ) { if ( i % 2 == 0 ) { even ++ ; } else { odd ++ ; } } } if ( even != odd ) { System . out . println ( - 1 ) ; } else { System . out . println ( even ) ; } } public static void main ( String [ ] args ) { int arr [ ] = { 3 , 2 , 7 , 6 } ; int N = arr . length ; minimumSwaps ( arr , N ) ; } }


"Minimum number of swaps required to make the string K periodic | Java code to find the minimum number of swaps required to make the String K periodic ; Mark all allowed characters as true ; Initialize the freq array to 0 ; Increase the frequency of each character ; Total number of periods of size K in the String ; Check if the current character is present in allowed and whether the current frequency is greater than all previous frequencies for this position ; Update the answer by subtracting the maxfrequency from total positions if there exist extra character at the end of the String apart from the n / k characters then add 1. ; Driver code"
How can the above be solved in Java?

 import java . util . * ; class GFG { static void minFlip ( String s , int n , int k , char a [ ] , int p ) { boolean allowed [ ] = new boolean [ 26 ] ; for ( int i = 0 ; i < p ; i ++ ) { allowed [ a [ i ] - ' a ' ] = true ; } char [ ] [ ] freq = new char [ k ] [ 26 ] ; for ( int i = 0 ; i < k ; i ++ ) for ( int j = 0 ; j < 26 ; j ++ ) freq [ i ] [ j ] = 0 ; for ( int i = 0 ; i < n ; i ++ ) { freq [ i % k ] [ s . charAt ( i ) - ' a ' ] += 1 ; } int ans = 0 ; int totalpositions = n / k ; for ( int i = 0 ; i < k ; i ++ ) { int maxfrequency = 0 ; for ( int j = 0 ; j < 26 ; j ++ ) { if ( freq [ i ] [ j ] > maxfrequency && allowed [ j ] == true ) maxfrequency = freq [ i ] [ j ] ; } ans += ( totalpositions - maxfrequency + ( ( i % k < n % k ) ? 1 : 0 ) ) ; } System . out . print ( ans + "
"); } public static void main ( String [ ] args ) { String S = " nihsiakyt " ; int n = S . length ( ) ; int K = 3 ; char [ ] A = { ' n ' , ' i ' , ' p ' , ' s ' , ' q ' } ; int p = A . length ; minFlip ( S , n , K , A , p ) ; } }


"Minimum number of swaps required to minimize sum of absolute differences between adjacent array elements | Java program for the above approach ; Pair class ; Function to find the minimum number of swaps required to sort the array in increasing order ; Stores the array elements with its index ; Sort the array in the increasing order ; Keeps the track of visited elements ; Stores the count of swaps required ; Traverse array elements ; If the element is already swapped or at correct position ; Find out the number of nodes in this cycle ; Update the value of j ; Move to the next element ; Increment cycle_size ; Update the ans by adding current cycle ; Function to find the minimum number of swaps required to sort the array in decreasing order ; Stores the array elements with its index ; Sort the array in the descending order ; Keeps track of visited elements ; Stores the count of resultant swap required ; Traverse array elements ; If the element is already swapped or at correct position ; Find out the number of node in this cycle ; Update the value of j ; Move to the next element ; Increment the cycle_size ; Update the ans by adding current cycle size ; Function to find minimum number of swaps required to minimize the sum of absolute difference of adjacent elements ; Sort in ascending order ; Sort in descending order ; Return the minimum value ; Driver code"
How can the above be solved in Java?

import java . lang . * ; import java . util . * ; class pair { int first , second ; pair ( int first , int second ) { this . first = first ; this . second = second ; } } class GFG { static int minSwapsAsc ( int [ ] arr , int n ) { pair [ ] arrPos = new pair [ n ] ; for ( int i = 0 ; i < n ; i ++ ) { arrPos [ i ] = new pair ( arr [ i ] , i ) ; } Arrays . sort ( arrPos , ( a , b ) -> a . first - b . first ) ; boolean [ ] vis = new boolean [ n ] ; int ans = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( vis [ i ] arrPos [ i ] . second == i ) continue ; int cycle_size = 0 ; int j = i ; while ( ! vis [ j ] ) { vis [ j ] = true ; j = arrPos [ j ] . second ; cycle_size ++ ; } if ( cycle_size > 0 ) { ans += ( cycle_size - 1 ) ; } } return ans ; } static int minSwapsDes ( int [ ] arr , int n ) { pair [ ] arrPos = new pair [ n ] ; for ( int i = 0 ; i < n ; i ++ ) { arrPos [ i ] = new pair ( arr [ i ] , i ) ; } Arrays . sort ( arrPos , ( a , b ) -> b . first - a . first ) ; boolean [ ] vis = new boolean [ n ] ; int ans = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( vis [ i ] arrPos [ i ] . second == i ) continue ; int cycle_size = 0 ; int j = i ; while ( ! vis [ j ] ) { vis [ j ] = true ; j = arrPos [ j ] . second ; cycle_size ++ ; } if ( cycle_size > 0 ) { ans += ( cycle_size - 1 ) ; } } return ans ; } static int minimumSwaps ( int [ ] arr ) { int S1 = minSwapsAsc ( arr , arr . length ) ; int S2 = minSwapsDes ( arr , arr . length ) ; return Math . min ( S1 , S2 ) ; } public static void main ( String [ ] args ) { int [ ] arr = { 3 , 4 , 2 , 5 , 1 } ; System . out . println ( minimumSwaps ( arr ) ) ; } }


"Minimum number of swaps required to sort an array | Java program to find minimum number of swaps required to sort an array ; Function returns the minimum number of swaps required to sort the array ; Create two arrays and use as pairs where first array is element and second array is position of first element ; Sort the array by array element values to get right position of every element as the elements of second array . ; To keep track of visited elements . Initialize all elements as not visited or false . ; Initialize result ; Traverse array elements ; already swapped and corrected or already present at correct pos ; find out the number of node in this cycle and add in ans ; move to next node ; Update answer by adding current cycle . ; Return result ; Driver class ; Driver program to test the above function"
How can the above be solved in Java?

import javafx . util . Pair ; import java . util . ArrayList ; import java . util . * ; class GfG { public static int minSwaps ( int [ ] arr ) { int n = arr . length ; ArrayList < Pair < Integer , Integer > > arrpos = new ArrayList < Pair < Integer , Integer > > ( ) ; for ( int i = 0 ; i < n ; i ++ ) arrpos . add ( new Pair < Integer , Integer > ( arr [ i ] , i ) ) ; arrpos . sort ( new Comparator < Pair < Integer , Integer > > ( ) { @ Override public int compare ( Pair < Integer , Integer > o1 , Pair < Integer , Integer > o2 ) { if ( o1 . getKey ( ) > o2 . getKey ( ) ) return - 1 ; else if ( o1 . getKey ( ) . equals ( o2 . getKey ( ) ) ) return 0 ; else return 1 ; } } ) ; Boolean [ ] vis = new Boolean [ n ] ; Arrays . fill ( vis , false ) ; int ans = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( vis [ i ] || arrpos . get ( i ) . getValue ( ) == i ) continue ; int cycle_size = 0 ; int j = i ; while ( ! vis [ j ] ) { vis [ j ] = true ; j = arrpos . get ( j ) . getValue ( ) ; cycle_size ++ ; } if ( cycle_size > 0 ) { ans += ( cycle_size - 1 ) ; } } return ans ; } } class MinSwaps { public static void main ( String [ ] args ) { int [ ] a = { 1 , 5 , 4 , 3 , 2 } ; GfG g = new GfG ( ) ; System . out . println ( g . minSwaps ( a ) ) ; } }


"Minimum number of swaps required to sort an array | Java program to find minimum number of swaps required to sort an array ; Return the minimum number of swaps required to sort the array ; Hashmap which stores the indexes of the input array ; This is checking whether the current element is at the right place or not ; If not , swap this element with the index of the element which should come here ; Update the indexes in the hashmap accordingly ; Driver class ; Driver program to test the above function ; Output will be 5"
How can the above be solved in Java?

import java . util . * ; import java . io . * ; class GfG { public int minSwaps ( int [ ] arr , int N ) { int ans = 0 ; int [ ] temp = Arrays . copyOfRange ( arr , 0 , N ) ; HashMap < Integer , Integer > h = new HashMap < Integer , Integer > ( ) ; Arrays . sort ( temp ) ; for ( int i = 0 ; i < N ; i ++ ) { h . put ( arr [ i ] , i ) ; } for ( int i = 0 ; i < N ; i ++ ) { if ( arr [ i ] != temp [ i ] ) { ans ++ ; int init = arr [ i ] ; swap ( arr , i , h . get ( temp [ i ] ) ) ; h . put ( init , h . get ( temp [ i ] ) ) ; h . put ( temp [ i ] , i ) ; } } return ans ; } public void swap ( int [ ] arr , int i , int j ) { int temp = arr [ i ] ; arr [ i ] = arr [ j ] ; arr [ j ] = temp ; } } class Main { public static void main ( String [ ] args ) throws Exception { int [ ] a = { 101 , 758 , 315 , 730 , 472 , 619 , 460 , 479 } ; int n = a . length ; System . out . println ( new GfG ( ) . minSwaps ( a , n ) ) ; } }