"Gapful Numbers | Java program for the above approach ; Find the first digit ; Find total number of digits - 1 ; Find first digit ; Return first digit ; Find the last digit ; Return the last digit ; A function to check Gapful numbers ; Return true if n is gapful number ; Driver code ; Given number ; Function call"
How can the above be solved in Java?

class GFG { static int firstDigit ( int n ) { int digits = ( int ) ( Math . log ( n ) / Math . log ( 10 ) ) ; n = ( int ) ( n / Math . pow ( 10 , digits ) ) ; return n ; } static int lastDigit ( int n ) { return ( n % 10 ) ; } static boolean isGapful ( int n ) { int first_dig = firstDigit ( n ) ; int last_dig = lastDigit ( n ) ; int concatenation = first_dig * 10 + last_dig ; return ( n % concatenation == 0 ) ; } public static void main ( String [ ] args ) { int n = 108 ; if ( isGapful ( n ) ) System . out . print ( " Yes " ) ; else System . out . print ( " No " ) ; } }


"Geek | Java program for the above approach ; Function to calculate the N - th Geek - onacci Number ; Stores the geekonacci series ; Store the first three terms of the series ; Iterate over the range [ 3 , N ] ; Update the value of arr [ i ] as the sum of previous 3 terms in the series ; Return the last element of arr [ ] as the N - th term ; Driver Code"
How can the above be solved in Java?

import java . io . * ; import java . lang . * ; import java . util . * ; class GFG { static int find ( int A , int B , int C , int N ) { int [ ] arr = new int [ N ] ; arr [ 0 ] = A ; arr [ 1 ] = B ; arr [ 2 ] = C ; for ( int i = 3 ; i < N ; i ++ ) { arr [ i ] = arr [ i - 1 ] + arr [ i - 2 ] + arr [ i - 3 ] ; } return arr [ N - 1 ] ; } public static void main ( String [ ] args ) { int A = 1 , B = 3 , C = 2 , N = 4 ; System . out . print ( find ( A , B , C , N ) ) ; } }


"Generate 0 and 1 with 25 % and 75 % probability | Java program to print 1 with 75 % probability and 0 with 25 % probability ; Random Function to that returns 0 or 1 with equal probability ; rand ( ) function will generate odd or even number with equal probability . If rand ( ) generates odd number , the function will return 1 else it will return 0. ; Random Function to that returns 1 with 75 % probability and 0 with 25 % probability using Bitwise OR ; Driver code ; Initialize random number generator srand ( time ( null ) ) ;"
How can the above be solved in Java?

class GFG { static int rand50 ( ) { return ( int ) ( 10 * Math . random ( ) ) & 1 ; } static int rand75 ( ) { return rand50 ( ) | rand50 ( ) ; } public static void main ( String [ ] args ) { for ( int i = 0 ; i < 50 ; i ++ ) { System . out . print ( rand75 ( ) ) ; } } }


"Generate Array whose difference of each element with its left yields the given Array | Java implementation of the above approach ; Function to find the sequence ; Initializing 1 st element ; Creating sequence in terms of x ; Finding min element ; Finding value of x ; Creating original sequence ; Output original sequence ; Driver code"
How can the above be solved in Java?

class GFG { static void find_seq ( int arr [ ] , int m , int n ) { int b [ ] = new int [ n ] ; int x = 0 ; b [ 0 ] = x ; for ( int i = 0 ; i < n - 1 ; i ++ ) { b [ i + 1 ] = x + arr [ i ] + b [ i ] ; } int mn = n ; for ( int i = 0 ; i < n ; i ++ ) { mn = Math . min ( mn , b [ i ] ) ; } x = 1 - mn ; for ( int i = 0 ; i < n ; i ++ ) { b [ i ] += x ; } for ( int i = 0 ; i < n ; i ++ ) { System . out . print ( b [ i ] + " ▁ " ) ; } System . out . println ( ) ; } public static void main ( String [ ] args ) { int N = 3 ; int arr [ ] = new int [ ] { - 2 , 1 } ; int M = arr . length ; find_seq ( arr , M , N ) ; } }


"Generate Binary Strings of length N using Branch and Bound | Java Program to generate Binary Strings using Branch and Bound ; Creating a Node class ; Queue that maintains the list of live Nodes ; Utility function to generate binary strings of length n ; If list is full print combination ; Create a new vector for new combination ; iterate while length is not equal to n ; Driver code ; Initiate Generation Create a root Node ; Instantiate the Queue"
How can the above be solved in Java?

import java . io . * ; import java . util . * ; class Node { int soln [ ] ; int level ; ArrayList < Node > child ; Node parent ; Node ( Node parent , int level , int N ) { this . parent = parent ; this . level = level ; this . soln = new int [ N ] ; } } class GFG { static int N ; public static Queue < Node > Q ; public static void generate ( Node n ) { if ( n . level == N ) { for ( int i = 0 ; i <= N - 1 ; i ++ ) { System . out . print ( n . soln [ i ] ) ; } System . out . println ( ) ; } else { n . child = new ArrayList < Node > ( ) ; int l = n . level ; for ( int i = 0 ; i <= 1 ; i ++ ) { Node x = new Node ( n , l + 1 , N ) ; for ( int k = 0 ; k < l ; k ++ ) { x . soln [ k ] = n . soln [ k ] ; } x . soln [ l ] = i ; n . child . add ( x ) ; Q . add ( x ) ; } } } public static void main ( String args [ ] ) { N = 3 ; Node root = new Node ( null , 0 , N ) ; Q = new LinkedList < Node > ( ) ; Q . add ( root ) ; while ( Q . size ( ) != 0 ) { Node E = Q . poll ( ) ; generate ( E ) ; } } }


"Generate Bitonic Sequence of length N from integers in a given range | Java program for the above approach ; Function to construct bitonic sequence of length N from integers in the range [ L , R ] ; If sequence is not possible ; Store the resultant list ; If size of deque < n ; Add elements from start ; Print the stored in the list ; Driver Code ; Function Call"
How can the above be solved in Java?

import java . util . * ; class GFG { public static void bitonicSequence ( int num , int lower , int upper ) { if ( num > ( upper - lower ) * 2 + 1 ) { System . out . println ( - 1 ) ; return ; } Deque < Integer > ans = new ArrayDeque < > ( ) ; for ( int i = 0 ; i < Math . min ( upper - lower + 1 , num - 1 ) ; i ++ ) ans . add ( upper - i ) ; for ( int i = 0 ; i < num - ans . size ( ) ; i ++ ) ans . addFirst ( upper - i - 1 ) ; System . out . println ( ans ) ; } public static void main ( String [ ] args ) { int N = 5 , L = 3 , R = 10 ; bitonicSequence ( N , L , R ) ; } }


"Generate K co | Java implementation of the above approach ; Function prints the required pairs ; First co - prime pair ; As a pair ( 1 n ) has already been Printed ; If i is a factor of N ; Since ( i , i ) won 't form  a coprime pair ; Driver Code"
How can the above be solved in Java?

 import java . util . * ; class GFG { static void FindPairs ( int n , int k ) { System . out . print ( 1 + " ▁ " + n + "
"); k -- ; for ( long i = 2 ; i <= Math . sqrt ( n ) ; i ++ ) { if ( n % i == 0 ) { System . out . print ( 1 + " ▁ " + i + "
"); k -- ; if ( k == 0 ) break ; if ( i != n / i ) { System . out . print ( 1 + " ▁ " + n / i + "
"); k -- ; } if ( k == 0 ) break ; } } } public static void main ( String [ ] args ) { int N = 100 ; int K = 5 ; FindPairs ( N , K ) ; } }


"Generate N integers satisfying the given conditions | Java implementation of the approach ; Create a boolean array " prime [ 0 . . n ] " and initialize all entries it as true . A value in prime [ i ] will finally be false if i is Not a prime , else true . ; If prime [ p ] is not changed , then it is a prime ; Set all multiples of p to non - prime ; Function to find the first n odd prime numbers ; To store the current count of prime numbers ; Starting with 3 as 2 is an even prime number ; If i is prime ; Print i and increment count ; Driver code ; Create the sieve"
How can the above be solved in Java?

import java . util . * ; class GFG { static int MAX = 1000000 ; static boolean [ ] prime = new boolean [ MAX + 1 ] ; static void SieveOfEratosthenes ( ) { for ( int i = 0 ; i <= MAX ; i ++ ) prime [ i ] = true ; prime [ 1 ] = false ; for ( int p = 2 ; p * p <= MAX ; p ++ ) { if ( prime [ p ] == true ) { for ( int i = p * 2 ; i <= MAX ; i += p ) prime [ i ] = false ; } } } static void solve ( int n ) { int count = 0 ; for ( int i = 3 ; count < n ; i ++ ) { if ( prime [ i ] ) { System . out . print ( i + " ▁ " ) ; count ++ ; } } } public static void main ( String [ ] args ) { SieveOfEratosthenes ( ) ; int n = 6 ; solve ( n ) ; } }


"Generate a Binary String without any consecutive 0 ' s ▁ and ▁ at ▁ most ▁ K ▁ consecutive ▁ 1' s | Java implementation of the above approach ; Function to construct the binary string ; Conditions when string construction is not possible ; Stores maximum 1 's that  can be placed in between ; Place 0 's ; Place 1 's in between ; Count remaining M 's ; Place 1 's at the end ; Place 1 's at the beginning ; Return the final string ; Driver code"
How can the above be solved in Java?

class GFG { static String ConstructBinaryString ( int N , int M , int K ) { if ( M < ( N - 1 ) || M > K * ( N + 1 ) ) return " - 1" ; String ans = " " ; int l = Math . min ( K , M / ( N - 1 ) ) ; int temp = N ; while ( temp != 0 ) { temp -- ; ans += '0' ; if ( temp == 0 ) break ; for ( int i = 0 ; i < l ; i ++ ) { ans += '1' ; } } M -= ( N - 1 ) * l ; if ( M == 0 ) return ans ; l = Math . min ( M , K ) ; for ( int i = 0 ; i < l ; i ++ ) ans += '1' ; M -= l ; while ( M > 0 ) { ans = '1' + ans ; M -- ; } return ans ; } public static void main ( String [ ] args ) { int N = 5 , M = 9 , K = 2 ; System . out . println ( ConstructBinaryString ( N , M , K ) ) ; } }


"Generate a Matrix such that given Matrix elements are equal to Bitwise OR of all corresponding row and column elements of generated Matrix | Java program for the above approach ; Function to find the matrix , A [ ] [ ] satisfying the given conditions ; Store the final matrix ; Initialize all the elements of the matrix A with 1 ; Traverse the matrix B [ ] [ ] row - wise ; If B [ i ] [ j ] is equal to 0 ; Mark all the elements of ith row of A [ ] [ ] as 0 ; Mark all the elements of jth column of A [ ] [ ] as 0 ; Check if the matrix B [ ] [ ] can be made using matrix A [ ] [ ] ; Store the bitwise OR of all elements of A [ ] [ ] in ith row and jth column ; Traverse through ith row ; Traverse through jth column ; If B [ i ] [ j ] is not equal to c , print " Not ▁ Possible " ; Print the final matrix A [ ] [ ] ; Driver Code ; Function Call"
How can the above be solved in Java?

import java . io . * ; class GFG { static void findOriginalMatrix ( int [ ] [ ] B , int N , int M ) { int [ ] [ ] A = new int [ N ] [ M ] ; for ( int i = 0 ; i < N ; ++ i ) { for ( int j = 0 ; j < M ; ++ j ) { A [ i ] [ j ] = 1 ; } } for ( int i = 0 ; i < N ; ++ i ) { for ( int j = 0 ; j < M ; ++ j ) { if ( B [ i ] [ j ] == 0 ) { for ( int k = 0 ; k < M ; ++ k ) { A [ i ] [ k ] = 0 ; } for ( int k = 0 ; k < N ; ++ k ) { A [ k ] [ j ] = 0 ; } } } } for ( int i = 0 ; i < N ; ++ i ) { for ( int j = 0 ; j < M ; ++ j ) { int c = 0 ; for ( int k = 0 ; k < M ; ++ k ) { if ( c == 1 ) break ; c += A [ i ] [ k ] ; } for ( int k = 0 ; k < N ; ++ k ) { if ( c == 1 ) break ; c += A [ k ] [ j ] ; } if ( c != B [ i ] [ j ] ) { System . out . println ( " Not ▁ Possible " ) ; return ; } } } for ( int i = 0 ; i < N ; ++ i ) { for ( int j = 0 ; j < M ; ++ j ) { System . out . print ( A [ i ] [ j ] + " ▁ " ) ; } System . out . println ( ) ; } } public static void main ( String [ ] args ) { int [ ] [ ] B = new int [ ] [ ] { { 1 , 1 , 1 } , { 1 , 1 , 1 } } ; int N = B . length ; int M = B [ 0 ] . length ; findOriginalMatrix ( B , N , M ) ; } }


"Generate a String from given Strings P and Q based on the given conditions | Java Program to implement the above approach ; Function to generate a string S from string P and Q according to the given conditions ; Stores the frequencies ; Counts occurrences of each characters ; Reduce the count of the character which is also present in Q ; Stores the resultant string ; Index in freq [ ] to segregate the string ; Add Q to the resulting string ; Driver Code ; Function call"
How can the above be solved in Java?

import java . util . * ; import java . lang . * ; import java . io . * ; class GFG { public static void manipulateStrings ( String P , String Q ) { int [ ] freq = new int [ 26 ] ; for ( int i = 0 ; i < P . length ( ) ; i ++ ) { freq [ P . charAt ( i ) - ' a ' ] ++ ; } for ( int i = 0 ; i < Q . length ( ) ; i ++ ) { freq [ Q . charAt ( i ) - ' a ' ] -- ; } StringBuilder sb = new StringBuilder ( ) ; int pos = Q . charAt ( 0 ) - ' a ' ; for ( int i = 0 ; i <= pos ; i ++ ) { while ( freq [ i ] > 0 ) { char c = ( char ) ( ' a ' + i ) ; sb . append ( c ) ; freq [ i ] -- ; } } sb . append ( Q ) ; for ( int i = pos + 1 ; i < 26 ; i ++ ) { while ( freq [ i ] > 0 ) { char c = ( char ) ( ' a ' + i ) ; sb . append ( c ) ; freq [ i ] -- ; } } System . out . println ( sb ) ; } public static void main ( String [ ] args ) { String P = " geeksforgeeksfor " ; String Q = " for " ; manipulateStrings ( P , Q ) ; } }


"Generate a String of having N * N distinct non | Java Program to implement the above approach ; Function to construct a string having N * N non - palindromic substrings ; Driver Code"
How can the above be solved in Java?

class GFG { static void createString ( int N ) { for ( int i = 0 ; i < N ; i ++ ) { System . out . print ( ' a ' ) ; } for ( int i = 0 ; i < N ; i ++ ) { System . out . print ( ' b ' ) ; } } public static void main ( String [ ] args ) { int N = 4 ; createString ( N ) ; } }


"Generate a circular permutation with number of mismatching bits between pairs of adjacent elements exactly 1 | Java program for the above approach ; Function to find the permutation of integers from a given range such that number of mismatching bits between pairs of adjacent elements is 1 ; Initialize an arrayList to store the resultant permutation ; Store the index of rotation ; Iterate over the range [ 0 , N - 1 ] ; Traverse all the array elements up to ( 2 ^ k ) - th index in reverse ; If current element is S ; Check if S is zero ; Rotate the array by index value to the left ; Driver Code"
How can the above be solved in Java?

import java . io . * ; import java . util . * ; class GFG { public static List < Integer > circularPermutation ( int n , int start ) { List < Integer > res = new ArrayList < > ( List . of ( 0 ) ) , ret = new ArrayList < > ( ) ; int index = - 1 ; for ( int k = 0 , add = 1 << k ; k < n ; k ++ , add = 1 << k ) { for ( int i = res . size ( ) - 1 ; i >= 0 ; i -- ) { if ( res . get ( i ) + add == start ) index = res . size ( ) ; res . add ( res . get ( i ) + add ) ; } } if ( start == 0 ) return res ; while ( ret . size ( ) < res . size ( ) ) { ret . add ( res . get ( index ) ) ; index = ( index + 1 ) % res . size ( ) ; } return ret ; } public static void main ( String [ ] args ) { int N = 2 , S = 3 ; System . out . println ( circularPermutation ( N , S ) ) ; } }


"Generate a combination of minimum coins that sums to a given value | Java program for the above approach ; dp array to memoize the results ; List to store the result ; Function to find the minimum number of coins to make the sum equals to X ; Base case ; If previously computed subproblem occurred ; Initialize result ; Try every coin that has smaller value than n ; Check for Integer . MAX_VALUE to avoid overflow and see if result can be minimized ; Memoizing value of current state ; Function to find the possible combination of coins to make the sum equal to X ; Base Case ; Print Solutions ; Try every coin that has value smaller than n ; Add current denominations ; Backtrack ; Function to find the minimum combinations of coins for value X ; Initialize dp with - 1 ; Min coins ; If no solution exists ; Backtrack to find the solution ; Driver code ; Set of possible denominations ; Function Call"
How can the above be solved in Java?

import java . util . * ; class GFG { static final int MAX = 100000 ; static int [ ] dp = new int [ MAX + 1 ] ; static List < Integer > denomination = new LinkedList < Integer > ( ) ; static int countMinCoins ( int n , int C [ ] , int m ) { if ( n == 0 ) { dp [ 0 ] = 0 ; return 0 ; } if ( dp [ n ] != - 1 ) return dp [ n ] ; int ret = Integer . MAX_VALUE ; for ( int i = 0 ; i < m ; i ++ ) { if ( C [ i ] <= n ) { int x = countMinCoins ( n - C [ i ] , C , m ) ; if ( x != Integer . MAX_VALUE ) ret = Math . min ( ret , 1 + x ) ; } } dp [ n ] = ret ; return ret ; } static void findSolution ( int n , int C [ ] , int m ) { if ( n == 0 ) { for ( int it : denomination ) { System . out . print ( it + " ▁ " ) ; } return ; } for ( int i = 0 ; i < m ; i ++ ) { if ( n - C [ i ] >= 0 && dp [ n - C [ i ] ] + 1 == dp [ n ] ) { denomination . add ( C [ i ] ) ; findSolution ( n - C [ i ] , C , m ) ; break ; } } } static void countMinCoinsUtil ( int X , int C [ ] , int N ) { for ( int i = 0 ; i < dp . length ; i ++ ) dp [ i ] = - 1 ; int isPossible = countMinCoins ( X , C , N ) ; if ( isPossible == Integer . MAX_VALUE ) { System . out . print ( " - 1" ) ; } else { findSolution ( X , C , N ) ; } } public static void main ( String [ ] args ) { int X = 21 ; int arr [ ] = { 2 , 3 , 4 , 5 } ; int N = arr . length ; countMinCoinsUtil ( X , arr , N ) ; } }


"Generate a list of n consecutive composite numbers ( An interesting method ) | Java program to print n consecutive composite numbers ; function to find factorial of given number ; Prints n consecutive numbers . ; Driver program to test above function"
How can the above be solved in Java?

class GFG { static long factorial ( int n ) { long res = 1 ; for ( int i = 2 ; i <= n ; i ++ ) { res *= i ; } return res ; } static void printNComposite ( int n ) { long fact = factorial ( n + 1 ) ; for ( int i = 2 ; i <= n + 1 ; ++ i ) { System . out . print ( fact + i + " ▁ " ) ; } } public static void main ( String [ ] args ) { int n = 4 ; printNComposite ( n ) ; } }


"Generate a matrix having even sum of all diagonals in each 2 x 2 submatrices | Java program for the above approach ; Function to construct a matrix such that the sum elements in both diagonals of every 2 * 2 matrices is even ; Stores odd numbers ; Stores even numbers ; Store matrix elements such that sum of elements in both diagonals of every 2 * 2 submatrices is even ; Fill all the values of matrix elements ; Update odd ; Update even ; Print the matrix ; Driver Code"
How can the above be solved in Java?

import java . io . * ; class GFG { static void generateMatrix ( int N ) { int odd = 1 ; int even = 2 ; int [ ] [ ] mat = new int [ N + 1 ] [ N + 1 ] ; for ( int i = 1 ; i <= N ; i ++ ) { for ( int j = 1 ; j <= N ; j ++ ) { if ( ( i + j ) % 2 == 0 ) { mat [ i ] [ j ] = odd ; odd += 2 ; } else { mat [ i ] [ j ] = even ; even += 2 ; } } } for ( int i = 1 ; i <= N ; i ++ ) { for ( int j = 1 ; j <= N ; j ++ ) { System . out . print ( mat [ i ] [ j ] + " ▁ " ) ; } System . out . println ( ) ; } } public static void main ( String [ ] args ) { int N = 4 ; generateMatrix ( N ) ; } }


"Generate a matrix having sum of secondary diagonal equal to a perfect square | Java program for the above approach ; Function to print the matrix whose sum of element in secondary diagonal is a perfect square ; Iterate for next N - 1 rows ; Print the current row after the left shift ; Driver Code ; Given N ; Fill the array with elements ranging from 1 to N ; Function Call"
How can the above be solved in Java?

class GFG { static void diagonalSumPerfectSquare ( int [ ] arr , int N ) { for ( int i = 0 ; i < N ; i ++ ) { for ( int j = 0 ; j < N ; j ++ ) { System . out . print ( arr [ ( j + i ) % 7 ] + " ▁ " ) ; } System . out . println ( ) ; } } public static void main ( String [ ] srgs ) { int N = 7 ; int [ ] arr = new int [ N ] ; for ( int i = 0 ; i < N ; i ++ ) { arr [ i ] = i + 1 ; } diagonalSumPerfectSquare ( arr , N ) ; } }


"Generate a matrix with each row and column of given sum | Java program for the above approach ; Function to generate a matrix with sum of each row equal to sum of r [ ] and sum of each column equal to sum of c [ ] ; Initialize a matrix ; Traverse each cell ( i , j ) of the matrix ; Assign the minimum of the row or column value ; Subtract the minimum from both row and column sum ; Print the matrix obtained ; Driver Code"
How can the above be solved in Java?

import java . io . * ; class GFG { static int [ ] [ ] restoreGem ( int [ ] r , int [ ] c ) { int [ ] [ ] dp = new int [ r . length ] [ c . length ] ; for ( int i = 0 ; i < r . length ; i ++ ) { for ( int j = 0 ; j < c . length ; j ++ ) { int m = Math . min ( r [ i ] , c [ j ] ) ; dp [ i ] [ j ] = m ; r [ i ] -= m ; c [ j ] -= m ; } } return dp ; } static void printMatrix ( int [ ] [ ] ans , int N , int M ) { for ( int i = 0 ; i < N ; i ++ ) { for ( int j = 0 ; j < M ; j ++ ) { System . out . print ( ans [ i ] [ j ] + " ▁ " ) ; } System . out . println ( ) ; } } public static void main ( String [ ] args ) { int [ ] rowSum = { 5 , 7 , 10 } ; int [ ] colSum = { 8 , 6 , 8 } ; int [ ] [ ] ans = restoreGem ( rowSum , colSum ) ; printMatrix ( ans , rowSum . length , colSum . length ) ; } }


"Generate a pair of integers from a range [ L , R ] whose LCM also lies within the range | Java implementation of the above approach ; Checking if any pair is possible or not in range ( l , r ) ; If not possible print ( - 1 ) ; Print LCM pair ; Driver code ; Function call"
How can the above be solved in Java?

 import java . util . * ; class GFG { static void lcmpair ( int l , int r ) { int x , y ; x = l ; y = 2 * l ; if ( y > r ) { System . out . print ( "-1
"); } else { System . out . print ( " X ▁ = ▁ " + x + " ▁ Y ▁ = ▁ " + y + "
"); } } public static void main ( String [ ] args ) { int l = 13 , r = 69 ; lcmpair ( l , r ) ; } }


"Generate a permutation of first N natural numbers having count of unique adjacent differences equal to K | Java program for the above approach ; Function to construct the list with exactly K unique adjacent element differences ; Stores the resultant array ; Stores the left and the right most element of the range ; Traverse the array ; If k is even , the add left to array and increment the left ; If k is odd , the add right to array and decrement the right ; Repeat the steps for k - 1 times ; Print the resultant list ; Driver Code"
How can the above be solved in Java?

class GFG { public static void makeList ( int N , int K ) { int [ ] list = new int [ N ] ; int left = 1 ; int right = N ; for ( int i = 0 ; i < N ; i ++ ) { if ( K % 2 == 0 ) { list [ i ] = left ; left = left + 1 ; } else { list [ i ] = right ; right = right - 1 ; } if ( K > 1 ) K -- ; } for ( int i = 0 ; i < list . length ; i ++ ) { System . out . print ( list [ i ] + " ▁ " ) ; } } public static void main ( String [ ] args ) { int N = 6 ; int K = 3 ; makeList ( N , K ) ; } }


"Generate a random Binary String of length N | Java program for the above approach ; Function to find a random number between 0 or 1 ; Generate the random number ; Return the generated number ; Function to generate a random binary string of length N ; Stores the empty string ; Iterate over the range [ 0 , N - 1 ] ; Store the random number ; Append it to the string ; Print the resulting string ; Driver Code"
How can the above be solved in Java?

class GFG { static int findRandom ( ) { int num = ( 1 + ( int ) ( Math . random ( ) * 100 ) ) % 2 ; return num ; } static void generateBinaryString ( int N ) { String S = " " ; for ( int i = 0 ; i < N ; i ++ ) { int x = findRandom ( ) ; S = S + String . valueOf ( x ) ; } System . out . println ( S ) ; } public static void main ( String [ ] args ) { int N = 7 ; generateBinaryString ( N ) ; } }


"Generate a random permutation of elements from range [ L , R ] ( Divide and Conquer ) | Java implementation of the approach ; To store the random permutation ; Utility function to print the generated permutation ; Function to return a random number between x and y ; Recursive function to generate the random permutation ; Base condition ; Random number returned from the function ; Inserting random number in vector ; Recursion call for [ l , n - 1 ] ; Recursion call for [ n + 1 , r ] ; Driver code ; Generate permutation ; Print the generated permutation"
How can the above be solved in Java?

import java . util . Vector ; class GFG { static Vector < Integer > permutation = new Vector < > ( ) ; static void printPermutation ( ) { permutation . stream ( ) . forEach ( ( i ) -> { System . out . print ( i + " ▁ " ) ; } ) ; } static int give_random_number ( int l , int r ) { int x = ( int ) ( Math . random ( ) % ( r - l + 1 ) + l ) ; return x ; } static void generate_random_permutation ( int l , int r ) { if ( l > r ) return ; int n = give_random_number ( l , r ) ; permutation . add ( n ) ; generate_random_permutation ( l , n - 1 ) ; generate_random_permutation ( n + 1 , r ) ; } public static void main ( String [ ] args ) { int l = 5 ; int r = 15 ; generate_random_permutation ( l , r ) ; printPermutation ( ) ; } }


"Generate a sequence such that float division of array elements is maximized | Java program for the above approach ; Function to place the parenthesis such that the result is maximized ; Store the required string ; Add the first integer to string ; If the size of array is 1 ; If the size of array is 2 , print the 1 st integer followed by / operator followed by the next integer ; If size of array is exceeds two , print 1 st integer concatenated with operators ' / ' , ' ( ' and next integers with the operator ' / ' ; Add parenthesis at the end ; Print the final expression ; Driver Code"
How can the above be solved in Java?

import java . io . * ; class GFG { static void generateSequence ( int arr [ ] , int n ) { String ans ; ans = Integer . toString ( arr [ 0 ] ) ; if ( n == 1 ) System . out . println ( ans ) ; else if ( n == 2 ) { System . out . println ( ans + " / " + Integer . toString ( arr [ 1 ] ) ) ; } else { ans += " / ( " + Integer . toString ( arr [ 1 ] ) ; for ( int i = 2 ; i < n ; i ++ ) { ans += " / " + Integer . toString ( arr [ i ] ) ; } ans += " ) " ; System . out . println ( ans ) ; } } public static void main ( String [ ] args ) { int arr [ ] = { 1000 , 100 , 10 , 2 } ; int N = arr . length ; generateSequence ( arr , N ) ; } }


"Generate a sequence with product N such that for every pair of indices ( i , j ) and i < j , arr [ j ] is divisible by arr [ i ] | Java program for the above approach ; Function to calculate the prime factors of N with their count ; Initialize a vector , say v ; Initialize the count ; Count the number of divisors ; Divide the value of N by 2 ; For factor 2 divides it ; Find all prime factors ; Count their frequency ; Push it to the vector ; Push N if it is not 1 ; Function to print the array that have the maximum size ; Stores the all prime factor and their powers ; Traverse the vector and find the maximum power of prime factor ; If max size is less than 2 ; Otherwise ; Print the maximum size of sequence ; Print the final sequence ; Print the prime factor ; Print the last value of the sequence ; Driver Code"
How can the above be solved in Java?

 import java . util . * ; class GFG { static class pair { int first , second ; public pair ( int first , int second ) { this . first = first ; this . second = second ; } } static Vector < pair > primeFactor ( int N ) { Vector < pair > v = new Vector < > ( ) ; int count = 0 ; while ( ( N % 2 ) == 0 ) { N >>= 1 ; count ++ ; } if ( count != 0 ) v . add ( new pair ( 2 , count ) ) ; for ( int i = 3 ; i <= Math . sqrt ( N ) ; i += 2 ) { count = 0 ; while ( N % i == 0 ) { count ++ ; N = N / i ; } if ( count != 0 ) { v . add ( new pair ( i , count ) ) ; } } if ( N > 2 ) v . add ( new pair ( N , 1 ) ) ; return v ; } static void printAnswer ( int n ) { Vector < pair > v = primeFactor ( n ) ; int maxi_size = 0 , prime_factor = 0 ; for ( int i = 0 ; i < v . size ( ) ; i ++ ) { if ( maxi_size < v . get ( i ) . second ) { maxi_size = v . get ( i ) . second ; prime_factor = v . get ( i ) . first ; } } if ( maxi_size < 2 ) { System . out . print ( 1 << ' ▁ ' ) ; } else { int product = 1 ; System . out . print ( maxi_size + "
"); for ( int i = 0 ; i < maxi_size - 1 ; i ++ ) { System . out . print ( prime_factor + " ▁ " ) ; product *= prime_factor ; } System . out . print ( ( n / product ) ) ; } } public static void main ( String [ ] args ) { int N = 360 ; printAnswer ( N ) ; } }


"Generate a sequence with the given operations | Java Implementation of above approach ; function to find minimum required permutation ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { static void StringMatch ( String s ) { int lo = 0 , hi = s . length ( ) , len = s . length ( ) ; Vector < Integer > ans = new Vector < > ( ) ; for ( int x = 0 ; x < len ; x ++ ) { if ( s . charAt ( x ) == ' I ' ) { ans . add ( lo ) ; lo += 1 ; } else { ans . add ( hi ) ; hi -= 1 ; } } ans . add ( lo ) ; System . out . print ( " [ " ) ; for ( int i = 0 ; i < ans . size ( ) ; i ++ ) { System . out . print ( ans . get ( i ) ) ; if ( i != ans . size ( ) - 1 ) System . out . print ( " , " ) ; } System . out . print ( " ] " ) ; } public static void main ( String [ ] args ) { String S = " IDID " ; StringMatch ( S ) ; } }


"Generate a string consisting of characters ' a ' and ' b ' that satisfy the given conditions | Java implementation of the approach ; Function to generate and print the required string ; More ' b ' , append " bba " ; More ' a ' , append " aab " ; Equal number of ' a ' and ' b ' append " ab " ; Driver code"
How can the above be solved in Java?

class GFG { static void generateString ( int A , int B ) { String rt = " " ; while ( 0 < A 0 < B ) { if ( A < B ) { if ( 0 < B -- ) { rt += ( ' b ' ) ; } if ( 0 < B -- ) { rt += ( ' b ' ) ; } if ( 0 < A -- ) { rt += ( ' a ' ) ; } } else if ( B < A ) { if ( 0 < A -- ) { rt += ( ' a ' ) ; } if ( 0 < A -- ) { rt += ( ' a ' ) ; } if ( 0 < B -- ) { rt += ( ' b ' ) ; } } else { if ( 0 < A -- ) { rt += ( ' a ' ) ; } if ( 0 < B -- ) { rt += ( ' b ' ) ; } } } System . out . println ( rt ) ; } public static void main ( String [ ] args ) { int A = 2 , B = 6 ; generateString ( A , B ) ; } }


"Generate a string from an array of alphanumeric strings based on given conditions | Java program for the above approach ; Function to generate required string ; To store the result ; Split name and number ; Stores the maximum number less than or equal to the length of name ; Check for number by parsing it to integer if it is greater than max number so far ; Check if no such number is found then we append X to the result . ; Otherwise ; Append max index of the name ; Return the final string ; Driver Code ; Function Call"
How can the above be solved in Java?

import java . io . * ; class GFG { public static String generatePassword ( String s [ ] , char T ) { StringBuilder result = new StringBuilder ( ) ; for ( String currentString : s ) { String person [ ] = currentString . split ( " : " ) ; String name = person [ 0 ] ; String number = person [ 1 ] ; int n = name . length ( ) ; int max = 0 ; for ( int i = 0 ; i < number . length ( ) ; i ++ ) { int temp = Integer . parseInt ( String . valueOf ( number . charAt ( i ) ) ) ; if ( temp > max && temp <= n ) max = temp ; } if ( max == 0 ) result . append ( T ) ; else result . append ( String . valueOf ( name . charAt ( max - 1 ) ) ) ; } return result . toString ( ) ; } public static void main ( String [ ] args ) { String arr [ ] = { " Geeks : 89167" , " gfg : 68795" } ; char T = ' X ' ; System . out . println ( generatePassword ( arr , T ) ) ; } }


"Generate a string of size N whose each substring of size M has exactly K distinct characters | Java program to generate a String of size N whose each subString of size M has exactly K distinct characters ; Function to generate the String ; Declare empty String ; counter for M ; counter for K ; Loop to generate String size of N ; Generating K distinct letters one by one ; After generating b distinct letters , append rest a - b letters as ' a ' ; Reset the counter value and repeat the process ; return final result String ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { static String generateString ( int N , int M , int K ) { String s = " " ; int cnt1 = 0 ; int cnt2 = 0 ; for ( int i = 0 ; i < N ; i ++ ) { cnt1 ++ ; cnt2 ++ ; if ( cnt1 <= M ) { if ( cnt2 <= K ) { s = s + ( char ) ( 96 + cnt1 ) ; } else { s = s + ' a ' ; } } else { cnt1 = 1 ; cnt2 = 1 ; s = s + ' a ' ; } } return s ; } public static void main ( String [ ] args ) { int N = 7 , M = 5 , K = 3 ; System . out . println ( generateString ( N , M , K ) ) ; } }


"Generate a string which differs by only a single character from all given strings | Java program to implement the above approach ; Function to check if a given string differs by a single character from all the strings in an array ; Traverse over the strings ; Stores the count of characters differing from the strings ; If differs by more than one character ; Function to find the string which only differ at one position from the all given strings of the array ; Size of the array ; Length of a string ; Replace i - th character by all possible characters ; Check if it differs by a single character from all other strings ; If desired string is obtained ; Print the answer ; Driver code ; Function call"
How can the above be solved in Java?

import java . util . * ; class GFG { static boolean check ( String ans , String [ ] s , int n , int m ) { for ( int i = 1 ; i < n ; ++ i ) { int count = 0 ; for ( int j = 0 ; j < m ; ++ j ) { if ( ans . charAt ( j ) != s [ i ] . charAt ( j ) ) count ++ ; } if ( count > 1 ) return false ; } return true ; } static String findString ( String [ ] s ) { int n = s . length ; String ans = s [ 0 ] ; int m = ans . length ( ) ; int flag = 0 ; for ( int i = 0 ; i < m ; ++ i ) { for ( int j = 0 ; j < 26 ; ++ j ) { String x = ans ; x = x . replace ( x . charAt ( i ) , ( char ) ( j + ' a ' ) ) ; if ( check ( x , s , n , m ) ) { ans = x ; flag = 1 ; break ; } } if ( flag == 1 ) break ; } if ( flag == 0 ) return " - 1" ; else return ans ; } public static void main ( String [ ] args ) { String s [ ] = { " geeks " , " teeds " } ; System . out . println ( findString ( s ) ) ; } }


"Generate a string with maximum possible alphabets with odd frequencies | Java program to generate a string of length n with maximum possible alphabets with each of them occuring odd number of times . ; Function to generate a string of length n with maximum possible alphabets each occuring odd number of times . ; If n is odd ; Add all characters from b - y ; Append a to fill the remaining length ; If n is even ; Add all characters from b - z ; Append a to fill the remaining length ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { static String generateTheString ( int n ) { String ans = " " ; if ( n % 2 != 0 ) { for ( int i = 0 ; i < Math . min ( n , 24 ) ; i ++ ) { ans += ( char ) ( ' b ' + i ) ; } if ( n > 24 ) { for ( int i = 0 ; i < ( n - 24 ) ; i ++ ) ans += ' a ' ; } } else { for ( int i = 0 ; i < Math . min ( n , 25 ) ; i ++ ) { ans += ( char ) ( ' b ' + i ) ; } if ( n > 25 ) { for ( int i = 0 ; i < ( n - 25 ) ; i ++ ) ans += ' a ' ; } } return ans ; } public static void main ( String [ ] args ) { int n = 34 ; System . out . println ( generateTheString ( n ) ) ; } }


"Generate a unique Array of length N with sum of all subarrays divisible by N | Java program for the above approach ; Function to print the required array ; Print the array ; Driver code"
How can the above be solved in Java?

class GFG { static void makeArray ( int a [ ] , int n ) { for ( int i = 1 ; i <= n ; i ++ ) System . out . print ( i * n + " ▁ " ) ; } public static void main ( String [ ] args ) { int N = 6 ; int arr [ ] = new int [ N ] ; makeArray ( arr , N ) ; } }


"Generate all N digit numbers having absolute difference as K between adjacent digits | Java program for the above approach ; Function that recursively finds the possible numbers and append into ans ; Base Case ; Check the sum of last digit and k less than or equal to 9 or not ; If k == 0 , then subtraction and addition does not make any difference Hence , subtraction is skipped ; Function to call checkUntil function for every integer from 1 to 9 ; check_util function recursively store all numbers starting from i ; Function to print the all numbers which satisfy the conditions ; Driver Code ; Given N and K ; To store the result ; Function Call ; Print Resultant Numbers"
How can the above be solved in Java?

import java . util . * ; class GFG { static void checkUntil ( int num , int K , int N , Vector < Integer > ans ) { if ( N == 1 ) { ans . add ( num ) ; return ; } if ( ( num % 10 + K ) <= 9 ) checkUntil ( 10 * num + ( num % 10 + K ) , K , N - 1 , ans ) ; if ( K > 0 ) { if ( ( num % 10 - K ) >= 0 ) checkUntil ( 10 * num + num % 10 - K , K , N - 1 , ans ) ; } } static void check ( int K , int N , Vector < Integer > ans ) { for ( int i = 1 ; i <= 9 ; i ++ ) { checkUntil ( i , K , N , ans ) ; } } static void print ( Vector < Integer > ans ) { for ( int i = 0 ; i < ans . size ( ) ; i ++ ) { System . out . print ( ans . get ( i ) + " , ▁ " ) ; } } public static void main ( String [ ] args ) { int N = 4 , K = 8 ; Vector < Integer > ans = new Vector < Integer > ( ) ; ; check ( K , N , ans ) ; print ( ans ) ; } }


"Generate all binary strings from given pattern | Recursive Java program to generate all binary strings formed by replacing each wildcard character by 0 or 1 ; Recursive function to generate all binary strings formed by replacing each wildcard character by 0 or 1 ; replace ' ? ' by '0' and recurse ; replace ' ? ' by '1' and recurse ; NOTE : Need to backtrack as string is passed by reference to the function ; driver code"
How can the above be solved in Java?

import java . util . * ; import java . lang . * ; import java . io . * ; class binStr { public static void print ( char str [ ] , int index ) { if ( index == str . length ) { System . out . println ( str ) ; return ; } if ( str [ index ] == ' ? ' ) { str [ index ] = '0' ; print ( str , index + 1 ) ; str [ index ] = '1' ; print ( str , index + 1 ) ; str [ index ] = ' ? ' ; } else print ( str , index + 1 ) ; } public static void main ( String [ ] args ) { String input = "1 ? ? 0?101" ; char [ ] str = input . toCharArray ( ) ; print ( str , 0 ) ; } }


"Generate all binary strings of length n with sub | Java implementation of the above approach ; Utility function to print the given binary string ; This function will be called recursively to generate the next bit for given binary string according to its current state ; Base - case : if the generated binary string meets the required length and the pattern "01" appears twice ; nextbit needs to be 0 because each time we call the function recursively , we call 2 times for 2 cases : next bit is 0 or 1 The is to assure that the binary string is printed one time only ; Generate the next bit for str and call recursive ; Assign first bit ; The next generated bit will wither be 0 or 1 ; } else If pattern "01" occurrence is < 2 ; Set next bit ; If pattern "01" appears then increase the occurrence of pattern ; If previous bit is 0 then next bit cannot be 1 ; Otherwise ; Driver code ; Length of the resulting strings must be at least 4 ; Generate all binary strings of length n with sub - string "01" appearing twice"
How can the above be solved in Java?

class GFG { static void printBinStr ( int [ ] str , int len ) { for ( int i = 0 ; i < len ; i ++ ) { System . out . print ( str [ i ] ) ; } System . out . println ( ) ; } static void generateBinStr ( int [ ] str , int len , int currlen , int occur , int nextbit ) { if ( currlen == len ) { if ( occur == 2 && nextbit == 0 ) { printBinStr ( str , len ) ; } return ; } if ( currlen == 0 ) { str [ 0 ] = nextbit ; generateBinStr ( str , len , currlen + 1 , occur , 0 ) ; generateBinStr ( str , len , currlen + 1 , occur , 1 ) ; if ( occur < 2 ) { str [ currlen ] = nextbit ; if ( str [ currlen - 1 ] == 0 && nextbit == 1 ) { occur += 1 ; } generateBinStr ( str , len , currlen + 1 , occur , 0 ) ; generateBinStr ( str , len , currlen + 1 , occur , 1 ) ; if ( str [ currlen - 1 ] == 0 && nextbit == 1 ) { return ; } else { str [ currlen ] = nextbit ; generateBinStr ( str , len , currlen + 1 , occur , 0 ) ; generateBinStr ( str , len , currlen + 1 , occur , 1 ) ; } } public static void main ( String [ ] args ) { int n = 5 ; if ( n < 4 ) { System . out . print ( - 1 ) ; } else { int [ ] str = new int [ n ] ; generateBinStr ( str , n , 0 , 0 , 0 ) ; generateBinStr ( str , n , 0 , 0 , 1 ) ; } } }


"Generate all cyclic permutations of a number | Java Program to generate all cyclic permutations of number ; Function to count the total number of digits in a number . ; Function to generate all cyclic permutations of a number ; Following three lines generates a circular pirmutation of a number . ; If all the permutations are checked and we obtain original number exit from loop . ; Driver Program"
How can the above be solved in Java?

class GFG { static int countdigits ( int N ) { int count = 0 ; while ( N > 0 ) { count ++ ; N = N / 10 ; } return count ; } static void cyclic ( int N ) { int num = N ; int n = countdigits ( N ) ; while ( true ) { System . out . println ( num ) ; int rem = num % 10 ; int dev = num / 10 ; num = ( int ) ( ( Math . pow ( 10 , n - 1 ) ) * rem + dev ) ; if ( num == N ) break ; } } public static void main ( String [ ] args ) { int N = 5674 ; cyclic ( N ) ; } }


"Generate all permutations of a string that follow given constraints | Simple Java program to print all permutations of a String that follow given constraint ; Check if current permutation is valid ; Recursively generate all permutation ; Driver Code"
How can the above be solved in Java?

import java . util . * ; class GFG { static void permute ( char [ ] str , int l , int r ) { if ( l == r ) { if ( ! String . valueOf ( str ) . contains ( " AB " ) ) System . out . print ( String . valueOf ( str ) + " ▁ " ) ; return ; } for ( int i = l ; i <= r ; i ++ ) { char tmp = str [ l ] ; str [ l ] = str [ i ] ; str [ i ] = tmp ; permute ( str , l + 1 , r ) ; tmp = str [ l ] ; str [ l ] = str [ i ] ; str [ i ] = tmp ; } } public static void main ( String [ ] args ) { String str = " ABC " ; permute ( str . toCharArray ( ) , 0 , str . length ( ) - 1 ) ; } }


"Generate all possible permutations of a Number divisible by N | Java program to implement the above approach ; Function to Swap two characters ; Function to generate all permutations and print the ones that are divisible by the N ; Convert String to integer ; Check for divisibility and print it ; Print all the permutations ; Swap characters ; Permute remaining characters ; Revoke the swaps ; Driver Code"
How can the above be solved in Java?

 class GFG { static void swap_ ( char [ ] a , int l , int i ) { char temp ; temp = a [ l ] ; a [ l ] = a [ i ] ; a [ i ] = temp ; } static void permute ( char [ ] str , int l , int r , int n ) { int i ; if ( l == r ) { int j = Integer . valueOf ( String . valueOf ( str ) ) ; if ( j % n == 0 ) System . out . print ( String . valueOf ( str ) + "
"); return ; } for ( i = l ; i < r ; i ++ ) { swap_ ( str , l , i ) ; permute ( str , l + 1 , r , n ) ; swap_ ( str , l , i ) ; } } public static void main ( String [ ] args ) { String str = "125" ; int n = 5 ; int len = str . length ( ) ; if ( len > 0 ) permute ( str . toCharArray ( ) , 0 , len , n ) ; } }


"Generate all possible sorted arrays from alternate elements of two given sorted arrays |  ; Function to generates and prints all sorted arrays from alternate elements of ' A [ i . . m - 1 ] ' and ' B [ j . . n - 1 ] ' If ' flag ' is true , then current element is to be included from A otherwise from B . ' len ' is the index in output array C [ ] . We print output array each time before including a character from A only if length of output array is greater than 0. We try than all possible combinations ; Include valid element from A ; Print output if there is at least one ' B ' in output array ' C ' ; Recur for all elements of A after current index ; this block works for the very first call to include the first element in the output array ; don 't increment lem as B is included yet ; include valid element from A and recur ; Include valid element from B and recur ; Wrapper function ; output array ; A utility function to print an array ; Driver program"
How can the above be solved in Java?

class GenerateArrays { void generateUtil ( int A [ ] , int B [ ] , int C [ ] , int i , int j , int m , int n , int len , boolean flag ) { if ( flag ) { if ( len != 0 ) printArr ( C , len + 1 ) ; for ( int k = i ; k < m ; k ++ ) { if ( len == 0 ) { C [ len ] = A [ k ] ; generateUtil ( A , B , C , k + 1 , j , m , n , len , ! flag ) ; } else if ( A [ k ] > C [ len ] ) { C [ len + 1 ] = A [ k ] ; generateUtil ( A , B , C , k + 1 , j , m , n , len + 1 , ! flag ) ; } } } else { for ( int l = j ; l < n ; l ++ ) { if ( B [ l ] > C [ len ] ) { C [ len + 1 ] = B [ l ] ; generateUtil ( A , B , C , i , l + 1 , m , n , len + 1 , ! flag ) ; } } } } void generate ( int A [ ] , int B [ ] , int m , int n ) { int C [ ] = new int [ m + n ] ; generateUtil ( A , B , C , 0 , 0 , m , n , 0 , true ) ; } 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 ) { GenerateArrays generate = new GenerateArrays ( ) ; int A [ ] = { 10 , 15 , 25 } ; int B [ ] = { 5 , 20 , 30 } ; int n = A . length ; int m = B . length ; generate . generate ( A , B , n , m ) ; } }


"Generate all possible strings formed by replacing letters with given respective symbols | Java program for the above approach ; Function to generate all possible string by replacing the characters with mapped symbols ; Base Case ; Function call with the P - th character not replaced ; Replace the P - th character ; Function call with the P - th character replaced ; Driver Code ; Function Call"
How can the above be solved in Java?

import java . util . HashMap ; class GFG { public static void generateLetters ( String S , int P , HashMap < Character , Character > M ) { if ( P == S . length ( ) ) { System . out . println ( S ) ; return ; } generateLetters ( S , P + 1 , M ) ; S = S . substring ( 0 , P ) + M . get ( S . charAt ( P ) ) + S . substring ( P + 1 ) ; generateLetters ( S , P + 1 , M ) ; return ; } public static void main ( String args [ ] ) { String S = " aBc " ; HashMap < Character , Character > M = new HashMap < Character , Character > ( ) ; M . put ( ' a ' , ' $ ' ) ; M . put ( ' B ' , ' # ' ) ; M . put ( ' c ' , ' ^ ' ) ; M . put ( ' d ' , ' & ' ) ; M . put ( '1' , ' * ' ) ; M . put ( '2' , ' ! ' ) ; M . put ( ' E ' , ' @ ' ) ; generateLetters ( S , 0 , M ) ; } }


"Generate all possible strings such that char at index i is either str1 [ i ] or str2 [ i ] | Java implementation of the approach ; Recursive function to generate the required strings ; If length of the current string is equal to the length of the given strings then the current string is part of the result ; Choosing the current character from the string a ; Choosing the current character from the string b ; Driver code ; Third argument is an empty string that we will be appended in the recursion calls Fourth arguments is the length of the resultant string so far"
How can the above be solved in Java?

class GFG { public static void generateStr ( String a , String b , String s , int count , int len ) { if ( count == len ) { System . out . println ( s ) ; return ; } generateStr ( a . substring ( 1 ) , b . substring ( 1 ) , s + a . charAt ( 0 ) , count + 1 , len ) ; generateStr ( a . substring ( 1 ) , b . substring ( 1 ) , s + b . charAt ( 0 ) , count + 1 , len ) ; } public static void main ( String [ ] args ) { String a = " abc " , b = " def " ; int n = a . length ( ) ; generateStr ( a , b , " " , 0 , n ) ; } }


"Generate all rotations of a given string | A simple Java program to generate all rotations of a given string ; Print all the rotated string . ; Concatenate str with itself ; Print all substrings of size n . Note that size of sb is 2 n ; Driver method"
How can the above be solved in Java?

class Test { static void printRotatedString ( String str ) { int n = str . length ( ) ; StringBuffer sb = new StringBuffer ( str ) ; sb . append ( str ) ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = 0 ; j != n ; j ++ ) System . out . print ( sb . charAt ( i + j ) ) ; System . out . println ( ) ; } } public static void main ( String [ ] args ) { String str = new String ( " geeks " ) ; printRotatedString ( str ) ; } }


"Generate all rotations of a given string | A simple Java program to generate all rotations of a given string ; Print all the rotated string . ; Generate all rotations one by one and print ; Current index in str ; Current index in temp ; Copying the second part from the point of rotation . ; Copying the first part from the point of rotation . ; Driver method"
How can the above be solved in Java?

class Test { static void printRotatedString ( String str ) { int len = str . length ( ) ; StringBuffer sb ; for ( int i = 0 ; i < len ; i ++ ) { sb = new StringBuffer ( ) ; int j = i ; int k = 0 ; for ( int k2 = j ; k2 < str . length ( ) ; k2 ++ ) { sb . insert ( k , str . charAt ( j ) ) ; k ++ ; j ++ ; } j = 0 ; while ( j < i ) { sb . insert ( k , str . charAt ( j ) ) ; j ++ ; k ++ ; } System . out . println ( sb ) ; } } public static void main ( String [ ] args ) { String str = new String ( " geeks " ) ; printRotatedString ( str ) ; } }


"Generate all rotations of a number | Java implementation of the approach ; Function to return the count of digits of n ; Function to print the left shift numbers ; Formula to calculate left shift from previous number ; Update the original number ; Driver Code"
How can the above be solved in Java?

class GFG { static int numberOfDigits ( int n ) { int cnt = 0 ; while ( n > 0 ) { cnt ++ ; n /= 10 ; } return cnt ; } static void cal ( int num ) { int digits = numberOfDigits ( num ) ; int powTen = ( int ) Math . pow ( 10 , digits - 1 ) ; for ( int i = 0 ; i < digits - 1 ; i ++ ) { int firstDigit = num / powTen ; int left = ( ( num * 10 ) + firstDigit ) - ( firstDigit * powTen * 10 ) ; System . out . print ( left + " ▁ " ) ; num = left ; } } public static void main ( String [ ] args ) { int num = 1445 ; cal ( num ) ; } }


"Generate all the binary strings of N bits | Java implementation of the above approach : ; Function to print the output ; Function to generate all binary strings ; First assign "0" at ith position and try for all other permutations for remaining positions ; And then assign "1" at ith position and try for all other permutations for remaining positions ; Driver Code ; Print all binary strings"
How can the above be solved in Java?

import java . util . * ; class GFG { static void printTheArray ( int arr [ ] , int n ) { for ( int i = 0 ; i < n ; i ++ ) { System . out . print ( arr [ i ] + " ▁ " ) ; } System . out . println ( ) ; } static void generateAllBinaryStrings ( int n , int arr [ ] , int i ) { if ( i == n ) { printTheArray ( arr , n ) ; return ; } arr [ i ] = 0 ; generateAllBinaryStrings ( n , arr , i + 1 ) ; arr [ i ] = 1 ; generateAllBinaryStrings ( n , arr , i + 1 ) ; } public static void main ( String args [ ] ) { int n = 4 ; int [ ] arr = new int [ n ] ; generateAllBinaryStrings ( n , arr , 0 ) ; } }


"Generate all unique partitions of an integer | Set 2 | Java implementation of the approach ; Array to store the numbers used to form the required sum ; Function to print the array which contains the unique partitions which are used to form the required sum ; Function to find all the unique partitions remSum = remaining sum to form maxVal is the maximum number that can be used to make the partition ; If remSum == 0 that means the sum is achieved so print the array ; i will begin from maxVal which is the maximum value which can be used to form the sum ; Store the number used in forming sum gradually in the array ; Since i used the rest of partition cant have any number greater than i hence second parameter is i ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { static int [ ] dp = new int [ 200 ] ; static int count = 0 ; static void print ( int idx ) { for ( int i = 1 ; i < idx ; i ++ ) { System . out . print ( dp [ i ] + " ▁ " ) ; } System . out . println ( " " ) ; } static void solve ( int remSum , int maxVal , int idx , int count ) { if ( remSum == 0 ) { print ( idx ) ; count ++ ; return ; } for ( int i = maxVal ; i >= 1 ; i -- ) { if ( i > remSum ) { continue ; } else if ( i <= remSum ) { dp [ idx ] = i ; solve ( remSum - i , i , idx + 1 , count ) ; } } } public static void main ( String [ ] args ) { int n = 4 , count = 0 ; solve ( n , n , 1 , count ) ; } }


"Generate an Array in which count of even and odd sum sub | Java implementation of the approach ; Function to generate and print the required array ; Find the number of odd prefix sums ; If no odd prefix sum found ; Calculating the number of even prefix sums ; Stores the current prefix sum ; If current prefix sum is even ; Print 0 until e = EvenPreSums - 1 ; Print 1 when e = EvenPreSums ; Print 0 for rest of the values ; Driver code"
How can the above be solved in Java?

import java . io . * ; class GFG { static void CreateArray ( int N , int even , int odd ) { int EvenPreSums = 1 ; int temp = - 1 ; int OddPreSums = 0 ; for ( int i = 0 ; i <= N + 1 ; i ++ ) { if ( i * ( ( N + 1 ) - i ) == odd ) { temp = 0 ; OddPreSums = i ; break ; } } if ( temp == - 1 ) { System . out . println ( temp ) ; } else { EvenPreSums = ( ( N + 1 ) - OddPreSums ) ; int e = 1 ; int o = 0 ; int CurrSum = 0 ; for ( int i = 0 ; i < N ; i ++ ) { if ( CurrSum % 2 == 0 ) { if ( e < EvenPreSums ) { e ++ ; System . out . print ( "0 ▁ " ) ; } else { o ++ ; System . out . print ( "1 ▁ " ) ; CurrSum ++ ; } } else { if ( e < EvenPreSums ) { e ++ ; System . out . print ( "1 ▁ " ) ; CurrSum ++ ; } else { o ++ ; System . out . print ( "0 ▁ " ) ; } } } System . out . println ( ) ; } } public static void main ( String [ ] args ) { int N = 15 ; int even = 60 , odd = 60 ; CreateArray ( N , even , odd ) ; } }


"Generate an Array such with elements maximized through swapping bits | Java implementation to find maximum sequence by swapping bits ; Function to generate the maximized array elements ; Traverse the array ; Iterate to count set and unset bits ; Count of unset bits ; Count of set bits ; Bitwise right shift ; Shifting all 1 ' s ▁ to ▁ MSB ▁ ▁ and ▁ 0' s to LSB ; Driver Code"
How can the above be solved in Java?

class GFG { public static void maximizedArray ( int arr [ ] , int N ) { int num , i = 0 ; for ( int l = N ; l > 0 ; l -- ) { num = arr [ i ] ; int one = 0 ; int zero = 0 ; while ( num != 0 ) { if ( num % 2 == 0 ) { zero ++ ; } else { one ++ ; } num = num >> 1 ; } for ( int j = zero ; j < ( one + zero ) ; j ++ ) { num += ( 1 << j ) ; } System . out . print ( num ) ; i ++ ; if ( N > 0 ) System . out . print ( " , ▁ " ) ; } } public static void main ( String args [ ] ) { int arr [ ] = { 8 , 15 , 9 , 10 , 14 } ; int N = arr . length ; maximizedArray ( arr , N ) ; } }


"Generate an N | Java Program to implement the above approach ; Fun dtion to print the required sequence ; Stores count of even and odd elements ; Stores sum of even and odd elements ; Print N / 2 even elements ; Print N / 2 - 1 odd elements ; Print final odd element ; Driver Code"
How can the above be solved in Java?

import java . io . * ; class GFG { static void Print ( int N ) { if ( ( N / 2 ) % 2 == 1 || ( N % 2 == 1 ) ) { System . out . print ( - 1 ) ; return ; } int CurEven = 2 , CurOdd = 1 ; int SumOdd = 0 , SumEven = 0 ; for ( int i = 0 ; i < ( N / 2 ) ; i ++ ) { System . out . print ( CurEven + " ▁ " ) ; SumEven += CurEven ; CurEven += 2 ; } for ( int i = 0 ; i < N / 2 - 1 ; i ++ ) { System . out . print ( CurOdd + " ▁ " ) ; SumOdd += CurOdd ; CurOdd += 2 ; } CurOdd = SumEven - SumOdd ; System . out . println ( CurOdd ) ; } public static void main ( String [ ] args ) { int N = 12 ; Print ( N ) ; } }


"Generate an N | Java program for above approach ; Function to print target array ; Sort the given array ; Seeking for index of elements with minimum diff . ; Seeking for index ; To store target array ; Copying element ; Copying remaining element ; Printing target array ; Driver code ; Given Input ; Function Call"
How can the above be solved in Java?

import java . io . * ; import java . util . * ; class GFG { public static void printArr ( int arr [ ] , int n ) { Arrays . sort ( arr ) ; int minDifference = 1000000007 ; int minIndex = - 1 ; for ( int i = 1 ; i < n ; i ++ ) { if ( minDifference > Math . abs ( arr [ i ] - arr [ i - 1 ] ) ) { minDifference = Math . abs ( arr [ i ] - arr [ i - 1 ] ) ; minIndex = i - 1 ; } } int Arr [ ] = new int [ n ] ; Arr [ 0 ] = arr [ minIndex ] ; Arr [ n - 1 ] = arr [ minIndex + 1 ] ; int pos = 1 ; for ( int i = minIndex + 2 ; i < n ; i ++ ) { Arr [ pos ++ ] = arr [ i ] ; } for ( int i = 0 ; i < minIndex ; i ++ ) { Arr [ pos ++ ] = arr [ i ] ; } for ( int i = 0 ; i < n ; i ++ ) { System . out . print ( Arr [ i ] + " ▁ " ) ; } } public static void main ( String [ ] args ) { int N = 8 ; int arr [ ] = { 4 , 6 , 2 , 6 , 8 , 2 , 6 , 4 } ; printArr ( arr , N ) ; } }


"Generate an N | Java program for tha above approach ; Function to print the permutation of size N with absolute difference of adjacent elements in range [ 2 , 4 ] ; If N is less than 4 ; Check if N is even ; Traverse through odd integers ; Update the value of i ; Traverse through even integers ; Driver Code"
How can the above be solved in Java?

import java . util . * ; class GFG { static void getPermutation ( int N ) { if ( N <= 3 ) { System . out . print ( - 1 ) ; return ; } int i = N ; if ( N % 2 == 0 ) i -- ; while ( i >= 1 ) { System . out . print ( i + " ▁ " ) ; i -= 2 ; } System . out . print ( 4 + " ▁ " + 2 + " ▁ " ) ; i = 6 ; while ( i <= N ) { System . out . print ( i + " ▁ " ) ; i += 2 ; } } public static void main ( String [ ] args ) { int N = 9 ; getPermutation ( N ) ; } }


"Generate an N | Java program for the above approach ; Function to calculate GCD of given array ; Utility function to check for all the combinations ; If a sequence of size N is obtained ; If gcd of current combination is K ; If current element from first array is divisible by K ; Recursively proceed further ; If current combination satisfies given condition ; Remove the element from the combination ; If current element from second array is divisible by K ; Recursively proceed further ; If current combination satisfies given condition ; Remove the element from the combination ; Function to check for all possible combinations ; Stores the subsequence ; If GCD of any sequence is not equal to K ; Driver Code ; Given arrays ; Given value of K ; Function call to generate a subsequence whose GCD is K"
How can the above be solved in Java?

import java . io . * ; import java . lang . * ; import java . util . * ; class GFG { static int GCD ( int a , int b ) { if ( b == 0 ) return a ; return GCD ( b , a % b ) ; } static int GCDArr ( ArrayList < Integer > a ) { int ans = a . get ( 0 ) ; for ( int val : a ) { ans = GCD ( ans , val ) ; } return ans ; } static boolean findSubseqUtil ( int a [ ] , int b [ ] , ArrayList < Integer > ans , int k , int i ) { if ( ans . size ( ) == a . length ) { if ( GCDArr ( ans ) == k ) { System . out . println ( ans ) ; return true ; } else { return false ; } } if ( a [ i ] % k == 0 ) { ans . add ( a [ i ] ) ; boolean temp = findSubseqUtil ( a , b , ans , k , i + 1 ) ; if ( temp == true ) return true ; ans . remove ( ans . size ( ) - 1 ) ; } if ( b [ i ] % k == 0 ) { ans . add ( b [ i ] ) ; boolean temp = findSubseqUtil ( a , b , ans , k , i + 1 ) ; if ( temp == true ) return true ; ans . remove ( ans . size ( ) - 1 ) ; } return false ; } static void findSubseq ( int A [ ] , int B [ ] , int K , int i ) { ArrayList < Integer > ans = new ArrayList < > ( ) ; boolean ret = findSubseqUtil ( A , B , ans , K , i ) ; if ( ret == false ) System . out . println ( - 1 ) ; } public static void main ( String [ ] args ) { int A [ ] = { 5 , 3 , 6 , 2 , 9 } ; int B [ ] = { 21 , 7 , 14 , 12 , 28 } ; int K = 3 ; findSubseq ( A , B , K , 0 ) ; } }


"Generate an N | Java program for the above approach ; Function to calculate GCD of two integers ; Function to calculate GCD of a given array ; Utility function to check for all the possible combinations ; If an N - length sequence is obtained ; If GCD of the sequence is K ; Otherwise ; Add an element from the first array ; Recursively proceed further ; If combination satisfies the necessary condition ; Remove the element from the combination ; Add an element from the second array ; Recursive proceed further ; If combination satisfies the necessary condition ; Remove the element from the combination ; Function to check all the possible combinations ; Stores the subsequence ; If GCD is not equal to K for any combination ; Driver code ; Given arrays ; Given value of K ; Function call to generate the required subsequence"
How can the above be solved in Java?

import java . util . * ; import java . lang . * ; class GFG { static int GCD ( int a , int b ) { if ( b < 1 ) return a ; return GCD ( b , a % b ) ; } static int GCDArr ( ArrayList < Integer > a ) { int ans = a . get ( 0 ) ; for ( int i : a ) ans = GCD ( ans , i ) ; return ans ; } static boolean findSubseqUtil ( ArrayList < Integer > a , ArrayList < Integer > b , ArrayList < Integer > ans , int k , int i ) { if ( ans . size ( ) == a . size ( ) ) { if ( GCDArr ( ans ) == k ) { System . out . print ( " [ " ) ; int m = ans . size ( ) ; for ( int j = 0 ; j < m - 1 ; j ++ ) System . out . print ( ans . get ( j ) + " , ▁ " ) ; System . out . print ( ans . get ( m - 1 ) + " ] " ) ; return true ; } else return false ; } ans . add ( a . get ( i ) ) ; boolean temp = findSubseqUtil ( a , b , ans , k , i + 1 ) ; if ( temp ) return true ; ans . remove ( ans . size ( ) - 1 ) ; ans . add ( b . get ( i ) ) ; temp = findSubseqUtil ( a , b , ans , k , i + 1 ) ; if ( temp ) return true ; ans . remove ( ans . size ( ) - 1 ) ; return false ; } static void findSubseq ( ArrayList < Integer > A , ArrayList < Integer > B , int K , int i ) { ArrayList < Integer > ans = new ArrayList < Integer > ( ) ; findSubseqUtil ( A , B , ans , K , i ) ; if ( ans . size ( ) < 1 ) System . out . println ( - 1 ) ; } public static void main ( String [ ] args ) { ArrayList < Integer > A = new ArrayList < > ( ) ; A . add ( 5 ) ; A . add ( 3 ) ; A . add ( 6 ) ; A . add ( 2 ) ; A . add ( 9 ) ; ArrayList < Integer > B = new ArrayList < Integer > ( ) ; B . add ( 21 ) ; B . add ( 7 ) ; B . add ( 14 ) ; B . add ( 12 ) ; B . add ( 28 ) ; int K = 3 ; findSubseq ( A , B , K , 0 ) ; } }


"Generate an N | Java program for the above approach ; Function to conan array with given conditions ; Traverse the array arr [ ] ; Stores closest power of 2 less than or equal to arr [ i ] ; Stores R into brr [ i ] ; Print array elements ; Driver Code ; Given array ; Size of the array ; Function Call"
How can the above be solved in Java?

import java . util . * ; class GFG { static void constructArray ( int arr [ ] , int N ) { int brr [ ] = new int [ N ] ; for ( int i = 0 ; i < N ; i ++ ) { int K = ( int ) ( Math . log ( arr [ i ] ) / Math . log ( 2 ) ) ; int R = ( int ) Math . pow ( 2 , K ) ; brr [ i ] = R ; } for ( int i = 0 ; i < N ; i ++ ) { System . out . print ( brr [ i ] + " ▁ " ) ; } } public static void main ( String [ ] args ) { int arr [ ] = { 11 , 5 , 7 , 3 , 2 } ; int N = arr . length ; constructArray ( arr , N ) ; } }


"Generate an N | Java program for the above approach ; Function to generate all prime numbers upto 10 ^ 6 ; Initialize sieve [ ] as 1 ; Iterate over the range [ 2 , N ] ; If current element is non - prime ; Make all multiples of i as 0 ; Function to construct an array A [ ] satisfying the given conditions ; Stores the resultant array ; Stores all prime numbers ; Sieve of Erastosthenes ; Append the integer i if it is a prime ; Indicates current position in list of prime numbers ; Traverse the array arr [ ] ; If already filled with another prime number ; If A [ i ] is not filled but A [ ind ] is filled ; Store A [ i ] = A [ ind ] ; If none of them were filled ; To make sure A [ i ] does not affect other values , store next prime number ; Print the resultant array ; Driver Code ; Function Call"
How can the above be solved in Java?

import java . util . * ; class GFG { static int [ ] sieve = new int [ 10000000 ] ; static void sieveOfPrimes ( ) { Arrays . fill ( sieve , 1 ) ; int N = 1000000 ; for ( int i = 2 ; i * i <= N ; i ++ ) { if ( sieve [ i ] == 0 ) continue ; for ( int j = i * i ; j <= N ; j += i ) sieve [ j ] = 0 ; } } static void getArray ( int [ ] arr , int N ) { int A [ ] = new int [ N ] ; Arrays . fill ( A , 0 ) ; ArrayList < Integer > v = new ArrayList < Integer > ( ) ; sieveOfPrimes ( ) ; for ( int i = 2 ; i <= 1000000 ; i ++ ) if ( sieve [ i ] != 0 ) v . add ( i ) ; int j = 0 ; for ( int i = 0 ; i < N ; i ++ ) { int ind = arr [ i ] ; if ( A [ i ] != 0 ) continue ; else if ( A [ ind ] != 0 ) A [ i ] = A [ ind ] ; else { int prime = v . get ( j ++ ) ; A [ i ] = prime ; A [ ind ] = A [ i ] ; } } for ( int i = 0 ; i < N ; i ++ ) { System . out . print ( A [ i ] + " ▁ " ) ; } } public static void main ( String [ ] args ) { int arr [ ] = { 4 , 1 , 2 , 3 , 4 } ; int N = arr . length ; getArray ( arr , N ) ; } }


"Generate an N | Java program for the above approach ; Function to minimize the maximum element present in an N - length array having sum of elements divisible by K ; Return the ceil value of ( K / N ) ; Driver code"
How can the above be solved in Java?

class GFG { static int minimumValue ( int N , int K ) { return ( int ) Math . ceil ( ( double ) K / ( double ) N ) ; } public static void main ( String [ ] args ) { int N = 4 , K = 50 ; System . out . print ( minimumValue ( N , K ) ) ; } }


"Generate an N | Java program to implement the above approach ; Function to construct an array with sum of each subarray divisible by K ; Traverse a loop from 1 to N ; Print i - th multiple of K ; Driver Code"
How can the above be solved in Java?

import java . io . * ; import java . util . * ; class GFG { static void construct_Array ( int N , int K ) { for ( int i = 1 ; i <= N ; i ++ ) { System . out . print ( K * i + " ▁ " ) ; } } public static void main ( String [ ] args ) { int N = 3 , K = 3 ; construct_Array ( N , K ) ; } }


"Generate an N | Java program to implement the above approach ; Function to generate a String of length N having longest palindromic subString of length K ; Fill first K characters with ' a ' ; Stores a non - palindromic sequence to be repeated for N - k slots ; Print N - k remaining characters ; Driver Code ; Given N and K"
How can the above be solved in Java?

import java . util . * ; class GFG { static void String_palindrome ( int N , int K ) { for ( int i = 0 ; i < K ; i ++ ) System . out . print ( " a " ) ; String s = " bcd " ; for ( int i = 0 ; i < N - K ; i ++ ) System . out . print ( s . charAt ( i % 3 ) ) ; } public static void main ( String [ ] args ) { int N = 5 , K = 3 ; String_palindrome ( N , K ) ; } }


"Generate an alternate increasing and decreasing Array | Java program to generate an increasing and decreasing array ; Function that returns generated array ; Dynamically allocate array ; START = 0 , END = N ; Iterate over array ; if Str [ i ] == ' I ' assign arr [ i ] as START and increment START ; if str [ i ] == ' D ' assign arr [ i ] as END and decrement END ; Assign A [ N ] as START ; Return starting address of array A ; Driver code"
How can the above be solved in Java?

class GFG { static int [ ] DiStirngMatch ( String Str ) { int N = Str . length ( ) ; int [ ] arr = new int [ N + 1 ] ; int START = 0 , END = N ; for ( int i = 0 ; i < N ; i ++ ) { if ( Str . charAt ( i ) == ' I ' ) arr [ i ] = START ++ ; if ( Str . charAt ( i ) == ' D ' ) arr [ i ] = END -- ; } arr [ N ] = START ; return arr ; } public static void main ( String [ ] args ) { String Str = " IDID " ; int N = Str . length ( ) ; int [ ] ptr = DiStirngMatch ( Str ) ; for ( int i = 0 ; i <= N ; i ++ ) System . out . print ( ptr [ i ] + " ▁ " ) ; } }


"Generate an alternate odd | Java program to implement the above approach ; Function to print the required sequence ; Print ith odd number ; Driver code ; Function call"
How can the above be solved in Java?

import java . util . * ; class GFG { static void findNumbers ( int n ) { int i = 0 ; while ( i <= n ) { System . out . print ( 2 * i * i + 4 * i + 1 + i % 2 + " ▁ " ) ; i ++ ; } } public static void main ( String [ ] args ) { int n = 6 ; findNumbers ( n ) ; } }


"Generate an array B [ ] from the given array A [ ] which satisfies the given conditions | Java implementation of the approach Utility function to print the array elements ; Utility function to print the array elements ; Function to generate and print the required array ; To switch the ceil and floor function alternatively ; For every element of the array ; If the number is odd then print the ceil or floor value after division by 2 ; Use the ceil and floor alternatively ; If arr [ i ] is even then it will be completely divisible by 2 ; Driver code"
How can the above be solved in Java?

import java . util . * ; import java . lang . * ; class GFG { static void printArr ( int arr [ ] , int n ) { for ( int i = 0 ; i < n ; i ++ ) System . out . print ( arr [ i ] + " ▁ " ) ; } static void generateArr ( int arr [ ] , int n ) { boolean flip = true ; for ( int i = 0 ; i < n ; i ++ ) { if ( ( arr [ i ] & 1 ) != 0 ) { if ( flip ^= true ) System . out . print ( ( int ) ( Math . ceil ( arr [ i ] / 2.0 ) ) + " ▁ " ) ; else System . out . print ( ( int ) ( Math . floor ( arr [ i ] / 2.0 ) ) + " ▁ " ) ; } else { System . out . print ( arr [ i ] / 2 + " ▁ " ) ; } } } public static void main ( String [ ] args ) { int arr [ ] = { 3 , - 5 , - 7 , 9 , 2 , - 2 } ; int n = arr . length ; generateArr ( arr , n ) ; } }


"Generate an array consisting of most frequent greater elements present on the right side of each array element | Java program for the above approach ; Function to generate an array containing the most frequent greater element on the right side of each array element ; Stores the generated array ; Traverse the array arr [ ] ; Store the result for the current index and its frequency ; Iterate over the right subarray ; Store the frequency of the current array element ; If the frequencies are equal ; Update ans to smaller of the two elements ; If count of new element is more than count of ans ; Insert answer in the array ; Print the resultant array ; Driver Code ; Given Input"
How can the above be solved in Java?

import java . io . * ; import java . util . * ; class GFG { static void findArray ( int arr [ ] , int n ) { Vector < Integer > v = new Vector < Integer > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { int ans = - 1 , old_c = 0 ; for ( int j = i + 1 ; j < n ; j ++ ) { if ( arr [ j ] > arr [ i ] ) { int curr_c = 0 ; for ( int k = j ; k < n ; k ++ ) { if ( arr [ k ] == arr [ j ] ) { curr_c ++ ; } } ; if ( curr_c == old_c ) { if ( arr [ j ] < ans ) ans = arr [ j ] ; } if ( curr_c > old_c ) { ans = arr [ j ] ; old_c = curr_c ; } } } v . add ( ans ) ; } for ( int i = 0 ; i < v . size ( ) ; i ++ ) System . out . print ( v . get ( i ) + " ▁ " ) ; } public static void main ( String [ ] args ) { int arr [ ] = { 4 , 5 , 2 , 25 , 10 , 5 , 10 , 3 , 10 , 5 } ; int size = arr . length ; findArray ( arr , size ) ; } }


"Generate an array from given pairs of adjacent elements | Java program of the above approach ; Utility function to find original array ; Map to store all neighbors for each element ; Vector to store original elements ; Stotrs which array elements are visited ; Adjacency list to store neighbors of each array element ; Find the first corner element ; Stores first element of the original array ; Push it into the original array ; Mark as visited ; Traversing the neighbors and check if the elements are visited or not ; Traverse adjacent elements ; If element is not visited ; Push it into res ; Mark as visited ; Update the next adjacent ; Print original array ; Driver Code ; Given pairs of adjacent elements"
How can the above be solved in Java?

import java . io . * ; import java . util . * ; class Pair { int first , second ; Pair ( int first , int second ) { this . first = first ; this . second = second ; } } class GFG { static void find_original_array ( List < Pair > A ) { @ SuppressWarnings ( " unchecked " ) Map < Integer , List < Integer > > mp = new HashMap ( ) ; List < Integer > res = new ArrayList < Integer > ( ) ; @ SuppressWarnings ( " unchecked " ) Map < Integer , Boolean > visited = new HashMap ( ) ; for ( Pair it : A ) { List < Integer > temp ; temp = ( mp . containsKey ( it . first ) ) ? mp . get ( it . first ) : new ArrayList < Integer > ( ) ; temp . add ( it . second ) ; mp . put ( it . first , temp ) ; temp = ( mp . containsKey ( it . second ) ) ? mp . get ( it . second ) : new ArrayList < Integer > ( ) ; temp . add ( it . first ) ; mp . put ( it . second , temp ) ; } int it = 0 ; for ( Map . Entry < Integer , List < Integer > > entry : mp . entrySet ( ) ) { if ( entry . getValue ( ) . size ( ) == 1 ) { it = entry . getKey ( ) ; } } int adjacent = it ; res . add ( it ) ; visited . put ( it , true ) ; while ( res . size ( ) != A . size ( ) + 1 ) { for ( int elements : mp . get ( adjacent ) ) { if ( ! visited . containsKey ( elements ) ) { res . add ( elements ) ; visited . put ( elements , true ) ; adjacent = elements ; } } } for ( int val : res ) { System . out . print ( val + " ▁ " ) ; } } public static void main ( String [ ] args ) { @ SuppressWarnings ( " unchecked " ) List < Pair > A = new ArrayList ( ) ; A . add ( new Pair ( 5 , 1 ) ) ; A . add ( new Pair ( 3 , 4 ) ) ; A . add ( new Pair ( 3 , 5 ) ) ; find_original_array ( A ) ; } }


"Generate an array having sum of Euler Totient Function of all elements equal to N | Java program for the above approach ; Function to construct the array such the sum of values of Euler Totient functions of all array elements is N ; Stores the resultant array ; Find divisors in sqrt ( N ) ; If N is divisible by i ; Push the current divisor ; If N is not a perfect square ; Push the second divisor ; Print the resultant array ; Driver Code ; Function Call"
How can the above be solved in Java?

import java . util . * ; class GFG { static void constructArray ( int N ) { ArrayList < Integer > ans = new ArrayList < Integer > ( ) ; for ( int i = 1 ; i * i <= N ; i ++ ) { if ( N % i == 0 ) { ans . add ( i ) ; if ( N != ( i * i ) ) { ans . add ( N / i ) ; } } } for ( int it : ans ) { System . out . print ( it + " ▁ " ) ; } } public static void main ( String [ ] args ) { int N = 12 ; constructArray ( N ) ; } }


"Generate an array of K elements such that sum of elements is N and the condition a [ i ] < a [ i + 1 ] <= 2 * a [ i ] is met | Set 2 | Java implementation of the approach ; Function that print the desired array which satisfies the given conditions ; If the lowest filling condition is void , then it is not possible to generate the required array ; Increase all the elements by cnt ; Start filling from the back till the number is a [ i + 1 ] <= 2 * a [ i ] ; Get the number to be filled ; If it is less than the remaining numbers to be filled ; less than remaining numbers to be filled ; Get the sum of the array ; If this condition is void at any stage during filling up , then print - 1 ; Else add it to the sum ; If the sum condition is not satisified , then print - 1 ; Print the generated array ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { static void solve ( int n , int k ) { int mini = 0 ; int x1 = 1 ; int [ ] a = new int [ k ] ; for ( int i = 1 ; i <= k ; i ++ ) { mini += x1 ; a [ i - 1 ] = x1 ; x1 += 1 ; } if ( n < mini ) { System . out . print ( " - 1" ) ; return ; } int rem = n - mini ; int cnt = rem / k ; rem = rem % k ; for ( int i = 0 ; i < k ; i ++ ) a [ i ] += cnt ; for ( int i = k - 1 ; i > 0 && rem > 0 ; i -- ) { int xx = a [ i - 1 ] * 2 ; int left = xx - a [ i ] ; if ( rem >= left ) { a [ i ] = xx ; rem -= left ; } else { a [ i ] += rem ; rem = 0 ; } } int sum = a [ 0 ] ; for ( int i = 1 ; i < k ; i ++ ) { if ( a [ i ] > 2 * a [ i - 1 ] ) { System . out . print ( " - 1" ) ; return ; } sum += a [ i ] ; } if ( sum != n ) { System . out . print ( " - 1" ) ; return ; } for ( int i = 0 ; i < k ; i ++ ) System . out . print ( a [ i ] + " ▁ " ) ; } public static void main ( String [ ] args ) { int n = 26 , k = 6 ; solve ( n , k ) ; } }


"Generate an array of given size with equal count and sum of odd and even numbers | Java implementation to find the array containing same count of even and odd elements with equal sum of even and odd elements ; Function to find the array such that the array contains the same count of even and odd elements with equal sum of even and odd elements ; Length of array which is not divisible by 4 is unable to form such array ; Loop to find the resulted array containing the same count of even and odd elements ; Find the total sum of even elements ; Find the total sum of odd elements ; Find the difference between the total sum of even and odd elements ; The difference will be added in the last odd element ; Driver Code"
How can the above be solved in Java?

 class GFG { static void findSolution ( int N ) { if ( N % 4 != 0 ) System . out . print ( - 1 + "
"); else { int temp = 0 , sum_odd = 0 ; int sum_even = 0 ; int result [ ] = new int [ N ] ; for ( int i = 0 ; i < N ; i += 2 ) { temp += 2 ; result [ i + 1 ] = temp ; sum_even += result [ i + 1 ] ; result [ i ] = temp - 1 ; sum_odd += result [ i ] ; } int diff = sum_even - sum_odd ; result [ N - 2 ] += diff ; for ( int i = 0 ; i < N ; i ++ ) System . out . print ( result [ i ] + " ▁ " ) ; System . out . print ( "
"); } } public static void main ( String [ ] args ) { int N = 8 ; findSolution ( N ) ; } }


"Generate an array of maximum sum such that each element exceeds all elements present either on its left or right | Java program for the above approach ; Function to construct the array having maximum sum satisfying the given criteria ; Declaration of the array arrA [ ] and ans [ ] ; Stores the maximum sum of the resultant array ; Initialize the array arrA [ ] ; Traversing the array arrA [ ] ; Initialize the array arrB [ ] ; Assign the maximum element to the current element ; Form the first increasing till every index i ; Make the current element as the maximum element ; Forming decreasing from the index i + 1 to the index N ; Initialize the sum ; Find the total sum ; Check if the total sum is at least the sum found then make ans as ansB ; Print the final array formed ; Driver Code"
How can the above be solved in Java?

import java . io . * ; class GFG { static void maximumSumArray ( int arr [ ] , int N ) { int [ ] arrA = new int [ ( N ) ] ; int [ ] ans = new int [ ( N ) ] ; int maxSum = 0 ; for ( int i = 0 ; i < N ; i ++ ) arrA [ i ] = arr [ i ] ; for ( int i = 0 ; i < N ; i ++ ) { int [ ] arrB = new int [ ( N ) ] ; int maximum = arrA [ i ] ; arrB [ i ] = maximum ; for ( int j = i - 1 ; j >= 0 ; j -- ) { arrB [ j ] = Math . min ( maximum , arrA [ j ] ) ; maximum = arrB [ j ] ; } maximum = arrA [ i ] ; for ( int j = i + 1 ; j < N ; j ++ ) { arrB [ j ] = Math . min ( maximum , arrA [ j ] ) ; maximum = arrB [ j ] ; } int sum = 0 ; for ( int j = 0 ; j < N ; j ++ ) sum += arrB [ j ] ; if ( sum > maxSum ) { maxSum = sum ; ans = arrB ; } } for ( int val : ans ) { System . out . print ( val + " ▁ " ) ; } } public static void main ( String [ ] args ) { int A [ ] = { 10 , 6 , 8 } ; int N = A . length ; maximumSumArray ( A , N ) ; } }


"Generate an array of minimum sum whose XOR of same | Java implementation of the above approach ; Function to generate an array whose XOR with same - indexed elements of the given array is always a prime ; Traverse the array ; If current array element is 2 ; Print its XOR with 3 ; Otherwise ; Print its XOR with 2 ; Driver code ; Given array ; Size of the array ; Prints the required array"
How can the above be solved in Java?

class GFG { private static void minXOR ( int Arr [ ] , int N ) { for ( int i = 0 ; i < N ; i ++ ) { if ( Arr [ i ] == 2 ) { System . out . print ( ( Arr [ i ] ^ 3 ) + " ▁ " ) ; } else { System . out . print ( ( Arr [ i ] ^ 2 ) + " ▁ " ) ; } } } public static void main ( String [ ] args ) { int Arr [ ] = { 5 , 4 , 7 , 6 } ; int N = Arr . length ; minXOR ( Arr , N ) ; } }


"Generate an array of size K which satisfies the given conditions | Java implementation of the approach ; Function to generate and print the required array ; Initializing the array ; Finding r ( from above approach ) ; If r < 0 ; Finding ceiling and floor values ; Fill the array with ceiling values ; Fill the array with floor values ; Add 1 , 2 , 3 , ... with corresponding values ; There is no solution for below cases ; Modify A [ 1 ] and A [ k - 1 ] to get the required array ; Driver Code"
How can the above be solved in Java?

 class GFG { static void generateArray ( int n , int k ) { int [ ] array = new int [ k ] ; int remaining = n - ( k * ( k + 1 ) / 2 ) ; if ( remaining < 0 ) System . out . print ( " NO " ) ; int right_most = remaining % k ; int high = ( int ) Math . ceil ( remaining / ( k * 1.0 ) ) ; int low = ( int ) Math . floor ( remaining / ( k * 1.0 ) ) ; for ( int i = k - right_most ; i < k ; i ++ ) array [ i ] = high ; for ( int i = 0 ; i < ( k - right_most ) ; i ++ ) array [ i ] = low ; for ( int i = 0 ; i < k ; i ++ ) array [ i ] += i + 1 ; if ( k - 1 != remaining k == 1 ) { for ( int u : array ) System . out . print ( u + " ▁ " ) ; } else if ( k == 2 k == 3 ) System . out . printf ( "-1
"); else { array [ 1 ] -= 1 ; array [ k - 1 ] += 1 ; for ( int u : array ) System . out . print ( u + " ▁ " ) ; } } public static void main ( String [ ] args ) { int n = 26 , k = 6 ; generateArray ( n , k ) ; } }


"Generate an array of size N according to the given rules | Java implementation to generate an array of size N by following the given rules ; Function to search the most recent location of element N If not present in the array it will return - 1 ; Function to generate an array of size N by following the given rules ; Loop to fill the array as per the given rules ; Check for the occurrence of arr [ i - 1 ] ; Driver code"
How can the above be solved in Java?

class GFG { static int a [ ] ; static int search ( int a [ ] , int k , int x ) { int j ; for ( j = k - 1 ; j > - 1 ; j -- ) { if ( a [ j ] == x ) return j ; } return - 1 ; } static void genArray ( int [ ] arr , int N ) { for ( int i = 0 ; i < N - 1 ; i ++ ) { if ( search ( arr , i , arr [ i ] ) == - 1 ) arr [ i + 1 ] = 0 ; else arr [ i + 1 ] = ( i - search ( arr , i , arr [ i ] ) ) ; } } public static void main ( String [ ] args ) { int N = 5 ; int size = N + 1 ; int a [ ] = new int [ N ] ; genArray ( a , N ) ; for ( int i = 0 ; i < N ; i ++ ) System . out . print ( a [ i ] + " ▁ " ) ; } }


"Generate an array with K positive numbers such that arr [ i ] is either | Java program for the above approach ; Function to generate the resultant sequence of first N natural numbers ; Initialize an array of size N ; Stores the sum of positive and negative elements ; Mark the first N - K elements as negative ; Update the value of arr [ i ] ; Update the value of sumNeg ; Mark the remaining K elements as positive ; Update the value of arr [ i ] ; Update the value of sumPos ; If the sum of the sequence is negative , then print - 1 ; Print the required sequence ; Driver code"
How can the above be solved in Java?

import java . util . Arrays ; class GFG { static void findSequence ( int n , int k ) { int [ ] arr = new int [ n ] ; int sumPos = 0 , sumNeg = 0 ; for ( int i = 0 ; i < n - k ; i ++ ) { arr [ i ] = - ( i + 1 ) ; sumNeg += arr [ i ] ; } for ( int i = n - k ; i < n ; i ++ ) { arr [ i ] = i + 1 ; sumPos += arr [ i ] ; } if ( Math . abs ( sumNeg ) >= sumPos ) { System . out . print ( - 1 ) ; return ; } for ( int i = 0 ; i < n ; i ++ ) System . out . print ( arr [ i ] + " ▁ " ) ; } public static void main ( String args [ ] ) { int N = 10 , K = 6 ; findSequence ( N , K ) ; } }


"Generate an array with product of all subarrays of length exceeding one divisible by K | Java program for the above approach ; Function to check if the required array can be generated or not ; To check if divisor exists ; To store divisiors of K ; Check if K is prime or not ; If array can be generated ; Print d1 and d2 alternatively ; No such array can be generated ; Driver Code ; Given N and K ; Function Call"
How can the above be solved in Java?

class GFG { public static void array_divisbleby_k ( int N , int K ) { boolean flag = false ; int d1 = 0 , d2 = 0 ; for ( int i = 2 ; i * i <= K ; i ++ ) { if ( K % i == 0 ) { flag = true ; d1 = i ; d2 = K / i ; break ; } } if ( flag ) { for ( int i = 0 ; i < N ; i ++ ) { if ( i % 2 == 1 ) { System . out . print ( d2 + " ▁ " ) ; } else { System . out . print ( d1 + " ▁ " ) ; } } } else { System . out . print ( - 1 ) ; } } public static void main ( String [ ] args ) { int N = 5 , K = 21 ; array_divisbleby_k ( N , K ) ; } }


"Generate array having differences between count of occurrences of every array element on its left and right | Java program of the above approach ; Function to construct array of differences of counts on the left and right of the given array ; Initialize left and right frequency arrays ; Construct left cumulative frequency table ; Construct right cumulative frequency table ; Print the result ; Driver Code ; Function Call"
How can the above be solved in Java?

import java . io . * ; class GFG { static void constructArray ( int A [ ] , int N ) { int [ ] left = new int [ N + 1 ] ; int [ ] right = new int [ N + 1 ] ; int [ ] X = new int [ N + 1 ] ; int [ ] Y = new int [ N + 1 ] ; for ( int i = 0 ; i < N ; i ++ ) { X [ i ] = left [ A [ i ] ] ; left [ A [ i ] ] ++ ; } for ( int i = N - 1 ; i >= 0 ; i -- ) { Y [ i ] = right [ A [ i ] ] ; right [ A [ i ] ] ++ ; } for ( int i = 0 ; i < N ; i ++ ) { System . out . print ( Y [ i ] - X [ i ] + " ▁ " ) ; } } public static void main ( String [ ] args ) { int A [ ] = { 3 , 2 , 1 , 2 , 3 } ; int N = A . length ; constructArray ( A , N ) ; } }


"Generate array with minimum sum which can be deleted in P steps | Java implementation of the approach ; Function to find the required array ; calculating minimum possible sum ; Array ; place first P natural elements ; Fill rest of the elements with 1 ; Driver Code"
How can the above be solved in Java?

 class GFG { static void findArray ( int N , int P ) { int ans = ( P * ( P + 1 ) ) / 2 + ( N - P ) ; int arr [ ] = new int [ N + 1 ] ; for ( int i = 1 ; i <= P ; i ++ ) { arr [ i ] = i ; } for ( int i = P + 1 ; i <= N ; i ++ ) { arr [ i ] = 1 ; } System . out . print ( " The ▁ Minimum ▁ Possible ▁ Sum ▁ is : ▁ " + ans + "
"); System . out . print ( "The Array Elements are:
"); for ( int i = 1 ; i <= N ; i ++ ) { System . out . print ( arr [ i ] + " ▁ " ) ; } } public static void main ( String [ ] args ) { int N = 5 , P = 3 ; findArray ( N , P ) ; } }


"Generate elements of the array following given conditions | Java implementation of the approach ; Function to generate the required array ; Initialize cnt variable for assigning unique value to prime and its multiples ; When we get a prime for the first time then assign a unique smallest value to it and all of its multiples ; Print the generated array ; Driver code"
How can the above be solved in Java?

import java . io . * ; class GFG { static void specialSieve ( int n ) { int cnt = 0 ; int prime [ ] = new int [ n + 1 ] ; for ( int i = 0 ; i <= n ; i ++ ) prime [ i ] = 0 ; for ( int i = 2 ; i <= n ; i ++ ) { if ( ! ( prime [ i ] > 0 ) ) { cnt ++ ; for ( int j = i ; j <= n ; j += i ) prime [ j ] = cnt ; } } for ( int i = 2 ; i <= n ; i ++ ) System . out . print ( prime [ i ] + " ▁ " ) ; } public static void main ( String [ ] args ) { int n = 6 ; specialSieve ( n ) ; } }


"Generate first K multiples of N using Bitwise operators | Java program to implement the above approach ; Function to print the first K multiples of N ; Print the value of N * i ; Iterate each bit of N and add Math . pow ( 2 , pos ) , where pos is the index of each set bit ; Check if current bit at pos j is fixed or not ; For next set bit ; Driver Code"
How can the above be solved in Java?

 import java . util . * ; class GFG { static void Kmultiples ( int n , int k ) { int a = n ; for ( int i = 1 ; i <= k ; i ++ ) { System . out . print ( n + " ▁ * ▁ " + i + " ▁ = ▁ " + a + "
"); int j = 0 ; while ( n >= ( 1 << j ) ) { a += n & ( 1 << j ) ; j ++ ; } } } public static void main ( String [ ] args ) { int N = 16 , K = 7 ; Kmultiples ( N , K ) ; } }


"Generate k digit numbers with digits in strictly increasing order | Java program to generate well ordered numbers with k digits . ; number -- > Current value of number . x -- > Current digit to be considered k -- > Remaining number of digits ; Try all possible greater digits ; Generates all well ordered numbers of length k . ; Driver Code"
How can the above be solved in Java?

class Generate { static void printWellOrdered ( int number , int x , int k ) { if ( k == 0 ) { System . out . print ( number + " ▁ " ) ; return ; } for ( int i = ( x + 1 ) ; i < 10 ; i ++ ) printWellOrdered ( number * 10 + i , i , k - 1 ) ; } static void generateWellOrdered ( int k ) { printWellOrdered ( 0 , 0 , k ) ; } public static void main ( String [ ] args ) { int k = 3 ; generateWellOrdered ( k ) ; } }


"Generate lexicographically smallest string of 0 , 1 and 2 with adjacent swaps allowed | Java implementation of the approach ; Function to print the required string ; count number of 1 s ; To check if the all the 1 s have been used or not ; Print all the 1 s if any 2 is encountered ; If str [ i ] = 0 or str [ i ] = 2 ; If 1 s are not printed yet ; Driver code"
How can the above be solved in Java?

class GFG { static void printString ( char [ ] str , int n ) { int ones = 0 ; for ( int i = 0 ; i < n ; i ++ ) if ( str [ i ] == '1' ) ones ++ ; boolean used = false ; for ( int i = 0 ; i < n ; i ++ ) { if ( str [ i ] == '2' && ! used ) { used = true ; for ( int j = 0 ; j < ones ; j ++ ) System . out . print ( "1" ) ; } if ( str [ i ] != '1' ) System . out . print ( str [ i ] ) ; } if ( ! used ) for ( int j = 0 ; j < ones ; j ++ ) System . out . print ( "1" ) ; } public static void main ( String [ ] args ) { String str = "100210" ; int n = str . length ( ) ; printString ( str . toCharArray ( ) , n ) ; } }


"Generate longest possible array with product K such that each array element is divisible by its previous adjacent element | java program for the above approach ; Function to construct longest array with product K such that each element is divisible by its previous element ; Stores the prime factors of K ; Stores the power to which primefactor i is raised ; Sort prime factors in descending order ; Stores the final array ; Multiply the last element by K ; Print the constructed array ; Driver Code"
How can the above be solved in Java?

import java . io . * ; import java . lang . * ; import java . util . * ; class GFG { static void findLongestArray ( int K ) { ArrayList < int [ ] > primefactors = new ArrayList < > ( ) ; int K_temp = K ; for ( int i = 2 ; i * i <= K ; i ++ ) { int count = 0 ; while ( K_temp % i == 0 ) { K_temp /= i ; count ++ ; } if ( count > 0 ) primefactors . add ( new int [ ] { count , i } ) ; } if ( K_temp != 1 ) primefactors . add ( new int [ ] { 1 , K_temp } ) ; Collections . sort ( primefactors , ( x , y ) -> { if ( x [ 0 ] != y [ 0 ] ) return y [ 0 ] - x [ 0 ] ; return y [ 1 ] - x [ 1 ] ; } ) ; int n = primefactors . get ( 0 ) [ 0 ] ; int val = primefactors . get ( 0 ) [ 1 ] ; int answer [ ] = new int [ n ] ; Arrays . fill ( answer , val ) ; answer [ n - 1 ] *= K ; for ( int i = 0 ; i < n ; i ++ ) { answer [ n - 1 ] /= val ; } System . out . print ( " { " ) ; for ( int i = 0 ; i < answer . length ; i ++ ) { if ( i == answer . length - 1 ) System . out . print ( answer [ i ] + " } " ) ; else System . out . print ( answer [ i ] + " , ▁ " ) ; } } public static void main ( String [ ] args ) { int K = 4 ; findLongestArray ( K ) ; } }


"Generate minimum sum sequence of integers with even elements greater | Java implementation of above approach ; Function to print the required sequence ; arr [ ] will hold the sequence sum variable will store the sum of the sequence ; If sum of the sequence is odd ; Print the sequence ; Driver Code"
How can the above be solved in Java?

class GFG { static void make_sequence ( int N ) { int [ ] arr = new int [ N + 1 ] ; int sum = 0 ; for ( int i = 1 ; i <= N ; i ++ ) { if ( i % 2 == 1 ) arr [ i ] = 1 ; else arr [ i ] = 2 ; sum += arr [ i ] ; } if ( sum % 2 == 1 ) arr [ 2 ] = 3 ; for ( int i = 1 ; i <= N ; i ++ ) System . out . print ( arr [ i ] + " ▁ " ) ; } public static void main ( String [ ] args ) { int N = 9 ; make_sequence ( N ) ; } }


"Generate n | Java program to generate n - bit Gray codes ; This function generates all n bit Gray codes and prints the generated codes ; Base case ; Recursive case ; Append 0 to the first half ; Append 1 to the second half ; Function to generate the Gray code of N bits ; print contents of arr ; Driver Code"
How can the above be solved in Java?

import java . io . * ; import java . util . * ; class GFG { static ArrayList < String > generateGray ( int n ) { if ( n <= 0 ) { ArrayList < String > temp = new ArrayList < String > ( ) { { add ( "0" ) ; } } ; return temp ; } if ( n == 1 ) { ArrayList < String > temp = new ArrayList < String > ( ) { { add ( "0" ) ; add ( "1" ) ; } } ; return temp ; } ArrayList < String > recAns = generateGray ( n - 1 ) ; ArrayList < String > mainAns = new ArrayList < String > ( ) ; for ( int i = 0 ; i < recAns . size ( ) ; i ++ ) { String s = recAns . get ( i ) ; mainAns . add ( "0" + s ) ; } for ( int i = recAns . size ( ) - 1 ; i >= 0 ; i -- ) { String s = recAns . get ( i ) ; mainAns . add ( "1" + s ) ; } return mainAns ; } static void generateGrayarr ( int n ) { ArrayList < String > arr = new ArrayList < String > ( ) ; arr = generateGray ( n ) ; for ( int i = 0 ; i < arr . size ( ) ; i ++ ) { System . out . println ( arr . get ( i ) ) ; } } public static void main ( String [ ] args ) { generateGrayarr ( 3 ) ; } }


"Generate n | Java program to generate n - bit Gray codes ; This function generates all n bit Gray codes and prints the generated codes ; base case ; ' arr ' will store all generated codes ; start with one - bit pattern ; Every iteration of this loop generates 2 * i codes from previously generated i codes . ; Enter the prviously generated codes again in arr [ ] in reverse order . Nor arr [ ] has double number of codes . ; append 0 to the first half ; append 1 to the second half ; print contents of arr [ ] ; Driver program to test above function"
How can the above be solved in Java?

import java . util . * ; class GfG { static void generateGrayarr ( int n ) { if ( n <= 0 ) return ; ArrayList < String > arr = new ArrayList < String > ( ) ; arr . add ( "0" ) ; arr . add ( "1" ) ; int i , j ; for ( i = 2 ; i < ( 1 << n ) ; i = i << 1 ) { for ( j = i - 1 ; j >= 0 ; j -- ) arr . add ( arr . get ( j ) ) ; for ( j = 0 ; j < i ; j ++ ) arr . set ( j , "0" + arr . get ( j ) ) ; for ( j = i ; j < 2 * i ; j ++ ) arr . set ( j , "1" + arr . get ( j ) ) ; } for ( i = 0 ; i < arr . size ( ) ; i ++ ) System . out . println ( arr . get ( i ) ) ; } public static void main ( String [ ] args ) { generateGrayarr ( 3 ) ; } }


"Generate n | Java program to generate n - bit gray codes ; Function to convert decimal to binary ; leftmost digits are filled with 0 ; Function to generate gray code ; generate gray code of corresponding binary number of integer i . ; printing gray code ; Driver code"
How can the above be solved in Java?

import java . io . * ; class GFG { static void decimalToBinaryNumber ( int x , int n ) { int [ ] binaryNumber = new int [ x ] ; int i = 0 ; while ( x > 0 ) { binaryNumber [ i ] = x % 2 ; x = x / 2 ; i ++ ; } for ( int j = 0 ; j < n - i ; j ++ ) System . out . print ( '0' ) ; for ( int j = i - 1 ; j >= 0 ; j -- ) System . out . print ( binaryNumber [ j ] ) ; } static void generateGrayarr ( int n ) { int N = 1 << n ; for ( int i = 0 ; i < N ; i ++ ) { int x = i ^ ( i >> 1 ) ; decimalToBinaryNumber ( x , n ) ; System . out . println ( ) ; } } public static void main ( String [ ] args ) { int n = 3 ; generateGrayarr ( n ) ; } }


"Generate original array from difference between every two consecutive elements | Java program to implement the above approach ; Function to print the required permutation ; Take x = 0 for simplicity ; Calculate aint the differences and store it in a vector ; Preserve the original array ; Check if aint the consecutive elements have difference = 1 ; If consecutive elements don 't have  difference 1 at any position then  the answer is impossible ; Else store the indices and values at those indices in a map and finainty print them ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { static void findPerm ( int n , Vector < Integer > differences ) { Vector < Integer > ans = new Vector < Integer > ( ) ; ans . clear ( ) ; ans . add ( 0 ) ; int x = 0 ; for ( int i = 0 ; i <= n - 2 ; ++ i ) { int diff = differences . get ( i ) ; x = x + diff ; ans . add ( x ) ; } Vector < Integer > anss = new Vector < Integer > ( ) ; for ( Integer obj : ans ) anss . add ( obj ) ; Collections . sort ( ans ) ; int flag = - 1 ; for ( int i = 1 ; i <= n - 1 ; ++ i ) { int res = ans . get ( i ) - ans . get ( i - 1 ) ; if ( res != 1 ) { flag = 0 ; } } if ( flag == 0 ) { System . out . print ( - 1 ) ; return ; } else { Map < Integer , Integer > mpp = new HashMap < > ( ) ; mpp . clear ( ) ; int j = 1 ; Vector < Integer > value_at_index = new Vector < Integer > ( ) ; for ( Integer x1 : ans ) { mpp . put ( x1 , j ) ; ++ j ; } for ( Integer x2 : anss ) { value_at_index . add ( mpp . get ( x2 ) ) ; } for ( Integer x3 : value_at_index ) { System . out . print ( x3 + " ▁ " ) ; } System . out . println ( ) ; } } public static void main ( String [ ] args ) { Vector < Integer > differences = new Vector < Integer > ( ) ; differences . add ( 2 ) ; differences . add ( - 3 ) ; differences . add ( 2 ) ; int n = differences . size ( ) + 1 ; findPerm ( n , differences ) ; } }


"Generate permutation of 1 to N such that absolute difference of consecutive numbers give K distinct integers | Java implementation of the above approach ; Function to generate a permutation of integers from 1 to N such that the absolute difference of all the two consecutive integers give K distinct integers ; To store the permutation ; For sequence 1 2 3. . . ; For sequence N , N - 1 , N - 2. . . ; Flag is used to alternate between the above if else statements ; If last element added was r + 1 ; If last element added was l - 1 ; Print the permutation ; Driver code"
How can the above be solved in Java?

import java . util . Vector ; class GFG { static void printPermutation ( int N , int K ) { Vector < Integer > res = new Vector < > ( ) ; int l = 1 , r = N , flag = 0 ; for ( int i = 0 ; i < K ; i ++ ) { if ( flag == 0 ) { res . add ( l ) ; l ++ ; } else { res . add ( r ) ; r -- ; } flag ^= 1 ; } if ( flag != 1 ) { for ( int i = r ; i >= l ; i -- ) { res . add ( i ) ; } } else { for ( int i = l ; i <= r ; i ++ ) { res . add ( i ) ; } } for ( Integer i : res ) { System . out . print ( i + " ▁ " ) ; } } public static void main ( String [ ] args ) { int N = 10 , K = 4 ; printPermutation ( N , K ) ; } }