"Print all numbers up to N having product of digits equal to K | Java Program to implement the above approach ; Function to find the product of digits of a number ; Stores the product of digits of a number ; Return the product ; Function to print all numbers upto N having product of digits equal to K ; Stores whether any number satisfying the given conditions exists or not ; Iterate over the range [ 1 , N ] ; If product of digits of arr [ i ] is equal to K or not ; Print that number ; If no numbers are found ; Driver Code ; Given value of N & K ; Function call to print all numbers from [ 1 , N ] with product of digits K"
How can the above be solved in Java?

import java . io . * ; import java . util . * ; class GFG { static int productOfDigits ( int N ) { int product = 1 ; while ( N != 0 ) { product = product * ( N % 10 ) ; N = N / 10 ; } return product ; } static void productOfDigitsK ( int N , int K ) { int flag = 0 ; for ( int i = 1 ; i <= N ; ++ i ) { if ( K == productOfDigits ( i ) ) { System . out . print ( i + " ▁ " ) ; flag = 1 ; } } if ( flag == 0 ) System . out . println ( - 1 ) ; } public static void main ( String [ ] args ) { int N = 500 , K = 10 ; productOfDigitsK ( N , K ) ; } }


"Print all numbers up to N in words in lexicographical order | Java program for the above approach ; Function to convert a number to words ; Stores the digits ; Base cases ; Stores strings of unit place ; Stores strings for corner cases ; Stores strings for ten 's place digits ; Stores strings for powers of 10 ; If given number contains a single digit ; Iterate over all the digits ; Represent first 2 digits in words ; Represent last 2 digits in words ; Explicitly handle corner cases [ 10 , 19 ] ; Explicitly handle corner case 20 ; For rest of the two digit numbers i . e . , 21 to 99 ; Function to print all the numbers up to n in lexicographical order ; Convert all numbers in words ; Sort all strings ; Print answer ; Driver Code"
How can the above be solved in Java?

import java . util . * ; class GFG { static String convert_to_words ( int n ) { char num [ ] = String . valueOf ( n ) . toCharArray ( ) ; int len = num . length ; String ans = " " ; if ( len == 0 ) { ans += " Empty ▁ String " ; return ans ; } String [ ] single_digits = new String [ ] { " zero " , " one " , " two " , " three " , " four " , " five " , " six " , " seven " , " eight " , " nine " } ; String [ ] two_digits = new String [ ] { " " , " ten " , " eleven " , " twelve " , " thirteen " , " fourteen " , " fifteen " , " sixteen " , " seventeen " , " eighteen " , " nineteen " } ; String [ ] tens_multiple = new String [ ] { " " , " " , " twenty " , " thirty " , " forty " , " fifty " , " sixty " , " seventy " , " eighty " , " ninety " } ; String [ ] tens_power = new String [ ] { " hundred " , " thousand " } ; if ( len == 1 ) { ans += single_digits [ num [ 0 ] - '0' ] ; return ans ; } int x = 0 ; while ( x < num . length ) { if ( len >= 3 ) { if ( num [ x ] - '0' != 0 ) { ans += single_digits [ num [ x ] - '0' ] ; ans += " ▁ " ; ans += tens_power [ len - 3 ] ; ans += " ▁ " ; } -- len ; } else { if ( num [ x ] - '0' == 1 ) { int sum = num [ x ] - '0' + num [ x ] - '0' ; ans += two_digits [ sum ] ; return ans ; } else if ( num [ x ] - '0' == 2 && num [ x + 1 ] - '0' == 0 ) { ans += " twenty " ; return ans ; } else { int i = ( num [ x ] - '0' ) ; if ( i > 0 ) { ans += tens_multiple [ i ] ; ans += " ▁ " ; } else ans += " " ; ++ x ; if ( num [ x ] - '0' != 0 ) ans += single_digits [ num [ x ] - '0' ] ; } } ++ x ; } return " " ; } static void lexNumbers ( int n ) { Vector < String > s = new Vector < String > ( ) ; for ( int i = 1 ; i <= n ; i ++ ) { s . add ( convert_to_words ( i ) ) ; } Collections . sort ( s ) ; Vector < String > ans = new Vector < String > ( ) ; for ( int i = 0 ; i < n ; i ++ ) ans . add ( s . get ( i ) ) ; for ( int i = 0 ; i < n - 1 ; i ++ ) System . out . print ( ans . get ( i ) + " , ▁ " ) ; System . out . print ( ans . get ( n - 1 ) ) ; } public static void main ( String [ ] args ) { int n =...


"Print all numbers whose set of prime factors is a subset of the set of the prime factors of X | Java program to implement the above approach ; Function to print all the numbers ; Iterate for every element in the array ; Find the gcd ; Iterate till gcd is 1 of number and x ; Divide the number by gcd ; Find the new gcdg ; If the number is 1 at the end then print the number ; If no numbers have been there ; Drivers code"
How can the above be solved in Java?

class GFG { static void printNumbers ( int a [ ] , int n , int x ) { boolean flag = false ; for ( int i = 0 ; i < n ; i ++ ) { int num = a [ i ] ; int g = __gcd ( num , x ) ; while ( g != 1 ) { num /= g ; g = __gcd ( num , x ) ; } if ( num == 1 ) { flag = true ; System . out . print ( a [ i ] + " ▁ " ) ; } } if ( ! flag ) System . out . println ( " There ▁ are ▁ no ▁ such ▁ numbers " ) ; } static int __gcd ( int a , int b ) { if ( b == 0 ) return a ; return __gcd ( b , a % b ) ; } public static void main ( String [ ] args ) { int x = 60 ; int a [ ] = { 2 , 5 , 10 , 7 , 17 } ; int n = a . length ; printNumbers ( a , n , x ) ; } }


"Print all pairs of anagrams in a given array of strings | Java program to Print all pairs of anagrams in a given array of strings ; function to check whether two strings are anagram of each other ; Create two count arrays and initialize all values as 0 ; For each character in input strings , increment count in the corresponding count array ; If both strings are of different length . Removing this condition will make the program fail for strings like " aaca " and " aca " ; See if there is any non - zero value in count array ; This function prints all anagram pairs in a given array of strings ; Driver program to test to pront printDups"
How can the above be solved in Java?

public class GFG { static final int NO_OF_CHARS = 256 ; static boolean areAnagram ( String str1 , String str2 ) { int [ ] count = new int [ NO_OF_CHARS ] ; int i ; for ( i = 0 ; i < str1 . length ( ) && i < str2 . length ( ) ; i ++ ) { count [ str1 . charAt ( i ) ] ++ ; count [ str2 . charAt ( i ) ] -- ; } if ( str1 . length ( ) != str2 . length ( ) ) return false ; for ( i = 0 ; i < NO_OF_CHARS ; i ++ ) if ( count [ i ] != 0 ) return false ; return true ; } static void findAllAnagrams ( String arr [ ] , int n ) { for ( int i = 0 ; i < n ; i ++ ) for ( int j = i + 1 ; j < n ; j ++ ) if ( areAnagram ( arr [ i ] , arr [ j ] ) ) System . out . println ( arr [ i ] + " ▁ is ▁ anagram ▁ of ▁ " + arr [ j ] ) ; } public static void main ( String args [ ] ) { String arr [ ] = { " geeksquiz " , " geeksforgeeks " , " abcd " , " forgeeksgeeks " , " zuiqkeegs " } ; int n = arr . length ; findAllAnagrams ( arr , n ) ; } }


"Print all pairs with given sum | C ++ code to implement the above approach ; Driver code"
How can the above be solved in Java?

import java . util . Arrays ; public class SumOfPairs { public void pairedElements ( int arr [ ] , int sum ) { int low = 0 ; int high = arr . length - 1 ; while ( low < high ) { if ( arr [ low ] + arr [ high ] == sum ) { System . out . println ( " The ▁ pair ▁ is ▁ : ▁ ( " + arr [ low ] + " , ▁ " + arr [ high ] + " ) " ) ; } if ( arr [ low ] + arr [ high ] > sum ) { high -- ; } else { low ++ ; } } } public static void main ( String [ ] args ) { int arr [ ] = { 2 , 3 , 4 , - 2 , 6 , 8 , 9 , 11 } ; Arrays . sort ( arr ) ; SumOfPairs sp = new SumOfPairs ( ) ; sp . pairedElements ( arr , 6 ) ; } }


"Print all pairs with given sum | Java implementation of simple method to find count of pairs with given sum . ; Returns number of pairs in arr [ 0. . n - 1 ] with sum equal to ' sum ' ; Store counts of all elements in map m ; Traverse through all elements ; Search if a pair can be formed with arr [ i ] . ; Driver code"
How can the above be solved in Java?

 import java . util . * ; class GFG { static void printPairs ( int arr [ ] , int n , int sum ) { HashMap < Integer , Integer > mp = new HashMap < Integer , Integer > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { int rem = sum - arr [ i ] ; if ( mp . containsKey ( rem ) ) { int count = mp . get ( rem ) ; for ( int j = 0 ; j < count ; j ++ ) System . out . print ( " ( " + rem + " , ▁ " + arr [ i ] + " ) " + "
"); } if ( mp . containsKey ( arr [ i ] ) ) { mp . put ( arr [ i ] , mp . get ( arr [ i ] ) + 1 ) ; } else { mp . put ( arr [ i ] , 1 ) ; } } } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 5 , 7 , - 1 , 5 } ; int n = arr . length ; int sum = 6 ; printPairs ( arr , n , sum ) ; } }


"Print all pairs with given sum | Java implementation of simple method to find print pairs with given sum . ; Returns number of pairs in arr [ 0. . n - 1 ] with sum equal to ' sum ' ; Consider all possible pairs and check their sums ; Driver Code"
How can the above be solved in Java?

class GFG { static void printPairs ( int arr [ ] , int n , int sum ) { for ( int i = 0 ; i < n ; i ++ ) for ( int j = i + 1 ; j < n ; j ++ ) if ( arr [ i ] + arr [ j ] == sum ) System . out . println ( " ( " + arr [ i ] + " , ▁ " + arr [ j ] + " ) " ) ; } public static void main ( String [ ] arg ) { int arr [ ] = { 1 , 5 , 7 , - 1 , 5 } ; int n = arr . length ; int sum = 6 ; printPairs ( arr , n , sum ) ; } }


"Print all palindrome dates between the given years | Java implementation of the approach ; Returns true if given year is valid ; Return true if year is a multiple pf 4 and not multiple of 100. OR year is multiple of 400. ; Returns true if given year is valid or not . ; If year , month and day are not in given range ; Handle February month with leap year ; Months of April , June , Sept and Nov must have number of days less than or equal to 30. ; Function to print the palindrome dates between the given years ; For every year ; Current year as a String ; To store the reverse of year ; Get the day and the month ; If the current palindrome date is valid ; Driver code"
How can the above be solved in Java?

 class GFG { static int MAX_VALID_YR = 9999 ; static int MIN_VALID_YR = 1800 ; static boolean isLeap ( int year ) { return ( ( ( year % 4 == 0 ) && ( year % 100 != 0 ) ) || ( year % 400 == 0 ) ) ; } static boolean isValidDate ( int d , int m , int y ) { if ( y > MAX_VALID_YR y < MIN_VALID_YR ) return false ; if ( m < 1 m > 12 ) return false ; if ( d < 1 d > 31 ) return false ; if ( m == 2 ) { if ( isLeap ( y ) ) return ( d <= 29 ) ; else return ( d <= 28 ) ; } if ( m == 4 m == 6 m == 9 m == 11 ) return ( d <= 30 ) ; return true ; } static void printPalindromeDates ( int y1 , int y2 ) { for ( int year = y1 ; year <= y2 ; year ++ ) { String str = String . valueOf ( year ) ; String rev = str ; rev = reverse ( rev ) ; int day = Integer . parseInt ( rev . substring ( 0 , 2 ) ) ; int month = Integer . parseInt ( rev . substring ( 2 , 2 + 2 ) ) ; if ( isValidDate ( day , month , year ) ) { System . out . print ( rev + str + "
"); } } } static String reverse ( String input ) { char [ ] a = input . toCharArray ( ) ; int l , r = a . length - 1 ; for ( l = 0 ; l < r ; l ++ , r -- ) { char temp = a [ l ] ; a [ l ] = a [ r ] ; a [ r ] = temp ; } return String . valueOf ( a ) ; } public static void main ( String [ ] args ) { int y1 = 2001 , y2 = 2005 ; printPalindromeDates ( y1 , y2 ) ; } }


"Print all palindromic paths from top left to bottom right in a matrix | Java program to print all palindromic paths from top left to bottom right in a grid . ; i and j are row and column indexes of current cell ( initially these are 0 and 0 ) . ; If we have not reached bottom right corner , keep exlporing ; If we reach bottom right corner , we check if if the path used is palindrome or not . ; Driver code"
How can the above be solved in Java?

public class PalinPath { public static boolean isPalin ( String str ) { int len = str . length ( ) / 2 ; for ( int i = 0 ; i < len ; i ++ ) { if ( str . charAt ( i ) != str . charAt ( str . length ( ) - i - 1 ) ) return false ; } return true ; } public static void palindromicPath ( String str , char a [ ] [ ] , int i , int j , int m , int n ) { if ( j < m - 1 i < n - 1 ) { if ( i < n - 1 ) palindromicPath ( str + a [ i ] [ j ] , a , i + 1 , j , m , n ) ; if ( j < m - 1 ) palindromicPath ( str + a [ i ] [ j ] , a , i , j + 1 , m , n ) ; } else { str = str + a [ n - 1 ] [ m - 1 ] ; if ( isPalin ( str ) ) System . out . println ( str ) ; } } public static void main ( String args [ ] ) { char arr [ ] [ ] = { { ' a ' , ' a ' , ' a ' , ' b ' } , { ' b ' , ' a ' , ' a ' , ' a ' } , { ' a ' , ' b ' , ' b ' , ' a ' } } ; String str = " " ; palindromicPath ( str , arr , 0 , 0 , 4 , 3 ) ; } }


"Print all paths from a given source to a destination using BFS | Java program to print all paths of source to destination in given graph ; utility function for printing the found path in graph ; Utility function to check if current vertex is already present in path ; Utility function for finding paths in graph from source to destination ; Create a queue which stores the paths ; Path vector to store the current path ; If last vertex is the desired destination then print the path ; Traverse to all the nodes connected to current vertex and push new path to queue ; Driver code ; number of vertices ; Construct a graph ; Function for finding the paths"
How can the above be solved in Java?

import java . io . * ; import java . util . * ; class Graph { private static void printPath ( List < Integer > path ) { int size = path . size ( ) ; for ( Integer v : path ) { System . out . print ( v + " ▁ " ) ; } System . out . println ( ) ; } private static boolean isNotVisited ( int x , List < Integer > path ) { int size = path . size ( ) ; for ( int i = 0 ; i < size ; i ++ ) if ( path . get ( i ) == x ) return false ; return true ; } private static void findpaths ( List < List < Integer > > g , int src , int dst , int v ) { Queue < List < Integer > > queue = new LinkedList < > ( ) ; List < Integer > path = new ArrayList < > ( ) ; path . add ( src ) ; queue . offer ( path ) ; while ( ! queue . isEmpty ( ) ) { path = queue . poll ( ) ; int last = path . get ( path . size ( ) - 1 ) ; if ( last == dst ) { printPath ( path ) ; } List < Integer > lastNode = g . get ( last ) ; for ( int i = 0 ; i < lastNode . size ( ) ; i ++ ) { if ( isNotVisited ( lastNode . get ( i ) , path ) ) { List < Integer > newpath = new ArrayList < > ( path ) ; newpath . add ( lastNode . get ( i ) ) ; queue . offer ( newpath ) ; } } } } public static void main ( String [ ] args ) { List < List < Integer > > g = new ArrayList < > ( ) ; int v = 4 ; for ( int i = 0 ; i < 4 ; i ++ ) { g . add ( new ArrayList < > ( ) ) ; } g . get ( 0 ) . add ( 3 ) ; g . get ( 0 ) . add ( 1 ) ; g . get ( 0 ) . add ( 2 ) ; g . get ( 1 ) . add ( 3 ) ; g . get ( 2 ) . add ( 0 ) ; g . get ( 2 ) . add ( 1 ) ; int src = 2 , dst = 3 ; System . out . println ( " path ▁ from ▁ src ▁ " + src + " ▁ to ▁ dst ▁ " + dst + " ▁ are ▁ " ) ; findpaths ( g , src , dst , v ) ; } }


"Print all perfect squares from the given range | Java implementation of the approach ; Function to print all the perfect squares from the given range ; For every element from the range ; If current element is a perfect square ; Driver code"
How can the above be solved in Java?

import java . io . * ; class GFG { static void perfectSquares ( int l , int r ) { for ( int i = l ; i <= r ; i ++ ) { if ( Math . sqrt ( i ) == ( int ) Math . sqrt ( i ) ) System . out . print ( i + " ▁ " ) ; } } public static void main ( String [ ] args ) { int l = 2 , r = 24 ; perfectSquares ( l , r ) ; } }


"Print all perfect squares from the given range | Java implementation of the approach ; Function to print all the perfect squares from the given range ; Getting the very first number ; First number 's square ; Next number is at the difference of ; While the perfect squares are from the range ; Print the perfect square ; Get the next perfect square ; Next odd number to be added ; Driver code"
How can the above be solved in Java?

class GFG { static void perfectSquares ( float l , float r ) { int number = ( int ) Math . ceil ( Math . sqrt ( l ) ) ; int n2 = number * number ; number = ( number * 2 ) + 1 ; while ( ( n2 >= l && n2 <= r ) ) { System . out . print ( n2 + " ▁ " ) ; n2 = n2 + number ; number += 2 ; } } public static void main ( String [ ] args ) { int l = 2 , r = 24 ; perfectSquares ( l , r ) ; } }


"Print all permutation of a string using ArrayList | Java implementation of the approach ; Utility function to print the contents of the ArrayList ; Function to returns the arraylist which contains all the permutation of str ; If string is empty ; Return an empty arraylist ; Take first character of str ; Take sub - string starting from the second character ; Recurvise call ; Store the generated permutations into the resultant arraylist ; Return the resultant arraylist ; Driver code"
How can the above be solved in Java?

import java . util . ArrayList ; public class GFG { static void printArrayList ( ArrayList < String > arrL ) { arrL . remove ( " " ) ; for ( int i = 0 ; i < arrL . size ( ) ; i ++ ) System . out . print ( arrL . get ( i ) + " ▁ " ) ; } public static ArrayList < String > getPermutation ( String str ) { if ( str . length ( ) == 0 ) { ArrayList < String > empty = new ArrayList < > ( ) ; empty . add ( " " ) ; return empty ; } char ch = str . charAt ( 0 ) ; String subStr = str . substring ( 1 ) ; ArrayList < String > prevResult = getPermutation ( subStr ) ; ArrayList < String > Res = new ArrayList < > ( ) ; for ( String val : prevResult ) { for ( int i = 0 ; i <= val . length ( ) ; i ++ ) { Res . add ( val . substring ( 0 , i ) + ch + val . substring ( i ) ) ; } } return Res ; } public static void main ( String [ ] args ) { String str = " abc " ; printArrayList ( getPermutation ( str ) ) ; } }


"Print all permutations of a number N greater than itself | Java implementation to print all the permutation greater than the integer N ; Function to print all the permutation which are greater than N itself ; Iterate and count the number of digits in N ; vector to print the permutations of N ; Store digits of N in the vector num ; Iterate over every permutation of N which is greater than N ; Print the current permutation of N ; Function to print all the permutation which are greater than N itself ; Driver Code"
How can the above be solved in Java?

 import java . util . * ; class GFG { static void printPermutation ( int N ) { int temp = N , count = 0 ; while ( temp > 0 ) { count ++ ; temp /= 10 ; } int [ ] num = new int [ count ] ; while ( N > 0 ) { num [ count -- - 1 ] = N % 10 ; N = N / 10 ; } while ( next_permutation ( num ) ) { for ( int i = 0 ; i < num . length ; i ++ ) System . out . print ( num [ i ] ) ; System . out . print ( "
"); } } static boolean next_permutation ( int [ ] p ) { for ( int a = p . length - 2 ; a >= 0 ; -- a ) if ( p [ a ] < p [ a + 1 ] ) for ( int b = p . length - 1 ; ; -- b ) if ( p [ b ] > p [ a ] ) { int t = p [ a ] ; p [ a ] = p [ b ] ; p [ b ] = t ; for ( ++ a , b = p . length - 1 ; a < b ; ++ a , -- b ) { t = p [ a ] ; p [ a ] = p [ b ] ; p [ b ] = t ; } return true ; } return false ; } public static void main ( String [ ] args ) { int N = 324 ; printPermutation ( N ) ; } }


"Print all positions of a given string having count of smaller characters equal on both sides | Java program to implement the above approach ; Function to find indexes of the given String that satisfy the condition ; Stores length of given String ; Stores frequency of each character of str ; Update frequency of current character ; cntLeftFreq [ i ] Stores frequency of characters present on the left side of index i . ; Traverse the given String ; Stores count of smaller characters on left side of i . ; Stores count of smaller characters on Right side of i . ; Traverse smaller characters on left side of index i . ; Update cntLeft ; Update cntRight ; Update cntLeftFreq [ str [ i ] ] ; If count of smaller elements on both sides equal ; Print current index ; ; Driver Code"
How can the above be solved in Java?

import java . util . * ; class GFG { static void printIndexes ( char [ ] str ) { int N = str . length ; int [ ] cntFreq = new int [ 256 ] ; for ( int i = 0 ; i < N ; i ++ ) { cntFreq [ str [ i ] ] ++ ; } int [ ] cntLeftFreq = new int [ 256 ] ; for ( int i = 0 ; i < N ; i ++ ) { int cntLeft = 0 ; int cntRight = 0 ; for ( int j = str [ i ] - 1 ; j >= 0 ; j -- ) { cntLeft += cntLeftFreq [ j ] ; cntRight += cntFreq [ j ] - cntLeftFreq [ j ] ; } cntLeftFreq [ str [ i ] ] ++ ; if ( cntLeft == cntRight && cntLeft != 0 ) { System . out . print ( i + " ▁ " ) ; } } } public static void main ( String [ ] args ) { String str = " aabacdabbb " ; printIndexes ( str . toCharArray ( ) ) ; } }


"Print all possible K | Java program to implement the above approach ; Function to print all subsequences of length K from N natural numbers whose sum equal to N ; Base case ; Iterate over the range [ 1 , N ] ; Insert i into temp ; Pop i from temp ; Utility function to print all subsequences of length K with sum equal to N ; Store all subsequences of length K from N natural numbers ; Store current subsequence of length K from N natural numbers ; Stores total count of subsequences ; Print all subsequences ; Treaverse all subsequences ; Print current subsequence ; If current element is last element of subsequence ; If current subsequence is last subsequence from n natural numbers ; Driver code"
How can the above be solved in Java?

import java . io . * ; import java . util . * ; import java . util . stream . Collectors ; class GFG { static void findSub ( List < List < Integer > > res , int sum , int K , int N , List < Integer > temp ) { if ( K == 0 && sum == 0 ) { List < Integer > newList = temp . stream ( ) . collect ( Collectors . toList ( ) ) ; res . add ( newList ) ; return ; } if ( sum <= 0 K <= 0 ) { return ; } for ( int i = 1 ; i <= N ; i ++ ) { temp . add ( i ) ; findSub ( res , sum - i , K - 1 , N , temp ) ; temp . remove ( temp . size ( ) - 1 ) ; } } static void UtilPrintSubsequncesOfKSumN ( int N , int K ) { @ SuppressWarnings ( " unchecked " ) List < List < Integer > > res = new ArrayList ( ) ; @ SuppressWarnings ( " unchecked " ) List < Integer > temp = new ArrayList ( ) ; findSub ( res , N , K , N , temp ) ; int sz = res . size ( ) ; System . out . print ( " { ▁ " ) ; for ( int i = 0 ; i < sz ; i ++ ) { System . out . print ( " { ▁ " ) ; for ( int j = 0 ; j < K ; j ++ ) { if ( j == K - 1 ) System . out . print ( res . get ( i ) . get ( j ) + " ▁ " ) ; else System . out . print ( res . get ( i ) . get ( j ) + " , ▁ " ) ; } if ( i == sz - 1 ) System . out . print ( " } " ) ; else System . out . print ( " } , ▁ " ) ; } System . out . print ( " ▁ } " ) ; } public static void main ( String [ ] args ) { int N = 4 ; int K = 2 ; UtilPrintSubsequncesOfKSumN ( N , K ) ; } }


"Print all possible combinations of words from Dictionary using Trie | Java implementation of the approach ; Trie node ; isEndOfWord is true if node represents the end of the word ; Returns new trie node ; If not present , inserts key into trie If the key is prefix of trie node , marks the node as leaf node ; Mark node as leaf ; Returns true if the key is present in the trie ; Result stores the current prefix with spaces between words ; Process all prefixes one by one ; Extract subString from 0 to i in prefix ; If trie conatins this prefix then check for the remaining String . Otherwise ignore this prefix ; If no more elements are there then print ; Add this element to the previous prefix ; If ( result == word ) then return If you don 't want to print last word ; Driver code"
How can the above be solved in Java?

 class GFG { static int ALPHABET_SIZE = 26 ; static class TrieNode { TrieNode [ ] children = new TrieNode [ ALPHABET_SIZE ] ; boolean isEndOfWord ; public TrieNode ( ) { super ( ) ; } } ; static TrieNode getNode ( ) { TrieNode pNode = new TrieNode ( ) ; pNode . isEndOfWord = false ; for ( int i = 0 ; i < ALPHABET_SIZE ; i ++ ) pNode . children [ i ] = null ; return pNode ; } static void insert ( TrieNode root , String key ) { TrieNode pCrawl = root ; for ( int i = 0 ; i < key . length ( ) ; i ++ ) { int index = key . charAt ( i ) - ' a ' ; if ( pCrawl . children [ index ] == null ) pCrawl . children [ index ] = getNode ( ) ; pCrawl = pCrawl . children [ index ] ; } pCrawl . isEndOfWord = true ; } static boolean search ( TrieNode root , String key ) { TrieNode pCrawl = root ; for ( int i = 0 ; i < key . length ( ) ; i ++ ) { int index = key . charAt ( i ) - ' a ' ; if ( pCrawl . children [ index ] == null ) return false ; pCrawl = pCrawl . children [ index ] ; } return ( pCrawl != null && pCrawl . isEndOfWord ) ; } static void wordBreakAll ( TrieNode root , String word , int n , String result ) { for ( int i = 1 ; i <= n ; i ++ ) { String prefix = word . substring ( 0 , i ) ; if ( search ( root , prefix ) ) { if ( i == n ) { result += prefix ; System . out . print ( " 	 " + result + "
"); return ; } wordBreakAll ( root , word . substring ( i , n ) , n - i , result + prefix + " ▁ " ) ; } } } public static void main ( String [ ] args ) { new TrieNode ( ) ; TrieNode root = getNode ( ) ; String dictionary [ ] = { " sam " , " sung " , " samsung " } ; int n = dictionary . length ; for ( int i = 0 ; i < n ; i ++ ) { insert ( root , dictionary [ i ] ) ; } for ( int i = 0 ; i < n ; i ++ ) { System . out . print ( dictionary [ i ] + ":
"); wordBreakAll ( root , dictionary [ i ] , dictionary [ i ] . length ( ) , " " ) ; } } }


"Print all possible pair with prime XOR in the Array | Java implementation of the above approach ; Function for Sieve of Eratosthenes ; If i is prime , then make all multiples of i false ; Function to print all Pairs whose XOR is prime ; if A [ i ] ^ A [ j ] is prime , then print this pair ; Driver Code ; Generate all the prime number ; Function Call"
How can the above be solved in Java?

class GFG { static int sz = ( int ) 1e5 ; static boolean [ ] isPrime = new boolean [ sz + 1 ] ; static void generatePrime ( ) { int i , j ; for ( i = 2 ; i <= sz ; i ++ ) isPrime [ i ] = true ; for ( i = 2 ; i * i <= sz ; i ++ ) { if ( isPrime [ i ] ) { for ( j = i * i ; j < sz ; j += i ) { isPrime [ j ] = false ; } } } } static void Pair_of_PrimeXor ( int A [ ] , int n ) { for ( int i = 0 ; i < n ; i ++ ) { for ( int j = i + 1 ; j < n ; j ++ ) { if ( isPrime [ ( A [ i ] ^ A [ j ] ) ] ) { System . out . print ( " ( " + A [ i ] + " , ▁ " + A [ j ] + " ) ▁ " ) ; } } } } public static void main ( String [ ] args ) { int A [ ] = { 1 , 3 , 6 , 11 } ; int n = A . length ; generatePrime ( ) ; Pair_of_PrimeXor ( A , n ) ; } }


"Print all possible paths from top left to bottom right of a mXn matrix | Java program to Print all possible paths from top left to bottom right of a mXn matrix ; If we reach the bottom of maze , we can only move right ; path . append ( maze [ i ] [ k ] ) ; If we hit this block , it means one path is completed . Add it to paths list and print ; If we reach to the right most corner , we can only move down ; path . append ( maze [ j ] [ k ] ) If we hit this block , it means one path is completed . Add it to paths list and print ; Add current element to the path list path . append ( maze [ i ] [ j ] ) ; Move down in y direction and call findPathsUtil recursively ; Move down in y direction and call findPathsUtil recursively ;  ; Driver code"
How can the above be solved in Java?

import java . io . * ; import java . util . * ; class GFG { static ArrayList < ArrayList < Integer > > allPaths = new ArrayList < ArrayList < Integer > > ( ) ; static void findPathsUtil ( ArrayList < ArrayList < Integer > > maze , int m , int n , int i , int j , ArrayList < Integer > path , int indx ) { if ( i == m - 1 ) { for ( int k = j ; k < n ; k ++ ) { path . set ( indx + k - j , maze . get ( i ) . get ( k ) ) ; } System . out . print ( " [ " + path . get ( 0 ) + " , ▁ " ) ; for ( int z = 1 ; z < path . size ( ) - 1 ; z ++ ) { System . out . print ( path . get ( z ) + " , ▁ " ) ; } System . out . println ( path . get ( path . size ( ) - 1 ) + " ] " ) ; allPaths . add ( path ) ; return ; } if ( j == n - 1 ) { for ( int k = i ; k < m ; k ++ ) { path . set ( indx + k - i , maze . get ( k ) . get ( j ) ) ; } System . out . print ( " [ " + path . get ( 0 ) + " , ▁ " ) ; for ( int z = 1 ; z < path . size ( ) - 1 ; z ++ ) { System . out . print ( path . get ( z ) + " , ▁ " ) ; } System . out . println ( path . get ( path . size ( ) - 1 ) + " ] " ) ; allPaths . add ( path ) ; return ; } path . set ( indx , maze . get ( i ) . get ( j ) ) ; findPathsUtil ( maze , m , n , i + 1 , j , path , indx + 1 ) ; findPathsUtil ( maze , m , n , i , j + 1 , path , indx + 1 ) ; } static void findPaths ( ArrayList < ArrayList < Integer > > maze , int m , int n ) { ArrayList < Integer > path = new ArrayList < Integer > ( ) ; for ( int i = 0 ; i < m + n - 1 ; i ++ ) { path . add ( 0 ) ; } findPathsUtil ( maze , m , n , 0 , 0 , path , 0 ) ; } public static void main ( String [ ] args ) { ArrayList < ArrayList < Integer > > maze = new ArrayList < ArrayList < Integer > > ( ) ; maze . add ( new ArrayList < Integer > ( Arrays . asList ( 1 , 2 , 3 ) ) ) ; maze . add ( new ArrayList < Integer > ( Arrays . asList ( 4 , 5 , 6 ) ) ) ; maze . add ( new ArrayList < Integer > ( Arrays . asList ( 7 , 8 , 9 ) ) ) ; findPaths ( maze , 3 , 3 ) ; } }


"Print all possible strings that can be made by placing spaces | Java program to print all strings that can be made by placing spaces ; Function to print all subsequences ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { static void printSubsequences ( String s ) { char [ ] str = s . toCharArray ( ) ; int n = str . length ; int opsize = ( int ) ( Math . pow ( 2 , n - 1 ) ) ; for ( int counter = 0 ; counter < opsize ; counter ++ ) { for ( int j = 0 ; j < n ; j ++ ) { System . out . print ( str [ j ] ) ; if ( ( counter & ( 1 << j ) ) > 0 ) System . out . print ( " ▁ " ) ; } System . out . println ( ) ; } } public static void main ( String [ ] args ) { String str = " AB " ; printSubsequences ( str ) ; } }


"Print all possible strings that can be made by placing spaces | Java program to print permutations of a given string with spaces ; Function recursively prints the strings having space pattern i and j are indices in ' String ▁ str ' and ' buf [ ] ' respectively ; Either put the character ; Or put a space followed by next character ; Function creates buf [ ] to store individual output string and uses printPatternUtil ( ) to print all permutations ; Buffer to hold the string containing spaces 2 n - 1 characters and 1 string terminator ; Copy the first character as it is , since it will be always at first position ; Driver program"
How can the above be solved in Java?

import java . io . * ; class Permutation { static void printPatternUtil ( String str , char buf [ ] , int i , int j , int n ) { if ( i == n ) { buf [ j ] = ' \0' ; System . out . println ( buf ) ; return ; } buf [ j ] = str . charAt ( i ) ; printPatternUtil ( str , buf , i + 1 , j + 1 , n ) ; buf [ j ] = ' ▁ ' ; buf [ j + 1 ] = str . charAt ( i ) ; printPatternUtil ( str , buf , i + 1 , j + 2 , n ) ; } static void printPattern ( String str ) { int len = str . length ( ) ; char [ ] buf = new char [ 2 * len ] ; buf [ 0 ] = str . charAt ( 0 ) ; printPatternUtil ( str , buf , 1 , 1 , len ) ; } public static void main ( String [ ] args ) { String str = " ABCD " ; printPattern ( str ) ; } }


"Print all possible ways to split an array into K subsets | Java program for above approach ; Utility function to find all possible ways to split array into K subsets ; If count of elements in K subsets are greater than or equal to N ; If count of subsets formed is equal to K ; Print K subsets by splitting array into K subsets ; Print current subset ; If current element is the last element of the subset ; Otherwise ; If any subset is occupied , then push the element in that first ; Recursively do the same for remaining elements ; Backtrack ; Otherwise , push it in an empty subset and increase the subset count by 1 ; Break to avoid the case of going in other empty subsets , if available , and forming the same combination ; Function to to find all possible ways to split array into K subsets ; Stores K subset by splitting array into K subsets ; Size of each subset must be less than the number of elements ; Driver function ; Given array ; Given K ; Size of the array ; Prints all possible splits into subsets"
How can the above be solved in Java?

import java . util . * ; import java . lang . * ; class Gfg { static void PartitionSub ( int arr [ ] , int i , int N , int K , int nos , ArrayList < ArrayList < Integer > > v ) { if ( i >= N ) { if ( nos == K ) { for ( int x = 0 ; x < v . size ( ) ; x ++ ) { System . out . print ( " { ▁ " ) ; for ( int y = 0 ; y < v . get ( x ) . size ( ) ; y ++ ) { System . out . print ( v . get ( x ) . get ( y ) ) ; if ( y == v . get ( x ) . size ( ) - 1 ) { System . out . print ( " ▁ " ) ; } else { System . out . print ( " , ▁ " ) ; } } if ( x == v . size ( ) - 1 ) { System . out . print ( " } " ) ; } else { System . out . print ( " } , ▁ " ) ; } } System . out . println ( ) ; ; } return ; } for ( int j = 0 ; j < K ; j ++ ) { if ( v . get ( j ) . size ( ) > 0 ) { v . get ( j ) . add ( arr [ i ] ) ; PartitionSub ( arr , i + 1 , N , K , nos , v ) ; v . get ( j ) . remove ( v . get ( j ) . size ( ) - 1 ) ; } else { v . get ( j ) . add ( arr [ i ] ) ; PartitionSub ( arr , i + 1 , N , K , nos + 1 , v ) ; v . get ( j ) . remove ( v . get ( j ) . size ( ) - 1 ) ; break ; } } } static void partKSubsets ( int arr [ ] , int N , int K ) { ArrayList < ArrayList < Integer > > v = new ArrayList < > ( ) ; for ( int i = 0 ; i < K ; i ++ ) v . add ( new ArrayList < > ( ) ) ; if ( K == 0 K > N ) { System . out . println ( " Not ▁ Possible " ) ; } else { System . out . println ( " The ▁ Subset ▁ Combinations ▁ are : ▁ " ) ; PartitionSub ( arr , 0 , N , K , 0 , v ) ; } } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 2 , 3 , 4 } ; int K = 2 ; int N = arr . length ; partKSubsets ( arr , N , K ) ; } }


"Print all proper fractions with denominators less than equal to N | Java program to implement the above approach ; Function to print all proper fractions ; If the numerator and the denominator are coprime ; Driver code"
How can the above be solved in Java?

class GFG { static void printFractions ( int n ) { for ( int i = 1 ; i < n ; i ++ ) { for ( int j = i + 1 ; j <= n ; j ++ ) { if ( __gcd ( i , j ) == 1 ) { String a = String . valueOf ( i ) ; String b = String . valueOf ( j ) ; System . out . print ( a + " / " + b + " , ▁ " ) ; } } } } static int __gcd ( int a , int b ) { return b == 0 ? a : __gcd ( b , a % b ) ; } public static void main ( String [ ] args ) { int n = 3 ; printFractions ( n ) ; } }


"Print all root to leaf paths of an N | Java program for the above approach ; Structure of an N ary tree node ; Parameterized Constructor ; Function to print the root to leaf path of the given N - ary Tree ; Print elements in the vector ; Utility function to print all root to leaf paths of an Nary Tree ; If root is null ; Insert current node 's  data into the vector ; If current node is a leaf node ; Print the path ; Pop the leaf node and return ; Recur for all children of the current node ; Recursive Function Call ; Function to print root to leaf path ; If root is null , return ; Stores the root to leaf path ; Utility function call ; Driver Code ; Given N - Ary tree ; Function Call"
How can the above be solved in Java?

import java . util . ArrayList ; class GFG { static class Node { int data ; ArrayList < Node > child ; public Node ( int x ) { this . data = x ; this . child = new ArrayList < > ( ) ; } } ; static void printPath ( ArrayList < Integer > vec ) { for ( int ele : vec ) { System . out . print ( ele + " ▁ " ) ; } System . out . println ( ) ; } static void printAllRootToLeafPaths ( Node root , ArrayList < Integer > vec ) { if ( root == null ) return ; vec . add ( root . data ) ; if ( root . child . isEmpty ( ) ) { printPath ( vec ) ; vec . remove ( vec . size ( ) - 1 ) ; return ; } for ( int i = 0 ; i < root . child . size ( ) ; i ++ ) printAllRootToLeafPaths ( root . child . get ( i ) , vec ) ; vec . remove ( vec . size ( ) - 1 ) ; } static void printAllRootToLeafPaths ( Node root ) { if ( root == null ) return ; ArrayList < Integer > vec = new ArrayList < > ( ) ; printAllRootToLeafPaths ( root , vec ) ; } public static void main ( String [ ] args ) { Node root = new Node ( 1 ) ; ( root . child ) . add ( new Node ( 2 ) ) ; ( root . child ) . add ( new Node ( 3 ) ) ; ( root . child . get ( 0 ) . child ) . add ( new Node ( 4 ) ) ; ( root . child . get ( 1 ) . child ) . add ( new Node ( 5 ) ) ; ( root . child . get ( 1 ) . child ) . add ( new Node ( 6 ) ) ; ( root . child . get ( 1 ) . child . get ( 1 ) . child ) . add ( new Node ( 7 ) ) ; ( root . child . get ( 1 ) . child . get ( 1 ) . child ) . add ( new Node ( 8 ) ) ; printAllRootToLeafPaths ( root ) ; } }


"Print all root to leaf paths with there relative positions | Java program to print all root to leaf paths with there relative position ; tree structure ; Function create new node ; Store path information ; Prints given root to leaf path with underscores ; Find the minimum horizontal distance value in current root to leaf path ; Find minimum horizontal distance ; Print the root to leaf path with " _ " that indicate the related position ; Current tree node ; Print underscore ; Print current key ; A utility function print all path from root to leaf working of this function is similar to function of " Print _ vertical _ order " : Print paths of binary tree in vertical order www . geeksforgeeks . org / print - binary - tree - vertical - order - set - 2 / https : ; Base case ; Leaf node ; Add leaf node and then print path ; Store current path information ; Call left sub_tree ; Call left sub_tree ; Base case ; Driver code"
How can the above be solved in Java?

import java . util . ArrayList ; class Graph { static final int MAX_PATH_SIZE = 1000 ; static class Node { char data ; Node left , right ; } ; static Node newNode ( char data ) { Node temp = new Node ( ) ; temp . data = data ; temp . left = temp . right = null ; return temp ; } static class PATH { int Hd ; char key ; public PATH ( int Hd , char key ) { this . Hd = Hd ; this . key = key ; } public PATH ( ) { } } ; static void printPath ( ArrayList < PATH > path , int size ) { int minimum_Hd = Integer . MAX_VALUE ; PATH p ; for ( int it = 0 ; it < size ; it ++ ) { p = path . get ( it ) ; minimum_Hd = Math . min ( minimum_Hd , p . Hd ) ; } for ( int it = 0 ; it < size ; it ++ ) { p = path . get ( it ) ; int noOfUnderScores = Math . abs ( p . Hd - minimum_Hd ) ; for ( int i = 0 ; i < noOfUnderScores ; i ++ ) System . out . print ( " _ " ) ; System . out . println ( p . key ) ; } System . out . println ( " = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = " ) ; } static void printAllPathsUtil ( Node root , ArrayList < PATH > AllPath , int HD , int order ) { if ( root == null ) return ; if ( root . left == null && root . right == null ) { AllPath . set ( order , new PATH ( HD , root . data ) ) ; printPath ( AllPath , order + 1 ) ; return ; } AllPath . set ( order , new PATH ( HD , root . data ) ) ; printAllPathsUtil ( root . left , AllPath , HD - 1 , order + 1 ) ; printAllPathsUtil ( root . right , AllPath , HD + 1 , order + 1 ) ; } static void printAllPaths ( Node root ) { if ( root == null ) return ; ArrayList < PATH > Allpaths = new ArrayList < > ( ) ; for ( int i = 0 ; i < MAX_PATH_SIZE ; i ++ ) { Allpaths . add ( new PATH ( ) ) ; } printAllPathsUtil ( root , Allpaths , 0 , 0 ) ; } public static void main ( String [ ] args ) { Node root = newNode ( ' A ' ) ; root . left = newNode ( ' B ' ) ; root . right = newNode ( ' C ' ) ; root . left . left = newNode ( ' D ' ) ; root . left . right = newNode ( ' E ' ) ; root . right . left = newNode ( ' F ' ) ; root . right . right = newNode ( ' G ' ) ;...


"Print all safe primes below N | Java implementation of the approach ; Function to print first n safe primes ; Initialize all entries of integer array as 1. A value in prime [ i ] will finally be 0 if i is Not a prime , else 1 ; 0 and 1 are not primes ; If prime [ p ] is not changed , then it is a prime ; Update all multiples of p ; If i is prime ; 2 p + 1 ; If 2 p + 1 is also a prime then set prime [ 2 p + 1 ] = 2 ; i is a safe prime ; Driver code"
How can the above be solved in Java?

class GFG { static void printSafePrimes ( int n ) { int prime [ ] = new int [ n + 1 ] ; for ( int i = 2 ; i <= n ; i ++ ) prime [ i ] = 1 ; prime [ 0 ] = prime [ 1 ] = 0 ; for ( int p = 2 ; p * p <= n ; p ++ ) { if ( prime [ p ] == 1 ) { for ( int i = p * 2 ; i <= n ; i += p ) prime [ i ] = 0 ; } } for ( int i = 2 ; i <= n ; i ++ ) { if ( prime [ i ] != 0 ) { int temp = ( 2 * i ) + 1 ; if ( temp <= n && prime [ temp ] != 0 ) prime [ temp ] = 2 ; } } for ( int i = 5 ; i <= n ; i ++ ) if ( prime [ i ] == 2 ) System . out . print ( i + " ▁ " ) ; } public static void main ( String [ ] args ) { int n = 20 ; printSafePrimes ( n ) ; } }


"Print all sequences of given length | Java program of above approach ; A utility function that prints a given arr [ ] of length size ; The core function that recursively generates and prints all sequences of length k ; A function that uses printSequencesRecur ( ) to prints all sequences from 1 , 1 , . .1 to n , n , . . n ; Driver Program to test above functions"
How can the above be solved in Java?

class GfG { static void printArray ( int arr [ ] , int size ) { for ( int i = 0 ; i < size ; i ++ ) System . out . print ( arr [ i ] + " ▁ " ) ; System . out . println ( ) ; return ; } static void printSequencesRecur ( int arr [ ] , int n , int k , int index ) { int i ; if ( k == 0 ) { printArray ( arr , index ) ; } if ( k > 0 ) { for ( i = 1 ; i <= n ; ++ i ) { arr [ index ] = i ; printSequencesRecur ( arr , n , k - 1 , index + 1 ) ; } } } static void printSequences ( int n , int k ) { int arr [ ] = new int [ k ] ; printSequencesRecur ( arr , n , k , 0 ) ; return ; } public static void main ( String [ ] args ) { int n = 3 ; int k = 2 ; printSequences ( n , k ) ; } }


"Print all strings of maximum length from an array of strings | Java program to implement the above approach ; Function to find the length of the longest String from the given array of Strings ; Traverse the array ; Stores the length of current String ; Update maximum length ; Return the maximum length ; Function to print the longest Strings from the array ; Find the Strings having length equals to len ; Print the resultant vector of Strings ; Function to print all the longest Strings from the array ; Find the length of longest String ; Find and print all the Strings having length equals to max ; Driver Code"
How can the above be solved in Java?

import java . util . * ; class GFG { static int maxLength ( String [ ] arr ) { int len = Integer . MIN_VALUE ; int N = arr . length ; for ( int i = 0 ; i < N ; i ++ ) { int l = arr [ i ] . length ( ) ; if ( len < l ) { len = l ; } } return len ; } static void maxStrings ( String [ ] arr , int len ) { int N = arr . length ; Vector < String > ans = new Vector < String > ( ) ; for ( int i = 0 ; i < N ; i ++ ) { if ( len == arr [ i ] . length ( ) ) { ans . add ( arr [ i ] ) ; } } for ( int i = 0 ; i < ans . size ( ) ; i ++ ) { System . out . print ( ans . get ( i ) + " ▁ " ) ; } } static void printStrings ( String [ ] arr ) { int max = maxLength ( arr ) ; maxStrings ( arr , max ) ; } public static void main ( String [ ] args ) { String [ ] arr = { " aba " , " aa " , " ad " , " vcd " , " aba " } ; printStrings ( arr ) ; } }


"Print all submasks of a given mask | Java Program for above approach ; Function to print the submasks of N ; Driver Code"
How can the above be solved in Java?

import java . util . * ; class GFG { static void SubMasks ( int N ) { for ( int S = N ; S > 0 ; S = ( S - 1 ) & N ) { System . out . print ( S + " ▁ " ) ; } } public static void main ( String args [ ] ) { int N = 25 ; SubMasks ( N ) ; } }


"Print all subsequences of a string | Iterative Method | Java program to print all Subsequences of a String in iterative manner ; Function to find subsequence ; Check if jth bit in binary is 1 ; If jth bit is 1 , include it in subsequence ; Function to print all subsequences ; Map to store subsequence lexicographically by length ; Total number of non - empty subsequence in String is 2 ^ len - 1 ; i = 0 , corresponds to empty subsequence ; Subsequence for binary pattern i ; Storing sub in map ; it . first is length of Subsequence it . second is set < String > ; ii is iterator of type set < String > ; Driver code"
How can the above be solved in Java?

import java . util . ArrayList ; import java . util . Arrays ; import java . util . HashMap ; import java . util . HashSet ; import java . util . Map ; import java . util . SortedMap ; import java . util . TreeMap ; class Graph { static String subsequence ( String s , int binary , int len ) { String sub = " " ; for ( int j = 0 ; j < len ; j ++ ) if ( ( binary & ( 1 << j ) ) != 0 ) sub += s . charAt ( j ) ; return sub ; } static void possibleSubsequences ( String s ) { SortedMap < Integer , HashSet < String > > sorted_subsequence = new TreeMap < Integer , HashSet < String > > ( ) ; int len = s . length ( ) ; int limit = ( int ) Math . pow ( 2 , len ) ; for ( int i = 1 ; i <= limit - 1 ; i ++ ) { String sub = subsequence ( s , i , len ) ; if ( ! sorted_subsequence . containsKey ( sub . length ( ) ) ) sorted_subsequence . put ( sub . length ( ) , new HashSet < > ( ) ) ; sorted_subsequence . get ( sub . length ( ) ) . add ( sub ) ; } for ( Map . Entry < Integer , HashSet < String > > it : sorted_subsequence . entrySet ( ) ) { System . out . println ( " Subsequences ▁ of ▁ length ▁ = ▁ " + it . getKey ( ) + " ▁ are : " ) ; for ( String ii : it . getValue ( ) ) System . out . print ( ii + " ▁ " ) ; System . out . println ( ) ; } } public static void main ( String [ ] args ) { String s = " aabc " ; possibleSubsequences ( s ) ; } }


"Print all subsequences of a string | Java Program to print all subsequence of a given string . ; Set to store all the subsequences ; Function computes all the subsequence of an string ; Iterate over the entire string ; Iterate from the end of the string to generate substrings ; Drop kth character in the substring and if its not in the set then recur ; Drop character from the string ; Driver code"
How can the above be solved in Java?

import java . util . HashSet ; public class Subsequence { static HashSet < String > st = new HashSet < > ( ) ; static void subsequence ( String str ) { for ( int i = 0 ; i < str . length ( ) ; i ++ ) { for ( int j = str . length ( ) ; j > i ; j -- ) { String sub_str = str . substring ( i , j ) ; if ( ! st . contains ( sub_str ) ) st . add ( sub_str ) ; for ( int k = 1 ; k < sub_str . length ( ) - 1 ; k ++ ) { StringBuffer sb = new StringBuffer ( sub_str ) ; sb . deleteCharAt ( k ) ; if ( ! st . contains ( sb ) ) ; subsequence ( sb . toString ( ) ) ; } } } } public static void main ( String [ ] args ) { String s = " aabc " ; subsequence ( s ) ; System . out . println ( st ) ; } }


"Print all subsequences of a string | Java program to generate power set in lexicographic order . ; str : Stores input string n : Length of str . curr : Stores current permutation index : Index in current permutation , curr ; base case ; backtracking ; Generates power set in lexicographic order . ; Driver code"
How can the above be solved in Java?

class GFG { static void printSubSeqRec ( String str , int n , int index , String curr ) { if ( index == n ) { return ; } if ( curr != null && ! curr . trim ( ) . isEmpty ( ) ) { System . out . println ( curr ) ; } for ( int i = index + 1 ; i < n ; i ++ ) { curr += str . charAt ( i ) ; printSubSeqRec ( str , n , i , curr ) ; curr = curr . substring ( 0 , curr . length ( ) - 1 ) ; } } static void printSubSeq ( String str ) { int index = - 1 ; String curr = " " ; printSubSeqRec ( str , str . length ( ) , index , curr ) ; } public static void main ( String [ ] args ) { String str = " cab " ; printSubSeq ( str ) ; } }


"Print all substring of a number without any conversion | Java implementation of above approach ; Function to print the substrings of a number ; Calculate the total number of digits ; 0.5 has been added because of it will return double value like 99.556 ; Print all the numbers from starting position ; Update the no . ; Update the no . of digits ; Driver code"
How can the above be solved in Java?

import java . util . * ; import java . lang . * ; import java . io . * ; class GFG { static void printSubstrings ( int n ) { int s = ( int ) Math . log10 ( n ) ; int d = ( int ) ( Math . pow ( 10 , s ) + 0.5 ) ; int k = d ; while ( n > 0 ) { while ( d > 0 ) { System . out . println ( n / d ) ; d = d / 10 ; } n = n % k ; k = k / 10 ; d = k ; } } public static void main ( String args [ ] ) { int n = 123 ; printSubstrings ( n ) ; } }


"Print all the combinations of N elements by changing sign such that their sum is divisible by M |  ; Function to print all the combinations ; Iterate for all combinations ; Initially 100 in binary if n is 3 as 1 << ( 3 - 1 ) = 100 in binary ; Iterate in the array and assign signs to the array elements ; If the j - th bit from left is set take ' + ' sign ; Right shift to check if jth bit is set or not ; re - initialize ; Iterate in the array elements ; If the jth from left is set ; right shift ; Driver code"
How can the above be solved in Java?

import java . io . * ; class GFG { static void printCombinations ( int a [ ] , int n , int m ) { for ( int i = 0 ; i < ( 1 << n ) ; i ++ ) { int sum = 0 ; int num = 1 << ( n - 1 ) ; for ( int j = 0 ; j < n ; j ++ ) { if ( ( i & num ) > 0 ) sum += a [ j ] ; else sum += ( - 1 * a [ j ] ) ; num = num >> 1 ; } if ( sum % m == 0 ) { num = 1 << ( n - 1 ) ; for ( int j = 0 ; j < n ; j ++ ) { if ( ( i & num ) > 0 ) System . out . print ( " + " + a [ j ] + " ▁ " ) ; else System . out . print ( " - " + a [ j ] + " ▁ " ) ; num = num >> 1 ; } System . out . println ( ) ; } } } public static void main ( String args [ ] ) { int a [ ] = { 3 , 5 , 6 , 8 } ; int n = a . length ; int m = 5 ; printCombinations ( a , n , m ) ; } }


"Print all the combinations of a string in lexicographical order | Java program to find all combinations of a string in lexicographical order ; function to print string ; Method to found all combination of string it is based in tree ; return if level is equal size of string ; if occurrence of char is 0 then skip the iteration of loop ; decrease the char occurrence by 1 ; store the char in result ; print the string till level ; call the function from level + 1 ; backtracking ; declare the map for store each char with occurrence ; initialize the input array with all unique char ; initialize the count array with occurrence the unique char ; temporary char array for store the result ; store the element of input array ; store the element of count array ; size of map ( no of unique char ) ; size of original string ; call function for print string combination ; Driver code"
How can the above be solved in Java?

import java . util . HashMap ; class GFG { static void printResult ( char [ ] result , int len ) { for ( int i = 0 ; i <= len ; i ++ ) System . out . print ( result [ i ] ) ; System . out . println ( ) ; } static void stringCombination ( char [ ] result , char [ ] str , int [ ] count , int level , int size , int length ) { if ( level == size ) return ; for ( int i = 0 ; i < length ; i ++ ) { if ( count [ i ] == 0 ) continue ; count [ i ] -- ; result [ level ] = str [ i ] ; printResult ( result , level ) ; stringCombination ( result , str , count , level + 1 , size , length ) ; count [ i ] ++ ; } } static void combination ( String str ) { HashMap < Character , Integer > mp = new HashMap < > ( ) ; for ( int i = 0 ; i < str . length ( ) ; i ++ ) mp . put ( str . charAt ( i ) , mp . get ( str . charAt ( i ) ) == null ? 1 : mp . get ( str . charAt ( i ) ) + 1 ) ; char [ ] input = new char [ mp . size ( ) ] ; int [ ] count = new int [ mp . size ( ) ] ; char [ ] result = new char [ str . length ( ) ] ; int i = 0 ; for ( HashMap . Entry < Character , Integer > entry : mp . entrySet ( ) ) { input [ i ] = entry . getKey ( ) ; count [ i ] = entry . getValue ( ) ; i ++ ; } int length = mp . size ( ) ; int size = str . length ( ) ; stringCombination ( result , input , count , 0 , size , length ) ; } public static void main ( String [ ] args ) { String str = " ABC " ; combination ( str ) ; } }


"Print all the leaf nodes of Binary Heap | Java implementation to print the leaf nodes of a Binary Heap ; Function to calculate height of the Binary heap with given the count of the nodes ; Function to find the leaf nodes of binary heap ; Calculate the height of the complete binary tree ; if the height if h - 1 , then there should not be any child nodes ; Function to print the leaf nodes ; Driver Code"
How can the above be solved in Java?

import java . lang . * ; import java . util . * ; class GFG { static int height ( int N ) { return ( int ) Math . ceil ( Math . log ( N + 1 ) / Math . log ( 2 ) ) - 1 ; } static void findLeafNodes ( int arr [ ] , int n ) { int h = height ( n ) ; ArrayList < Integer > arrlist = new ArrayList < > ( ) ; for ( int i = n - 1 ; i >= 0 ; i -- ) { if ( height ( i + 1 ) == h ) { arrlist . add ( arr [ i ] ) ; } else if ( height ( i + 1 ) == h - 1 && n <= ( ( 2 * i ) + 1 ) ) { arrlist . add ( arr [ i ] ) ; } else { break ; } } printLeafNodes ( arrlist ) ; } static void printLeafNodes ( ArrayList < Integer > arrlist ) { for ( int i = arrlist . size ( ) - 1 ; i >= 0 ; i -- ) { System . out . print ( arrlist . get ( i ) + " ▁ " ) ; } } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 } ; findLeafNodes ( arr , arr . length ) ; } }


"Print all the non | Java program to print all the non - repeating words from the two given sentences ; Function to print all the non - repeating words from the two given sentences ; Concatenate the two Strings into one ; Iterating over the whole concatenated String ; Searching for the word in A . If while searching , we reach the end of the String , then the word is not present in the String ; Initialise word for the next iteration ; Driver code"
How can the above be solved in Java?

class GFG { static void removeRepeating ( String s1 , String s2 ) { String s3 = s1 + " ▁ " + s2 + " ▁ " ; String words = " " ; int i = 0 ; for ( char x : s3 . toCharArray ( ) ) { if ( x == ' ▁ ' ) { if ( ! s1 . contains ( words ) || ! s2 . contains ( words ) ) System . out . print ( words ) ; words = " ▁ " ; } else { words = words + x ; } } } public static void main ( String [ ] args ) { String s1 = " I ▁ have ▁ go ▁ a ▁ pen " ; String s2 = " I ▁ want ▁ to ▁ go ▁ park " ; removeRepeating ( s1 , s2 ) ; } }


"Print all the pairs that contains the positive and negative values of an element | Java program to find pairs of positive and negative values present in an array . ; Function ; Sort the array ; Traverse the array ; For every arr [ i ] < 0 element , do a binary search for arr [ i ] > 0. ; If found , print the pair . ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { static void printPairs ( int arr [ ] , int n ) { boolean pair_exists = false ; Arrays . sort ( arr ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( arr [ i ] < 0 ) { if ( java . util . Arrays . binarySearch ( arr , - arr [ i ] ) != - 1 ) { System . out . println ( arr [ i ] + " , ▁ " + - arr [ i ] ) ; pair_exists = true ; } } else break ; } if ( pair_exists == false ) System . out . println ( " No ▁ such ▁ pair ▁ exists " ) ; } public static void main ( String args [ ] ) { int arr [ ] = { 4 , 8 , 9 , - 4 , 1 , - 1 , - 8 , - 9 } ; int n = arr . length ; printPairs ( arr , n ) ; } }


"Print all the pairs that contains the positive and negative values of an element | Java program to find pairs of positive and negative values present in an array ; Function to print pairs of positive and negative values present in the array ; Store all the positive elements in the unordered_set ; Start traversing the array ; Check if the positive value of current element exists in the set or not ; Print that pair ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { static void printPairs ( int arr [ ] , int n ) { Set < Integer > pairs = new HashSet < Integer > ( ) ; boolean pair_exists = false ; for ( int i = 0 ; i < n ; i ++ ) if ( arr [ i ] > 0 ) pairs . add ( arr [ i ] ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( arr [ i ] < 0 ) if ( pairs . contains ( - arr [ i ] ) ) { System . out . println ( arr [ i ] + " , ▁ " + - arr [ i ] ) ; pair_exists = true ; } } if ( pair_exists == false ) System . out . println ( " No ▁ such ▁ pair ▁ exists " ) ; } public static void main ( String args [ ] ) { int arr [ ] = { 4 , 8 , 9 , - 4 , 1 , - 1 , - 8 , - 9 } ; int n = arr . length ; printPairs ( arr , n ) ; } }


"Print all the permutation of length L using the elements of an array | Iterative | Java implementation for above approach ; Convert the number to Lth base and print the sequence ; Sequence is of length L ; Print the ith element of sequence ; Print all the permuataions ; There can be ( len ) ^ l permutations ; Convert i to len th base ; Driver code ; function call"
How can the above be solved in Java?

import java . io . * ; class GFG { static void convert_To_Len_th_base ( int n , int arr [ ] , int len , int L ) { for ( int i = 0 ; i < L ; i ++ ) { System . out . print ( arr [ n % len ] ) ; n /= len ; } System . out . println ( ) ; } static void print ( int arr [ ] , int len , int L ) { for ( int i = 0 ; i < ( int ) Math . pow ( len , L ) ; i ++ ) { convert_To_Len_th_base ( i , arr , len , L ) ; } } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 2 , 3 } ; int len = arr . length ; int L = 2 ; print ( arr , len , L ) ; } }


"Print all the sum pairs which occur maximum number of times | Java implementation of above approach ; Function to find the sum pairs that occur the most ; Hash - table ; Keep a count of sum pairs ; Variables to store maximum occurrence ; Iterate in the hash table ; Print all sum pair which occur maximum number of times ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { static void findSumPairs ( int a [ ] , int n ) { Map < Integer , Integer > mpp = new HashMap < > ( ) ; for ( int i = 0 ; i < n - 1 ; i ++ ) { for ( int j = i + 1 ; j < n ; j ++ ) { mpp . put ( a [ i ] + a [ j ] , mpp . get ( a [ i ] + a [ j ] ) == null ? 1 : mpp . get ( a [ i ] + a [ j ] ) + 1 ) ; } } int occur = 0 ; for ( Map . Entry < Integer , Integer > entry : mpp . entrySet ( ) ) { if ( entry . getValue ( ) > occur ) { occur = entry . getValue ( ) ; } } for ( Map . Entry < Integer , Integer > entry : mpp . entrySet ( ) ) { if ( entry . getValue ( ) == occur ) System . out . println ( entry . getKey ( ) ) ; } } public static void main ( String args [ ] ) { int a [ ] = { 1 , 8 , 3 , 11 , 4 , 9 , 2 , 7 } ; int n = a . length ; findSumPairs ( a , n ) ; } }


"Print all triplets in sorted array that form AP | Java implementation to print all the triplets in given array that form Arithmetic Progression ; Function to print all triplets in given sorted array that forms AP ; Search other two elements of AP with arr [ i ] as middle . ; if a triplet is found ; Since elements are distinct , arr [ k ] and arr [ j ] cannot form any more triplets with arr [ i ] ; If middle element is more move to higher side , else move lower side . ; Driver code"
How can the above be solved in Java?

import java . io . * ; class GFG { static void findAllTriplets ( int arr [ ] , int n ) { for ( int i = 1 ; i < n - 1 ; i ++ ) { for ( int j = i - 1 , k = i + 1 ; j >= 0 && k < n ; ) { if ( arr [ j ] + arr [ k ] == 2 * arr [ i ] ) { System . out . println ( arr [ j ] + " ▁ " + arr [ i ] + " ▁ " + arr [ k ] ) ; k ++ ; j -- ; } else if ( arr [ j ] + arr [ k ] < 2 * arr [ i ] ) k ++ ; else j -- ; } } } public static void main ( String [ ] args ) { int arr [ ] = { 2 , 6 , 9 , 12 , 17 , 22 , 31 , 32 , 35 , 42 } ; int n = arr . length ; findAllTriplets ( arr , n ) ; } }


"Print all triplets in sorted array that form AP | Java program to print all triplets in given array that form Arithmetic Progression ; Function to print all triplets in given sorted array that forms AP ; Use hash to find if there is a previous element with difference equal to arr [ j ] - arr [ i ] ; Driver code"
How can the above be solved in Java?

import java . io . * ; import java . util . * ; class GFG { static void printAllAPTriplets ( int [ ] arr , int n ) { ArrayList < Integer > s = new ArrayList < Integer > ( ) ; for ( int i = 0 ; i < n - 1 ; i ++ ) { for ( int j = i + 1 ; j < n ; j ++ ) { int diff = arr [ j ] - arr [ i ] ; boolean exists = s . contains ( arr [ i ] - diff ) ; if ( exists ) System . out . println ( arr [ i ] - diff + " ▁ " + arr [ i ] + " ▁ " + arr [ j ] ) ; } s . add ( arr [ i ] ) ; } } public static void main ( String args [ ] ) { int [ ] arr = { 2 , 6 , 9 , 12 , 17 , 22 , 31 , 32 , 35 , 42 } ; int n = arr . length ; printAllAPTriplets ( arr , n ) ; } }


"Print all triplets with given sum | A simple Java program to find three elements whose sum is equal to given sum ; Prints all triplets in arr [ ] with given sum ; Driver code"
How can the above be solved in Java?

import java . io . * ; class GFG { static void findTriplets ( int arr [ ] , int n , int sum ) { for ( int i = 0 ; i < n - 2 ; i ++ ) { for ( int j = i + 1 ; j < n - 1 ; j ++ ) { for ( int k = j + 1 ; k < n ; k ++ ) { if ( arr [ i ] + arr [ j ] + arr [ k ] == sum ) { System . out . println ( arr [ i ] + " ▁ " + arr [ j ] + " ▁ " + arr [ k ] ) ; } } } } } public static void main ( String [ ] args ) { int arr [ ] = { 0 , - 1 , 2 , - 3 , 1 } ; int n = arr . length ; findTriplets ( arr , n , - 2 ) ; } }


"Print all triplets with given sum | Java program to find triplets in a given array whose sum is equal to given sum . ; function to print triplets with given sum ; Find all pairs with sum equals to " sum - arr [ i ] " ; Driver code"
How can the above be solved in Java?

 import java . util . * ; class GFG { static void findTriplets ( int arr [ ] , int n , int sum ) { for ( int i = 0 ; i < n - 1 ; i ++ ) { HashSet < Integer > s = new HashSet < > ( ) ; for ( int j = i + 1 ; j < n ; j ++ ) { int x = sum - ( arr [ i ] + arr [ j ] ) ; if ( s . contains ( x ) ) System . out . printf ( "%d %d %d
", x, arr[i], arr[j]); else s . add ( arr [ j ] ) ; } } } public static void main ( String [ ] args ) { int arr [ ] = { 0 , - 1 , 2 , - 3 , 1 } ; int sum = - 2 ; int n = arr . length ; findTriplets ( arr , n , sum ) ; } }


"Print all ways to reach the Nth stair with the jump of 1 or 2 units at a time | Java program for the above approach ; Function to find all the ways to reach Nth stair using one or two jumps ; Base Cases ; Recur for jump1 and jump2 ; Stores the total possible jumps ; Add "1" with every element present in jump1 ; Add "2" with every element present in jump2 ; Driver Code"
How can the above be solved in Java?

import java . util . * ; class GFG { static ArrayList < String > TotalPossibleJumps ( int N ) { if ( ( N - 1 ) == 0 ) { ArrayList < String > newvec = new ArrayList < String > ( ) ; newvec . add ( " " ) ; return newvec ; } else { if ( N < 0 ) { ArrayList < String > newvec = new ArrayList < String > ( ) ; return newvec ; } } ArrayList < String > jump1 = TotalPossibleJumps ( N - 1 ) ; ArrayList < String > jump2 = TotalPossibleJumps ( N - 2 ) ; ArrayList < String > totaljumps = new ArrayList < String > ( ) ; for ( String s : jump1 ) { totaljumps . add ( "1" + s ) ; } for ( String s : jump2 ) { totaljumps . add ( "2" + s ) ; } return totaljumps ; } public static void main ( String [ ] args ) { int N = 3 ; ArrayList < String > Ans = TotalPossibleJumps ( N ) ; for ( String it : Ans ) System . out . println ( it ) ; } }


"Print all words matching a pattern in CamelCase Notation Dictionary | Java program to print all words in the CamelCase dictionary that matches with a given pattern ; Alphabet size ( # of upper - Case characters ) ; A Trie node ; isLeaf is true if the node represents end of a word ; vector to store list of complete words in leaf node ; Function to insert word into the Trie ; consider only uppercase characters ; get current character position ; mark last node as leaf ; push word into vector associated with leaf node ; Function to print all children of Trie node root ; if current node is leaf ; recurse for all children of root node ; search for pattern in Trie and print all words matching that pattern ; Invalid pattern ; print all words matching that pattern ; Main function to print all words in the CamelCase dictionary that matches with a given pattern ; construct Trie root node ; Construct Trie from given dict ; search for pattern in Trie ; Driver function ; dictionary of words where each word follows CamelCase notation ; pattern consisting of uppercase characters only"
How can the above be solved in Java?

import java . util . ArrayList ; import java . util . Arrays ; import java . util . List ; public class CamelCase { static final int ALPHABET_SIZE = 26 ; static class TrieNode { TrieNode [ ] children = new TrieNode [ ALPHABET_SIZE ] ; boolean isLeaf ; List < String > word ; public TrieNode ( ) { isLeaf = false ; for ( int i = 0 ; i < ALPHABET_SIZE ; i ++ ) children [ i ] = null ; word = new ArrayList < String > ( ) ; } } static TrieNode root ; static void insert ( String word ) { int index ; TrieNode pCrawl = root ; for ( int level = 0 ; level < word . length ( ) ; level ++ ) { if ( Character . isLowerCase ( word . charAt ( level ) ) ) continue ; index = word . charAt ( level ) - ' A ' ; if ( pCrawl . children [ index ] == null ) pCrawl . children [ index ] = new TrieNode ( ) ; pCrawl = pCrawl . children [ index ] ; } pCrawl . isLeaf = true ; ( pCrawl . word ) . add ( word ) ; } static void printAllWords ( TrieNode root ) { if ( root . isLeaf ) { for ( String str : root . word ) System . out . println ( str ) ; } for ( int i = 0 ; i < ALPHABET_SIZE ; i ++ ) { TrieNode child = root . children [ i ] ; if ( child != null ) printAllWords ( child ) ; } } static boolean search ( String pattern ) { int index ; TrieNode pCrawl = root ; for ( int level = 0 ; level < pattern . length ( ) ; level ++ ) { index = pattern . charAt ( level ) - ' A ' ; if ( pCrawl . children [ index ] == null ) return false ; pCrawl = pCrawl . children [ index ] ; } printAllWords ( pCrawl ) ; return true ; } static void findAllWords ( List < String > dict , String pattern ) { root = new TrieNode ( ) ; for ( String word : dict ) insert ( word ) ; if ( ! search ( pattern ) ) System . out . println ( " No ▁ match ▁ found " ) ; } public static void main ( String args [ ] ) { List < String > dict = Arrays . asList ( " Hi " , " Hello " , " HelloWorld " , " HiTech " , " HiGeek " , " HiTechWorld " , " HiTechCity " , " HiTechLab " ) ; String pattern = " HT " ; findAllWords ( dict , pattern ) ; } }


"Print alternate elements of an array | Java program to implement the above approach ; Function to print Alternate elements of the given array ; Print elements at odd positions ; If currIndex stores even index or odd position ; Driver Code"
How can the above be solved in Java?

import java . io . * ; class GFG { static void printAlter ( int [ ] arr , int N ) { for ( int currIndex = 0 ; currIndex < N ; currIndex ++ ) { if ( currIndex % 2 == 0 ) { System . out . print ( arr [ currIndex ] + " ▁ " ) ; } } } public static void main ( String [ ] args ) { int [ ] arr = { 1 , 2 , 3 , 4 , 5 } ; int N = arr . length ; printAlter ( arr , N ) ; } }


"Print alternate elements of an array | Java program to implement the above approach ; Function to print Alternate elements of the given array ; Print elements at odd positions ; Print elements of array ; Driver Code"
How can the above be solved in Java?

import java . io . * ; class GFG { static void printAlter ( int [ ] arr , int N ) { for ( int currIndex = 0 ; currIndex < N ; currIndex += 2 ) { System . out . print ( arr [ currIndex ] + " ▁ " ) ; } } public static void main ( String [ ] args ) { int [ ] arr = { 1 , 2 , 3 , 4 , 5 } ; int N = arr . length ; printAlter ( arr , N ) ; } }


"Print alternate nodes from all levels of a Binary Tree | Java program to implement the above approach ; Structure of a Node ; Print alternate nodes of a binary tree ; Store nodes of each level ; Store count of nodes of current level ; Print alternate nodes of the current level ; If left child exists ; Store left child ; If right child exists ; Store right child ; Driver Code ; Create a tree"
How can the above be solved in Java?

import java . util . * ; class GFG { static class Node { int data ; Node left ; Node right ; Node ( int val ) { data = val ; left = right = null ; } } ; static void PrintAlternate ( Node root ) { Queue < Node > Q = new LinkedList < > ( ) ; Q . add ( root ) ; while ( ! Q . isEmpty ( ) ) { int N = Q . size ( ) ; for ( int i = 0 ; i < N ; i ++ ) { Node temp = Q . peek ( ) ; Q . remove ( ) ; if ( i % 2 == 0 ) { System . out . print ( temp . data + " ▁ " ) ; } if ( temp . left != null ) { Q . add ( temp . left ) ; } if ( temp . right != null ) { Q . add ( temp . right ) ; } } System . out . println ( ) ; } } public static void main ( String [ ] args ) { Node root ; root = new Node ( 71 ) ; root . left = new Node ( 88 ) ; root . right = new Node ( 99 ) ; root . left . left = new Node ( 4 ) ; root . left . right = new Node ( 5 ) ; root . right . left = new Node ( 6 ) ; root . right . right = new Node ( 7 ) ; root . left . left . left = new Node ( 8 ) ; root . left . left . right = new Node ( 9 ) ; root . left . right . left = new Node ( 10 ) ; root . left . right . right = new Node ( 11 ) ; root . right . left . right = new Node ( 13 ) ; root . right . right . left = new Node ( 14 ) ; PrintAlternate ( root ) ; } }


"Print an N x M matrix such that each row and column has all the vowels in it | Java implementation of the approach ; Function to print the required matrix ; Impossible to generate the required matrix ; Store all the vowels ; Print the matrix ; Print vowels for every index ; Shift the vowels by one ; Driver code"
How can the above be solved in Java?

class GFG { static void printMatrix ( int n , int m ) { if ( n < 5 m < 5 ) { System . out . print ( - 1 ) ; return ; } char [ ] s = " aeiou " . toCharArray ( ) ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = 0 ; j < m ; j ++ ) { System . out . print ( s [ j % 5 ] + " ▁ " ) ; } System . out . println ( ) ; char c = s [ 0 ] ; for ( int k = 0 ; k < 4 ; k ++ ) { s [ k ] = s [ k + 1 ] ; } s [ 4 ] = c ; } } public static void main ( String [ ] args ) { int n = 5 , m = 5 ; printMatrix ( n , m ) ; } }


"Print any pair of integers with sum of GCD and LCM equals to N | Java implementation to print any pair of integers whose summation of GCD and LCM is equal to integer N ; Function to print the required pair ; Print the pair ; Driver code"
How can the above be solved in Java?

class GFG { static void printPair ( int n ) { System . out . print ( 1 + " ▁ " + ( n - 1 ) ) ; } public static void main ( String [ ] args ) { int n = 14 ; printPair ( n ) ; } }


"Print array elements in alternatively increasing and decreasing order | Java program to print array elements in alternative increasing and decreasing order ; Function to print array elements in alternative increasing and decreasing order ; First sort the array in increasing order ; start with 2 elements in increasing order ; till all the elements are not printed ; printing the elements in increasing order ; else printing the elements in decreasing order ; increasing the number of elements to printed in next iteration ; Driver Code"
How can the above be solved in Java?

import java . util . * ; class Solution { static void printArray ( int arr [ ] , int n ) { Arrays . sort ( arr ) ; int l = 0 , r = n - 1 , flag = 0 , i ; int k = 2 ; while ( l <= r ) { if ( flag == 0 ) { for ( i = l ; i < l + k && i <= r ; i ++ ) System . out . print ( arr [ i ] + " ▁ " ) ; flag = 1 ; l = i ; } { for ( i = r ; i > r - k && i >= l ; i -- ) System . out . print ( arr [ i ] + " ▁ " ) ; flag = 0 ; r = i ; } k ++ ; } } public static void main ( String args [ ] ) { int n = 6 ; int arr [ ] = { 1 , 2 , 3 , 4 , 5 , 6 } ; printArray ( arr , n ) ; } }


"Print array of strings in sorted order without copying one string into another | Java implementation to print array of strings in sorted order without copying one string into another ; function to print strings in sorted order ; Initially the index of the strings are assigned to the ' index [ ] ' ; selection sort technique is applied ; with the help of ' index [ ] ' strings are being compared ; index of the smallest string is placed at the ith index of ' index [ ] ' ; printing strings in sorted order ; Driver program to test above"
How can the above be solved in Java?

class GFG { static void printInSortedOrder ( String arr [ ] , int n ) { int index [ ] = new int [ n ] ; int i , j , min ; for ( i = 0 ; i < n ; i ++ ) { index [ i ] = i ; } for ( i = 0 ; i < n - 1 ; i ++ ) { min = i ; for ( j = i + 1 ; j < n ; j ++ ) { if ( arr [ index [ min ] ] . compareTo ( arr [ index [ j ] ] ) > 0 ) { min = j ; } } if ( min != i ) { int temp = index [ min ] ; index [ min ] = index [ i ] ; index [ i ] = temp ; } } for ( i = 0 ; i < n ; i ++ ) { System . out . print ( arr [ index [ i ] ] + " ▁ " ) ; } } static public void main ( String [ ] args ) { String arr [ ] = { " geeks " , " quiz " , " geeks " , " for " } ; int n = 4 ; printInSortedOrder ( arr , n ) ; } }


"Print characters and their frequencies in order of occurrence using Binary Tree | Java implementation of the above approach ; Node in the tree where data holds the character of the String and cnt holds the frequency ; Function to add a new node to the Binary Tree ; Create a new node and populate its data part , set cnt as 1 and left and right children as null ; Function to add a node to the Binary Tree in level order ; Use the queue data structure for level order insertion and push the root of tree to Queue ; If the character to be inserted is present , update the cnt ; If the left child is empty add a new node as the left child ; If the character is present as a left child , update the cnt and exit the loop ; Add the left child to the queue for further processing ; If the right child is empty , add a new node to the right ; If the character is present as a right child , update the cnt and exit the loop ; Add the right child to the queue for further processing ; Function to print the level order traversal of the Binary Tree ; Add the root to the queue ; If the cnt of the character is more then one , display cnt ; If the cnt of character is one , display character only ; Add the left child to the queue for further processing ; Add the right child to the queue for further processing ; Driver code ; Add individual characters to the String one by one in level order ; Print the level order of the constructed binary tree"
How can the above be solved in Java?

import java . util . * ; class GFG { static class node { char data ; int cnt ; node left , right ; } ; static node add ( char data ) { node newnode = new node ( ) ; newnode . data = data ; newnode . cnt = 1 ; newnode . left = newnode . right = null ; return newnode ; } static node addinlvlorder ( node root , char data ) { if ( root == null ) { return add ( data ) ; } Queue < node > Q = new LinkedList < node > ( ) ; Q . add ( root ) ; while ( ! Q . isEmpty ( ) ) { node temp = Q . peek ( ) ; Q . remove ( ) ; if ( temp . data == data ) { temp . cnt ++ ; break ; } if ( temp . left == null ) { temp . left = add ( data ) ; break ; } else { if ( temp . left . data == data ) { temp . left . cnt ++ ; break ; } Q . add ( temp . left ) ; } if ( temp . right == null ) { temp . right = add ( data ) ; break ; } else { if ( temp . right . data == data ) { temp . right . cnt ++ ; break ; } Q . add ( temp . right ) ; } } return root ; } static void printlvlorder ( node root ) { Queue < node > Q = new LinkedList < node > ( ) ; Q . add ( root ) ; while ( ! Q . isEmpty ( ) ) { node temp = Q . peek ( ) ; if ( temp . cnt > 1 ) { System . out . print ( ( temp . data + " " + temp . cnt ) ) ; } else { System . out . print ( ( char ) temp . data ) ; } Q . remove ( ) ; if ( temp . left != null ) { Q . add ( temp . left ) ; } if ( temp . right != null ) { Q . add ( temp . right ) ; } } } public static void main ( String [ ] args ) { String s = " geeksforgeeks " ; node root = null ; for ( int i = 0 ; i < s . length ( ) ; i ++ ) { root = addinlvlorder ( root , s . charAt ( i ) ) ; } printlvlorder ( root ) ; } }


"Print characters in decreasing order of frequency | Java implementation of the approach ; Function to print the characters of the given String in decreasing order of their frequencies ; To store the ; Map 's size ; While there are elements in the map ; Finding the maximum value from the map ; Print the character alongwith its frequency ; Delete the maximum value ; Driver code"
How can the above be solved in Java?

 import java . util . * ; class GFG { static void printChar ( char [ ] arr , int len ) { HashMap < Character , Integer > occ = new HashMap < Character , Integer > ( ) ; for ( int i = 0 ; i < len ; i ++ ) if ( occ . containsKey ( arr [ i ] ) ) { occ . put ( arr [ i ] , occ . get ( arr [ i ] ) + 1 ) ; } else { occ . put ( arr [ i ] , 1 ) ; } int size = occ . size ( ) ; while ( size -- > 0 ) { int currentMax = 0 ; char arg_max = 0 ; for ( Map . Entry < Character , Integer > it : occ . entrySet ( ) ) { if ( it . getValue ( ) > currentMax || ( it . getValue ( ) == currentMax && it . getKey ( ) > arg_max ) ) { arg_max = it . getKey ( ) ; currentMax = it . getValue ( ) ; } } System . out . print ( arg_max + " ▁ - ▁ " + currentMax + "
"); occ . remove ( arg_max ) ; } } public static void main ( String [ ] args ) { String str = " geeksforgeeks " ; int len = str . length ( ) ; printChar ( str . toCharArray ( ) , len ) ; } }


"Print combinations of distinct numbers which add up to give sum N | Java implementation of the approach ; arr [ ] to store all the distinct elements index - next location in array num - given number reducedNum - reduced number ; Set to store all the distinct elements ; Base condition ; Iterate over all the elements and store it into the set ; Calculate the sum of all the elements of the set ; Compare whether the sum is equal to n or not , if it is equal to n print the numbers ; Find previous number stored in the array ; Store all the numbers recursively into the arr [ ] ; Function to find all the distinct combinations of n ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { static void findCombinationsUtil ( int arr [ ] , int index , int n , int red_num ) { HashSet < Integer > s = new HashSet < > ( ) ; int sum = 0 ; if ( red_num < 0 ) { return ; } if ( red_num == 0 ) { for ( int i = 0 ; i < index ; i ++ ) { s . add ( arr [ i ] ) ; } for ( Integer itr : s ) { sum = sum + itr ; } if ( sum == n ) { for ( Integer i : s ) { System . out . print ( i + " ▁ " ) ; } System . out . println ( ) ; return ; } } int prev = ( index == 0 ) ? 1 : arr [ index - 1 ] ; for ( int k = prev ; k <= n ; k ++ ) { if ( index < n ) { arr [ index ] = k ; findCombinationsUtil ( arr , index + 1 , n , red_num - k ) ; } } } static void findCombinations ( int n ) { int [ ] a = new int [ n ] ; findCombinationsUtil ( a , 0 , n , n ) ; } public static void main ( String arr [ ] ) { int n = 7 ; findCombinations ( n ) ; } }


"Print common nodes on path from root ( or common ancestors ) | Java Program to find common nodes for given two nodes ; Class to represent Tree node ; Class to count full nodes of Tree ; Utility function to find the LCA of two given values n1 and n2 . ; Base case ; If either n1 or n2 matches with root 's key,  report the presence by returning root (Note  that if a key is ancestor of other, then the  ancestor key becomes LCA ; Look for keys in left and right subtrees ; If both of the above calls return Non - NULL , then one key is present in once subtree and other is present in other , So this node is the LCA ; Otherwise check if left subtree or right subtree is LCA ; Utility Function to print all ancestors of LCA ; base cases ; If target is present in either left or right subtree of this node , then print this node ; Else return false ; Function to find nodes common to given two nodes ; Driver program to test above functions ; Let us create Binary Tree shown in above example"
How can the above be solved in Java?

import java . util . LinkedList ; class Node { int data ; Node left , right ; public Node ( int item ) { data = item ; left = null ; right = null ; } } class BinaryTree { static Node root ; static Node findLCA ( Node root , int n1 , int n2 ) { if ( root == null ) return null ; if ( root . data == n1 root . data == n2 ) return root ; Node left_lca = findLCA ( root . left , n1 , n2 ) ; Node right_lca = findLCA ( root . right , n1 , n2 ) ; if ( left_lca != null && right_lca != null ) return root ; return ( left_lca != null ) ? left_lca : right_lca ; } static boolean printAncestors ( Node root , int target ) { if ( root == null ) return false ; if ( root . data == target ) { System . out . print ( root . data + " ▁ " ) ; return true ; } if ( printAncestors ( root . left , target ) || printAncestors ( root . right , target ) ) { System . out . print ( root . data + " ▁ " ) ; return true ; } return false ; } static boolean findCommonNodes ( Node root , int first , int second ) { Node LCA = findLCA ( root , first , second ) ; if ( LCA == null ) return false ; printAncestors ( root , LCA . data ) ; return true ; } public static void main ( String args [ ] ) { BinaryTree tree = new BinaryTree ( ) ; tree . root = new Node ( 1 ) ; tree . root . left = new Node ( 2 ) ; tree . root . right = new Node ( 3 ) ; tree . root . left . left = new Node ( 4 ) ; tree . root . left . right = new Node ( 5 ) ; tree . root . right . left = new Node ( 6 ) ; tree . root . right . right = new Node ( 7 ) ; tree . root . left . left . left = new Node ( 8 ) ; tree . root . right . left . left = new Node ( 9 ) ; tree . root . right . left . right = new Node ( 10 ) ; if ( findCommonNodes ( root , 9 , 7 ) == false ) System . out . println ( " No ▁ Common ▁ nodes " ) ; } }


"Print consecutive characters together in a line | Java program to print consecutive characters together in a line . ; Driver code"
How can the above be solved in Java?

 class GFG { static void print ( String str1 ) { char str [ ] = str1 . toCharArray ( ) ; System . out . print ( str [ 0 ] ) ; for ( int i = 1 ; i < str . length ; i ++ ) { if ( ( str [ i ] == str [ i - 1 ] + 1 ) || ( str [ i ] == str [ i - 1 ] - 1 ) ) { System . out . print ( str [ i ] ) ; } else { System . out . print ( "
" + str[i]); } } } public static void main ( String [ ] args ) { String str = " ABCXYZACCD " ; print ( str ) ; } }


"Print cousins of a given node in Binary Tree | Java program to print cousins of a node ; A Binary Tree Node ; A utility function to create a new Binary Tree Node ; It returns level of the node if it is present in tree , otherwise returns 0. ; base cases ; If node is present in left subtree ; If node is not present in left subtree ; Print nodes at a given level such that sibling of node is not printed if it exists ; Base cases ; If current node is parent of a node with given level ; Recur for left and right subtrees ; This function prints cousins of a given node ; Get level of given node ; Print nodes of given level . ; Driver Program to test above functions"
How can the above be solved in Java?

class GfG { static class Node { int data ; Node left , right ; } static Node newNode ( int item ) { Node temp = new Node ( ) ; temp . data = item ; temp . left = null ; temp . right = null ; return temp ; } static int getLevel ( Node root , Node node , int level ) { if ( root == null ) return 0 ; if ( root == node ) return level ; int downlevel = getLevel ( root . left , node , level + 1 ) ; if ( downlevel != 0 ) return downlevel ; return getLevel ( root . right , node , level + 1 ) ; } static void printGivenLevel ( Node root , Node node , int level ) { if ( root == null level < 2 ) return ; if ( level == 2 ) { if ( root . left == node root . right == node ) return ; if ( root . left != null ) System . out . print ( root . left . data + " ▁ " ) ; if ( root . right != null ) System . out . print ( root . right . data + " ▁ " ) ; } else if ( level > 2 ) { printGivenLevel ( root . left , node , level - 1 ) ; printGivenLevel ( root . right , node , level - 1 ) ; } } static void printCousins ( Node root , Node node ) { int level = getLevel ( root , node , 1 ) ; printGivenLevel ( root , node , level ) ; } public static void main ( String [ ] args ) { Node root = newNode ( 1 ) ; root . left = newNode ( 2 ) ; root . right = newNode ( 3 ) ; root . left . left = newNode ( 4 ) ; root . left . right = newNode ( 5 ) ; root . left . right . right = newNode ( 15 ) ; root . right . left = newNode ( 6 ) ; root . right . right = newNode ( 7 ) ; root . right . left . right = newNode ( 8 ) ; printCousins ( root , root . left . right ) ; } }


"Print digit 's position to be removed to make a number divisible by 6 | Java program to print digit 's position to be removed to make number divisible by 6 ; function to print the number divisible by 6 after exactly removing a digit ; stores the sum of all elements ; traverses the string and converts string to number array and sums up ; if ( a [ n - 1 ] % 2 != 0 ) ODD CHECK ; if second last is odd or sum of n - 1 elements are not divisible by 3. ; second last is even and print n - 1 elements removing last digit ; last digit removed ; counter to check if any element after removing , its sum % 3 == 0 ; traverse till second last element ; to check if any element after removing , its sum % 3 == 0 ; the leftmost element ; break at the leftmost element ; stores the right most element ; if no element has been found as a [ i + 1 ] > a [ i ] ; if second last is even , then remove last if ( sum - last ) % 3 == 0 ; if no element which on removing gives sum % 3 == 0 ; driver program to test the above function"
How can the above be solved in Java?

import java . util . * ; class solution { static void greatest ( String s ) { int n = s . length ( ) ; int [ ] a = new int [ n ] ; int sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) { a [ i ] = s . charAt ( i ) - '0' ; sum += a [ i ] ; } { if ( a [ n - 2 ] % 2 != 0 || ( sum - a [ n - 1 ] ) % 3 != 0 ) { System . out . println ( " - 1" ) ; } else { System . out . println ( n ) ; } } else { int re = sum % 3 ; int del = - 1 ; int flag = 0 ; for ( int i = 0 ; i < n - 1 ; i ++ ) { if ( ( a [ i ] ) % 3 == re ) { if ( a [ i + 1 ] > a [ i ] ) { del = i ; flag = 1 ; break ; } else { del = i ; } } } if ( flag == 0 ) { if ( a [ n - 2 ] % 2 == 0 && re == a [ n - 1 ] % 3 ) del = n - 1 ; } if ( del == - 1 ) System . out . println ( - 1 ) ; else { System . out . println ( del + 1 ) ; } } } public static void main ( String args [ ] ) { String s = "7510222" ; greatest ( s ) ; } }


"Print digits for each array element that does not divide any digit of that element | Java program for the above approach ; Function to find digits for each array element that doesn 't divide any digit  of the that element ; Traverse the array arr [ ] ; Iterate over the range [ 2 , 9 ] ; Stores if there exists any digit in arr [ i ] which is divisible by j ; If any digit of the number is divisible by j ; If the digit j doesn 't  divide any digit of arr[i] ; Driver Code"
How can the above be solved in Java?

import java . io . * ; import java . util . * ; class GFG { static void indivisibleDigits ( int [ ] arr , int N ) { for ( int i = 0 ; i < N ; i ++ ) { System . out . print ( arr [ i ] + " : ▁ " ) ; for ( int j = 2 ; j < 10 ; j ++ ) { int temp = arr [ i ] ; boolean flag = true ; while ( temp > 0 ) { if ( ( temp % 10 ) != 0 && ( temp % 10 ) % j == 0 ) { flag = false ; break ; } temp /= 10 ; } if ( flag ) { System . out . print ( j + " ▁ " ) ; } } System . out . println ( ) ; } } public static void main ( String [ ] args ) { int [ ] arr = { 4162 , 1152 , 99842 } ; int N = arr . length ; indivisibleDigits ( arr , N ) ; } }


"Print distinct sorted permutations with duplicates allowed in input | Java program to print all permutations of a string in sorted order . ; Calculating factorial of a number ; Method to print the array ; Method to find total number of permutations ; Building HashMap to store frequencies of all characters . ; Traversing hashmap and finding duplicate elements . ; Start traversing from the end and find position ' i - 1' of the first character which is greater than its successor . ; Finding smallest character after ' i - 1' and greater than temp [ i - 1 ] ; Swapping the above found characters . ; Sort all digits from position next to ' i - 1' to end of the string . ; Print the String ; Sorting String ; Print first permutation ; Finding the total permutations ; Driver Code"
How can the above be solved in Java?

import java . io . * ; import java . util . * ; class Solution { static int factorial ( int n ) { int f = 1 ; for ( int i = 1 ; i <= n ; i ++ ) f = f * i ; return f ; } static void print ( char [ ] temp ) { for ( int i = 0 ; i < temp . length ; i ++ ) System . out . print ( temp [ i ] ) ; System . out . println ( ) ; } static int calculateTotal ( char [ ] temp , int n ) { int f = factorial ( n ) ; HashMap < Character , Integer > hm = new HashMap < Character , Integer > ( ) ; for ( int i = 0 ; i < temp . length ; i ++ ) { if ( hm . containsKey ( temp [ i ] ) ) hm . put ( temp [ i ] , hm . get ( temp [ i ] ) + 1 ) ; else hm . put ( temp [ i ] , 1 ) ; } for ( Map . Entry e : hm . entrySet ( ) ) { Integer x = ( Integer ) e . getValue ( ) ; if ( x > 1 ) { int temp5 = factorial ( x ) ; f = f / temp5 ; } } return f ; } static void nextPermutation ( char [ ] temp ) { int i ; for ( i = temp . length - 1 ; i > 0 ; i -- ) if ( temp [ i ] > temp [ i - 1 ] ) break ; int min = i ; int j , x = temp [ i - 1 ] ; for ( j = i + 1 ; j < temp . length ; j ++ ) if ( ( temp [ j ] < temp [ min ] ) && ( temp [ j ] > x ) ) min = j ; char temp_to_swap ; temp_to_swap = temp [ i - 1 ] ; temp [ i - 1 ] = temp [ min ] ; temp [ min ] = temp_to_swap ; Arrays . sort ( temp , i , temp . length ) ; print ( temp ) ; } static void printAllPermutations ( String s ) { char temp [ ] = s . toCharArray ( ) ; Arrays . sort ( temp ) ; print ( temp ) ; int total = calculateTotal ( temp , temp . length ) ; for ( int i = 1 ; i < total ; i ++ ) nextPermutation ( temp ) ; } public static void main ( String [ ] args ) { String s = " AAB " ; printAllPermutations ( s ) ; } }


"Print equal sum sets of array ( Partition Problem ) | Set 2 | Java program to print equal sum sets of array . ; Function to print equal sum sets of array . ; Finding sum of array elements ; Check sum is even or odd . If odd then array cannot be partitioned . Print - 1 and return . ; Divide sum by 2 to find sum of two possible subsets . ; Boolean DP table to store result of states . dp [ i , j ] = true if there is a subset of elements in first i elements of array that has sum equal to j . ; If number of elements are zero , then no sum can be obtained . ; Sum 0 can be obtained by not selecting any element . ; Fill the DP table in bottom up manner . ; Excluding current element . ; Including current element ; Required sets set1 and set2 . ; If partition is not possible print - 1 and return . ; Start from last element in dp table . ; If current element does not contribute to k , then it belongs to set 2. ; If current element contribute to k then it belongs to set 1. ; Print elements of both the sets . ; Driver Code"
How can the above be solved in Java?

 import java . io . * ; import java . util . * ; class GFG { static void printEqualSumSets ( int [ ] arr , int n ) { int i , currSum , sum = 0 ; for ( i = 0 ; i < arr . length ; i ++ ) sum += arr [ i ] ; if ( ( sum & 1 ) == 1 ) { System . out . print ( " - 1" ) ; return ; } int k = sum >> 1 ; boolean [ ] [ ] dp = new boolean [ n + 1 ] [ k + 1 ] ; for ( i = 1 ; i <= k ; i ++ ) dp [ 0 ] [ i ] = false ; for ( i = 0 ; i <= n ; i ++ ) dp [ i ] [ 0 ] = true ; for ( i = 1 ; i <= n ; i ++ ) { for ( currSum = 1 ; currSum <= k ; currSum ++ ) { dp [ i ] [ currSum ] = dp [ i - 1 ] [ currSum ] ; if ( arr [ i - 1 ] <= currSum ) dp [ i ] [ currSum ] = dp [ i ] [ currSum ] | dp [ i - 1 ] [ currSum - arr [ i - 1 ] ] ; } } List < Integer > set1 = new ArrayList < Integer > ( ) ; List < Integer > set2 = new ArrayList < Integer > ( ) ; if ( ! dp [ n ] [ k ] ) { System . out . print ( "-1
"); return ; } i = n ; currSum = k ; while ( i > 0 && currSum >= 0 ) { if ( dp [ i - 1 ] [ currSum ] ) { i -- ; set2 . add ( arr [ i ] ) ; } else if ( dp [ i - 1 ] [ currSum - arr [ i - 1 ] ] ) { i -- ; currSum -= arr [ i ] ; set1 . add ( arr [ i ] ) ; } } System . out . print ( " Set ▁ 1 ▁ elements : ▁ " ) ; for ( i = 0 ; i < set1 . size ( ) ; i ++ ) System . out . print ( set1 . get ( i ) + " ▁ " ) ; System . out . print ( " Set 2 elements : "); for ( i = 0 ; i < set2 . size ( ) ; i ++ ) System . out . print ( set2 . get ( i ) + " ▁ " ) ; } public static void main ( String args [ ] ) { int [ ] arr = new int [ ] { 5 , 5 , 1 , 11 } ; int n = arr . length ; printEqualSumSets ( arr , n ) ; } }


"Print equal sum sets of array ( Partition problem ) | Set 1 | Java program to print equal sum two subsets of an array if it can be partitioned into subsets . ; Declare Lists to store both the sets . ; / Function to print the equal sum sets of the array . ; / Print set 1. ; / Print set 2. ; Utility function to find the sets of the array which have equal sum . ; If entire array is traversed , compare both the sums . ; If sums are equal print both sets and return true to show sets are found . ; If sums are not equal then return sets are not found . ; Add current element to set 1. ; Recursive call after adding current element to set 1. ; If this inclusion results in equal sum sets partition then return true to show desired sets are found . ; If not then backtrack by removing current element from set1 and include it in set 2. ; Recursive call after including current element to set 2. ; Return true if array arr can be partitioned into two equal sum sets or not . ; Calculate sum of elements in array . ; If sum is odd then array cannot be partitioned . ; / Find both the sets . ; Driver code"
How can the above be solved in Java?

import java . io . * ; import java . util . * ; public class GFG { static List < Integer > set1 = new ArrayList < Integer > ( ) ; static List < Integer > set2 = new ArrayList < Integer > ( ) ; static void printSets ( ) { int i ; for ( i = 0 ; i < set1 . size ( ) ; i ++ ) { System . out . print ( set1 . get ( i ) + " ▁ " ) ; } System . out . println ( ) ; for ( i = 0 ; i < set2 . size ( ) ; i ++ ) { System . out . print ( set2 . get ( i ) + " ▁ " ) ; } } static boolean findSets ( Integer [ ] arr , int n , int sum1 , int sum2 , int pos ) { if ( pos == n ) { if ( sum1 == sum2 ) { printSets ( ) ; return true ; } else return false ; } set1 . add ( arr [ pos ] ) ; boolean res = findSets ( arr , n , sum1 + arr [ pos ] , sum2 , pos + 1 ) ; if ( res == true ) return res ; set1 . remove ( set1 . size ( ) - 1 ) ; set2 . add ( arr [ pos ] ) ; res = findSets ( arr , n , sum1 , sum2 + arr [ pos ] , pos + 1 ) ; if ( res == false ) if ( set2 . size ( ) > 0 ) set2 . remove ( set2 . size ( ) - 1 ) ; return res ; } static boolean isPartitionPoss ( Integer [ ] arr , int n ) { int sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) sum += arr [ i ] ; if ( sum % 2 != 0 ) return false ; return findSets ( arr , n , 0 , 0 , 0 ) ; } public static void main ( String args [ ] ) { Integer [ ] arr = { 5 , 5 , 1 , 11 } ; int n = arr . length ; if ( isPartitionPoss ( arr , n ) == false ) { System . out . print ( " - 1" ) ; } } }


"Print first K distinct Moran numbers from a given array |  ; Function to calculate the sum of digits of a number ; Stores the sum of digits ; Add the digit to sum ; Remove digit ; Returns the sum of digits ; Function to check if a number is prime or not ; If r has any divisor ; Set r as non - prime ; Function to check if a number is moran number ; Calculate sum of digits ; Check if n is divisible by the sum of digits ; Calculate the quotient ; If the quotient is prime ; Function to print the first K Moran numbers from the array ; Sort the given array ; Initialise a set ; Traverse the array from the end ; If the current array element is a Moran number ; Insert into the set ; Driver Code"
How can the above be solved in Java?

 import java . io . * ; import java . util . * ; class GFG { static int digiSum ( int a ) { int sum = 0 ; while ( a != 0 ) { sum += a % 10 ; a = a / 10 ; } return sum ; } static boolean isPrime ( int r ) { boolean s = true ; for ( int i = 2 ; i * i <= r ; i ++ ) { if ( r % i == 0 ) { s = false ; break ; } } return s ; } static boolean isMorannumber ( int n ) { int dup = n ; int sum = digiSum ( dup ) ; if ( n % sum == 0 ) { int c = n / sum ; if ( isPrime ( c ) ) { return true ; } } return false ; } static void FirstKMorannumber ( int [ ] a , int n , int k ) { int X = k ; Arrays . sort ( a ) ; TreeSet < Integer > s = new TreeSet < Integer > ( ) ; for ( int i = n - 1 ; i >= 0 && k > 0 ; i -- ) { if ( isMorannumber ( a [ i ] ) ) { s . add ( a [ i ] ) ; k -- ; } } if ( k > 0 ) { System . out . println ( X + " ▁ Moran ▁ numbers ▁ are " + " ▁ not ▁ present ▁ in ▁ the ▁ array " ) ; return ; } for ( int value : s ) System . out . print ( value + " , ▁ " ) ; System . out . print ( "
"); } public static void main ( String [ ] args ) { int [ ] A = { 34 , 198 , 21 , 42 , 63 , 45 , 22 , 44 , 43 } ; int K = 4 ; int N = A . length ; FirstKMorannumber ( A , N , K ) ; } }


"Print first N Mosaic numbers | Java implementation of the approach ; Function to return the nth mosaic number ; Iterate from 2 to the number ; If i is the factor of n ; Find the count where i ^ count is a factor of n ; Divide the number by i ; Increase the count ; Multiply the answer with count and i ; Return the answer ; Function to print first N Mosaic numbers ; Driver code"
How can the above be solved in Java?

class GFG { static int mosaic ( int n ) { int i , ans = 1 ; for ( i = 2 ; i <= n ; i ++ ) { if ( n % i == 0 && n > 0 ) { int count = 0 ; while ( n % i == 0 ) { n /= i ; count ++ ; } ans *= count * i ; } } return ans ; } static void nMosaicNumbers ( int n ) { for ( int i = 1 ; i <= n ; i ++ ) System . out . print ( mosaic ( i ) + " ▁ " ) ; } public static void main ( String [ ] args ) { int n = 10 ; nMosaicNumbers ( n ) ; } }


"Print first N terms of Lower Wythoff sequence | Java implementation of the approach ; Function to print the first n terms of the lower Wythoff sequence ; Calculate value of phi ; Find the numbers ; a ( n ) = floor ( n * phi ) ; Print the nth numbers ; Driver code"
How can the above be solved in Java?

class GFG { static void lowerWythoff ( int n ) { double phi = ( 1 + Math . sqrt ( 5 ) ) / 2.0 ; for ( int i = 1 ; i <= n ; i ++ ) { double ans = Math . floor ( i * phi ) ; System . out . print ( ( int ) ans ) ; if ( i != n ) System . out . print ( " ▁ , ▁ " ) ; } } public static void main ( String [ ] args ) { int n = 5 ; lowerWythoff ( n ) ; } }