"Rat in a Maze Problem when movement in all possible directions is allowed | Java implementation of the above approach ; Vector to store all the possible paths ; Function returns true if the move taken is valid else it will return false . ; Function to print all the possible paths from ( 0 , 0 ) to ( n - 1 , n - 1 ) . ; This will check the initial point ( i . e . ( 0 , 0 ) ) to start the paths . ; If reach the last cell ( n - 1 , n - 1 ) then store the path and return ; Mark the cell as visited ; Check if downward move is valid ; Check if the left move is valid ; Check if the right move is valid ; Check if the upper move is valid ; Mark the cell as unvisited for other possible paths ; Function to store and print all the valid paths ; Call the utility function to find the valid paths ; Print all possible paths ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { static Vector < String > possiblePaths = new Vector < > ( ) ; static String path = " " ; static final int MAX = 5 ; static boolean isSafe ( int row , int col , int m [ ] [ ] , int n , boolean visited [ ] [ ] ) { if ( row == - 1 row == n col == - 1 col == n visited [ row ] [ col ] m [ row ] [ col ] == 0 ) return false ; return true ; } static void printPathUtil ( int row , int col , int m [ ] [ ] , int n , boolean visited [ ] [ ] ) { if ( row == - 1 row == n col == - 1 col == n visited [ row ] [ col ] m [ row ] [ col ] == 0 ) return ; if ( row == n - 1 && col == n - 1 ) { possiblePaths . add ( path ) ; return ; } visited [ row ] [ col ] = true ; if ( isSafe ( row + 1 , col , m , n , visited ) ) { path += ' D ' ; printPathUtil ( row + 1 , col , m , n , visited ) ; path = path . substring ( 0 , path . length ( ) - 1 ) ; } if ( isSafe ( row , col - 1 , m , n , visited ) ) { path += ' L ' ; printPathUtil ( row , col - 1 , m , n , visited ) ; path = path . substring ( 0 , path . length ( ) - 1 ) ; } if ( isSafe ( row , col + 1 , m , n , visited ) ) { path += ' R ' ; printPathUtil ( row , col + 1 , m , n , visited ) ; path = path . substring ( 0 , path . length ( ) - 1 ) ; } if ( isSafe ( row - 1 , col , m , n , visited ) ) { path += ' U ' ; printPathUtil ( row - 1 , col , m , n , visited ) ; path = path . substring ( 0 , path . length ( ) - 1 ) ; } visited [ row ] [ col ] = false ; } static void printPath ( int m [ ] [ ] , int n ) { boolean [ ] [ ] visited = new boolean [ n ] [ MAX ] ; printPathUtil ( 0 , 0 , m , n , visited ) ; for ( int i = 0 ; i < possiblePaths . size ( ) ; i ++ ) System . out . print ( possiblePaths . get ( i ) + " ▁ " ) ; } public static void main ( String [ ] args ) { int m [ ] [ ] = { { 1 , 0 , 0 , 0 , 0 } , { 1 , 1 , 1 , 1 , 1 } , { 1 , 1 , 1 , 0 , 1 } , { 0 , 0 , 0 , 0 , 1 } , { 0 , 0 , 0 , 0 , 1 } } ; int n = m . length ; printPath ( m , n ) ; } }


"Rat in a Maze with multiple steps or jump allowed | Java program to solve Rat in a Maze problem using backtracking ; Maze size ; A utility function to print solution matrix sol [ N ] [ N ] ; A utility function to check if x , y is valid index for N * N maze ; if ( x , y outside maze ) return false ; This function solves the Maze problem using Backtracking . It mainly uses solveMazeUtil ( ) to solve the problem . It returns false if no path is possible , otherwise return true and prints the path in the form of 1 s . Please note that there may be more than one solutions , this function prints one of the feasible solutions . ; A recursive utility function to solve Maze problem ; if ( x , y is goal ) return true ; Check if maze [ x ] [ y ] is valid ; mark x , y as part of solution path ; Move forward in x direction ; Move forward in x direction ; If moving in x direction doesn 't give  solution then Move down in y direction  ; If none of the above movements work then BACKTRACK : unmark x , y as part of solution path ; Driver Code"
How can the above be solved in Java?

 class GFG { static int N = 4 ; static void printSolution ( int sol [ ] [ ] ) { for ( int i = 0 ; i < N ; i ++ ) { for ( int j = 0 ; j < N ; j ++ ) { System . out . printf ( " ▁ % d ▁ " , sol [ i ] [ j ] ) ; } System . out . printf ( "
"); } } static boolean isSafe ( int maze [ ] [ ] , int x , int y ) { if ( x >= 0 && x < N && y >= 0 && y < N && maze [ x ] [ y ] != 0 ) { return true ; } return false ; } static boolean solveMaze ( int maze [ ] [ ] ) { int sol [ ] [ ] = { { 0 , 0 , 0 , 0 } , { 0 , 0 , 0 , 0 } , { 0 , 0 , 0 , 0 } , { 0 , 0 , 0 , 0 } } ; if ( solveMazeUtil ( maze , 0 , 0 , sol ) == false ) { System . out . printf ( " Solution ▁ doesn ' t ▁ exist " ) ; return false ; } printSolution ( sol ) ; return true ; } static boolean solveMazeUtil ( int maze [ ] [ ] , int x , int y , int sol [ ] [ ] ) { if ( x == N - 1 && y == N - 1 ) { sol [ x ] [ y ] = 1 ; return true ; } if ( isSafe ( maze , x , y ) == true ) { sol [ x ] [ y ] = 1 ; for ( int i = 1 ; i <= maze [ x ] [ y ] && i < N ; i ++ ) { if ( solveMazeUtil ( maze , x + i , y , sol ) == true ) { return true ; } if ( solveMazeUtil ( maze , x , y + i , sol ) == true ) { return true ; } } sol [ x ] [ y ] = 0 ; return false ; } return false ; } public static void main ( String [ ] args ) { int maze [ ] [ ] = { { 2 , 1 , 0 , 0 } , { 3 , 0 , 0 , 1 } , { 0 , 1 , 0 , 1 } , { 0 , 0 , 0 , 1 } } ; solveMaze ( maze ) ; } }


"Rat in a Maze | Backtracking using Stack | Java program to solve Rat in a maze problem with backtracking using stack ; default value for direction set to 0 ( Up ) ; maze of n * m matrix ; Driver code ; Initially setting the visited array to true ( unvisited ) ; Maze matrix ; Initially starting at ( 0 , 0 ) . ; Food coordinates Coordinates of food ; Pop the top node and move to the left , right , top , down or retract back according the value of node 's  dir variable. ; Increment the direction and push the node in the stack again . ; If we reach the Food coordinates return true ; Checking the Up direction . ; Checking the left direction ; Checking the down direction ; Checking the right direction ; If none of the direction can take the rat to the Food , retract back to the path where the rat came from . ; If the stack is empty and no path is found return false ."
How can the above be solved in Java?

 import java . util . Stack ; class Node { private int x , y ; private int dir ; public Node ( int i , int j ) { this . x = i ; this . y = j ; this . dir = 0 ; } public int getX ( ) { return x ; } public void setX ( int x ) { this . x = x ; } public int getY ( ) { return y ; } public void setY ( int y ) { this . y = y ; } public int getDir ( ) { return dir ; } public void setDir ( int dir ) { this . dir = dir ; } } public class RatInMaze { private static final int N = 4 ; private static final int M = 5 ; int n = N , m = M ; private static boolean [ ] [ ] visited = new boolean [ N ] [ M ] ; public static void main ( String [ ] args ) { setVisited ( true ) ; int maze [ ] [ ] = { { 1 , 0 , 1 , 1 , 0 } , { 1 , 1 , 1 , 0 , 1 } , { 0 , 1 , 0 , 1 , 1 } , { 1 , 1 , 1 , 1 , 1 } } ; if ( isReachable ( maze ) ) { System . out . println ( "Path Found!
"); } else System . out . println ( "No Path Found!
"); } private static void setVisited ( boolean b ) { for ( int i = 0 ; i < visited . length ; i ++ ) { for ( int j = 0 ; j < visited [ i ] . length ; j ++ ) { visited [ i ] [ j ] = b ; } } } private static boolean isReachable ( int maze [ ] [ ] ) { int i = 0 , j = 0 ; int fx , fy ; fx = 2 ; fy = 3 ; Stack < Node > s = new Stack < Node > ( ) ; Node temp = new Node ( i , j ) ; s . push ( temp ) ; while ( ! s . empty ( ) ) { temp = s . peek ( ) ; int d = temp . getDir ( ) ; i = temp . getX ( ) ; j = temp . getY ( ) ; temp . setDir ( temp . getDir ( ) + 1 ) ; s . pop ( ) ; s . push ( temp ) ; if ( i == fx && j == fy ) { return true ; } if ( d == 0 ) { if ( i - 1 >= 0 && maze [ i - 1 ] [ j ] == 1 && visited [ i - 1 ] [ j ] ) { Node temp1 = new Node ( i - 1 , j ) ; visited [ i - 1 ] [ j ] = false ; s . push ( temp1 ) ; } } else if ( d == 1 ) { if ( j - 1 >= 0 && maze [ i ] [ j - 1 ] == 1 && visited [ i ] [ j - 1 ] ) { Node temp1 = new Node ( i , j - 1 ) ; visited [ i ] [ j - 1 ] = false ; s . push ( temp1 ) ; } } else if ( d == 2 ) { if ( i + 1 < N && maze [ i + 1 ] [ j ] == 1 && visited [ i + 1 ] [ j ] ) { Node temp1 = new Node...


"Rat in a Maze | Backtracking | Java program to solve Rat in a Maze problem using backtracking ; Size of the maze ; A utility function to print solution matrix sol [ N ] [ N ] ; A utility function to check if x , y is valid index for N * N maze ; if ( x , y outside maze ) return false ; This function solves the Maze problem using Backtracking . It mainly uses solveMazeUtil ( ) to solve the problem . It returns false if no path is possible , otherwise return true and prints the path in the form of 1 s . Please note that there may be more than one solutions , this function prints one of the feasible solutions . ; A recursive utility function to solve Maze problem ; if ( x , y is goal ) return true ; Check if maze [ x ] [ y ] is valid ; Check if the current block is already part of solution path . ; mark x , y as part of solution path ; Move forward in x direction ; If moving in x direction doesn 't give  solution then Move down in y direction  ; If moving in y direction doesn 't give  solution then Move backwards in x direction  ; If moving backwards in x direction doesn 't give  solution then Move upwards in y direction  ; If none of the above movements works then BACKTRACK : unmark x , y as part of solution path ; driver program to test above function"
How can the above be solved in Java?

public class RatMaze { static int N ; void printSolution ( int sol [ ] [ ] ) { for ( int i = 0 ; i < N ; i ++ ) { for ( int j = 0 ; j < N ; j ++ ) System . out . print ( " ▁ " + sol [ i ] [ j ] + " ▁ " ) ; System . out . println ( ) ; } } boolean isSafe ( int maze [ ] [ ] , int x , int y ) { return ( x >= 0 && x < N && y >= 0 && y < N && maze [ x ] [ y ] == 1 ) ; } boolean solveMaze ( int maze [ ] [ ] ) { int sol [ ] [ ] = new int [ N ] [ N ] ; if ( solveMazeUtil ( maze , 0 , 0 , sol ) == false ) { System . out . print ( " Solution ▁ doesn ' t ▁ exist " ) ; return false ; } printSolution ( sol ) ; return true ; } boolean solveMazeUtil ( int maze [ ] [ ] , int x , int y , int sol [ ] [ ] ) { if ( x == N - 1 && y == N - 1 && maze [ x ] [ y ] == 1 ) { sol [ x ] [ y ] = 1 ; return true ; } if ( isSafe ( maze , x , y ) == true ) { if ( sol [ x ] [ y ] == 1 ) return false ; sol [ x ] [ y ] = 1 ; if ( solveMazeUtil ( maze , x + 1 , y , sol ) ) return true ; if ( solveMazeUtil ( maze , x , y + 1 , sol ) ) return true ; if ( solveMazeUtil ( maze , x - 1 , y , sol ) ) return true ; if ( solveMazeUtil ( maze , x , y - 1 , sol ) ) return true ; sol [ x ] [ y ] = 0 ; return false ; } return false ; } public static void main ( String args [ ] ) { RatMaze rat = new RatMaze ( ) ; int maze [ ] [ ] = { { 1 , 0 , 0 , 0 } , { 1 , 1 , 0 , 1 } , { 0 , 1 , 0 , 0 } , { 1 , 1 , 1 , 1 } } ; N = maze . length ; rat . solveMaze ( maze ) ; } }


"Ratio of area of two nested polygons formed by connecting midpoints of sides of a regular N | Java program for the above approach ; Function to calculate the ratio of area of N - th and ( N + 1 ) - th nested polygons formed by connecting midpoints ; Stores the value of PI ; Calculating area the factor ; Printing the ratio precise upto 6 decimal places ; Driver Code"
How can the above be solved in Java?

import java . io . * ; class GFG { static void AreaFactor ( int n ) { double pi = 3.14159265 ; double areaf = 1 / ( Math . cos ( pi / n ) * Math . cos ( pi / n ) ) ; System . out . format ( " % .6f " , areaf ) ; } public static void main ( String [ ] args ) { int n = 4 ; AreaFactor ( n ) ; } }


"Ratio of mth and nth terms of an A . P . with given ratio of sums | Java code to calculate ratio ; function to calculate ratio of mth and nth term ; ratio will be tm / tn = ( 2 * m - 1 ) / ( 2 * n - 1 ) ; Driver code"
How can the above be solved in Java?

import java . io . * ; class Nth { static float CalculateRatio ( float m , float n ) { return ( 2 * m - 1 ) / ( 2 * n - 1 ) ; } } class GFG { public static void main ( String [ ] args ) { float m = 6 , n = 2 ; Nth a = new Nth ( ) ; System . out . println ( a . CalculateRatio ( m , n ) ) ; } }


"Ratio of the distance between the centers of the circles and the point of intersection of two direct common tangents to the circles | Java program to find the ratio of the distance between the centers of the circles and the point of intersection of two direct common tangents to the circles which do not touch each other ; Function to find the GCD ; Function to find the ratio ; Driver code"
How can the above be solved in Java?

class GFG { static int GCD ( int a , int b ) { return ( b != 0 ? GCD ( b , a % b ) : a ) ; } static void ratiotang ( int r1 , int r2 ) { System . out . println ( " The ▁ ratio ▁ is ▁ " + r1 / GCD ( r1 , r2 ) + " ▁ : ▁ " + r2 / GCD ( r1 , r2 ) ) ; } public static void main ( String args [ ] ) { int r1 = 4 , r2 = 6 ; ratiotang ( r1 , r2 ) ; } }


"Ratio of the distance between the centers of the circles and the point of intersection of two transverse common tangents to the circles | Java program to find the ratio of the distance between the centres of the circles and the point of intersection of two transverse common tangents to the circles which do not touch each other ; Function to find the ratio ; Driver code"
How can the above be solved in Java?

import java . io . * ; class GFG { static int GCD ( int a , int b ) { return ( b != 0 ? GCD ( b , a % b ) : a ) ; } static void ratiotang ( int r1 , int r2 ) { System . out . println ( " The ▁ ratio ▁ is ▁ " + r1 / GCD ( r1 , r2 ) + " : " + r2 / GCD ( r1 , r2 ) ) ; } public static void main ( String [ ] args ) { int r1 = 4 , r2 = 8 ; ratiotang ( r1 , r2 ) ; } }


"Reallocation of elements based on Locality of Reference | Java program to implement search for an item that is searched again and again . ; A function to perform sequential search . ; Linearly search the element ; If not found ; Shift elements before one position ; Driver Code"
How can the above be solved in Java?

import java . util . * ; class solution { static boolean search ( int [ ] arr , int n , int x ) { int res = - 1 ; for ( int i = 0 ; i < n ; i ++ ) if ( x == arr [ i ] ) res = i ; if ( res == - 1 ) return false ; int temp = arr [ res ] ; for ( int i = res ; i > 0 ; i -- ) arr [ i ] = arr [ i - 1 ] ; arr [ 0 ] = temp ; return true ; } public static void main ( String args [ ] ) { int [ ] arr = { 12 , 25 , 36 , 85 , 98 , 75 , 89 , 15 , 63 , 66 , 64 , 74 , 27 , 83 , 97 } ; int [ ] q = { 63 , 63 , 86 , 63 , 78 } ; int n = arr . length ; int m = q . length ; for ( int i = 0 ; i < m ; i ++ ) { if ( search ( arr , n , q [ i ] ) == true ) System . out . print ( " Yes ▁ " ) ; else System . out . print ( " No ▁ " ) ; } } }


"Rearrange Odd and Even values in Alternate Fashion in Ascending Order | Java implementation of the above approach ; Collection . sort ( ) sorts the collection in ascending order ; Vector v1 = new Vector ( ) ; to insert even values Vector v2 = new Vector ( ) ; to insert odd values ; Set flag to true if first element is even ; Start rearranging array ; If first element is even ; Else , first element is Odd ; Print the rearranged array ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { static void AlternateRearrange ( int arr [ ] , int n ) { Arrays . sort ( arr ) ; for ( int i = 0 ; i < n ; i ++ ) if ( arr [ i ] % 2 == 0 ) v1 . add ( arr [ i ] ) ; else v2 . add ( arr [ i ] ) ; int index = 0 , i = 0 , j = 0 ; boolean flag = false ; if ( arr [ 0 ] % 2 == 0 ) flag = true ; while ( index < n ) { if ( flag == true ) { arr [ index ] = ( int ) v1 . get ( i ) ; i += 1 ; index += 1 ; flag = ! flag ; } else { arr [ index ] = ( int ) v2 . get ( j ) ; j += 1 ; index += 1 ; flag = ! flag ; } } for ( i = 0 ; i < n ; i ++ ) System . out . print ( arr [ i ] + " ▁ " ) ; } public static void main ( String [ ] args ) { int arr [ ] = { 9 , 8 , 13 , 2 , 19 , 14 } ; int n = arr . length ; AlternateRearrange ( arr , n ) ; } }


"Rearrange a Linked List in Zig | Java program for the above approach ; Node class ; Print Linked List ; Swap both nodes ; Rearrange the linked list in zig zag way ; Driver Code ; 0 means the current element should be smaller than the next"
How can the above be solved in Java?

import java . io . * ; class Node { int data ; Node next ; Node ( int data ) { this . data = data ; } } public class GFG { private Node head ; public void printLL ( ) { Node t = head ; while ( t != null ) { System . out . print ( t . data + " ▁ - > " ) ; t = t . next ; } System . out . println ( ) ; } public void swap ( Node a , Node b ) { if ( a == null b == null ) return ; int temp = a . data ; a . data = b . data ; b . data = temp ; } public Node zigZag ( Node node , int flag ) { if ( node == null node . next == null ) { return node ; } if ( flag == 0 ) { if ( node . data > node . next . data ) { swap ( node , node . next ) ; } return zigZag ( node . next , 1 ) ; } else { if ( node . data < node . next . data ) { swap ( node , node . next ) ; } return zigZag ( node . next , 0 ) ; } } public static void main ( String [ ] args ) { GFG lobj = new GFG ( ) ; lobj . head = new Node ( 11 ) ; lobj . head . next = new Node ( 15 ) ; lobj . head . next . next = new Node ( 20 ) ; lobj . head . next . next . next = new Node ( 5 ) ; lobj . head . next . next . next . next = new Node ( 10 ) ; lobj . printLL ( ) ; int flag = 0 ; lobj . zigZag ( lobj . head , flag ) ; System . out . println ( " LL ▁ in ▁ zig ▁ zag ▁ fashion ▁ : ▁ " ) ; lobj . printLL ( ) ; } }


"Rearrange a binary string as alternate x and y occurrences | Java program to arrange given string ; Function which arrange the given string ; Counting number of 0 ' s ▁ and ▁ 1' s in the given string . ; Printing first all 0 ' s ▁ x - times ▁ ▁ and ▁ decrement ▁ count ▁ of ▁ 0' s x - times and do the similar task with '1' ; Driver Code"
How can the above be solved in Java?

import java . io . * ; class GFG { static void arrangeString ( String str , int x , int y ) { int count_0 = 0 ; int count_1 = 0 ; int len = str . length ( ) ; for ( int i = 0 ; i < len ; i ++ ) { if ( str . charAt ( i ) == '0' ) count_0 ++ ; else count_1 ++ ; } while ( count_0 > 0 count_1 > 0 ) { for ( int j = 0 ; j < x && count_0 > 0 ; j ++ ) { if ( count_0 > 0 ) { System . out . print ( "0" ) ; count_0 -- ; } } for ( int j = 0 ; j < y && count_1 > 0 ; j ++ ) { if ( count_1 > 0 ) { System . out . print ( "1" ) ; count_1 -- ; } } } } public static void main ( String [ ] args ) { String str = "01101101101101101000000" ; int x = 1 ; int y = 2 ; arrangeString ( str , x , y ) ; } }


"Rearrange a linked list such that all even and odd positioned nodes are together | Java program to rearrange a linked list in such a way that all odd positioned node are stored before all even positioned nodes ; Linked List Node ; A utility function to create a new node ; Rearranges given linked list such that all even positioned nodes are before odd positioned . Returns new head of linked List . ; Corner case ; Initialize first nodes of even and odd lists ; Remember the first node of even list so that we can connect the even list at the end of odd list . ; If there are no more nodes , then connect first node of even list to the last node of odd list ; Connecting odd nodes ; If there are NO more even nodes after current odd . ; Connecting even nodes ; A utility function to print a linked list ; Driver code"
How can the above be solved in Java?

class GfG { static class Node { int data ; Node next ; } static Node newNode ( int key ) { Node temp = new Node ( ) ; temp . data = key ; temp . next = null ; return temp ; } static Node rearrangeEvenOdd ( Node head ) { if ( head == null ) return null ; Node odd = head ; Node even = head . next ; Node evenFirst = even ; while ( 1 == 1 ) { if ( odd == null || even == null || ( even . next ) == null ) { odd . next = evenFirst ; break ; } odd . next = even . next ; odd = even . next ; if ( odd . next == null ) { even . next = null ; odd . next = evenFirst ; break ; } even . next = odd . next ; even = odd . next ; } return head ; } static void printlist ( Node node ) { while ( node != null ) { System . out . print ( node . data + " - > " ) ; node = node . next ; } System . out . println ( " NULL " ) ; } public static void main ( String [ ] args ) { Node head = newNode ( 1 ) ; head . next = newNode ( 2 ) ; head . next . next = newNode ( 3 ) ; head . next . next . next = newNode ( 4 ) ; head . next . next . next . next = newNode ( 5 ) ; System . out . println ( " Given ▁ Linked ▁ List " ) ; printlist ( head ) ; head = rearrangeEvenOdd ( head ) ; System . out . println ( " Modified ▁ Linked ▁ List " ) ; printlist ( head ) ; } }


"Rearrange a string S1 such that another given string S2 is not its subsequence | Java program for the above approach ; Function to rearrange characters in string S1 such that S2 is not a subsequence of it ; Store the frequencies of characters of string s2 ; Traverse the string s2 ; Update the frequency ; Find the number of unique characters in s2 ; Increment unique by 1 if the condition satisfies ; Check if the number of unique characters in string s2 is 1 ; Store the unique character frequency ; Store occurence of it in s1 ; Find count of that character in the string s1 ; Increment count by 1 if that unique character is same as current character ; If count count_in_s1 is less than count_in_s2 , then print s1 and return ; Otherwise , there is no possible arrangement ; Checks if any character in s2 is less than its next character ; Iterate the string , s2 ; If s [ i ] is greater than the s [ i + 1 ] ; Set inc to 0 ; If inc = 1 , print s1 in decreasing order ; Otherwise , print s1 in increasing order ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { static void rearrangeString ( char [ ] s1 , char [ ] s2 ) { int [ ] cnt = new int [ 26 ] ; for ( int i = 0 ; i < s2 . length ; i ++ ) cnt [ s2 [ i ] - ' a ' ] ++ ; int unique = 0 ; for ( int i = 0 ; i < 26 ; i ++ ) if ( cnt [ i ] != 0 ) unique ++ ; if ( unique == 1 ) { int count_in_s2 = s2 . length ; int count_in_s1 = 0 ; for ( int i = 0 ; i < s1 . length ; i ++ ) if ( s1 [ i ] == s2 [ 0 ] ) count_in_s1 ++ ; if ( count_in_s1 < count_in_s2 ) { System . out . print ( new String ( s1 ) ) ; return ; } System . out . print ( - 1 ) ; } else { int inc = 1 ; for ( int i = 0 ; i < s2 . length - 1 ; i ++ ) if ( s2 [ i ] > s2 [ i + 1 ] ) inc = 0 ; if ( inc == 1 ) { Arrays . sort ( s1 ) ; for ( int k = 0 ; k < s1 . length / 2 ; k ++ ) { char temp = s1 [ k ] ; s1 [ k ] = s1 [ s1 . length - k - 1 ] ; s1 [ s1 . length - k - 1 ] = temp ; } System . out . print ( new String ( s1 ) ) ; } else { Arrays . sort ( s1 ) ; System . out . print ( new String ( s1 ) ) ; } } } public static void main ( String [ ] args ) { char [ ] s1 = " abcd " . toCharArray ( ) ; char [ ] s2 = " ab " . toCharArray ( ) ; rearrangeString ( s1 , s2 ) ; } }


"Rearrange a string in sorted order followed by the integer sum | Java program for above implementation ; Method to return string in lexicographic order followed by integers sum ; Traverse the string ; Count occurrence of uppercase alphabets ; Store sum of integers ; Traverse for all characters A to Z ; Append the current character in the string no . of times it occurs in the given string ; Append the sum of integers ; return resultant string ; Driver method"
How can the above be solved in Java?

class Test { static final int MAX_CHAR = 26 ; static String arrangeString ( String str ) { int char_count [ ] = new int [ MAX_CHAR ] ; int sum = 0 ; for ( int i = 0 ; i < str . length ( ) ; i ++ ) { if ( Character . isUpperCase ( str . charAt ( i ) ) ) char_count [ str . charAt ( i ) - ' A ' ] ++ ; else sum = sum + ( str . charAt ( i ) - '0' ) ; } String res = " " ; for ( int i = 0 ; i < MAX_CHAR ; i ++ ) { char ch = ( char ) ( ' A ' + i ) ; while ( char_count [ i ] -- != 0 ) res = res + ch ; } if ( sum > 0 ) res = res + sum ; return res ; } public static void main ( String args [ ] ) { String str = " ACCBA10D2EW30" ; System . out . println ( arrangeString ( str ) ) ; } }


"Rearrange a string in the form of integer sum followed by the minimized character | Java implementation of above approach ; function to return maximum volume ; separate digits and alphabets ; change digit sum to string ; change alphabet sum to string ; concatenate sum to alphabets string ; Driver code"
How can the above be solved in Java?

import java . util . * ; class Solution { static String separateChar ( String str ) { int n = str . length ( ) , digitSum = 0 ; int alphabetSum = 0 , j = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( str . charAt ( i ) >= '0' && str . charAt ( i ) <= '9' ) { digitSum += ( int ) ( str . charAt ( i ) - '0' ) ; } else { alphabetSum += str . charAt ( i ) - ' a ' + 1 ; alphabetSum %= 26 ; } } String sumStr = " " + ( digitSum ) ; char alphabetStr = ( char ) ( alphabetSum + ' a ' - 1 ) ; sumStr += alphabetStr ; return sumStr ; } public static void main ( String args [ ] ) { String str = "3652adyz3423" ; System . out . println ( separateChar ( str ) ) ; } }


"Rearrange a string to maximize the minimum distance between any pair of vowels | Java program for the above approach ; Function to rearrange the String such that the minimum distance between any of vowels is maximum . ; Store vowels and consonants ; Iterate over the characters of String ; If current character is a vowel ; If current character is a consonant ; Stores count of vowels and consonants respectively ; Stores the resultant String ; Stores count of consonants appended into ans ; Append vowel to ans ; Append consonants ; Append consonant to ans ; Update temp ; Remove the taken elements of consonant ; Return final ans ; Driver Code ; Function Call"
How can the above be solved in Java?

import java . util . * ; class GFG { static String solution ( String s ) { Vector < Character > vowel = new Vector < Character > ( ) ; Vector < Character > consonant = new Vector < Character > ( ) ; for ( char i : s . toCharArray ( ) ) { if ( i == ' a ' i == ' e ' i == ' i ' i == ' o ' i == ' u ' ) { vowel . add ( i ) ; } else { consonant . add ( i ) ; } } int Nc , Nv ; Nv = vowel . size ( ) ; Nc = consonant . size ( ) ; int M = Nc / ( Nv - 1 ) ; String ans = " " ; int consotnant_till = 0 ; for ( char i : vowel ) { ans += i ; int temp = 0 ; for ( int j = consotnant_till ; j < Math . min ( Nc , consotnant_till + M ) ; j ++ ) { ans += consonant . get ( j ) ; temp ++ ; } consotnant_till += temp ; } return ans ; } public static void main ( String [ ] args ) { String str = " aaaabbbcc " ; System . out . print ( solution ( str ) ) ; } }


"Rearrange all elements of array which are multiples of x in increasing order | Java implementation of the approach ; Function to sort all the multiples of x from the array in ascending order ; Insert all multiples of 5 to a vector ; Sort the vector ; update the array elements ; Driver code ; Print the result"
How can the above be solved in Java?

import java . util . Collections ; import java . util . Vector ; class GFG { static void sortMultiples ( int arr [ ] , int n , int x ) { Vector < Integer > v = new Vector < Integer > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( arr [ i ] % x == 0 ) { v . add ( arr [ i ] ) ; } } Collections . sort ( v ) ; int j = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( arr [ i ] % x == 0 ) { arr [ i ] = v . get ( j ++ ) ; } } } public static void main ( String [ ] args ) { int arr [ ] = { 125 , 3 , 15 , 6 , 100 , 5 } ; int x = 5 ; int n = arr . length ; sortMultiples ( arr , n , x ) ; for ( int i = 0 ; i < n ; i ++ ) { System . out . print ( arr [ i ] + " ▁ " ) ; } } }


"Rearrange an Array such that Sum of same | Java program to implement the above approach ; Function to rearrange the array such that no same - indexed subset have sum equal to that in the original array ; Initialize a vector ; Iterate the array ; Sort the vector ; Shift of elements to the index of its next cyclic element ; Print the answer ; Driver Code"
How can the above be solved in Java?

import java . io . * ; import java . util . * ; class GFG { static class pair { int first , second ; pair ( int first , int second ) { this . first = first ; this . second = second ; } } static void printNewArray ( List < Integer > a , int n ) { List < pair > v = new ArrayList < > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { v . add ( new pair ( a . get ( i ) , i ) ) ; } Collections . sort ( v , ( pair s1 , pair s2 ) -> { return s1 . first - s2 . first ; } ) ; int ans [ ] = new int [ n ] ; for ( int i = 0 ; i < n ; i ++ ) { ans [ v . get ( ( i + 1 ) % n ) . second ] = v . get ( i ) . first ; } for ( int i = 0 ; i < n ; i ++ ) { System . out . print ( ans [ i ] + " ▁ " ) ; } } public static void main ( String args [ ] ) { List < Integer > a = Arrays . asList ( 4 , 1 , 2 , 5 , 3 ) ; int n = a . size ( ) ; printNewArray ( a , n ) ; } }


"Rearrange an array in maximum minimum form | Set 1 | Java program to rearrange an array in minimum maximum form ; Prints max at first position , min at second position second max at third position , second min at fourth position and so on . ; Auxiliary array to hold modified array ; Indexes of smallest and largest elements from remaining array . ; To indicate whether we need to copy rmaining largest or remaining smallest at next position ; Store result in temp [ ] ; Driver code"
How can the above be solved in Java?

import java . util . Arrays ; public class GFG { static void rearrange ( int [ ] arr , int n ) { int temp [ ] = arr . clone ( ) ; int small = 0 , large = n - 1 ; boolean flag = true ; for ( int i = 0 ; i < n ; i ++ ) { if ( flag ) arr [ i ] = temp [ large -- ] ; else arr [ i ] = temp [ small ++ ] ; flag = ! flag ; } } public static void main ( String [ ] args ) { int arr [ ] = new int [ ] { 1 , 2 , 3 , 4 , 5 , 6 } ; System . out . println ( " Original ▁ Array ▁ " ) ; System . out . println ( Arrays . toString ( arr ) ) ; rearrange ( arr , arr . length ) ; System . out . println ( " Modified ▁ Array ▁ " ) ; System . out . println ( Arrays . toString ( arr ) ) ; } }


"Rearrange an array in maximum minimum form | Set 2 ( O ( 1 ) extra space ) | Java program to rearrange an array in minimum maximum form ; Prints max at first position , min at second position second max at third position , second min at fourth position and so on . ; initialize index of first minimum and first maximum element ; store maximum element of array ; traverse array elements ; at even index : we have to put maximum element ; at odd index : we have to put minimum element ; array elements back to it 's original form ; Driver code"
How can the above be solved in Java?

public class Main { public static void rearrange ( int arr [ ] , int n ) { int max_idx = n - 1 , min_idx = 0 ; int max_elem = arr [ n - 1 ] + 1 ; for ( int i = 0 ; i < n ; i ++ ) { if ( i % 2 == 0 ) { arr [ i ] += ( arr [ max_idx ] % max_elem ) * max_elem ; max_idx -- ; } else { arr [ i ] += ( arr [ min_idx ] % max_elem ) * max_elem ; min_idx ++ ; } } for ( int i = 0 ; i < n ; i ++ ) arr [ i ] = arr [ i ] / max_elem ; } public static void main ( String args [ ] ) { int arr [ ] = { 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 } ; int n = arr . length ; System . out . println ( " Original ▁ Array " ) ; for ( int i = 0 ; i < n ; i ++ ) System . out . print ( arr [ i ] + " ▁ " ) ; rearrange ( arr , n ) ; System . out . print ( " Modified Array "); for ( int i = 0 ; i < n ; i ++ ) System . out . print ( arr [ i ] + " ▁ " ) ; } }


"Rearrange an array in maximum minimum form | Set 2 ( O ( 1 ) extra space ) | Java program to rearrange an array in minimum maximum form ; Prints max at first position , min at second position second max at third position , second min at fourth position and so on . ; initialize index of first minimum and first maximum element ; traverse array elements ; at even index : we have to put maximum element ; at odd index : we have to put minimum element ; Driver code"
How can the above be solved in Java?

public class Main { public static void rearrange ( int arr [ ] , int n ) { int max_ele = arr [ n - 1 ] ; int min_ele = arr [ 0 ] ; for ( int i = 0 ; i < n ; i ++ ) { if ( i % 2 == 0 ) { arr [ i ] = max_ele ; max_ele -= 1 ; } else { arr [ i ] = min_ele ; min_ele += 1 ; } } } public static void main ( String args [ ] ) { int arr [ ] = { 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 } ; int n = arr . length ; System . out . println ( " Original ▁ Array " ) ; for ( int i = 0 ; i < n ; i ++ ) System . out . print ( arr [ i ] + " ▁ " ) ; rearrange ( arr , n ) ; System . out . print ( " Modified Array "); for ( int i = 0 ; i < n ; i ++ ) System . out . print ( arr [ i ] + " ▁ " ) ; } }


"Rearrange an array so that arr [ i ] becomes arr [ arr [ i ] ] with O ( 1 ) extra space |  ; The function to rearrange an array in - place so that arr [ i ] becomes arr [ arr [ i ] ] . ; First step : Increase all values by ( arr [ arr [ i ] ] % n ) * n ; Second Step : Divide all values by n ; A utility function to print an array of size n ; Driver program to test above functions"
How can the above be solved in Java?

class Rearrange { void rearrange ( int arr [ ] , int n ) { for ( int i = 0 ; i < n ; i ++ ) arr [ i ] += ( arr [ arr [ i ] ] % n ) * n ; for ( int i = 0 ; i < n ; i ++ ) arr [ i ] /= n ; } void printArr ( int arr [ ] , int n ) { for ( int i = 0 ; i < n ; i ++ ) System . out . print ( arr [ i ] + " ▁ " ) ; System . out . println ( " " ) ; } public static void main ( String [ ] args ) { Rearrange rearrange = new Rearrange ( ) ; int arr [ ] = { 3 , 2 , 0 , 1 } ; int n = arr . length ; System . out . println ( " Given ▁ Array ▁ is ▁ : " ) ; rearrange . printArr ( arr , n ) ; rearrange . rearrange ( arr , n ) ; System . out . println ( " Modified ▁ Array ▁ is ▁ : " ) ; rearrange . printArr ( arr , n ) ; } }


"Rearrange an array such that ' arr [ j ] ' becomes ' i ' if ' arr [ i ] ' is ' j ' | Set 1 | A simple JAVA program to rearrange contents of arr [ ] such that arr [ j ] becomes j if arr [ i ] is j ; A simple method to rearrange ' arr [ 0 . . n - 1 ] ' so that ' arr [ j ] ' becomes ' i ' if ' arr [ i ] ' is ' j ' ; retrieving old value and storing with the new one ; retrieving new value ; A utility function to print contents of arr [ 0. . n - 1 ] ; Driver code"
How can the above be solved in Java?

class GFG { static void rearrange ( int arr [ ] , int n ) { for ( int i = 0 ; i < n ; i ++ ) { arr [ arr [ i ] % n ] += i * n ; } for ( int i = 0 ; i < n ; i ++ ) { arr [ i ] /= n ; } } static void printArray ( int arr [ ] , int n ) { for ( int i = 0 ; i < n ; i ++ ) { System . out . print ( arr [ i ] + " ▁ " ) ; } System . out . println ( ) ; } public static void main ( String [ ] args ) { int arr [ ] = { 2 , 0 , 1 , 4 , 5 , 3 } ; int n = arr . length ; System . out . println ( " Given ▁ array ▁ is ▁ : ▁ " ) ; printArray ( arr , n ) ; rearrange ( arr , n ) ; System . out . println ( " Modified ▁ array ▁ is ▁ : " ) ; printArray ( arr , n ) ; } }


"Rearrange an array such that ' arr [ j ] ' becomes ' i ' if ' arr [ i ] ' is ' j ' | Set 1 | A simple Java program to rearrange contents of arr [ ] such that arr [ j ] becomes j if arr [ i ] is j ; A simple method to rearrange ' arr [ 0 . . n - 1 ] ' so that ' arr [ j ] ' becomes ' i ' if ' arr [ i ] ' is ' j ' ; Create an auxiliary array of same size ; Store result in temp [ ] ; Copy temp back to arr [ ] ; A utility function to print contents of arr [ 0. . n - 1 ] ; Driver program to test above functions"
How can the above be solved in Java?

class RearrangeArray { void rearrangeNaive ( int arr [ ] , int n ) { int temp [ ] = new int [ n ] ; int i ; for ( i = 0 ; i < n ; i ++ ) temp [ arr [ i ] ] = i ; for ( i = 0 ; i < n ; i ++ ) arr [ i ] = temp [ i ] ; } void printArray ( int arr [ ] , int n ) { int i ; for ( i = 0 ; i < n ; i ++ ) { System . out . print ( arr [ i ] + " ▁ " ) ; } System . out . println ( " " ) ; } public static void main ( String [ ] args ) { RearrangeArray arrange = new RearrangeArray ( ) ; int arr [ ] = { 1 , 3 , 0 , 2 } ; int n = arr . length ; System . out . println ( " Given ▁ array ▁ is ▁ " ) ; arrange . printArray ( arr , n ) ; arrange . rearrangeNaive ( arr , n ) ; System . out . println ( " Modified ▁ array ▁ is ▁ " ) ; arrange . printArray ( arr , n ) ; } }


"Rearrange an array such that arr [ i ] = i | Java program for above approach ; Function to tranform the array ; Iterate over the array ; Checf is any ar [ j ] exists such that ar [ j ] is equal to i ; Iterate over array ; If not present ; Print the output ; Driver Code ; Function Call"
How can the above be solved in Java?

class GFG { public static void fixArray ( int ar [ ] , int n ) { int i , j , temp ; for ( i = 0 ; i < n ; i ++ ) { for ( j = 0 ; j < n ; j ++ ) { if ( ar [ j ] == i ) { temp = ar [ j ] ; ar [ j ] = ar [ i ] ; ar [ i ] = temp ; break ; } } } for ( i = 0 ; i < n ; i ++ ) { if ( ar [ i ] != i ) { ar [ i ] = - 1 ; } } System . out . println ( " Array ▁ after ▁ Rearranging " ) ; for ( i = 0 ; i < n ; i ++ ) { System . out . print ( ar [ i ] + " ▁ " ) ; } } public static void main ( String [ ] args ) { int n , ar [ ] = { - 1 , - 1 , 6 , 1 , 9 , 3 , 2 , - 1 , 4 , - 1 } ; n = ar . length ; fixArray ( ar , n ) ; } }


"Rearrange an array such that product of every two consecutive elements is a multiple of 4 | Java program to rearray array elements such that the product of every two consecutive elements is a multiple of ; Function to rearrange array elements such that the every two consecutive elements is a multiple of 4 ; If element is odd ; Odd ; If element is divisible by 4 ; Divisible by 4 ; If element is not divisible by 4 ; Even but not divisible by 4 ; Condition for rearrangement to be possible ; Print ODD . get ( i ) and FOUR . get ( i ) consecutively ; Print the remaining FOUR . get ( i ) , if any ; Condition for rearrangement to be possible ; Print ODD . get ( i ) and FOUR . get ( i ) consecutively ; Print the remaining FOUR . get ( i ) , if any ; Print the NON_FOUR . get ( i ) elements at the end ; No possible configuration ; Driver Code"
How can the above be solved in Java?

import java . io . * ; import java . util . * ; class GFG { public static void Permute ( Vector < Integer > arr , int n ) { int odd = 0 , four = 0 ; int non_four = 0 ; Vector < Integer > ODD = new Vector < Integer > ( ) ; Vector < Integer > FOUR = new Vector < Integer > ( n ) ; Vector < Integer > NON_FOUR = new Vector < Integer > ( n ) ; for ( int x : arr ) { if ( x % 2 != 0 ) { odd ++ ; ODD . add ( x ) ; } else if ( x % 4 == 0 ) { four ++ ; FOUR . add ( x ) ; } else { non_four ++ ; NON_FOUR . add ( x ) ; } } if ( non_four == 0 && four >= odd - 1 ) { int x = ODD . size ( ) ; int y = FOUR . size ( ) ; int i ; for ( i = 0 ; i < x ; i ++ ) { System . out . print ( ODD . get ( i ) + " ▁ " ) ; if ( i < y ) System . out . print ( FOUR . get ( i ) + " ▁ " ) ; } while ( i < y ) System . out . print ( FOUR . get ( i ) + " ▁ " ) ; System . out . println ( ) ; } else if ( non_four > 0 && four >= odd ) { int x = ODD . size ( ) ; int y = FOUR . size ( ) ; int i ; for ( i = 0 ; i < x ; i ++ ) { System . out . print ( ODD . get ( i ) + " ▁ " ) ; if ( i < y ) System . out . print ( FOUR . get ( i ) + " ▁ " ) ; } while ( i < y ) System . out . print ( FOUR . get ( i ) + " ▁ " ) ; for ( int j = 0 ; j < ( int ) NON_FOUR . size ( ) ; j ++ ) System . out . print ( NON_FOUR . get ( j ) + " ▁ " ) ; System . out . println ( ) ; } else System . out . println ( " Not ▁ Possible " ) ; } public static void main ( String [ ] args ) { Vector < Integer > arr = new Vector < Integer > ( ) ; arr . add ( 2 ) ; arr . add ( 7 ) ; arr . add ( 1 ) ; arr . add ( 8 ) ; arr . add ( 2 ) ; arr . add ( 8 ) ; Permute ( arr , arr . size ( ) ) ; } }


"Rearrange an array to make similar indexed elements different from that of another array | Java program for the above approach ; Function to find the arrangement of array B [ ] such that element at each index of A [ ] and B [ ] are not equal ; Length of array ; Print not possible , if arrays only have single equal element ; Reverse array B ; Traverse over arrays to check if there is any index where A [ i ] and B [ i ] are equal ; Swap B [ i ] with B [ i - 1 ] ; Break the loop ; Print required arrangement of array B ; Driver Code ; Given arrays A [ ] and B [ ] ; Function Call"
How can the above be solved in Java?

import java . util . * ; import java . lang . * ; class GFG { static void RearrangeB ( int [ ] A , int [ ] B ) { int n = A . length ; if ( n == 1 && A [ 0 ] == B [ 0 ] ) { System . out . println ( " - 1" ) ; return ; } for ( int i = 0 ; i < n / 2 ; i ++ ) { int t = B [ i ] ; B [ i ] = B [ n - i - 1 ] ; B [ n - i - 1 ] = t ; } for ( int i = 0 ; i < n - 1 ; i ++ ) { if ( B [ i ] == A [ i ] ) { int t = B [ i + 1 ] ; B [ i + 1 ] = B [ i ] ; B [ i ] = t ; break ; } } for ( int k : B ) System . out . print ( k + " ▁ " ) ; } public static void main ( String [ ] args ) { int [ ] A = { 2 , 4 , 5 , 8 } ; int [ ] B = { 2 , 4 , 5 , 8 } ; RearrangeB ( A , B ) ; } }


"Rearrange an array to maximize i * arr [ i ] | Java program for the Optimal Solution ; Function to calculate the maximum points earned by making an optimal selection on the given array ; Sorting the array ; Variable to store the total points earned ; Driver code"
How can the above be solved in Java?

import java . io . * ; import java . util . * ; class GFG { static int findOptimalSolution ( int [ ] a , int N ) { Arrays . sort ( a ) ; int points = 0 ; for ( int i = 0 ; i < N ; i ++ ) { points += a [ i ] * i ; } return points ; } public static void main ( String args [ ] ) { int [ ] a = { 1 , 4 , 2 , 3 , 9 } ; int N = a . length ; System . out . println ( findOptimalSolution ( a , N ) ) ; } }


"Rearrange an array to maximize sum of Bitwise AND of same | Java program for the above approach ; Function to implement recursive DP ; If i is equal to N ; If dp [ i ] [ mask ] is not equal to - 1 ; Iterate over the array B [ ] ; If current element is not yet selected ; Update dp [ i ] [ mask ] ; Return dp [ i ] [ mask ] ; Function to obtain maximum sum of Bitwise AND of same - indexed elements from the arrays A [ ] and B [ ] ; Stores all dp - states ; Returns the maximum value returned by the function maximizeAnd ( ) ; Driver Code"
How can the above be solved in Java?

import java . io . * ; import java . lang . * ; import java . util . * ; public class GFG { static int maximizeAnd ( int i , int mask , int A [ ] , int B [ ] , int N , int [ ] [ ] dp ) { if ( i == N ) return 0 ; if ( dp [ i ] [ mask ] != - 1 ) return dp [ i ] [ mask ] ; for ( int j = 0 ; j < N ; ++ j ) { if ( ( mask & ( 1 << j ) ) == 0 ) { dp [ i ] [ mask ] = Math . max ( dp [ i ] [ mask ] , ( A [ i ] & B [ j ] ) + maximizeAnd ( i + 1 , mask | ( 1 << j ) , A , B , N , dp ) ) ; } } return dp [ i ] [ mask ] ; } static int maximizeAndUtil ( int A [ ] , int B [ ] , int N ) { int dp [ ] [ ] = new int [ N ] [ ( 1 << N ) + 1 ] ; for ( int dd [ ] : dp ) Arrays . fill ( dd , - 1 ) ; return maximizeAnd ( 0 , 0 , A , B , N , dp ) ; } public static void main ( String [ ] args ) { int A [ ] = { 3 , 5 , 7 , 11 } ; int B [ ] = { 2 , 6 , 10 , 12 } ; int N = A . length ; System . out . print ( maximizeAndUtil ( A , B , N ) ) ; } }


"Rearrange and update array elements as specified by the given queries | Java program to implement the above approach ; Function to perform the given operations ; Dequeue to store the array elements ; Insert all element of the array into the dequeue ; Stores the size of the queue ; Traverse each query ; Query for left shift . ; Extract the element at the front of the queue ; Pop the element at the front of the queue ; Push the element at the back of the queue ; Query for right shift ; Extract the element at the back of the queue ; Pop the element at the back of the queue ; Push the element at the front of the queue ; Query for update ; Query to get the value ; Driver Code ; All possible Queries"
How can the above be solved in Java?

import java . util . * ; class GFG { static void Queries ( int arr [ ] , int N , int [ ] [ ] Q ) { Vector < Integer > dq = new Vector < > ( ) ; for ( int i = 0 ; i < N ; i ++ ) { dq . add ( arr [ i ] ) ; } int sz = Q . length ; for ( int i = 0 ; i < sz ; i ++ ) { if ( Q [ i ] [ 0 ] == 0 ) { int front = dq . get ( 0 ) ; dq . remove ( 0 ) ; dq . add ( front ) ; } else if ( Q [ i ] [ 0 ] == 1 ) { int back = dq . elementAt ( dq . size ( ) - 1 ) ; dq . remove ( dq . size ( ) - 1 ) ; dq . add ( 0 , back ) ; } else if ( Q [ i ] [ 0 ] == 2 ) { dq . set ( Q [ i ] [ 1 ] , Q [ i ] [ 2 ] ) ; } else { System . out . print ( dq . get ( Q [ i ] [ 1 ] ) + " ▁ " ) ; } } } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 2 , 3 , 4 , 5 } ; int N = arr . length ; int [ ] [ ] Q = { { 0 } , { 1 } , { 3 , 1 } , { 2 , 2 , 54 } , { 3 , 2 } } ; Queries ( arr , N , Q ) ; } }


"Rearrange array by interchanging positions of even and odd elements in the given array | Java program for the above approach ; Function to replace each even element by odd and vice - versa in a given array ; Stores length of array ; Traverse array ; If current element is even then swap it with odd ; Perform Swap ; Change the sign ; If current element is odd then swap it with even ; Perform Swap ; Change the sign ; Marked element positive ; Print final array ; Driver Code ; Given array arr [ ] ; Function Call"
How can the above be solved in Java?

import java . util . * ; import java . lang . * ; class GFG { static void replace ( int [ ] arr ) { int n = arr . length ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = i + 1 ; j < n ; j ++ ) { if ( arr [ i ] >= 0 && arr [ j ] >= 0 && arr [ i ] % 2 == 0 && arr [ j ] % 2 != 0 ) { int tmp = arr [ i ] ; arr [ i ] = arr [ j ] ; arr [ j ] = tmp ; arr [ j ] = - arr [ j ] ; break ; } else if ( arr [ i ] >= 0 && arr [ j ] >= 0 && arr [ i ] % 2 != 0 && arr [ j ] % 2 == 0 ) { int tmp = arr [ i ] ; arr [ i ] = arr [ j ] ; arr [ j ] = tmp ; arr [ j ] = - arr [ j ] ; break ; } } } for ( int i = 0 ; i < n ; i ++ ) arr [ i ] = Math . abs ( arr [ i ] ) ; for ( int i = 0 ; i < n ; i ++ ) System . out . print ( arr [ i ] + " ▁ " ) ; } public static void main ( String [ ] args ) { int [ ] arr = { 1 , 3 , 2 , 4 } ; replace ( arr ) ; } }


"Rearrange array by interchanging positions of even and odd elements in the given array | Java program for the above approach ; Function to replace odd elements with even elements and vice versa ; Length of the array ; Traverse the given array ; If arr [ i ] is visited ; Find the next odd element ; Find next even element ; Mark them visited ; Swap them ; Print the final array ; Driver Code ; Given array arr [ ] ; Function Call"
How can the above be solved in Java?

import java . io . * ; class GFG { static void swapEvenOdd ( int arr [ ] ) { int n = arr . length ; int o = - 1 , e = - 1 ; for ( int i = 0 ; i < n ; i ++ ) { if ( arr [ i ] < 0 ) continue ; int r = - 1 ; if ( arr [ i ] % 2 == 0 ) { o ++ ; while ( arr [ o ] % 2 == 0 arr [ o ] < 0 ) o ++ ; r = o ; } else { e ++ ; while ( arr [ e ] % 2 == 1 arr [ e ] < 0 ) e ++ ; r = e ; } arr [ i ] *= - 1 ; arr [ r ] *= - 1 ; int tmp = arr [ i ] ; arr [ i ] = arr [ r ] ; arr [ r ] = tmp ; } for ( int i = 0 ; i < n ; i ++ ) { System . out . print ( ( - 1 * arr [ i ] ) + " ▁ " ) ; } } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 3 , 2 , 4 } ; swapEvenOdd ( arr ) ; } }


"Rearrange array by interchanging positions of even and odd elements in the given array | Java program for the above approach ; Function to replace odd elements with even elements and vice versa ; Push the first element to stack ; iterate the array and swap even and odd ; pop and swap ; print the arr [ ] ; Driver code ; Given array arr ; length of the arr ; Function Call"
How can the above be solved in Java?

import java . io . * ; import java . lang . * ; import java . util . * ; class GFG { static void swapEvenOdd ( int arr [ ] , int N ) { Stack < int [ ] > stack = new Stack < > ( ) ; stack . push ( new int [ ] { 0 , arr [ 0 ] } ) ; for ( int i = 1 ; i < N ; i ++ ) { if ( ! stack . isEmpty ( ) ) { if ( arr [ i ] % 2 != stack . peek ( ) [ 1 ] % 2 ) { int pop [ ] = stack . pop ( ) ; int index = pop [ 0 ] , val = pop [ 1 ] ; arr [ index ] = arr [ i ] ; arr [ i ] = val ; } else stack . push ( new int [ ] { i , arr [ i ] } ) ; } else stack . push ( new int [ ] { i , arr [ i ] } ) ; } for ( int i = 0 ; i < N ; i ++ ) System . out . print ( arr [ i ] + " ▁ " ) ; } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 3 , 2 , 4 } ; int N = arr . length ; swapEvenOdd ( arr , N ) ; } }


"Rearrange array elements excluded by given ranges to maximize sum of subarrays starting from the first index | Java program for the above approach ; Function that finds the maximum sum all subarrays from the starting index after rearranging the array ; Stores elements after rearranging ; Keeps track of visited elements ; Traverse the queries ; Mark elements that are not allowed to rearranged ; Stores the indices ; Get indices and elements that are allowed to rearranged ; Store the current index and element ; Sort vector v in descending order ; Insert elements in array ; Stores the resultant sum ; Stores the prefix sums ; Traverse the given array ; Return the maximum sum ; Driver Code ; Given array ; Given size ; Queries ; Number of queries ; Function Call"
How can the above be solved in Java?

import java . util . * ; class GFG { static int maxSum ( int n , int a [ ] , int [ ] [ ] l , int q ) { Vector < Integer > v = new Vector < > ( ) ; int [ ] d = new int [ n ] ; for ( int i = 0 ; i < q ; i ++ ) { for ( int x = l [ i ] [ 0 ] ; x <= l [ i ] [ 1 ] ; x ++ ) { if ( d [ x ] == 0 ) { d [ x ] = 1 ; } } } HashSet < Integer > st = new HashSet < > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( d [ i ] == 0 ) { v . add ( a [ i ] ) ; st . add ( i ) ; } } Collections . sort ( v ) ; Collections . reverse ( v ) ; int c = 0 ; for ( int it : st ) { a [ it ] = v . get ( c ) ; c ++ ; } int pref_sum = 0 ; int temp_sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) { temp_sum += a [ i ] ; pref_sum += temp_sum ; } return pref_sum ; } public static void main ( String [ ] args ) { int [ ] arr = { - 8 , 4 , - 2 , - 6 , 4 , 7 , 1 } ; int N = arr . length ; int [ ] [ ] q = { { 0 , 0 } , { 4 , 5 } } ; int queries = q . length ; System . out . print ( maxSum ( N , arr , q , queries ) ) ; } }


"Rearrange array elements such that Bitwise AND of first N | Java implementation of the approach ; Utility function to print the elements of an array ; Function to find the required arrangement ; There has to be atleast 2 elements ; Minimum element from the array ; Swap any occurrence of the minimum element with the last element ; Find the bitwise AND of the first ( n - 1 ) elements ; If the bitwise AND is equal to the last element then print the arrangement ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { static void printArr ( int [ ] arr , int n ) { for ( int i = 0 ; i < n ; i ++ ) System . out . print ( arr [ i ] + " ▁ " ) ; } static void findArrangement ( int arr [ ] , int n ) { if ( n < 2 ) { System . out . print ( " - 1" ) ; return ; } int minVal = Arrays . stream ( arr ) . min ( ) . getAsInt ( ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( arr [ i ] == minVal ) { swap ( arr , i , n - 1 ) ; break ; } } int andVal = arr [ 0 ] ; for ( int i = 1 ; i < n - 1 ; i ++ ) { andVal &= arr [ i ] ; } if ( andVal == arr [ n - 1 ] ) printArr ( arr , n ) ; else System . out . print ( " - 1" ) ; } static int [ ] swap ( int [ ] arr , int i , int j ) { int temp = arr [ i ] ; arr [ i ] = arr [ j ] ; arr [ j ] = temp ; return arr ; } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 5 , 3 , 3 } ; int n = arr . length ; findArrangement ( arr , n ) ; } }


"Rearrange array elements to maximize the sum of MEX of all prefix arrays | Java program for the above approach ; Function to find the maximum sum of MEX of prefix arrays for any arrangement of the given array ; Stores the final arrangement ; Sort the array in increasing order ; Iterate over the array arr [ ] ; Iterate over the array , arr [ ] and push the remaining occurrences of the elements into ans [ ] ; Print the array , ans [ ] ; Driver Code ; Given array ; Store the size of the array ; Function Call"
How can the above be solved in Java?

import java . util . Arrays ; class GFG { static void maximumMex ( int arr [ ] , int N ) { int ans [ ] = new int [ 2 * N ] ; Arrays . sort ( ans ) ; int j = 0 ; for ( int i = 0 ; i < N ; i ++ ) { if ( i == 0 arr [ i ] != arr [ i - 1 ] ) { j += 1 ; ans [ j ] = arr [ i ] ; } } for ( int i = 0 ; i < N ; i ++ ) { if ( i > 0 && arr [ i ] == arr [ i - 1 ] ) { j += 1 ; ans [ j ] = arr [ i ] ; } } for ( int i = 0 ; i < N ; i ++ ) System . out . print ( ans [ i ] + " ▁ " ) ; } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 0 , 0 } ; int N = arr . length ; maximumMex ( arr , N ) ; } }


"Rearrange array such that all even | Java Program to implement the above approach ; Function to check if it the array can be rearranged such such that every even indices contains an even element ; Stores the count of even elements ; Traverse array to count even numbers ; If even_no_count exceeds count of even indices ; Driver Code"
How can the above be solved in Java?

import java . io . * ; import java . util . * ; class GFG { static void checkPossible ( int a [ ] ) { int even_no_count = 0 ; for ( int i = 0 ; i < a . length ; i ++ ) { if ( a [ i ] % 2 == 0 ) even_no_count ++ ; } if ( a . length / 2 > even_no_count ) { System . out . println ( " No " ) ; return ; } System . out . println ( " Yes " ) ; int j = 0 ; for ( int i = 1 ; i < a . length ; i += 2 ) { if ( a [ i ] % 2 == 0 ) continue ; else { while ( j < a . length && a [ j ] % 2 != 0 ) j += 2 ; a [ i ] += a [ j ] ; a [ j ] = a [ i ] - a [ j ] ; a [ i ] -= a [ j ] ; } } for ( int i = 0 ; i < a . length ; i ++ ) { System . out . print ( a [ i ] + " ▁ " ) ; } } public static void main ( String args [ ] ) { int arr [ ] = { 2 , 3 , 4 , 5 , 6 , 7 } ; checkPossible ( arr ) ; } }


"Rearrange array such that arr [ i ] >= arr [ j ] if i is even and arr [ i ] <= arr [ j ] if i is odd and j < i | Java program to rearrange the array as per the given condition ; function to rearrange the array ; total even positions ; total odd positions ; copy original array in an auxiliary array ; sort the auxiliary array ; fill up odd position in original array ; fill up even positions in original array ; display array ; Driver function"
How can the above be solved in Java?

import java . util . * ; import java . lang . * ; public class GfG { public static void rearrangeArr ( int arr [ ] , int n ) { int evenPos = n / 2 ; int oddPos = n - evenPos ; int [ ] tempArr = new int [ n ] ; for ( int i = 0 ; i < n ; i ++ ) tempArr [ i ] = arr [ i ] ; Arrays . sort ( tempArr ) ; int j = oddPos - 1 ; for ( int i = 0 ; i < n ; i += 2 ) { arr [ i ] = tempArr [ j ] ; j -- ; } j = oddPos ; for ( int i = 1 ; i < n ; i += 2 ) { arr [ i ] = tempArr [ j ] ; j ++ ; } for ( int i = 0 ; i < n ; i ++ ) System . out . print ( arr [ i ] + " ▁ " ) ; } public static void main ( String argc [ ] ) { int [ ] arr = new int [ ] { 1 , 2 , 3 , 4 , 5 , 6 , 7 } ; int size = 7 ; rearrangeArr ( arr , size ) ; } }


"Rearrange array such that difference of adjacent elements is in descending order | Java implementation to Rearrange array such that difference of adjacent elements is in descending order ; Function to print array in given order ; Sort the array ; Check elements till the middle index ; Check if length is odd print the middle index at last ; Print the remaining elements in the described order ; Driver code ; Array declaration ; Size of array"
How can the above be solved in Java?

import java . util . * ; class GFG { static void printArray ( int [ ] a , int n ) { Arrays . sort ( a ) ; int i = 0 ; int j = n - 1 ; while ( i <= j ) { if ( i == j ) { System . out . print ( a [ i ] + " ▁ " ) ; } else { System . out . print ( a [ j ] + " ▁ " ) ; System . out . print ( a [ i ] + " ▁ " ) ; } i = i + 1 ; j = j - 1 ; } System . out . println ( ) ; } public static void main ( String [ ] args ) { int arr1 [ ] = { 1 , 2 , 3 , 4 , 5 , 6 } ; int n1 = arr1 . length ; printArray ( arr1 , n1 ) ; } }


"Rearrange array such that even index elements are smaller and odd index elements are greater | Java code to rearrange an array such that even index elements are smaller and odd index elements are greater than their next . ; Rearrange ; Utility that prints out an array in a line ; Driver code"
How can the above be solved in Java?

 class GFG { static void rearrange ( int arr [ ] , int n ) { int temp ; for ( int i = 0 ; i < n - 1 ; i ++ ) { if ( i % 2 == 0 && arr [ i ] > arr [ i + 1 ] ) { temp = arr [ i ] ; arr [ i ] = arr [ i + 1 ] ; arr [ i + 1 ] = temp ; } if ( i % 2 != 0 && arr [ i ] < arr [ i + 1 ] ) { temp = arr [ i ] ; arr [ i ] = arr [ i + 1 ] ; arr [ i + 1 ] = temp ; } } } static void printArray ( int arr [ ] , int size ) { for ( int i = 0 ; i < size ; i ++ ) System . out . print ( arr [ i ] + " ▁ " ) ; System . out . println ( ) ; } public static void main ( String [ ] args ) { int arr [ ] = { 6 , 4 , 2 , 1 , 8 , 3 } ; int n = arr . length ; System . out . print ( "Before rearranging:
"); printArray ( arr , n ) ; rearrange ( arr , n ) ; System . out . print ( "After rearranging:
"); printArray ( arr , n ) ; } }


"Rearrange array to make Bitwise XOR of similar indexed elements of two arrays is same | Java program for the above approach ; Function to rearrange the array B [ ] such that A [ i ] ^ B [ i ] is same for each element ; Store frequency of elements ; Stores xor value ; Taking xor of all the values of both arrays ; Store frequency of B [ ] ; Find the array B [ ] after rearrangement ; If the updated value is present then decrement its frequency ; Otherwise return empty vector ; Utility function to rearrange the array B [ ] such that A [ i ] ^ B [ i ] is same for each element ; Store rearranged array B ; If rearrangement possible ; Otherwise return - 1 ; Driver Code ; Given vector A ; Given vector B ; Size of the vector ; Function Call"
How can the above be solved in Java?

import java . io . * ; import java . util . * ; class GFG { static ArrayList < Integer > rearrangeArray ( ArrayList < Integer > A , ArrayList < Integer > B , int N ) { HashMap < Integer , Integer > m = new HashMap < Integer , Integer > ( ) ; int xor_value = 0 ; for ( int i = 0 ; i < N ; i ++ ) { xor_value ^= A . get ( i ) ; xor_value ^= B . get ( i ) ; m . put ( B . get ( i ) , m . getOrDefault ( B . get ( i ) + 1 , 0 ) ) ; } for ( int i = 0 ; i < N ; i ++ ) { B . set ( i , A . get ( i ) ^ xor_value ) ; if ( m . getOrDefault ( B . get ( i ) , - 1 ) != - 1 ) { m . put ( B . get ( i ) , m . getOrDefault ( B . get ( i ) , 0 ) - 1 ) ; } else return ( new ArrayList < Integer > ( ) ) ; } return B ; } static void rearrangeArrayUtil ( ArrayList < Integer > A , ArrayList < Integer > B , int N ) { ArrayList < Integer > ans = rearrangeArray ( A , B , N ) ; if ( ans . size ( ) != 0 ) { for ( int i = 0 ; i < ans . size ( ) ; i ++ ) { System . out . print ( ans . get ( i ) + " ▁ " ) ; } } else { System . out . println ( " - 1" ) ; } } public static void main ( String [ ] args ) { ArrayList < Integer > A = new ArrayList < Integer > ( Arrays . asList ( 13 , 21 , 33 , 49 , 53 ) ) ; ArrayList < Integer > B = new ArrayList < Integer > ( Arrays . asList ( 54 , 50 , 34 , 22 , 14 ) ) ; int N = ( int ) A . size ( ) ; rearrangeArrayUtil ( A , B , N ) ; } }


"Rearrange array to make decimal equivalents of reversed binary representations of array elements sorted | Java program for the above approach ; Function to reverse the bits of a number ; Stores the reversed number ; Divide rev by 2 ; If the value of N is odd ; Update the value of N ; Return the final value of rev ; Function for rearranging the array element according to the given rules ; Stores the new array elements ; Function for rearranging the array ; Stores the new array ; Function to sort the array by reversing binary representation ; Creating a new array ; Sort the array with the key ; Get arr from newArr ; Print the sorted array ; Driver Code"
How can the above be solved in Java?

import java . io . * ; import java . lang . * ; import java . util . * ; class GFG { static int keyFunc ( int n ) { int rev = 0 ; while ( n > 0 ) { rev = rev << 1 ; if ( ( n & 1 ) == 1 ) rev = rev ^ 1 ; n = n >> 1 ; } return rev ; } static int [ ] [ ] getNew ( int arr [ ] ) { int ans [ ] [ ] = new int [ arr . length ] [ 2 ] ; for ( int i = 0 ; i < arr . length ; i ++ ) ans [ i ] = new int [ ] { keyFunc ( arr [ i ] ) , arr [ i ] } ; return ans ; } static int [ ] getArr ( int [ ] [ ] arr ) { int ans [ ] = new int [ arr . length ] ; int idx = 0 ; for ( int i [ ] : arr ) ans [ idx ++ ] = i [ 1 ] ; return ans ; } static void sortArray ( int arr [ ] ) { int [ ] [ ] newArr = getNew ( arr ) ; Arrays . sort ( newArr , ( a , b ) -> { if ( Integer . compare ( a [ 0 ] , b [ 0 ] ) == 0 ) return Integer . compare ( a [ 1 ] , b [ 1 ] ) ; return Integer . compare ( a [ 0 ] , b [ 0 ] ) ; } ) ; arr = getArr ( newArr ) ; int n = arr . length ; System . out . print ( " [ " ) ; for ( int i = 0 ; i < n - 1 ; i ++ ) System . out . print ( arr [ i ] + " , ▁ " ) ; System . out . print ( arr [ n - 1 ] + " ] " ) ; } public static void main ( String [ ] args ) { int arr [ ] = { 43 , 52 , 61 , 41 } ; sortArray ( arr ) ; } }


"Rearrange array to make it non | Java program for above approach ; Function to check if the array can be made non - decreasing ; Iterate till N ; Find the minimum element ; Sort the array ; Iterate till N ; Check if the element is at its correct position ; Return the answer ; Driver Code ; Print the answer"
How can the above be solved in Java?

import java . io . * ; import java . util . * ; import java . math . * ; class GFG { public static boolean check ( int [ ] a , int n ) { int [ ] b = new int [ n ] ; int minElement = Integer . MAX_VALUE ; for ( int i = 0 ; i < n ; i ++ ) { b [ i ] = a [ i ] ; minElement = Math . min ( minElement , a [ i ] ) ; } Arrays . sort ( b ) ; int k = 1 ; for ( int i = 0 ; i < n ; i ++ ) { if ( a [ i ] != b [ i ] && a [ i ] % minElement != 0 ) { k = 0 ; break ; } } return k == 1 ? true : false ; } public static void main ( String [ ] args ) { int [ ] a = { 4 , 3 , 6 , 6 , 2 , 9 } ; int n = a . length ; if ( check ( a , n ) == true ) { System . out . println ( " Yes " ) ; } else { System . out . println ( " No " ) ; } } }


"Rearrange array to make product of prefix sum array non zero | Java program to implement the above approach ; Function to print array elements ; Function to rearrange array that satisfies the given condition ; Stores sum of elements of the given array ; Calculate totalSum ; If the totalSum is equal to 0 ; No possible way to rearrange array ; If totalSum exceeds 0 ; Rearrange the array in descending order ; Otherwise ; Rearrange the array in ascending order ; Driver Code"
How can the above be solved in Java?

 import java . util . * ; class GFG { static void printArr ( int arr [ ] , int N ) { for ( int i = 0 ; i < N ; i ++ ) { System . out . print ( arr [ i ] + " ▁ " ) ; } } static void rearrangeArr ( int arr [ ] , int N ) { int totalSum = 0 ; for ( int i = 0 ; i < N ; i ++ ) { totalSum += arr [ i ] ; } if ( totalSum == 0 ) { System . out . print ( " - 1" + "
"); } else if ( totalSum > 0 ) { Arrays . sort ( arr ) ; arr = reverse ( arr ) ; printArr ( arr , N ) ; } else { Arrays . sort ( arr ) ; printArr ( arr , N ) ; } } static int [ ] reverse ( int a [ ] ) { int i , n = a . length , t ; for ( i = 0 ; i < n / 2 ; i ++ ) { t = a [ i ] ; a [ i ] = a [ n - i - 1 ] ; a [ n - i - 1 ] = t ; } return a ; } public static void main ( String [ ] args ) { int arr [ ] = { 1 , - 1 , - 2 , 3 } ; int N = arr . length ; rearrangeArr ( arr , N ) ; } }


"Rearrange array to make sum of all subarrays starting from first index non | Java program for the above approach ; Function to rearrange the array such that sum of all elements of subarrays from the 1 st index is non - zero ; Initialize sum of subarrays ; Sum of all elements of array ; If sum is 0 , the required array could never be formed ; If sum is non zero , array might be formed ; Sort array in ascending order ; When current subarray sum becomes 0 replace it with the largest element ; Swap Operation ; If largest element is same as element to be replaced , then rearrangement impossible ; If b = 1 , then rearrangement is not possible . Hence check with reverse configuration ; Sort array in descending order ; When current subarray sum becomes 0 replace it with the smallest element ; Swap Operation ; If smallest element is same as element to be replaced , then rearrangement impossible ; If neither of the configurations worked then print " - 1" ; Otherwise , print the formed rearrangement ; Driver Code ; Given array ; Size of array ; Function Call"
How can the above be solved in Java?

import java . util . * ; import java . util . Arrays ; import java . util . Collections ; class GFG { static void rearrangeArray ( int a [ ] , int N ) { int sum = 0 ; for ( int i = 0 ; i < N ; i ++ ) { sum += a [ i ] ; } if ( sum == 0 ) { System . out . print ( " - 1" ) ; return ; } sum = 0 ; int b = 0 ; Arrays . sort ( a ) ; for ( int i = 0 ; i < N ; i ++ ) { sum += a [ i ] ; if ( sum == 0 ) { if ( a [ i ] != a [ N - 1 ] ) { sum -= a [ i ] ; int temp = a [ i ] ; a [ i ] = a [ N - 1 ] ; a [ N - 1 ] = temp ; sum += a [ i ] ; } else { b = 1 ; break ; } } } if ( b == 1 ) { b = 0 ; sum = 0 ; Arrays . sort ( a ) ; for ( int i = N - 1 ; i >= 0 ; i -- ) { sum += a [ i ] ; if ( sum == 0 ) { if ( a [ i ] != a [ 0 ] ) { sum -= a [ i ] ; int temp = a [ i ] ; a [ i ] = a [ 0 ] ; a [ 0 ] = temp ; sum += a [ i ] ; } else { b = 1 ; break ; } } } } if ( b == 1 ) { System . out . print ( " - 1" + " ▁ " ) ; return ; } for ( int i = 0 ; i < N ; i ++ ) { System . out . print ( a [ i ] + " ▁ " ) ; } } public static void main ( String args [ ] ) { int arr [ ] = { 1 , - 1 , 2 , 4 , 0 } ; int N = arr . length ; rearrangeArray ( arr , N ) ; } }


"Rearrange array to maximize count of local minima | Java program to implement the above approach ; Function to rearrange array elements to maximize count of local minima in the array ; Sort the array in ascending order ; Stores index of left pointer ; Stores index of right pointer ; Traverse the array elements ; If right is less than N ; Print array element ; Update right ; Print array element ; Update left ; Driver Code"
How can the above be solved in Java?

import java . util . * ; class GFG { static void rearrangeArrMaxcntMinima ( int arr [ ] , int N ) { Arrays . sort ( arr ) ; int left = 0 ; int right = N / 2 ; while ( left < N / 2 right < N ) { if ( right < N ) { System . out . print ( arr [ right ] + " ▁ " ) ; right ++ ; } if ( left < N / 2 ) { System . out . print ( arr [ left ] + " ▁ " ) ; left ++ ; } } } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 2 , 3 , 4 , 5 } ; int N = arr . length ; rearrangeArrMaxcntMinima ( arr , N ) ; } }


"Rearrange array to maximize count of triplets ( i , j , k ) such that arr [ i ] > arr [ j ] < arr [ k ] and i < j < k | Java program to implement the above approach ; Function to rearrange the array to maximize the count of triplets ; Sort the given array ; Stores the permutations of the given array ; Stores the index of the given array ; Place the first half of the given array ; Place the last half of the given array ; Stores the count of triplets ; Check the given conditions ; Driver Code"
How can the above be solved in Java?

import java . io . * ; import java . util . Arrays ; class GFG { static void ctTriplets ( int arr [ ] , int N ) { Arrays . sort ( arr ) ; int [ ] temp = new int [ N ] ; int index = 0 ; for ( int i = 1 ; i < N ; i += 2 ) { temp [ i ] = arr [ index ++ ] ; } for ( int i = 0 ; i < N ; i += 2 ) { temp [ i ] = arr [ index ++ ] ; } int ct = 0 ; for ( int i = 0 ; i < N ; i ++ ) { if ( i > 0 && i + 1 < N ) { if ( temp [ i ] < temp [ i + 1 ] && temp [ i ] < temp [ i - 1 ] ) { ct ++ ; } } } System . out . println ( " Count ▁ of ▁ triplets : " + ct ) ; System . out . print ( " Array : " ) ; for ( int i = 0 ; i < N ; i ++ ) { System . out . print ( temp [ i ] + " ▁ " ) ; } } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 2 , 3 , 4 , 5 , 6 } ; int N = arr . length ; ctTriplets ( arr , N ) ; } }


"Rearrange characters in a sorted string such that no pair of adjacent characters are the same | Java program for the above approach ; Function to check if a String S contains pair of adjacent characters that are equal or not ; Traverse the String S ; If S [ i ] and S [ i + 1 ] are equal ; Otherwise , return false ; Function to rearrange characters of a String such that no pair of adjacent characters are the same ; Initialize 3 variables ; Iterate until k < N ; If S [ i ] is not equal to S [ j ] ; Increment i and j by 1 ; If j equals k and increment the value of K by 1 ; Else ; If S [ j ] equals S [ k ] ; Increment k by 1 ; Else ; Swap ; Increment i and j by 1 ; If j equals k ; Increment k by 1 ; Function to rearrange characters in a String so that no two adjacent characters are same ; If String is already valid ; If size of the String is 2 ; Function Call ; Reversing the String ; Function Call ; If the String is valid ; Otherwise ; Driver Code"
How can the above be solved in Java?

import java . util . * ; class GFG { static char [ ] S = " aaabc " . toCharArray ( ) ; static boolean isAdjChar ( ) { for ( int i = 0 ; i < S . length - 1 ; i ++ ) { if ( S [ i ] == S [ i + 1 ] ) return true ; } return false ; } static void rearrangeStringUtil ( int N ) { int i = 0 , j = 1 , k = 2 ; while ( k < N ) { if ( S [ i ] != S [ j ] ) { i ++ ; j ++ ; if ( j == k ) { k ++ ; } } else { if ( S [ j ] == S [ k ] ) { k ++ ; } else { swap ( k , j ) ; i ++ ; j ++ ; if ( j == k ) { k ++ ; } } } } } static void swap ( int i , int j ) { char temp = S [ i ] ; S [ i ] = S [ j ] ; S [ j ] = temp ; } static String rearrangeString ( int N ) { if ( isAdjChar ( ) == false ) { return String . valueOf ( S ) ; } if ( S . length == 2 ) return " - 1" ; rearrangeStringUtil ( N ) ; reverse ( ) ; rearrangeStringUtil ( N ) ; if ( isAdjChar ( ) == false ) { return String . valueOf ( S ) ; } return " - 1" ; } static void reverse ( ) { int l , r = S . length - 1 ; for ( l = 0 ; l < r ; l ++ , r -- ) { char temp = S [ l ] ; S [ l ] = S [ r ] ; S [ r ] = temp ; } } public static void main ( String [ ] args ) { int N = S . length ; System . out . print ( rearrangeString ( N ) ) ; } }


"Rearrange characters of a string to make it a concatenation of palindromic substrings | Java program for the above approach ; Function to check if a string can be modified such that it can be split into palindromic substrings of length >= 2 ; Stores frequencies of characters ; Traverse the string ; Update frequency of each character ; Traverse the frequency array ; Update values of odd and eve ; Print the result ; Driver Code"
How can the above be solved in Java?

import java . io . * ; import java . lang . * ; import java . util . * ; class GFG { static void canSplit ( String S ) { int frequency [ ] = new int [ 26 ] ; int cnt_singles = 0 ; int k = 0 ; for ( int i = 0 ; i < S . length ( ) ; i ++ ) frequency [ S . charAt ( i ) - ' a ' ] ++ ; int odd = 0 , eve = 0 ; for ( int i = 0 ; i < 26 ; i ++ ) { if ( frequency [ i ] != 0 ) { odd += ( frequency [ i ] & 1 ) ; eve += frequency [ i ] / 2 ; } } if ( eve >= odd ) System . out . println ( " Yes " ) ; else System . out . println ( " No " ) ; } public static void main ( String [ ] args ) { String S = " aaabbbccc " ; canSplit ( S ) ; } }


"Rearrange characters to form palindrome if possible | Java program to rearrange a string to make palindrome ; Store counts of characters ; Find the number of odd elements . Takes O ( n ) ; odd_cnt = 1 only if the length of str is odd ; Generate first halh of palindrome ; Build a string of floor ( count / 2 ) occurrences of current character ; Attach the built string to end of and begin of second half ; Insert odd character if there is any ; Driver code"
How can the above be solved in Java?

import java . util . HashMap ; import java . util . Map . Entry ; class GFG { public static String getPalindrome ( String str ) { HashMap < Character , Integer > counting = new HashMap < > ( ) ; for ( char ch : str . toCharArray ( ) ) { if ( counting . containsKey ( ch ) ) { counting . put ( ch , counting . get ( ch ) + 1 ) ; } else { counting . put ( ch , 1 ) ; } } int oddCount = 0 ; char oddChar = 0 ; for ( Entry < Character , Integer > itr : counting . entrySet ( ) ) { if ( itr . getValue ( ) % 2 != 0 ) { oddCount ++ ; oddChar = itr . getKey ( ) ; } } if ( oddCount > 1 || oddCount == 1 && str . length ( ) % 2 == 0 ) { return " NO ▁ PALINDROME " ; } String firstHalf = " " , lastHalf = " " ; for ( Entry < Character , Integer > itr : counting . entrySet ( ) ) { String ss = " " ; for ( int i = 0 ; i < itr . getValue ( ) / 2 ; i ++ ) { ss += itr . getKey ( ) ; } firstHalf = firstHalf + ss ; lastHalf = ss + lastHalf ; } return ( oddCount == 1 ) ? ( firstHalf + oddChar + lastHalf ) : ( firstHalf + lastHalf ) ; } public static void main ( String [ ] args ) { String str = " mdaam " ; System . out . println ( getPalindrome ( str ) ) ; } }


"Rearrange given array to obtain positive prefix sums at exactly X indices | Java program for the above approach ; Function to rearrange the array according to the given condition ; Using 2 nd operation making all values positive ; Sort the array ; Assign K = N - K ; Count number of zeros ; If number of zeros if greater ; Using 2 nd operation convert it into one negative ; Using 2 nd operation convert it into one negative ; Print the array ; Driver Code ; Function Call"
How can the above be solved in Java?

import java . util . * ; class GFG { static int count ( int [ ] a ) { int counter = 0 ; for ( int i = 0 ; i < a . length ; i ++ ) { if ( a [ i ] == 0 ) { counter ++ ; } } return counter ; } static void rearrange ( int [ ] a , int n , int x ) { for ( int i = 0 ; i < n ; i ++ ) a [ i ] = Math . abs ( a [ i ] ) ; Arrays . sort ( a ) ; x = n - x ; int z = count ( a ) ; if ( x > n - z ) { System . out . println ( " - 1" ) ; return ; } for ( int i = 0 ; i < n && x > 0 ; i += 2 ) { a [ i ] = - a [ i ] ; x -- ; } for ( int i = n - 1 ; i >= 0 && x > 0 ; i -- ) { if ( a [ i ] > 0 ) { a [ i ] = - a [ i ] ; x -- ; } } for ( int i = 0 ; i < n ; i ++ ) { System . out . print ( a [ i ] + " ▁ " ) ; } } public static void main ( String [ ] args ) { int arr [ ] = { 0 , - 2 , 4 , 5 , - 3 } ; int K = 3 ; int N = arr . length ; rearrange ( arr , N , K ) ; } }


"Rearrange positive and negative numbers using inbuilt sort function | Java program to implement the above approach ; Rearrange the array with all negative integers on left and positive integers on right use recursion to split the array with first element as one half and the rest array as another and then merge it with head of the array in each step ; exit condition ; rearrange the array except the first element in each recursive call ; If the first element of the array is positive , then right - rotate the array by one place first and then reverse the merged array . ; Driver code"
How can the above be solved in Java?

 import java . io . * ; class GFG { static void printArray ( int [ ] array , int length ) { System . out . print ( " [ " ) ; for ( int i = 0 ; i < length ; i ++ ) { System . out . print ( array [ i ] ) ; if ( i < ( length - 1 ) ) System . out . print ( " , " ) ; else System . out . print ( "]
"); } } static void reverse ( int [ ] array , int start , int end ) { while ( start < end ) { int temp = array [ start ] ; array [ start ] = array [ end ] ; array [ end ] = temp ; start ++ ; end -- ; } } static void rearrange ( int [ ] array , int start , int end ) { if ( start == end ) return ; rearrange ( array , ( start + 1 ) , end ) ; if ( array [ start ] >= 0 ) { reverse ( array , ( start + 1 ) , end ) ; reverse ( array , start , end ) ; } } public static void main ( String [ ] args ) { int [ ] array = { - 12 , - 11 , - 13 , - 5 , - 6 , 7 , 5 , 3 , 6 } ; int length = array . length ; int countNegative = 0 ; for ( int i = 0 ; i < length ; i ++ ) { if ( array [ i ] < 0 ) countNegative ++ ; } System . out . print ( " array : ▁ " ) ; printArray ( array , length ) ; rearrange ( array , 0 , ( length - 1 ) ) ; reverse ( array , countNegative , ( length - 1 ) ) ; System . out . print ( " rearranged ▁ array : ▁ " ) ; printArray ( array , length ) ; } }


"Rearrange sorted array such that all odd indices elements comes before all even indices element | Java program for the above approach ; Function to print the array ; Function to rearrange the array such that odd indexed elements come before even indexed elements ; Reduces the size of array by one because last element does not need to be changed in case N = odd ; Initialize the variables ; Iterate over the range ; Add the modified element at the odd position ; Iterate over the range ; Add the modified element at the even position ; Iterate over the range ; Divide by thr maximum element ; Driver Code"
How can the above be solved in Java?

import java . io . * ; class GFG { static void printTheArray ( int arr [ ] , int N ) { for ( int i = 0 ; i < N ; i ++ ) System . out . print ( arr [ i ] + " ▁ " ) ; } static void rearrange ( int arr [ ] , int N ) { if ( ( N & 1 ) != 0 ) N -- ; int odd_idx = 1 , even_idx = 0 ; int i , max_elem = arr [ N - 1 ] + 1 ; for ( i = 0 ; i < N / 2 ; i ++ ) { arr [ i ] += ( arr [ odd_idx ] % max_elem ) * max_elem ; odd_idx += 2 ; } for ( ; i < N ; i ++ ) { arr [ i ] += ( arr [ even_idx ] % max_elem ) * max_elem ; even_idx += 2 ; } for ( i = 0 ; i < N ; i ++ ) { arr [ i ] = arr [ i ] / max_elem ; } } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 2 , 3 , 4 , 5 , 16 , 18 , 19 } ; int N = arr . length ; rearrange ( arr , N ) ; printTheArray ( arr , N ) ; } }


"Rearrange string such that no pair of adjacent characters are of the same type | Java program to implement the above approach ; Function to rearrange given alphanumeric String such that no two adjacent characters are of the same type ; Stores alphabets and digits ; Store the alphabets and digits separately in the Strings ; Stores the count of alphabets and digits ; If respective counts differ by 1 ; Desired arrangement not possible ; Stores the indexes ; Check if first character should be alphabet or digit ; Place alphabets and digits alternatively ; If current character needs to be alphabet ; If current character needs to be a digit ; Flip flag for alternate arrangement ; Return resultant String ; Driver Code ; Given String ; Function Call"
How can the above be solved in Java?

 class GFG { static String rearrange ( String s ) { String s1 = " " , s2 = " " , ans = " " ; char [ ] s3 = s . toCharArray ( ) ; for ( char x : s3 ) { if ( x >= ' a ' && x <= ' z ' ) s1 += x ; else s2 += x ; } int n = s1 . length ( ) ; int m = s2 . length ( ) ; if ( Math . abs ( n - m ) > 1 ) return " - 1" ; int i = 0 , j = 0 , k = 0 ; int flag = ( n >= m ) ? 1 : 0 ; while ( i < n && j < m ) { if ( flag != 0 ) ans += s1 . charAt ( i ++ ) ; else ans += s2 . charAt ( j ++ ) ; if ( flag == 1 ) flag = 0 ; else flag = 1 ; } return ans ; } public static void main ( String [ ] args ) { String str = " geeks2020" ; System . out . print ( rearrange ( str ) + "
"); } }


"Rearrange string to obtain Longest Palindromic Substring | Java program to implement the above approach ; Function to rearrange the string to get the longest palindromic substring ; Stores the length of str ; Store the count of occurrence of each character ; Traverse the string , str ; Count occurrence of each character ; Store the left half of the longest palindromic substring ; Store the right half of the longest palindromic substring ; Traverse the array , hash [ ] ; Append half of the characters to res1 ; Append half of the characters to res2 ; reverse string res2 to make res1 + res2 palindrome ; Store the remaining characters ; Check If any odd character appended to the middle of the resultant string or not ; Append all the character which occurs odd number of times ; If count of occurrence of characters is odd ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { static String longestPalinSub ( String str ) { int N = str . length ( ) ; int [ ] hash = new int [ 256 ] ; for ( int i = 0 ; i < N ; i ++ ) { hash [ str . charAt ( i ) ] ++ ; } StringBuilder res1 = new StringBuilder ( ) ; StringBuilder res2 = new StringBuilder ( ) ; for ( int i = 0 ; i < 256 ; i ++ ) { for ( int j = 0 ; j < hash [ i ] / 2 ; j ++ ) { res1 . append ( ( char ) i ) ; } for ( int j = ( hash [ i ] + 1 ) / 2 ; j < hash [ i ] ; j ++ ) { res2 . append ( ( char ) i ) ; } } StringBuilder tmp = res2 . reverse ( ) ; StringBuilder res3 = new StringBuilder ( ) ; boolean f = false ; for ( int i = 0 ; i < 256 ; i ++ ) { if ( hash [ i ] % 2 == 1 ) { if ( ! f ) { res1 . append ( ( char ) i ) ; f = true ; } else { res3 . append ( ( char ) i ) ; } } } return ( res1 . toString ( ) + tmp . toString ( ) + res3 . toString ( ) ) ; } public static void main ( String [ ] args ) { String str = " geeksforgeeks " ; System . out . println ( longestPalinSub ( str ) ) ; } }


"Rearrange the Array to maximize the elements which is smaller than both its adjacent elements | Java program for the above approach ; Function to rearrange array such that count of element that are smaller than their adjacent elements is maximum ; Stores the rearranged array ; Stores the maximum count of elements ; Sort the given array ; Place the smallest ( N - 1 ) / 2 elements at odd indices ; Placing the rest of the elements at remaining indices ; If no element of the array has been placed here ; Print the resultant array ; Driver Code ; Input ; Function call"
How can the above be solved in Java?

import java . io . * ; import java . util . * ; class GFG { public static void maximumIndices ( int arr [ ] , int N ) { int [ ] temp = new int [ N ] ; int maxIndices = ( N - 1 ) / 2 ; Arrays . sort ( arr ) ; for ( int i = 0 ; i < maxIndices ; i ++ ) { temp [ 2 * i + 1 ] = arr [ i ] ; } int j = 0 ; for ( int i = maxIndices ; i < N ; ) { if ( temp [ j ] == 0 ) { temp [ j ] = arr [ i ] ; i ++ ; } j ++ ; } for ( int i = 0 ; i < N ; i ++ ) { System . out . print ( temp [ i ] + " ▁ " ) ; } } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 2 , 3 , 4 } ; int N = 4 ; maximumIndices ( arr , N ) ; } }


"Rearrange the array to maximize the number of primes in prefix sum of the array | Java implementation of the approach ; Function to print the re - arranged array ; Count the number of ones and twos in a [ ] ; If the array element is 1 ; Array element is 2 ; If it has at least one 2 Fill up first 2 ; Decrease the cnt of ones if even ; Fill up with odd count of ones ; Fill up with remaining twos ; If even ones , then fill last position ; Print the rearranged array ; Driver code"
How can the above be solved in Java?

import java . io . * ; class GFG { static void solve ( int a [ ] , int n ) { int ones = 0 , twos = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( a [ i ] == 1 ) ones ++ ; else twos ++ ; } int ind = 0 ; if ( twos > 0 ) a [ ind ++ ] = 2 ; boolean evenOnes = ( ones % 2 == 0 ) ? true : false ; if ( evenOnes ) ones -= 1 ; for ( int i = 0 ; i < ones ; i ++ ) a [ ind ++ ] = 1 ; for ( int i = 0 ; i < twos - 1 ; i ++ ) a [ ind ++ ] = 2 ; if ( evenOnes ) a [ ind ++ ] = 1 ; for ( int i = 0 ; i < n ; i ++ ) System . out . print ( a [ i ] + " ▁ " ) ; } public static void main ( String [ ] args ) { int a [ ] = { 1 , 2 , 1 , 2 , 1 } ; int n = a . length ; solve ( a , n ) ; } }


"Rearrange the string to maximize the number of palindromic substrings | Java program to rearrange the string such to maximize the number of palindromic substrings ; Function to return the newString ; length of string ; hashing array ; iterate and count ; resulting string ; form the resulting string ; number of times character appears ; append to resulting string ; Driver code"
How can the above be solved in Java?

public class GFG { static String newString ( String s ) { int l = s . length ( ) ; int freq [ ] = new int [ 26 ] ; for ( int i = 0 ; i < l ; i ++ ) { freq [ s . charAt ( i ) - ' a ' ] += 1 ; } String ans = " " ; for ( int i = 0 ; i < 26 ; i ++ ) { for ( int j = 0 ; j < freq [ i ] ; j ++ ) { ans += ( char ) ( 97 + i ) ; } } return ans ; } public static void main ( String args [ ] ) { String s = " aabab " ; System . out . println ( newString ( s ) ) ; } }


"Rearrange two given arrays such that sum of same indexed elements lies within given range | Java program for the above approach ; Function to check if there exists any arrangements of the arrays such that sum of element lie in the range [ K / 2 , K ] ; Sort the array arr1 [ ] in increasing order ; Sort the array arr2 [ ] in decreasing order ; Traverse the array ; If condition is not satisfied break the loop ; Print the result ; Driver Code"
How can the above be solved in Java?

import java . io . * ; import java . util . * ; class GFG { static void checkArrangement ( Integer [ ] A1 , Integer [ ] A2 , int n , int k ) { Arrays . sort ( A1 ) ; Arrays . sort ( A2 , Collections . reverseOrder ( ) ) ; int flag = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( ( A1 [ i ] + A2 [ i ] > k ) || ( A1 [ i ] + A2 [ i ] < k / 2 ) ) { flag = 1 ; break ; } } if ( flag == 1 ) System . out . println ( " No " ) ; else System . out . println ( " Yes " ) ; } public static void main ( String [ ] args ) { Integer [ ] arr1 = { 1 , 3 , 4 , 5 } ; Integer [ ] arr2 = { 2 , 0 , 1 , 1 } ; int K = 6 ; int N = arr1 . length ; checkArrangement ( arr1 , arr2 , N , K ) ; } }


"Rearrange two given arrays to maximize sum of same indexed elements | Java program to implement the above approach ; Function to find the maximum possible sum by rearranging the given array elements ; Sort the array A [ ] in ascending order ; Sort the array B [ ] in descending order ; Stores maximum possible sum by rearranging array elements ; Traverse both the arrays ; Update maxSum ; Driver code"
How can the above be solved in Java?

import java . lang . Math ; import java . util . Arrays ; import java . util . Collections ; class GFG { static int MaxRearrngeSum ( Integer A [ ] , Integer B [ ] , int N ) { Arrays . sort ( A ) ; Arrays . sort ( B , Collections . reverseOrder ( ) ) ; int maxSum = 0 ; for ( int i = 0 ; i < N ; i ++ ) { maxSum += Math . abs ( A [ i ] - B [ i ] ) ; } return maxSum ; } public static void main ( String [ ] args ) { Integer A [ ] = { 1 , 2 , 2 , 4 , 5 } ; Integer B [ ] = { 5 , 5 , 5 , 6 , 6 } ; int N = A . length ; System . out . println ( MaxRearrngeSum ( A , B , N ) ) ; } }


"Recaman 's sequence | Java program to print n - th number in Recaman 's sequence ; Prints first n terms of Recaman sequence ; Create an array to store terms ; First term of the sequence is always 0 ; Fill remaining terms using recursive formula . ; If arr [ i - 1 ] - i is negative or already exists . ; Driver code"
How can the above be solved in Java?

import java . io . * ; class GFG { static void recaman ( int n ) { int arr [ ] = new int [ n ] ; arr [ 0 ] = 0 ; System . out . print ( arr [ 0 ] + " ▁ , " ) ; for ( int i = 1 ; i < n ; i ++ ) { int curr = arr [ i - 1 ] - i ; int j ; for ( j = 0 ; j < i ; j ++ ) { if ( ( arr [ j ] == curr ) curr < 0 ) { curr = arr [ i - 1 ] + i ; break ; } } arr [ i ] = curr ; System . out . print ( arr [ i ] + " , ▁ " ) ; } } public static void main ( String [ ] args ) { int n = 17 ; recaman ( n ) ; } }


"Recaman 's sequence | Java program to print n - th number in Recaman 's sequence ; Prints first n terms of Recaman sequence ; Print first term and store it in a hash ; Print remaining terms using recursive formula . ; If arr [ i - 1 ] - i is negative or already exists . ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { static void recaman ( int n ) { if ( n <= 0 ) return ; System . out . printf ( " % d , ▁ " , 0 ) ; HashSet < Integer > s = new HashSet < Integer > ( ) ; s . add ( 0 ) ; int prev = 0 ; for ( int i = 1 ; i < n ; i ++ ) { int curr = prev - i ; if ( curr < 0 || s . contains ( curr ) ) curr = prev + i ; s . add ( curr ) ; System . out . printf ( " % d , ▁ " , curr ) ; prev = curr ; } } public static void main ( String [ ] args ) { int n = 17 ; recaman ( n ) ; } }


"Rectangle with minimum possible difference between the length and the width | Java implementation of the approach ; Function to print the length ( l ) and breadth ( b ) of the rectangle having area = N and | l - b | as minimum as possible ; Driver code"
How can the above be solved in Java?

import java . io . * ; class GFG { static void find_rectangle ( int area ) { for ( int i = ( int ) Math . ceil ( Math . sqrt ( area ) ) ; i <= area ; i ++ ) { if ( area / i * i == area ) { System . out . println ( i + " ▁ " + ( int ) ( area / i ) ) ; return ; } } } public static void main ( String [ ] args ) { int area = 99 ; find_rectangle ( area ) ; } }


"Rectangle with minimum possible difference between the length and the width | Java implementation of the approach ; Function to print the length ( l ) and breadth ( b ) of the rectangle having area = N and | l - b | as minimum as possible ; i is a factor ; l >= sqrt ( area ) >= i ; so here l is + ve always ; Here l and b are length and breadth of the rectangle ; Driver code"
How can the above be solved in Java?

class GFG { static void find_rectangle ( int area ) { int l = 0 , b = 0 ; int M = ( int ) Math . sqrt ( area ) , ans ; for ( int i = M ; i >= 1 ; i -- ) { if ( area % i == 0 ) { l = ( area / i ) ; b = i ; break ; } } System . out . println ( " l ▁ = ▁ " + l + " , ▁ b ▁ = ▁ " + b ) ; } public static void main ( String [ ] args ) { int area = 99 ; find_rectangle ( area ) ; } }


"Rectangular ( or Pronic ) Numbers | Java Program to find n - th rectangular number ; Returns n - th rectangular number ; Driver code"
How can the above be solved in Java?

import java . io . * ; class GFG { static int findRectNum ( int n ) { return n * ( n + 1 ) ; } public static void main ( String [ ] args ) { int n = 6 ; System . out . println ( findRectNum ( n ) ) ; } }


"Recursive Implementation of atoi ( ) | Recursive Java program to compute atoi ( ) ; Recursive function to compute atoi ( ) ; Base case ( Only one digit ) ; If more than 1 digits , recur for ( n - 1 ) , multiplu result with 10 and add last digit ; Driver code"
How can the above be solved in Java?

class GFG { static int myAtoiRecursive ( String str , int n ) { if ( n == 1 ) { return str . charAt ( 0 ) - '0' ; } return ( 10 * myAtoiRecursive ( str , n - 1 ) + str . charAt ( n - 1 ) - '0' ) ; } public static void main ( String [ ] s ) { String str = "112" ; int n = str . length ( ) ; System . out . println ( myAtoiRecursive ( str , n ) ) ; } }


"Recursive Program to print multiplication table of a number | Java program to print table of a number using recursion ; Function that print the table of a given number using recursion ; Base Case ; Print the table for current iteration ; Recursive call to next iteration ; Driver Code ; Input number whose table is to print ; Function call to print the table"
How can the above be solved in Java?

class GFG { static void mul_table ( int N , int i ) { if ( i > 10 ) return ; System . out . println ( N + " ▁ * ▁ " + i + " ▁ = ▁ " + N * i ) ; mul_table ( N , i + 1 ) ; } public static void main ( String [ ] args ) { int N = 8 ; mul_table ( N , 1 ) ; } }


"Recursive Programs to find Minimum and Maximum elements of array | Recursive Java program to find maximum ; function to return maximum element using recursion ; if size = 0 means whole array has been traversed ; Driver code ; Function calling"
How can the above be solved in Java?

import java . util . * ; class GFG { public static int findMaxRec ( int A [ ] , int n ) { if ( n == 1 ) return A [ 0 ] ; return Math . max ( A [ n - 1 ] , findMaxRec ( A , n - 1 ) ) ; } public static void main ( String args [ ] ) { int A [ ] = { 1 , 4 , 45 , 6 , - 50 , 10 , 2 } ; int n = A . length ; System . out . println ( findMaxRec ( A , n ) ) ; } }


"Recursive Programs to find Minimum and Maximum elements of array | Recursive Java program to find minimum ; function to return minimum element using recursion ; if size = 0 means whole array has been traversed ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { public static int findMinRec ( int A [ ] , int n ) { if ( n == 1 ) return A [ 0 ] ; return Math . min ( A [ n - 1 ] , findMinRec ( A , n - 1 ) ) ; } public static void main ( String args [ ] ) { int A [ ] = { 1 , 4 , 45 , 6 , - 50 , 10 , 2 } ; int n = A . length ; System . out . println ( findMinRec ( A , n ) ) ; } }


"Recursive function to check if a string is palindrome | A recursive JAVA program to check whether a given String is palindrome or not ; A recursive function that check a str ( s . . e ) is palindrome or not . ; If there is only one character ; If first and last characters do not match ; If there are more than two characters , check if middle substring is also palindrome or not . ; An empty string is considered as palindrome ; Driver Code"
How can the above be solved in Java?

import java . io . * ; class GFG { static boolean isPalRec ( String str , int s , int e ) { if ( s == e ) return true ; if ( ( str . charAt ( s ) ) != ( str . charAt ( e ) ) ) return false ; if ( s < e + 1 ) return isPalRec ( str , s + 1 , e - 1 ) ; return true ; } static boolean isPalindrome ( String str ) { int n = str . length ( ) ; if ( n == 0 ) return true ; return isPalRec ( str , 0 , n - 1 ) ; } public static void main ( String args [ ] ) { String str = " geeg " ; if ( isPalindrome ( str ) ) System . out . println ( " Yes " ) ; else System . out . println ( " No " ) ; } }


"Recursive program for prime number | java Program to find whether a Number is Prime or Not using Recursion ; Returns true if n is prime , else return false . i is current divisor to check . ; Base cases ; Check for next divisor ; Driver program to test above function"
How can the above be solved in Java?

import java . util . * ; class GFG { static boolean isPrime ( int n , int i ) { if ( n <= 2 ) return ( n == 2 ) ? true : false ; if ( n % i == 0 ) return false ; if ( i * i > n ) return true ; return isPrime ( n , i + 1 ) ; } public static void main ( String [ ] args ) { int n = 15 ; if ( isPrime ( n , 2 ) ) System . out . println ( " Yes " ) ; else System . out . println ( " No " ) ; } }


"Recursive program to check if number is palindrome or not | Recursive Java program to check if the number is palindrome or not ; recursive function that returns the reverse of digits ; base case ; stores the reverse of a number ; Driver Code"
How can the above be solved in Java?

import java . io . * ; class GFG { static int rev ( int n , int temp ) { if ( n == 0 ) return temp ; temp = ( temp * 10 ) + ( n % 10 ) ; return rev ( n / 10 , temp ) ; } public static void main ( String [ ] args ) { int n = 121 ; int temp = rev ( n , 0 ) ; if ( temp == n ) System . out . println ( " yes " ) ; else System . out . println ( " no " ) ; } }


"Recursive program to insert a star between pair of identical characters | Recursive Java program to insert * between two consecutive same characters . ; Function to insert * at desired position ; Append current character ; If we reached last character ; If next character is same , append ' * ' ; Driver code"
How can the above be solved in Java?

class GFG { static String output = " " ; static void pairStar ( String input , int i ) { output = output + input . charAt ( i ) ; if ( i == input . length ( ) - 1 ) return ; if ( input . charAt ( i ) == input . charAt ( i + 1 ) ) output = output + ' * ' ; pairStar ( input , i + 1 ) ; } public static void main ( String [ ] args ) { String input = " geeks " ; pairStar ( input , 0 ) ; System . out . println ( output ) ; } }


"Recursive program to replace all occurrences of pi with 3.14 in a given string | Java program for above approach ; A simple recursive approach to replace all pi in a given function with "3.14" . Firstly function is declared we don 't  need any helper function one  function is enough ; Base case if s is empty or length of s is 1 return the s ; If the 0 th and 1 st element of s are p and i we have to handle them for rest we have to call recursion it will give the result ; Smalloutput is a variable used to store recursion result ; And we have to add the recursion result with the first part we handled and return the answer ; If not then we have to call recursion from 1 st to all elements then add recursion result to 1 st element and return it ; Driver code ; Function call"
How can the above be solved in Java?

class GFG { public static String replacePi ( String s ) { if ( s . length ( ) == 0 || s . length ( ) == 1 ) return s ; if ( s . charAt ( 0 ) == ' p ' && s . charAt ( 1 ) == ' i ' ) { String smallOutput = replacePi ( s . substring ( 2 ) ) ; return "3.14" + smallOutput ; } else { String smallOutput = replacePi ( s . substring ( 1 ) ) ; return s . charAt ( 0 ) + smallOutput ; } } public static void main ( String [ ] args ) { String s = " pipppiiipi " ; String result = replacePi ( s ) ; System . out . println ( result ) ; } }