"Prime triplets consisting of values up to N having difference between two elements equal to the third | Java program for the above approach ; Stores 1 and 0 at indices which are prime and non - prime respectively ; Function to find all prime numbers from the range [ 0 , N ] ; Iterate over the range [ 2 , sqrt ( N ) ] ; If p is a prime ; Update all tultiples of p as false ; Function to find all prime triplets satisfying the given conditions ; Generate all primes up to N ; Stores the triplets ; Iterate over the range [ 3 , N ] ; Check for the condition ; Store the triplets ; Print all the stored triplets ; Driver Code"
How can the above be solved in Java?

import java . util . * ; class GFG { static boolean [ ] prime = new boolean [ 100000 ] ; static void initialize ( ) { for ( int i = 0 ; i < 100000 ; i ++ ) prime [ i ] = true ; } static void SieveOfEratosthenes ( int n ) { for ( int p = 2 ; p * p <= n ; p ++ ) { if ( prime [ p ] == true ) { for ( int i = p * p ; i <= n ; i += p ) { prime [ i ] = false ; } } } } static void findTriplets ( int N ) { SieveOfEratosthenes ( N ) ; ArrayList < ArrayList < Integer > > V = new ArrayList < ArrayList < Integer > > ( ) ; for ( int i = 3 ; i <= N ; i ++ ) { if ( 2 + i <= N && prime [ i ] && prime [ 2 + i ] ) { ArrayList < Integer > a1 = new ArrayList < Integer > ( ) ; a1 . add ( 2 ) ; a1 . add ( i ) ; a1 . add ( i + 2 ) ; V . add ( a1 ) ; } } for ( int i = 0 ; i < V . size ( ) ; i ++ ) { System . out . println ( V . get ( i ) . get ( 0 ) + " ▁ " + V . get ( i ) . get ( 1 ) + " ▁ " + V . get ( i ) . get ( 2 ) ) ; } } public static void main ( String args [ ] ) { initialize ( ) ; int N = 8 ; findTriplets ( N ) ; } }


"Primitive Abundant Number | Java implementation of the above approach ; Function to sum of divisors ; Note that this loop runs till square root of N ; If divisors are equal , take only one of them ; Otherwise take both ; Function to check Abundant Number ; Return true if sum of divisors is greater than N . ; Function to check Deficient Number ; Check if sum ( n ) < 2 * n ; Function to check all proper divisors of N is deficient number or not ; If number itself is not abundant retuen false ; Find all divisors which divides ' num ' ; if ' i ' is divisor of ' num ' ; if both divisors are same then add it only once else add both ; Driver Code"
How can the above be solved in Java?

class GFG { static int getSum ( int n ) { int sum = 0 ; for ( int i = 1 ; i <= Math . sqrt ( n ) ; i ++ ) { if ( n % i == 0 ) { if ( n / i == i ) sum = sum + i ; else { sum = sum + i ; sum = sum + ( n / i ) ; } } } return sum ; } static boolean checkAbundant ( int n ) { return ( getSum ( n ) - n > n ) ; } static boolean isDeficient ( int n ) { return ( getSum ( n ) < ( 2 * n ) ) ; } static boolean checkPrimitiveAbundant ( int num ) { if ( ! checkAbundant ( num ) ) { return false ; } for ( int i = 2 ; i <= Math . sqrt ( num ) ; i ++ ) { if ( num % i == 0 && i != num ) { if ( i * i == num ) { if ( ! isDeficient ( i ) ) { return false ; } } else if ( ! isDeficient ( i ) || ! isDeficient ( num / i ) ) { return false ; } } } return true ; } public static void main ( String [ ] args ) { int n = 20 ; if ( checkPrimitiveAbundant ( n ) ) { System . out . print ( " Yes " ) ; } else { System . out . print ( " No " ) ; } } }


"Primitive root of a prime number n modulo n | Java program to find primitive root of a given number n ; Returns true if n is prime ; Corner cases ; This is checked so that we can skip middle five numbers in below loop ; Iterative Function to calculate ( x ^ n ) % p in O ( logy ) ; x = x % p ; Update x if it is more than or equal to p ; If y is odd , multiply x with result ; y must be even now y = y >> 1 ; y = y / 2 ; Utility function to store prime factors of a number ; Print the number of 2 s that divide n ; n must be odd at this point . So we can skip one element ( Note i = i + 2 ) ; While i divides n , print i and divide n ; This condition is to handle the case when n is a prime number greater than 2 ; Function to find smallest primitive root of n ; Check if n is prime or not ; Find value of Euler Totient function of n Since n is a prime number , the value of Euler Totient function is n - 1 as there are n - 1 relatively prime numbers . ; Find prime factors of phi and store in a set ; Check for every number from 2 to phi ; Iterate through all prime factors of phi . and check if we found a power with value 1 ; Check if r ^ ( ( phi ) / primefactors ) mod n is 1 or not ; If there was no power with value 1. ; If no primitive root found ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { static boolean isPrime ( int n ) { if ( n <= 1 ) { return false ; } if ( n <= 3 ) { return true ; } if ( n % 2 == 0 n % 3 == 0 ) { return false ; } for ( int i = 5 ; i * i <= n ; i = i + 6 ) { if ( n % i == 0 || n % ( i + 2 ) == 0 ) { return false ; } } return true ; } static int power ( int x , int y , int p ) { while ( y > 0 ) { if ( y % 2 == 1 ) { res = ( res * x ) % p ; } x = ( x * x ) % p ; } return res ; } static void findPrimefactors ( HashSet < Integer > s , int n ) { while ( n % 2 == 0 ) { s . add ( 2 ) ; n = n / 2 ; } for ( int i = 3 ; i <= Math . sqrt ( n ) ; i = i + 2 ) { while ( n % i == 0 ) { s . add ( i ) ; n = n / i ; } } if ( n > 2 ) { s . add ( n ) ; } } static int findPrimitive ( int n ) { HashSet < Integer > s = new HashSet < Integer > ( ) ; if ( isPrime ( n ) == false ) { return - 1 ; } int phi = n - 1 ; findPrimefactors ( s , phi ) ; for ( int r = 2 ; r <= phi ; r ++ ) { boolean flag = false ; for ( Integer a : s ) { if ( power ( r , phi / ( a ) , n ) == 1 ) { flag = true ; break ; } } if ( flag == false ) { return r ; } } return - 1 ; } public static void main ( String [ ] args ) { int n = 761 ; System . out . println ( " ▁ Smallest ▁ primitive ▁ root ▁ of ▁ " + n + " ▁ is ▁ " + findPrimitive ( n ) ) ; } }


"Print Ancestors of a given node in Binary Tree | A binary tree node has data , pointer to left child and a pointer to right child ; If target is present in tree , then prints the ancestors and returns true , otherwise returns false . ; base cases ; If target is present in either left or right subtree of this node , then print this node ; Else return false ; Driver program to test above functions ; Construct the following binary tree 1 / \ 2 3 / \ 4 5 / 7"
How can the above be solved in Java?

class Node { int data ; Node left , right , nextRight ; Node ( int item ) { data = item ; left = right = nextRight = null ; } } class BinaryTree { Node root ; boolean printAncestors ( Node node , int target ) { if ( node == null ) return false ; if ( node . data == target ) return true ; if ( printAncestors ( node . left , target ) || printAncestors ( node . right , target ) ) { System . out . print ( node . data + " ▁ " ) ; return true ; } return false ; } 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 . left . left . left = new Node ( 7 ) ; tree . printAncestors ( tree . root , 7 ) ; } }


"Print BST keys in given Range | O ( 1 ) Space | Java code to print BST keys in given Range in constant space using Morris traversal . ; Function to print the keys in range ; check if current node lies between n1 and n2 ; finding the inorder predecessor - inorder predecessor is the right most in left subtree or the left child , i . e in BST it is the maximum ( right most ) in left subtree . ; check if current node lies between n1 and n2 ; Helper function to create a new node ; Driver Code ; Constructed binary tree is 4 / \ 2 7 / \ / \ 1 3 6 10"
How can the above be solved in Java?

class GfG { static class node { int data ; node left , right ; } static void RangeTraversal ( node root , int n1 , int n2 ) { if ( root == null ) return ; node curr = root ; while ( curr != null ) { if ( curr . left == null ) { if ( curr . data <= n2 && curr . data >= n1 ) { System . out . print ( curr . data + " ▁ " ) ; } curr = curr . right ; } else { node pre = curr . left ; while ( pre . right != null && pre . right != curr ) pre = pre . right ; if ( pre . right == null ) { pre . right = curr ; curr = curr . left ; } else { pre . right = null ; if ( curr . data <= n2 && curr . data >= n1 ) { System . out . print ( curr . data + " ▁ " ) ; } curr = curr . right ; } } } } static node newNode ( int data ) { node temp = new node ( ) ; temp . data = data ; temp . right = null ; temp . left = null ; return temp ; } public static void main ( String [ ] args ) { node root = newNode ( 4 ) ; root . left = newNode ( 2 ) ; root . right = newNode ( 7 ) ; root . left . left = newNode ( 1 ) ; root . left . right = newNode ( 3 ) ; root . right . left = newNode ( 6 ) ; root . right . right = newNode ( 10 ) ; RangeTraversal ( root , 4 , 12 ) ; } }


"Print Binary Tree in 2 | Java Program to print binary tree in 2D ; A binary tree node ; Constructor that allocates a new node with the given data and null left and right pointers . ; Function to print binary tree in 2D It does reverse inorder traversal ; Base case ; Increase distance between levels ; Process right child first ; Print current node after space count ; Process left child ; Wrapper over print2DUtil ( ) ; Pass initial space count as 0 ; Driver code"
How can the above be solved in Java?

 class GFG { static final int COUNT = 10 ; static class Node { int data ; Node left , right ; Node ( int data ) { this . data = data ; this . left = null ; this . right = null ; } } ; static void print2DUtil ( Node root , int space ) { if ( root == null ) return ; space += COUNT ; print2DUtil ( root . right , space ) ; System . out . print ( "
"); for ( int i = COUNT ; i < space ; i ++ ) System . out . print ( " ▁ " ) ; System . out . print ( root . data + "
"); print2DUtil ( root . left , space ) ; } static void print2D ( Node root ) { print2DUtil ( root , 0 ) ; } public static void main ( String args [ ] ) { Node root = new Node ( 1 ) ; root . left = new Node ( 2 ) ; root . right = new Node ( 3 ) ; 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 . left = new Node ( 12 ) ; root . right . left . right = new Node ( 13 ) ; root . right . right . left = new Node ( 14 ) ; root . right . right . right = new Node ( 15 ) ; print2D ( root ) ; } }


"Print Bracket Number | Java implementation to print the bracket number ; function to print the bracket number ; used to print the bracket number for the left bracket ; used to obtain the bracket number for the right bracket ; traverse the given expression ' exp ' ; if current character is a left bracket ; print ' left _ bnum ' , ; push ' left _ bum ' on to the stack ' right _ bnum ' ; increment ' left _ bnum ' by 1 ; else if current character is a right bracket ; print the top element of stack ' right _ bnum ' it will be the right bracket number ; pop the top element from the stack ; Driver Code"
How can the above be solved in Java?

import java . io . * ; import java . util . * ; class GFG { static void printBracketNumber ( String exp , int n ) { int left_bnum = 1 ; Stack < Integer > right_bnum = new Stack < Integer > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( exp . charAt ( i ) == ' ( ' ) { System . out . print ( left_bnum + " ▁ " ) ; right_bnum . push ( left_bnum ) ; left_bnum ++ ; } else if ( exp . charAt ( i ) == ' ) ' ) { System . out . print ( right_bnum . peek ( ) + " ▁ " ) ; right_bnum . pop ( ) ; } } } public static void main ( String args [ ] ) { String exp = " ( a + ( b * c ) ) + ( d / e ) " ; int n = exp . length ( ) ; printBracketNumber ( exp , n ) ; } }


"Print Common Nodes in Two Binary Search Trees | Java program of iterative traversal based method to find common elements in two BSTs . ; A BST node ; A utility function to create a new node ; Function two print common elements in given two trees ; Create two stacks for two inorder traversals ; push the Nodes of first tree in stack s1 ; push the Nodes of second tree in stack s2 ; Both root1 and root2 are NULL here ; If current keys in two trees are same ; move to the inorder successor ; If Node of first tree is smaller , than that of second tree , then its obvious that the inorder successors of current Node can have same value as that of the second tree Node . Thus , we pop from s2 ; root2 is set to NULL , because we need new Nodes of tree 1 ; Both roots and both stacks are empty ; A utility function to do inorder traversal ; A utility function to insert a new Node with given key in BST ; If the tree is empty , return a new Node ; Otherwise , recur down the tree ; return the ( unchanged ) Node pointer ; Driver program ; Create first tree as shown in example ; Create second tree as shown in example"
How can the above be solved in Java?

 import java . util . * ; class GfG { static class Node { int key ; Node left , right ; } static Node newNode ( int ele ) { Node temp = new Node ( ) ; temp . key = ele ; temp . left = null ; temp . right = null ; return temp ; } static void printCommon ( Node root1 , Node root2 ) { Stack < Node > s1 = new Stack < Node > ( ) ; Stack < Node > s2 = new Stack < Node > ( ) ; while ( true ) { if ( root1 != null ) { s1 . push ( root1 ) ; root1 = root1 . left ; } else if ( root2 != null ) { s2 . push ( root2 ) ; root2 = root2 . left ; } else if ( ! s1 . isEmpty ( ) && ! s2 . isEmpty ( ) ) { root1 = s1 . peek ( ) ; root2 = s2 . peek ( ) ; if ( root1 . key == root2 . key ) { System . out . print ( root1 . key + " ▁ " ) ; s1 . pop ( ) ; s2 . pop ( ) ; root1 = root1 . right ; root2 = root2 . right ; } else if ( root1 . key < root2 . key ) { s1 . pop ( ) ; root1 = root1 . right ; root2 = null ; } else if ( root1 . key > root2 . key ) { s2 . pop ( ) ; root2 = root2 . right ; root1 = null ; } } else break ; } } static void inorder ( Node root ) { if ( root != null ) { inorder ( root . left ) ; System . out . print ( root . key + " ▁ " ) ; inorder ( root . right ) ; } } static Node insert ( Node node , int key ) { if ( node == null ) return newNode ( key ) ; if ( key < node . key ) node . left = insert ( node . left , key ) ; else if ( key > node . key ) node . right = insert ( node . right , key ) ; return node ; } public static void main ( String [ ] args ) { Node root1 = null ; root1 = insert ( root1 , 5 ) ; root1 = insert ( root1 , 1 ) ; root1 = insert ( root1 , 10 ) ; root1 = insert ( root1 , 0 ) ; root1 = insert ( root1 , 4 ) ; root1 = insert ( root1 , 7 ) ; root1 = insert ( root1 , 9 ) ; Node root2 = null ; root2 = insert ( root2 , 10 ) ; root2 = insert ( root2 , 7 ) ; root2 = insert ( root2 , 20 ) ; root2 = insert ( root2 , 4 ) ; root2 = insert ( root2 , 9 ) ; System . out . print ( " Tree ▁ 1 ▁ : ▁ " + "
");  inorder ( root1 ) ; System . out . println ( ) ; System . out . print ( " Tree ▁ 2 ▁ : ▁ " + "
");  inorder (...


"Print Concatenation of Zig | Java Program for above approach ; Function for zig - zag Concatenation ; Check is n is less or equal to 1 ; Iterate rowNum from 0 to n - 1 ; Iterate i till s . length ( ) - 1 ; Check is rowNum is 0 or n - 1 ; Driver Code"
How can the above be solved in Java?

import java . lang . * ; class Solution { private static String zigZagConcat ( String s , int n ) { if ( n <= 1 ) { return s ; } StringBuilder result = new StringBuilder ( ) ; for ( int rowNum = 0 ; rowNum < n ; rowNum ++ ) { int i = rowNum ; boolean up = true ; while ( i < s . length ( ) ) { result = result . append ( s . charAt ( i ) ) ; if ( rowNum == 0 rowNum == n - 1 ) { i += ( 2 * n - 2 ) ; } else { if ( up ) { i += ( 2 * ( n - rowNum ) - 2 ) ; } else { i += rowNum * 2 ; } up ^= true ; } } } return result . toString ( ) ; } public static void main ( String [ ] args ) { String str = " GEEKSFORGEEKS " ; int n = 3 ; System . out . println ( zigZagConcat ( str , n ) ) ; } }


"Print Concatenation of Zig | Java program to print string obtained by concatenation of different rows of Zig - Zag fashion ; Prints concatenation of all rows of str 's  Zig-Zag fashion ; Corner Case ( Only one row ) ; Find length of string ; Create an array of strings for all n rows ; Initialize index for array of strings arr [ ] ; True if we are moving down in rows , else false ; Traverse through given string ; append current character to current row ; If last row is reached , change direction to ' up ' ; If 1 st row is reached , change direction to ' down ' ; If direction is down , increment , else decrement ; Print concatenation of all rows ; Driver Code"
How can the above be solved in Java?

import java . util . Arrays ; class GFG { static void printZigZagConcat ( String str , int n ) { if ( n == 1 ) { System . out . print ( str ) ; return ; } char [ ] str1 = str . toCharArray ( ) ; int len = str . length ( ) ; String [ ] arr = new String [ n ] ; Arrays . fill ( arr , " " ) ; int row = 0 ; boolean down = true ; for ( int i = 0 ; i < len ; ++ i ) { arr [ row ] += ( str1 [ i ] ) ; if ( row == n - 1 ) { down = false ; } else if ( row == 0 ) { down = true ; } if ( down ) { row ++ ; } else { row -- ; } } for ( int i = 0 ; i < n ; ++ i ) { System . out . print ( arr [ i ] ) ; } } public static void main ( String [ ] args ) { String str = " GEEKSFORGEEKS " ; int n = 3 ; printZigZagConcat ( str , n ) ; } }


"Print Fibonacci Series in reverse order | Java Program to print Fibonacci series in reverse order ; assigning first and second elements ; storing sum in the preceding location ; printing array in reverse order ; Driver function"
How can the above be solved in Java?

import java . io . * ; class GFG { static void reverseFibonacci ( int n ) { int a [ ] = new int [ n ] ; a [ 0 ] = 0 ; a [ 1 ] = 1 ; for ( int i = 2 ; i < n ; i ++ ) { a [ i ] = a [ i - 2 ] + a [ i - 1 ] ; } for ( int i = n - 1 ; i >= 0 ; i -- ) { System . out . print ( a [ i ] + " ▁ " ) ; } } public static void main ( String [ ] args ) { int n = 5 ; reverseFibonacci ( n ) ; } }


"Print Fibonacci sequence using 2 variables | Simple Java Program to print Fibonacci sequence ; Driver code"
How can the above be solved in Java?

import java . io . * ; class GFG { static void fib ( int n ) { int a = 0 , b = 1 , c ; if ( n >= 0 ) System . out . print ( a + " ▁ " ) ; if ( n >= 1 ) System . out . print ( b + " ▁ " ) ; for ( int i = 2 ; i <= n ; i ++ ) { c = a + b ; System . out . print ( c + " ▁ " ) ; a = b ; b = c ; } } public static void main ( String [ ] args ) { fib ( 9 ) ; } }


"Print K 'th element in spiral form of matrix |  ; k - starting row index m - ending row index l - starting column index n - ending column index i - iterator ; check the first row from the remaining rows ; check the last column from the remaining columns ; check the last row from the remaining rows ; check the first column from the remaining columns ; Driver program to test above functions"
How can the above be solved in Java?

import java . io . * ; class GFG { static int R = 3 ; static int C = 6 ; static void spiralPrint ( int m , int n , int [ ] [ ] a , int c ) { int i , k = 0 , l = 0 ; int count = 0 ; while ( k < m && l < n ) { for ( i = l ; i < n ; ++ i ) { count ++ ; if ( count == c ) System . out . println ( a [ k ] [ i ] + " ▁ " ) ; } k ++ ; for ( i = k ; i < m ; ++ i ) { count ++ ; if ( count == c ) System . out . println ( a [ i ] [ n - 1 ] + " ▁ " ) ; } n -- ; if ( k < m ) { for ( i = n - 1 ; i >= l ; -- i ) { count ++ ; if ( count == c ) System . out . println ( a [ m - 1 ] [ i ] + " ▁ " ) ; } m -- ; } if ( l < n ) { for ( i = m - 1 ; i >= k ; -- i ) { count ++ ; if ( count == c ) System . out . println ( a [ i ] [ l ] + " ▁ " ) ; } l ++ ; } } } public static void main ( String [ ] args ) { int a [ ] [ ] = { { 1 , 2 , 3 , 4 , 5 , 6 } , { 7 , 8 , 9 , 10 , 11 , 12 } , { 13 , 14 , 15 , 16 , 17 , 18 } } ; int k = 17 ; spiralPrint ( R , C , a , k ) ; } }


"Print K 'th element in spiral form of matrix | Java program for Kth element in spiral form of matrix ; function for Kth element ; Element is in first row ; Element is in last column ; Element is in last row ; Element is in first column ; Recursion for sub - matrix . & A [ 1 ] [ 1 ] is address to next inside sub matrix . ; Driver code"
How can the above be solved in Java?


"Print Left View of a Binary Tree | Class containing left and right child of current node and key value ; Class to print the left view ; recursive function to print left view ; Base Case ; If this is the first node of its level ; Recur for left and right subtrees ; A wrapper over leftViewUtil ( ) ; testing for example nodes"
How can the above be solved in Java?

class Node { int data ; Node left , right ; public Node ( int item ) { data = item ; left = right = null ; } } class BinaryTree { Node root ; static int max_level = 0 ; void leftViewUtil ( Node node , int level ) { if ( node == null ) return ; if ( max_level < level ) { System . out . print ( " ▁ " + node . data ) ; max_level = level ; } leftViewUtil ( node . left , level + 1 ) ; leftViewUtil ( node . right , level + 1 ) ; } void leftView ( ) { leftViewUtil ( root , 1 ) ; } public static void main ( String args [ ] ) { BinaryTree tree = new BinaryTree ( ) ; tree . root = new Node ( 12 ) ; tree . root . left = new Node ( 10 ) ; tree . root . right = new Node ( 30 ) ; tree . root . right . left = new Node ( 25 ) ; tree . root . right . right = new Node ( 40 ) ; tree . leftView ( ) ; } }


"Print Left View of a Binary Tree | Java program to print left view of Binary Tree ; Binary tree node ; function to print left view of binary tree ; number of nodes at current level ; Traverse all nodes of current level ; Print the left most element at the level ; Add left node to queue ; Add right node to queue ; Driver code ; construct binary tree as shown in above diagram"
How can the above be solved in Java?

import java . util . * ; public class PrintRightView { private static class Node { int data ; Node left , right ; public Node ( int data ) { this . data = data ; this . left = null ; this . right = null ; } } private static void printLeftView ( Node root ) { if ( root == null ) return ; Queue < Node > queue = new LinkedList < > ( ) ; queue . add ( root ) ; while ( ! queue . isEmpty ( ) ) { int n = queue . size ( ) ; for ( int i = 1 ; i <= n ; i ++ ) { Node temp = queue . poll ( ) ; if ( i == 1 ) System . out . print ( temp . data + " ▁ " ) ; if ( temp . left != null ) queue . add ( temp . left ) ; if ( temp . right != null ) queue . add ( temp . right ) ; } } } public static void main ( String [ ] args ) { Node root = new Node ( 10 ) ; root . left = new Node ( 2 ) ; root . right = new Node ( 3 ) ; root . left . left = new Node ( 7 ) ; root . left . right = new Node ( 8 ) ; root . right . right = new Node ( 15 ) ; root . right . left = new Node ( 12 ) ; root . right . right . left = new Node ( 14 ) ; printLeftView ( root ) ; } }


"Print Longest Bitonic subsequence ( Space Optimized Approach ) | Java program to implement the above approach ; Function to print the longest bitonic subsequence ; Function to generate the longest bitonic subsequence ; Store the lengths of LIS ending at every index ; Store the lengths of LDS ending at every index ; Compute LIS for all indices ; Compute LDS for all indices ; Find the index having maximum value of lis [ i ] + lds [ i ] - 1 ; Stores the count of elements in increasing order in Bitonic subsequence ; Store the increasing subsequence ; Sort the bitonic subsequence to arrange smaller elements at the beginning ; Stores the count of elements in decreasing order in Bitonic subsequence ; Print the longest bitonic sequence ; Driver Code"
How can the above be solved in Java?

import java . util . * ; class GFG { static void printRes ( Vector < Integer > res ) { Enumeration enu = res . elements ( ) ; while ( enu . hasMoreElements ( ) ) { System . out . print ( enu . nextElement ( ) + " ▁ " ) ; } } static void printLBS ( int arr [ ] , int N ) { int lis [ ] = new int [ N ] ; int lds [ ] = new int [ N ] ; for ( int i = 0 ; i < N ; i ++ ) { lis [ i ] = lds [ i ] = 1 ; } for ( int i = 0 ; i < N ; i ++ ) { for ( int j = 0 ; j < i ; j ++ ) { if ( arr [ j ] < arr [ i ] ) { if ( lis [ i ] < lis [ j ] + 1 ) lis [ i ] = lis [ j ] + 1 ; } } } for ( int i = N - 1 ; i >= 0 ; i -- ) { for ( int j = N - 1 ; j > i ; j -- ) { if ( arr [ j ] < arr [ i ] ) { if ( lds [ i ] < lds [ j ] + 1 ) lds [ i ] = lds [ j ] + 1 ; } } } int MaxVal = arr [ 0 ] , inx = 0 ; for ( int i = 0 ; i < N ; i ++ ) { if ( MaxVal < lis [ i ] + lds [ i ] - 1 ) { MaxVal = lis [ i ] + lds [ i ] - 1 ; inx = i ; } } int ct1 = lis [ inx ] ; Vector < Integer > res = new Vector < Integer > ( ) ; for ( int i = inx ; i >= 0 && ct1 > 0 ; i -- ) { if ( lis [ i ] == ct1 ) { res . add ( arr [ i ] ) ; ct1 -- ; } } Collections . reverse ( res ) ; int ct2 = lds [ inx ] - 1 ; for ( int i = inx ; i < N && ct2 > 0 ; i ++ ) { if ( lds [ i ] == ct2 ) { res . add ( arr [ i ] ) ; ct2 -- ; } } printRes ( res ) ; } public static void main ( String [ ] args ) { int arr [ ] = { 80 , 60 , 30 , 40 , 20 , 10 } ; int N = arr . length ; printLBS ( arr , N ) ; } }


"Print Longest Palindromic Subsequence | Java program to print longest palindromic subsequence ; Returns LCS X and Y ; Following steps build L [ m + 1 ] [ n + 1 ] in bottom up fashion . Note that L [ i ] [ j ] contains length of LCS of X [ 0. . i - 1 ] and Y [ 0. . j - 1 ] ; Following code is used to print LCS ; Create a String length index + 1 and fill it with \ 0 ; Start from the right - most - bottom - most corner and one by one store characters in lcs [ ] ; If current character in X [ ] and Y are same , then current character is part of LCS ; Put current character in result ; reduce values of i , j and index ; If not same , then find the larger of two and go in the direction of larger value ; Returns longest palindromic subsequence of str ; Find reverse of str ; Return LCS of str and its reverse ; convert String to character array by using toCharArray ; Driver program to test above function"
How can the above be solved in Java?

class GFG { static String lcs ( String a , String b ) { int m = a . length ( ) ; int n = b . length ( ) ; char X [ ] = a . toCharArray ( ) ; char Y [ ] = b . toCharArray ( ) ; int L [ ] [ ] = new int [ m + 1 ] [ n + 1 ] ; for ( int i = 0 ; i <= m ; i ++ ) { for ( int j = 0 ; j <= n ; j ++ ) { if ( i == 0 j == 0 ) { L [ i ] [ j ] = 0 ; } else if ( X [ i - 1 ] == Y [ j - 1 ] ) { L [ i ] [ j ] = L [ i - 1 ] [ j - 1 ] + 1 ; } else { L [ i ] [ j ] = Math . max ( L [ i - 1 ] [ j ] , L [ i ] [ j - 1 ] ) ; } } } int index = L [ m ] [ n ] ; char [ ] lcs = new char [ index + 1 ] ; int i = m , j = n ; while ( i > 0 && j > 0 ) { if ( X [ i - 1 ] == Y [ j - 1 ] ) { lcs [ index - 1 ] = X [ i - 1 ] ; i -- ; j -- ; index -- ; } else if ( L [ i - 1 ] [ j ] > L [ i ] [ j - 1 ] ) { i -- ; } else { j -- ; } } String ans = " " ; for ( int x = 0 ; x < lcs . length ; x ++ ) { ans += lcs [ x ] ; } return ans ; } static String longestPalSubseq ( String str ) { String rev = str ; rev = reverse ( rev ) ; return lcs ( str , rev ) ; } static String reverse ( String str ) { String ans = " " ; char [ ] try1 = str . toCharArray ( ) ; for ( int i = try1 . length - 1 ; i >= 0 ; i -- ) { ans += try1 [ i ] ; } return ans ; } public static void main ( String [ ] args ) { String str = " GEEKSFORGEEKS " ; System . out . println ( longestPalSubseq ( str ) ) ; } }


"Print Longest Palindromic Subsequence | Java program to print longest palindromic subsequence ; Returns LCS X and Y ; Following steps build L [ m + 1 ] [ n + 1 ] in bottom up fashion . Note that L [ i ] [ j ] contains length of LCS of X [ 0. . i - 1 ] and Y [ 0. . j - 1 ] ; Following code is used to print LCS ; Create a String length index + 1 and fill it with \ 0 ; Start from the right - most - bottom - most corner and one by one store characters in lcs [ ] ; If current character in X [ ] and Y are same , then current character is part of LCS ; Put current character in result ; reduce values of i , j and index ; } If not same , then find the larger of two and go in the direction of larger value ; Returns longest palindromic subsequence of str ; Find reverse of str ; Return LCS of str and its reverse ; convert String to character array by using toCharArray ; Driver program to test above function"
How can the above be solved in Java?

class GFG { static String lcs ( String a , String b ) { int m = a . length ( ) ; int n = b . length ( ) ; char X [ ] = a . toCharArray ( ) ; char Y [ ] = b . toCharArray ( ) ; int L [ ] [ ] = new int [ m + 1 ] [ n + 1 ] ; for ( int i = 0 ; i <= m ; i ++ ) { for ( int j = 0 ; j <= n ; j ++ ) { if ( i == 0 j == 0 ) { L [ i ] [ j ] = 0 ; } else if ( X [ i - 1 ] == Y [ j - 1 ] ) { L [ i ] [ j ] = L [ i - 1 ] [ j - 1 ] + 1 ; } else { L [ i ] [ j ] = Math . max ( L [ i - 1 ] [ j ] , L [ i ] [ j - 1 ] ) ; } } } int index = L [ m ] [ n ] ; char [ ] lcs = new char [ index + 1 ] ; int i = m , j = n ; while ( i > 0 && j > 0 ) { if ( X [ i - 1 ] == Y [ j - 1 ] ) { lcs [ index - 1 ] = X [ i - 1 ] ; i -- ; j -- ; index -- ; else if ( L [ i - 1 ] [ j ] > L [ i ] [ j - 1 ] ) { i -- ; } else { j -- ; } } String ans = " " ; for ( int x = 0 ; x < lcs . length ; x ++ ) { ans += lcs [ x ] ; } return ans ; } static String longestPalSubseq ( String str ) { String rev = str ; rev = reverse ( rev ) ; return lcs ( str , rev ) ; } static String reverse ( String str ) { String ans = " " ; char [ ] try1 = str . toCharArray ( ) ; for ( int i = try1 . length - 1 ; i >= 0 ; i -- ) { ans += try1 [ i ] ; } return ans ; } public static void main ( String [ ] args ) { String str = " GEEKSFORGEEKS " ; System . out . println ( longestPalSubseq ( str ) ) ; } }


"Print Lower Hessenberg matrix of order N | Java implementation of the approach ; Function to print the Lower Hessenberg matrix of order n ; If element is above super - diagonal then print 0 ; Print a random digit for every non - zero element ; Driver code"
How can the above be solved in Java?

 class GFG { static void LowerHessenbergMatrix ( int n ) { for ( int i = 1 ; i <= n ; i ++ ) { for ( int j = 1 ; j <= n ; j ++ ) { if ( j > i + 1 ) System . out . print ( '0' + " ▁ " ) ; else { System . out . printf ( " % .0f " , Math . random ( ) * 10 ) ; System . out . print ( " ▁ " ) ; } } System . out . println ( "
"); } } public static void main ( String [ ] args ) { int n = 4 ; LowerHessenbergMatrix ( n ) ; } }


"Print N distinct numbers following the given operations | Java implementation to print N distinct numbers ; Function to print the required array ; Check if number is a multiple of 4 ; Printing left half of the array ; Printing Right Half of the array ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { static void printArr ( int n ) { if ( n % 4 == 0 ) { for ( int i = 1 ; i <= n / 2 ; i ++ ) System . out . print ( i * 2 + " ▁ " ) ; for ( int i = 1 ; i < n / 2 ; i ++ ) System . out . print ( i * 2 - 1 + " ▁ " ) ; System . out . println ( n + n / 2 - 1 ) ; } else System . out . print ( " - 1" ) ; } public static void main ( String [ ] args ) { int n = 22 ; printArr ( n ) ; } }


"Print N numbers such that their product is a Perfect Cube | Java program to find N numbers such that their product is a perfect cube ; Function to find the N numbers such that their product is a perfect cube ; Loop to traverse each number from 1 to N ; Print the cube of i as the ith term of the output ; Driver Code ; Function Call"
How can the above be solved in Java?

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


"Print N numbers such that their sum is a Perfect Cube | Java implementation to find the N numbers such that their sum is a perfect cube ; Function to find the N numbers such that their sum is a perfect cube ; Loop to find the Ith term of the Centered Hexagonal number ; Driver Code ; Function Call"
How can the above be solved in Java?

class GFG { static void findNumbers ( int n ) { int i = 1 ; while ( i <= n ) { System . out . print ( ( 3 * i * ( i - 1 ) + 1 ) + " ▁ " ) ; i ++ ; } } public static void main ( String [ ] args ) { int n = 4 ; findNumbers ( n ) ; } }


"Print N terms of Withoff Sequence | Java program to find Wythoff array ; Function to find the n , k term of Wythoff array ; tau = ( sqrt ( 5 ) + 1 ) / 2 ; Already_stored ; T ( n , - 1 ) = n - 1. ; T ( n , 0 ) = floor ( n * tau ) . ; T ( n , k ) = T ( n , k - 1 ) + T ( n , k - 2 ) for k >= 1. ; Store ; Return the ans ; Function to find first n terms of Wythoff array by traversing in anti - diagonal ; Map to store the Wythoff array ; Anti diagonal ; Driver code ; Function call"
How can the above be solved in Java?

import java . util . * ; public class GFG { static int Wythoff ( HashMap < Integer , HashMap < Integer , Integer > > mp , int n , int k ) { double tau = ( Math . sqrt ( 5 ) + 1 ) / 2.0 , t_n_k ; if ( mp . containsKey ( n ) && mp . get ( n ) . containsKey ( k ) && mp . get ( n ) . get ( k ) != 0 ) return mp . get ( n ) . get ( k ) ; if ( k == - 1 ) { return n - 1 ; } else if ( k == 0 ) { t_n_k = Math . floor ( n * tau ) ; } else { t_n_k = Wythoff ( mp , n , k - 1 ) + Wythoff ( mp , n , k - 2 ) ; } mp . put ( n , new HashMap < Integer , Integer > ( k , ( int ) t_n_k ) ) ; return ( int ) t_n_k ; } static void Wythoff_Array ( int n ) { int i = 0 , j = 0 , count = 0 ; HashMap < Integer , HashMap < Integer , Integer > > mp = new HashMap < Integer , HashMap < Integer , Integer > > ( ) ; while ( count < n ) { System . out . print ( Wythoff ( mp , i + 1 , j + 1 ) ) ; count ++ ; if ( count != n ) System . out . print ( " , ▁ " ) ; i ++ ; j -- ; if ( j < 0 ) { j = i ; i = 0 ; } } } public static void main ( String [ ] args ) { int n = 15 ; Wythoff_Array ( n ) ; } }


"Print N | Java program to print all N - bit binary ; Function to get the binary representation of the number N ; loop for each bit ; generate numbers in the range of ( 2 ^ N ) - 1 to 2 ^ ( N - 1 ) inclusive ; longest prefix check ; if counts of 1 is greater than counts of zero ; do sub - prefixes check ; Driver code ; Function call"
How can the above be solved in Java?

import java . io . * ; import java . util . * ; class GFG { static String getBinaryRep ( int N , int num_of_bits ) { String r = " " ; num_of_bits -- ; while ( num_of_bits >= 0 ) { if ( ( N & ( 1 << num_of_bits ) ) != 0 ) r += "1" ; else r += "0" ; num_of_bits -- ; } return r ; } static ArrayList < String > NBitBinary ( int N ) { ArrayList < String > r = new ArrayList < String > ( ) ; int first = 1 << ( N - 1 ) ; int last = first * 2 ; for ( int i = last - 1 ; i >= first ; -- i ) { int zero_cnt = 0 ; int one_cnt = 0 ; int t = i ; int num_of_bits = 0 ; while ( t > 0 ) { if ( ( t & 1 ) != 0 ) one_cnt ++ ; else zero_cnt ++ ; num_of_bits ++ ; t = t >> 1 ; } if ( one_cnt >= zero_cnt ) { boolean all_prefix_match = true ; int msk = ( 1 << num_of_bits ) - 2 ; int prefix_shift = 1 ; while ( msk > 0 ) { int prefix = ( msk & i ) >> prefix_shift ; int prefix_one_cnt = 0 ; int prefix_zero_cnt = 0 ; while ( prefix > 0 ) { if ( ( prefix & 1 ) != 0 ) prefix_one_cnt ++ ; else prefix_zero_cnt ++ ; prefix = prefix >> 1 ; } if ( prefix_zero_cnt > prefix_one_cnt ) { all_prefix_match = false ; break ; } prefix_shift ++ ; msk = msk & ( msk << 1 ) ; } if ( all_prefix_match ) { r . add ( getBinaryRep ( i , num_of_bits ) ) ; } } } return r ; } public static void main ( String [ ] args ) { int n = 4 ; ArrayList < String > results = NBitBinary ( n ) ; for ( int i = 0 ; i < results . size ( ) ; ++ i ) System . out . print ( results . get ( i ) + " ▁ " ) ; System . out . println ( ) ; } }


"Print N | Java program to print all N - bit binary ; function to generate n digit numbers ; if number generated ; Append 1 at the current number and reduce the remaining places by one ; If more ones than zeros , append 0 to the current number and reduce the remaining places by one ; Driver code ; Function call"
How can the above be solved in Java?

import java . io . * ; class GFG { static void printRec ( String number , int extraOnes , int remainingPlaces ) { if ( 0 == remainingPlaces ) { System . out . print ( number + " ▁ " ) ; return ; } printRec ( number + "1" , extraOnes + 1 , remainingPlaces - 1 ) ; if ( 0 < extraOnes ) printRec ( number + "0" , extraOnes - 1 , remainingPlaces - 1 ) ; } static void printNums ( int n ) { String str = " " ; printRec ( str , 0 , n ) ; } public static void main ( String [ ] args ) { int n = 4 ; printNums ( n ) ; } }


"Print Postorder traversal from given Inorder and Preorder traversals | Java program to print Postorder traversal from given Inorder and Preorder traversals . ; Find index of next item in preorder traversal in inorder . ; traverse left tree ; traverse right tree ; print root node at the end of traversal ; Driver code"
How can the above be solved in Java?

public class PrintPost { static int preIndex = 0 ; void printPost ( int [ ] in , int [ ] pre , int inStrt , int inEnd ) { if ( inStrt > inEnd ) return ; int inIndex = search ( in , inStrt , inEnd , pre [ preIndex ++ ] ) ; printPost ( in , pre , inStrt , inIndex - 1 ) ; printPost ( in , pre , inIndex + 1 , inEnd ) ; System . out . print ( in [ inIndex ] + " ▁ " ) ; } int search ( int [ ] in , int startIn , int endIn , int data ) { int i = 0 ; for ( i = startIn ; i < endIn ; i ++ ) if ( in [ i ] == data ) return i ; return i ; } public static void main ( String ars [ ] ) { int in [ ] = { 4 , 2 , 5 , 1 , 3 , 6 } ; int pre [ ] = { 1 , 2 , 4 , 5 , 3 , 6 } ; int len = in . length ; PrintPost tree = new PrintPost ( ) ; tree . printPost ( in , pre , 0 , len - 1 ) ; } }


import java . util . * ; public class PrintPost { static int preIndex = 0 ; void printPost ( int [ ] in , int [ ] pre , int inStrt , int inEnd , HashMap < Integer , Integer > hm ) { if ( inStrt > inEnd ) return ; int inIndex = hm . get ( pre [ preIndex ++ ] ) ; printPost ( in , pre , inStrt , inIndex - 1 , hm ) ; printPost ( in , pre , inIndex + 1 , inEnd , hm ) ; System . out . print ( in [ inIndex ] + " ▁ " ) ; } void printPostMain ( int [ ] in , int [ ] pre ) { int n = pre . length ; HashMap < Integer , Integer > hm = new HashMap < Integer , Integer > ( ) ; for ( int i = 0 ; i < n ; i ++ ) hm . put ( in [ i ] , i ) ; printPost ( in , pre , 0 , n - 1 , hm ) ; } public static void main ( String ars [ ] ) { int in [ ] = { 4 , 2 , 5 , 1 , 3 , 6 } ; int pre [ ] = { 1 , 2 , 4 , 5 , 3 , 6 } ; PrintPost tree = new PrintPost ( ) ; tree . printPostMain ( in , pre ) ; } }


"Print Postorder traversal from given Inorder and Preorder traversals | Java program to print postorder traversal from preorder and inorder traversals ; A utility function to search x in arr [ ] of size n ; Prints postorder traversal from given inorder and preorder traversals ; The first element in pre [ ] is always root , search it in in [ ] to find left and right subtrees ; If left subtree is not empty , print left subtree ; If right subtree is not empty , print right subtree ; Print root ; Driver code"
How can the above be solved in Java?

import java . util . Arrays ; class GFG { static int search ( int arr [ ] , int x , int n ) { for ( int i = 0 ; i < n ; i ++ ) if ( arr [ i ] == x ) return i ; return - 1 ; } static void printPostOrder ( int in1 [ ] , int pre [ ] , int n ) { int root = search ( in1 , pre [ 0 ] , n ) ; if ( root != 0 ) printPostOrder ( in1 , Arrays . copyOfRange ( pre , 1 , n ) , root ) ; if ( root != n - 1 ) printPostOrder ( Arrays . copyOfRange ( in1 , root + 1 , n ) , Arrays . copyOfRange ( pre , 1 + root , n ) , n - root - 1 ) ; System . out . print ( pre [ 0 ] + " ▁ " ) ; } public static void main ( String args [ ] ) { int in1 [ ] = { 4 , 2 , 5 , 1 , 3 , 6 } ; int pre [ ] = { 1 , 2 , 4 , 5 , 3 , 6 } ; int n = in1 . length ; System . out . println ( " Postorder ▁ traversal ▁ " ) ; printPostOrder ( in1 , pre , n ) ; } }


"Print Upper Hessenberg matrix of order N | Java implementation of the approach ; Function to print the Lower Hessenberg matrix of order n ; If element is above super - diagonal then print 0 ; Print a random digit for every non - zero element ; Driver code"
How can the above be solved in Java?

class GFG { static void UpperHessenbergMatrix ( int n ) { for ( int i = 1 ; i <= n ; i ++ ) { for ( int j = 1 ; j <= n ; j ++ ) { if ( i > j + 1 ) { System . out . print ( 0 + " ▁ " ) ; } else { System . out . print ( ( int ) ( Math . random ( ) * 10 ) + " ▁ " ) ; } } System . out . println ( ) ; } } public static void main ( String [ ] args ) { int n = 4 ; UpperHessenbergMatrix ( n ) ; } }


"Print a case where the given sorting algorithm fails | Java program to find a case where the given algorithm fails ; Function to print a case where the given sorting algorithm fails ; only case where it fails ; Driver Code"
How can the above be solved in Java?

import java . io . * ; class GFG { static void printCase ( int n ) { if ( n <= 2 ) { System . out . print ( - 1 ) ; return ; } for ( int i = n ; i >= 1 ; i -- ) System . out . print ( i + " ▁ " ) ; } public static void main ( String [ ] args ) { int n = 3 ; printCase ( n ) ; } }


"Print a closest string that does not contain adjacent duplicates | Java program to print a string with no adjacent duplicates by doing minimum changes to original string ; Function to print simple string ; If any two adjacent characters are equal ; Initialize it to ' a ' ; Traverse the loop until it is different from the left and right letter . ; Driver function"
How can the above be solved in Java?

import java . util . * ; import java . lang . * ; public class GfG { public static String noAdjacentDup ( String s1 ) { int n = s1 . length ( ) ; char [ ] s = s1 . toCharArray ( ) ; for ( int i = 1 ; i < n ; i ++ ) { if ( s [ i ] == s [ i - 1 ] ) { s [ i ] = ' a ' ; while ( s [ i ] == s [ i - 1 ] || ( i + 1 < n && s [ i ] == s [ i + 1 ] ) ) s [ i ] ++ ; i ++ ; } } return ( new String ( s ) ) ; } public static void main ( String argc [ ] ) { String s = " geeksforgeeks " ; System . out . println ( noAdjacentDup ( s ) ) ; } }


"Print a matrix in a spiral form starting from a point | Java program to print a matrix in spiral form ; Driver code ; Function calling"
How can the above be solved in Java?

import java . io . * ; class GFG { static void printSpiral ( int [ ] [ ] mat , int r , int c ) { int i , a = 0 , b = 2 ; int low_row = ( 0 > a ) ? 0 : a ; int low_column = ( 0 > b ) ? 0 : b - 1 ; int high_row = ( ( a + 1 ) >= r ) ? r - 1 : a + 1 ; int high_column = ( ( b + 1 ) >= c ) ? c - 1 : b + 1 ; while ( ( low_row > 0 - r && low_column > 0 - c ) ) { for ( i = low_column + 1 ; i <= high_column && i < c && low_row >= 0 ; ++ i ) System . out . print ( mat [ low_row ] [ i ] + " ▁ " ) ; low_row -= 1 ; for ( i = low_row + 2 ; i <= high_row && i < r && high_column < c ; ++ i ) System . out . print ( mat [ i ] [ high_column ] + " ▁ " ) ; high_column += 1 ; for ( i = high_column - 2 ; i >= low_column && i >= 0 && high_row < r ; -- i ) System . out . print ( mat [ high_row ] [ i ] + " ▁ " ) ; high_row += 1 ; for ( i = high_row - 2 ; i > low_row && i >= 0 && low_column >= 0 ; -- i ) System . out . print ( mat [ i ] [ low_column ] + " ▁ " ) ; low_column -= 1 ; } System . out . println ( ) ; } static public void main ( String [ ] args ) { int [ ] [ ] mat = { { 1 , 2 , 3 } , { 4 , 5 , 6 } , { 7 , 8 , 9 } } ; int r = 3 , c = 3 ; printSpiral ( mat , r , c ) ; } }


"Print a number as string of ' A ' and ' B ' in lexicographic order | Java implementation of the approach ; Function to calculate number of characters in corresponding string of ' A ' and ' B ' ; Since the minimum number of characters will be 1 ; Calculating number of characters ; Since k length string can represent at most pow ( 2 , k + 1 ) - 2 that is if k = 4 , it can represent at most pow ( 2 , 4 + 1 ) - 2 = 30 so we have to calculate the length of the corresponding string ; return the length of the corresponding string ; Function to print corresponding string of ' A ' and ' B ' ; Find length of string ; Since the first number that can be represented by k length string will be ( pow ( 2 , k ) - 2 ) + 1 and it will be AAA ... A , k times , therefore , N will store that how much we have to print ; At a particular time , we have to decide whether we have to print ' A ' or ' B ' , this can be check by calculating the value of pow ( 2 , k - 1 ) ; Print new line ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { static int no_of_characters ( int M ) { int k = 1 ; while ( true ) { if ( ( int ) Math . pow ( 2 , k + 1 ) - 2 < M ) k ++ ; else break ; } return k ; } static void print_string ( int M ) { int k , num , N ; k = no_of_characters ( M ) ; N = M - ( ( int ) Math . pow ( 2 , k ) - 2 ) ; while ( k > 0 ) { num = ( int ) Math . pow ( 2 , k - 1 ) ; if ( num >= N ) System . out . print ( " A " ) ; else { System . out . print ( " B " ) ; N -= num ; } k -- ; } System . out . println ( ) ; } public static void main ( String args [ ] ) { int M ; M = 30 ; print_string ( M ) ; M = 55 ; print_string ( M ) ; M = 100 ; print_string ( M ) ; } }


"Print a number containing K digits with digital root D | Java implementation of the above approach ; Function to find a number ; If d is 0 k has to be 1 ; Print k - 1 zeroes ; Driver code"
How can the above be solved in Java?

import java . io . * ; class GFG { static void printNumberWithDR ( int k , int d ) { if ( d == 0 && k != 1 ) System . out . print ( " - 1" ) ; else { System . out . print ( d ) ; k -- ; while ( k -- > 0 ) System . out . print ( "0" ) ; } } public static void main ( String [ ] args ) { int k = 4 , d = 4 ; printNumberWithDR ( k , d ) ; } }


"Print a number strictly less than a given number such that all its digits are distinct . | Java program to find a number less than n such that all its digits are distinct ; Function to find a number less than n such that all its digits are distinct ; looping through numbers less than n ; initializing a hash array ; creating a copy of i ; initializing variables to compare lengths of digits ; counting frequency of the digits ; checking if each digit is present once ; Driver code"
How can the above be solved in Java?

class GFG { static int findNumber ( int n ) { for ( int i = n - 1 ; i >= 0 ; i -- ) { int [ ] count = new int [ 10 ] ; int x = i ; int count1 = 0 , count2 = 0 ; while ( x > 0 ) { count [ x % 10 ] ++ ; x /= 10 ; count1 ++ ; } for ( int j = 0 ; j < 10 ; j ++ ) { if ( count [ j ] == 1 ) count2 ++ ; } if ( count1 == count2 ) return i ; } return - 1 ; } public static void main ( String [ ] args ) { int n = 8490 ; System . out . println ( findNumber ( n ) ) ; } }


"Print a pair of numbers with the given Sum and Product | Java program to find any pair which has sum S and product P . ; Prints roots of quadratic equation ax * 2 + bx + c = 0 ; calculating the sq root value for b * b - 4 * a * c ; Finding the roots ; Check if the roots are valid or not ; Finding the roots ; Check if the roots are valid or not ; when d < 0 ; No such pair exists in this case ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { static void findRoots ( int b , int c ) { int a = 1 ; int d = b * b - 4 * a * c ; double sqrt_val = Math . sqrt ( Math . abs ( d ) ) ; if ( d > 0 ) { double x = - b + sqrt_val ; double y = - b - sqrt_val ; int root1 = ( int ) ( x ) / ( 2 * a ) ; int root2 = ( int ) ( y ) / ( 2 * a ) ; if ( root1 + root2 == - 1 * b && root1 * root2 == c ) System . out . print ( root1 + " , ▁ " + root2 ) ; else System . out . print ( - 1 ) ; } else if ( d == 0 ) { int root = - b / ( 2 * a ) ; if ( root + root == - 1 * b && root * root == c ) System . out . print ( root + " , ▁ " + root ) ; else System . out . print ( - 1 ) ; } else { System . out . print ( - 1 ) ; } System . out . println ( ) ; } public static void main ( String [ ] args ) { int S = 5 , P = 6 ; findRoots ( - S , P ) ; S = 5 ; P = 9 ; findRoots ( - S , P ) ; } }


"Print all 3 digit repeating numbers in a very large number | Java program to print 3 digit repeating numbers ; function to print 3 digit repeating numbers ; Hashmap to store the frequency of a 3 digit number ; first three digit number ; if key already exists increase value by 1 ; Output the three digit numbers with frequency > 1 ; Driver Code ; Input string ; Calling Function"
How can the above be solved in Java?

import java . util . * ; import java . lang . * ; public class GFG { static void printNum ( String s ) { int i = 0 , j = 0 , val = 0 ; LinkedHashMap < Integer , Integer > hm = new LinkedHashMap < > ( ) ; val = ( s . charAt ( 0 ) - '0' ) * 100 + ( s . charAt ( 1 ) - '0' ) * 10 + ( s . charAt ( 2 ) - '0' ) ; hm . put ( val , 1 ) ; for ( i = 3 ; i < s . length ( ) ; i ++ ) { val = ( val % 100 ) * 10 + s . charAt ( i ) - '0' ; if ( hm . containsKey ( val ) ) { hm . put ( val , hm . get ( val ) + 1 ) ; } else { hm . put ( val , 1 ) ; } } for ( Map . Entry < Integer , Integer > en : hm . entrySet ( ) ) { int key = en . getKey ( ) ; int value = en . getValue ( ) ; if ( value > 1 ) System . out . println ( key + " ▁ - ▁ " + value + " ▁ times " ) ; } } public static void main ( String args [ ] ) { String input = "123412345123456" ; printNum ( input ) ; } }


"Print all Coprime path of a Binary Tree | Java program for printing Co - prime paths of binary Tree ; A Tree node ; Utility function to create a new node ; Vector to store all the prime numbers ; Function to store all the prime numbers in an array ; Create a boolean array " prime [ 0 . . N ] " and initialize all the entries in it as true . A value in prime [ i ] will finally be false if i is Not a prime , else true . ; If prime [ p ] is not changed , then it is a prime ; Update all multiples of p greater than or equal to the square of it numbers which are multiples of p and are less than p ^ 2 are already marked . ; Function to check whether Path is Co - prime or not ; Iterating through the array to find the maximum element in the array ; Incrementing the variable if any of the value has a factor ; If not co - prime ; Function to print a Co - Prime path ; Function to find co - prime paths of binary tree ; Base case ; Store the value in path vector ; Recursively call for left sub tree ; Recursively call for right sub tree ; Condition to check , if leaf node ; Condition to check , if path co - prime or not ; Print co - prime path ; Remove the last element from the path vector ; Function to find Co - Prime paths In a given binary tree ; To save all prime numbers ; Function call ; Driver Code ; Create Binary Tree as shown ; Print Co - Prime Paths"
How can the above be solved in Java?

import java . util . * ; class GFG { static class Node { int key ; Node left , right ; } ; static Node newNode ( int key ) { Node temp = new Node ( ) ; temp . key = key ; temp . left = temp . right = null ; return ( temp ) ; } static int N = 1000000 ; static Vector < Integer > prime = new Vector < Integer > ( ) ; static void SieveOfEratosthenes ( ) { boolean [ ] check = new boolean [ N + 1 ] ; Arrays . fill ( check , true ) ; for ( int p = 2 ; p * p <= N ; p ++ ) { if ( check [ p ] == true ) { prime . add ( p ) ; for ( int i = p * p ; i <= N ; i += p ) check [ i ] = false ; } } } static boolean isPathCo_Prime ( Vector < Integer > path ) { int max = 0 ; for ( int x : path ) { if ( max < x ) max = x ; } for ( int i = 0 ; i * prime . get ( i ) <= max / 2 ; i ++ ) { int ct = 0 ; for ( int x : path ) { if ( x % prime . get ( i ) == 0 ) ct ++ ; } if ( ct > 1 ) { return false ; } } return true ; } static void printCo_PrimePaths ( Vector < Integer > path ) { for ( int x : path ) { System . out . print ( x + " ▁ " ) ; } System . out . println ( ) ; } static void findCo_PrimePaths ( Node root , Vector < Integer > path ) { if ( root == null ) return ; path . add ( root . key ) ; findCo_PrimePaths ( root . left , path ) ; findCo_PrimePaths ( root . right , path ) ; if ( root . left == null && root . right == null ) { if ( isPathCo_Prime ( path ) ) { printCo_PrimePaths ( path ) ; } } path . remove ( path . size ( ) - 1 ) ; } static void printCo_PrimePaths ( Node node ) { SieveOfEratosthenes ( ) ; Vector < Integer > path = new Vector < Integer > ( ) ; findCo_PrimePaths ( node , path ) ; } public static void main ( String [ ] args ) { Node root = newNode ( 10 ) ; root . left = newNode ( 48 ) ; root . right = newNode ( 3 ) ; root . right . left = newNode ( 11 ) ; root . right . right = newNode ( 37 ) ; root . right . left . left = newNode ( 7 ) ; root . right . left . right = newNode ( 29 ) ; root . right . right . left = newNode ( 42 ) ; root . right . right . right = newNode ( 19 ) ; root . right . right . right . left =...


"Print all Good numbers in given range | Java program to print good numbers in a given range [ L , R ] ; Function to check whether n is a good number and doesn ' t ▁ contain ▁ ▁ digit ▁ ' d ' ; Get last digit and initialize sum from right side ; If last digit is d , return ; Traverse remaining digits ; Current digit ; If digit is d or digit is less than or equal to sum of digits on right side ; Update sum and n ; Print Good numbers in range [ L , R ] ; Traverse all numbers in given range ; If current numbers is good , print it ; Driver program ; Print good numbers in [ L , R ]"
How can the above be solved in Java?

import java . io . * ; class Numbers { static boolean isValid ( int n , int d ) { int digit = n % 10 ; int sum = digit ; if ( digit == d ) return false ; n /= 10 ; while ( n > 0 ) { digit = n % 10 ; if ( digit == d digit <= sum ) return false ; else { sum += digit ; n /= 10 ; } } return true ; } static void printGoodNumber ( int L , int R , int d ) { for ( int i = L ; i <= R ; i ++ ) { if ( isValid ( i , d ) ) System . out . print ( i + " ▁ " ) ; } } public static void main ( String [ ] args ) { int L = 410 , R = 520 , d = 3 ; printGoodNumber ( L , R , d ) ; } }


"Print all Perfect Numbers from an array whose sum of digits is also a Perfect Number | Java Program to implement the above approach ; Function to check if a number is perfect number or not ; Stores sum of proper divisors ; If sum of digits is equal to N , then it 's a perfect number ; Otherwise , not a perfect number ; Function to find the sum of digits of a number ; Stores sum of digits ; Return sum of digits ; Function to count perfect numbers from an array whose sum of digits is also perfect ; Traverse the array ; If number is perfect ; Stores sum of digits of the number ; If that is also perfect number ; Print that number ; Driver Code ; Given array ; Size of the array ; Function call to count perfect numbers having sum of digits also perfect"
How can the above be solved in Java?

import java . io . * ; import java . util . * ; class GFG { static boolean isPerfect ( int N ) { int sumOfDivisors = 1 ; for ( int i = 2 ; i <= N / 2 ; ++ i ) { if ( N % i == 0 ) { sumOfDivisors += i ; } } if ( sumOfDivisors == N ) { return true ; } else return false ; } static int sumOfDigits ( int N ) { int sum = 0 ; while ( N != 0 ) { sum += ( N % 10 ) ; N = N / 10 ; } return sum ; } static void countPerfectNumbers ( int arr [ ] , int N ) { for ( int i = 0 ; i < N ; ++ i ) { if ( isPerfect ( arr [ i ] ) ) { int sum = sumOfDigits ( arr [ i ] ) ; if ( isPerfect ( sum ) ) { System . out . print ( arr [ i ] + " ▁ " ) ; } } } } public static void main ( String [ ] args ) { int arr [ ] = { 3 , 8 , 12 , 28 , 6 } ; int N = arr . length ; countPerfectNumbers ( arr , N ) ; } }


"Print all Possible Decodings of a given Digit Sequence | Java program for the above approach ; Function to check if all the characters are lowercase or not ; Traverse the string ; If any character is not found to be in lowerCase ; Function to print the decodings ; If all characters are not in lowercase ; Function to return the character corresponding to given integer ; Function to return the decodings ; Base case ; Recursive call ; Stores the characters of two digit numbers ; Extract first digit and first two digits ; Check if it lies in the range of alphabets ; Next recursive call ; Combine both the output in a single final output array ; Index of final output array ; Store the elements of output1 in final output array ; Store the elements of output2 in final output array ; Result the result ; Driver Code ; Function call ; Print function call"
How can the above be solved in Java?

import java . io . * ; class GFG { public static boolean nonLower ( String s ) { for ( int i = 0 ; i < s . length ( ) ; i ++ ) { if ( ! Character . isLowerCase ( s . charAt ( i ) ) ) { return true ; } } return false ; } public static void printCodes ( String output [ ] ) { for ( int i = 0 ; i < output . length ; i ++ ) { if ( nonLower ( output [ i ] ) ) continue ; System . out . println ( output [ i ] ) ; } } public static char getChar ( int n ) { return ( char ) ( n + 96 ) ; } public static String [ ] getCode ( String str ) { if ( str . length ( ) == 0 ) { String ans [ ] = { " " } ; return ans ; } String output1 [ ] = getCode ( str . substring ( 1 ) ) ; String output2 [ ] = new String [ 0 ] ; int firstDigit = ( str . charAt ( 0 ) - '0' ) ; int firstTwoDigit = 0 ; if ( str . length ( ) >= 2 ) { firstTwoDigit = ( str . charAt ( 0 ) - '0' ) * 10 + ( str . charAt ( 1 ) - '0' ) ; if ( firstTwoDigit >= 10 && firstTwoDigit <= 26 ) { output2 = getCode ( str . substring ( 2 ) ) ; } } String output [ ] = new String [ output1 . length + output2 . length ] ; int k = 0 ; for ( int i = 0 ; i < output1 . length ; i ++ ) { char ch = getChar ( firstDigit ) ; output [ i ] = ch + output1 [ i ] ; k ++ ; } for ( int i = 0 ; i < output2 . length ; i ++ ) { char ch = getChar ( firstTwoDigit ) ; output [ k ] = ch + output2 [ i ] ; k ++ ; } return output ; } public static void main ( String [ ] args ) { String input = "101" ; String output [ ] = getCode ( input ) ; printCodes ( output ) ; } }


"Print all Strong numbers less than or equal to N | Java program for the above approach ; Store the factorial of all the digits from [ 0 , 9 ] ; Function to return true if number is strong or not ; Converting N to String so that can easily access all it 's digit ; sum will store summation of factorial of all digits of a number N ; Returns true of N is strong number ; Function to print all strong number till N ; Iterating from 1 to N ; Checking if a number is strong then print it ; Driver Code ; Given Number ; Function Call"
How can the above be solved in Java?

class GFG { static int [ ] factorial = { 1 , 1 , 2 , 6 , 24 , 120 , 720 , 5040 , 40320 , 362880 } ; public static boolean isStrong ( int N ) { String num = Integer . toString ( N ) ; int sum = 0 ; for ( int i = 0 ; i < num . length ( ) ; i ++ ) { sum += factorial [ Integer . parseInt ( num . charAt ( i ) + " " ) ] ; } return sum == N ; } public static void printStrongNumbers ( int N ) { for ( int i = 1 ; i <= N ; i ++ ) { if ( isStrong ( i ) ) { System . out . print ( i + " ▁ " ) ; } } } public static void main ( String [ ] args ) throws java . lang . Exception { int N = 1000 ; printStrongNumbers ( N ) ; } }


"Print all Subsequences of String which Start with Vowel and End with Consonant . | Java Program to generate all the subsequence starting with vowel and ending with consonant . ; Set to store all the subsequences ; It computes all the possible substring that starts with vowel and end with consonent ; iterate over the entire string ; test ith character for vowel ; if the ith character is vowel iterate from end of the string and check for consonant . ; test jth character for consonant . ; once we get a consonant add it to the hashset ; drop each character of the substring and recur to generate all subsequence of the substring ; Utility method to check vowel ; Utility method to check consonant ; 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 ++ ) { if ( isVowel ( str . charAt ( i ) ) ) { for ( int j = ( str . length ( ) - 1 ) ; j >= i ; j -- ) { if ( isConsonant ( str . charAt ( ( j ) ) ) ) { String str_sub = str . substring ( i , j + 1 ) ; st . add ( str_sub ) ; for ( int k = 1 ; k < str_sub . length ( ) - 1 ; k ++ ) { StringBuffer sb = new StringBuffer ( str_sub ) ; sb . deleteCharAt ( k ) ; subsequence ( sb . toString ( ) ) ; } } } } } } static boolean isVowel ( char c ) { return ( c == ' a ' c == ' e ' c == ' i ' c == ' o ' c == ' u ' ) ; } static boolean isConsonant ( char c ) { return ! isVowel ( c ) ; } public static void main ( String [ ] args ) { String s = " xabcef " ; subsequence ( s ) ; System . out . println ( st ) ; } }


"Print all array elements appearing more than N / K times | Java program to implement the above approach ; Function to + find the upper_bound of an array element ; Stores minimum index in which K lies ; Stores maximum index in which K lies ; Calculate the upper bound of K ; Stores mid element of l and r ; If arr [ mid ] is less than or equal to K ; Right subarray ; Left subarray ; Function to print all array elements whose frequency is greater than N / K ; Sort the array arr [ ] ; Stores index of an array element ; Traverse the array ; Stores upper bound of arr [ i ] ; If frequency of arr [ i ] is greater than N / 4 ; Update i ; Driver Code ; Given array arr [ ] ; Size of array ; Function Call"
How can the above be solved in Java?

import java . util . * ; class GFG { static int upperBound ( int arr [ ] , int N , int K ) { int l = 0 ; int r = N ; while ( l < r ) { int mid = ( l + r ) / 2 ; if ( arr [ mid ] <= K ) { l = mid + 1 ; } else { r = mid ; } } return l ; } static void NDivKWithFreq ( int arr [ ] , int N , int K ) { Arrays . sort ( arr ) ; int i = 0 ; while ( i < N ) { int X = upperBound ( arr , N , arr [ i ] ) ; if ( ( X - i ) > N / 4 ) { System . out . print ( arr [ i ] + " ▁ " ) ; } i = X ; } } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 2 , 2 , 6 , 6 , 6 , 6 , 7 , 10 } ; int N = arr . length ; int K = 4 ; NDivKWithFreq ( arr , N , K ) ; } }


"Print all array elements appearing more than N / K times | Java program to implement the above approach ; Function to print all array elements whose frequency is greater than N / K ; Sort the array , arr [ ] ; Traverse the array ; Stores frequency of arr [ i ] ; Traverse array elements which is equal to arr [ i ] ; Update cnt ; Update i ; If frequency of arr [ i ] is greater than ( N / K ) ; Driver Code"
How can the above be solved in Java?

import java . util . * ; class GFG { static void NDivKWithFreq ( int arr [ ] , int N , int K ) { Arrays . sort ( arr ) ; for ( int i = 0 ; i < N ; ) { int cnt = 1 ; while ( ( i + 1 ) < N && arr [ i ] == arr [ i + 1 ] ) { cnt ++ ; i ++ ; } if ( cnt > ( N / K ) ) { System . out . print ( arr [ i ] + " ▁ " ) ; } i ++ ; } } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 2 , 2 , 6 , 6 , 6 , 6 , 7 , 10 } ; int N = arr . length ; int K = 4 ; NDivKWithFreq ( arr , N , K ) ; } }


"Print all combinations generated by characters of a numeric string which does not exceed N | Java program for the above approach ; Store the current sequence of s ; Store the all the required sequences ; Function to print all sequences of S satisfying the required condition ; Print all Strings in the set ; Function to generate all sequences of String S that are at most N ; Iterate over String s ; Push ith character to combination ; Convert the String to number ; Check if the condition is true ; Push the current String to the final set of sequences ; Recursively call function ; Backtrack to its previous state ; Driver Code ; Function Call ; Print required sequences"
How can the above be solved in Java?

import java . util . * ; class GFG { static String combination = " " ; static HashSet < String > combinations = new LinkedHashSet < String > ( ) ; static void printSequences ( HashSet < String > combinations ) { for ( String s : combinations ) { System . out . print ( s + " ▁ " ) ; } } static void generateCombinations ( String s , int n ) { for ( int i = 0 ; i < s . length ( ) ; i ++ ) { combination += ( s . charAt ( i ) ) ; long x = Integer . valueOf ( combination ) ; if ( x <= n ) { combinations . add ( combination ) ; generateCombinations ( s , n ) ; } combination = combination . substring ( 0 , combination . length ( ) - 1 ) ; } } public static void main ( String [ ] args ) { String S = "124" ; int N = 100 ; generateCombinations ( S , N ) ; printSequences ( combinations ) ; } }


"Print all distinct Coprime sets possible from 1 to N | Java implementation to print all distinct co - prime sets possible for numbers from 1 to N ; Function to print all co - prime sets ; Check if n is less than 4 then simply print all values till n ; For all the values of n > 3 ; Check if n is even then every set will contain 2 adjacent elements up - to n ; If n is odd then every set will contain 2 adjacent element except the last set which will have last three elements ; Last element for odd case ; Driver code"
How can the above be solved in Java?

 import java . util . * ; class GFG { static void coPrimeSet ( int n ) { int firstadj , secadj ; if ( n < 4 ) { System . out . print ( " ( ▁ " ) ; for ( int i = 1 ; i <= n ; i ++ ) System . out . print ( i + " , ▁ " ) ; System . out . print ( ")
"); } else { if ( n % 2 == 0 ) { for ( int i = 0 ; i < n / 2 ; i ++ ) { firstadj = 2 * i + 1 ; secadj = 2 * i + 2 ; System . out . print ( " ( " + firstadj + " , ▁ " + secadj + ")
"); } } else { for ( int i = 0 ; i < n / 2 - 1 ; i ++ ) { firstadj = 2 * i + 1 ; secadj = 2 * i + 2 ; System . out . print ( " ( " + firstadj + " , ▁ " + secadj + ")
"); } System . out . print ( " ( " + ( n - 2 ) + " , ▁ " + ( n - 1 ) + " , ▁ " + n + ")
"); } } } public static void main ( String [ ] args ) { int n = 5 ; coPrimeSet ( n ) ; } }


"Print all distinct characters of a string in order ( 3 Methods ) | Java program to print distinct characters of a string . ; Function to print distinct characters in given string str [ ] ; count [ x ] is going to store count of character ' x ' in str . If x is not present , then it is going to store 0. ; index [ x ] is going to store index of character ' x ' in str . If x is not present or x is more than once , then it is going to store a value ( for example , length of string ) that cannot be a valid index in str [ ] ; Initialize counts of all characters and indexes of distinct characters . ; index [ i ] = n ; A value more than any index in str [ ] ; Traverse the input string ; Find current character and increment its count ; If this is first occurrence , then set value in index as index of it . ; If character repeats , then remove it from index [ ] ; Since size of index is constant , below operations take constant time . ; Driver code"
How can the above be solved in Java?

import java . util . Arrays ; public class GFG { static final int MAX_CHAR = 256 ; static void printDistinct ( String str ) { int n = str . length ( ) ; int [ ] count = new int [ MAX_CHAR ] ; int [ ] index = new int [ MAX_CHAR ] ; for ( int i = 0 ; i < MAX_CHAR ; i ++ ) { count [ i ] = 0 ; } for ( int i = 0 ; i < n ; i ++ ) { char x = str . charAt ( i ) ; ++ count [ x ] ; if ( count [ x ] == 1 && x != ' ▁ ' ) index [ x ] = i ; if ( count [ x ] == 2 ) index [ x ] = n ; } Arrays . sort ( index ) ; for ( int i = 0 ; i < MAX_CHAR && index [ i ] != n ; i ++ ) System . out . print ( str . charAt ( index [ i ] ) ) ; } public static void main ( String args [ ] ) { String str = " GeeksforGeeks " ; printDistinct ( str ) ; } }


"Print all distinct characters of a string in order ( 3 Methods ) | Java program to print distinct characters of a string . ; Print duplicates present in the passed string ; Create an array of size 256 and count of every character in it ; Count array with frequency of characters ; Print characters having count more than 0 ; Driver program"
How can the above be solved in Java?

public class GFG { static final int NO_OF_CHARS = 256 ; static void printDistinct ( String str ) { int [ ] count = new int [ NO_OF_CHARS ] ; int i ; for ( i = 0 ; i < str . length ( ) ; i ++ ) if ( str . charAt ( i ) != ' ▁ ' ) count [ ( int ) str . charAt ( i ) ] ++ ; int n = i ; for ( i = 0 ; i < n ; i ++ ) if ( count [ ( int ) str . charAt ( i ) ] == 1 ) System . out . print ( str . charAt ( i ) ) ; } public static void main ( String args [ ] ) { String str = " GeeksforGeeks " ; printDistinct ( str ) ; } }


"Print all distinct strings from a given array | Java program to implement the above approach ; Function to find the distinct strings from the given array ; Stores distinct strings from the given array ; Traverse the array ; If current string not present into the set ; Insert current string into the set ; Traverse the set DistString ; Print distinct string ; Driver code ; Stores length of the array"
How can the above be solved in Java?

import java . io . * ; import java . util . * ; class GFG { static void findDisStr ( List < String > arr , int N ) { Set < String > DistString = new HashSet < String > ( ) ; for ( int i = 0 ; i < N ; i ++ ) { if ( ! DistString . contains ( arr . get ( i ) ) ) { DistString . add ( arr . get ( i ) ) ; } } for ( String string : DistString ) { System . out . print ( string + " ▁ " ) ; } } public static void main ( String [ ] args ) { List < String > arr = Arrays . asList ( new String [ ] { " Geeks " , " For " , " Geeks " , " Code " , " Coder " } ) ; int N = arr . size ( ) ; findDisStr ( arr , N ) ; } }


"Print all full nodes in a Binary Tree | A binary tree node ; Traverses given tree in Inorder fashion and prints all nodes that have both children as non - empty . ; Driver program to test above function"
How can the above be solved in Java?

class Node { int data ; Node left , right ; Node ( int data ) { left = right = null ; this . data = data ; } } ; public class FullNodes { public static void findFullNode ( Node root ) { if ( root != null ) { findFullNode ( root . left ) ; if ( root . left != null && root . right != null ) System . out . print ( root . data + " ▁ " ) ; findFullNode ( root . right ) ; } } public static void main ( String args [ ] ) { Node root = new Node ( 1 ) ; root . left = new Node ( 2 ) ; root . right = new Node ( 3 ) ; root . left . left = new Node ( 4 ) ; root . right . left = new Node ( 5 ) ; root . right . right = new Node ( 6 ) ; root . right . left . right = new Node ( 7 ) ; root . right . right . right = new Node ( 8 ) ; root . right . left . right . left = new Node ( 9 ) ; findFullNode ( root ) ; } }


"Print all increasing sequences of length k from first n natural numbers | Java program to print all increasing sequences of length ' k ' such that the elements in every sequence are from first ' n ' natural numbers . ; A utility function to print contents of arr [ 0. . k - 1 ] ; A recursive function to print all increasing sequences of first n natural numbers . Every sequence should be length k . The array arr [ ] is used to store current sequence ; If length of current increasing sequence becomes k , print it ; Decide the starting number to put at current position : If length is 0 , then there are no previous elements in arr [ ] . So start putting new numbers with 1. If length is not 0 , then start from value of previous element plus 1. ; Increase length ; Put all numbers ( which are greater than the previous element ) at new position . ; This is important . The variable ' len ' is shared among all function calls in recursion tree . Its value must be brought back before next iteration of while loop ; This function prints all increasing sequences of first n natural numbers . The length of every sequence must be k . This function mainly uses printSeqUtil ( ) ; An array to store individual sequences ; Initial length of current sequence ; Driver Code"
How can the above be solved in Java?

 class GFG { static void printArr ( int [ ] arr , int k ) { for ( int i = 0 ; i < k ; i ++ ) System . out . print ( arr [ i ] + " ▁ " ) ; System . out . print ( "
"); } static void printSeqUtil ( int n , int k , int len , int [ ] arr ) { if ( len == k ) { printArr ( arr , k ) ; return ; } int i = ( len == 0 ) ? 1 : arr [ len - 1 ] + 1 ; len ++ ; while ( i < = n ) { arr [ len - 1 ] = i ; printSeqUtil ( n , k , len , arr ) ; i ++ ; } len -- ; } static void printSeq ( int n , int k ) { int [ ] arr = new int [ k ] ; int len = 0 ; printSeqUtil ( n , k , len , arr ) ; } static public void main ( String [ ] args ) { int k = 3 , n = 7 ; printSeq ( n , k ) ; } }


"Print all integers that are sum of powers of two given numbers | Java implementation of the approach ; Function to print powerful integers ; Set is used to store distinct numbers in sorted order ; Store all the powers of y < bound in a vector to avoid calculating them again and again ; x ^ i ; If num is within limits insert it into the set ; Break out of the inner loop ; Adding any number to it will be out of bounds ; Increment i ; Print the contents of the set ; Driver code ; Print powerful integers"
How can the above be solved in Java?

import java . util . * ; import java . lang . Math ; class GfG { static void powerfulIntegers ( int x , int y , int bound ) { Set < Integer > s = new HashSet < > ( ) ; ArrayList < Integer > powersOfY = new ArrayList < > ( ) ; int i ; powersOfY . add ( 1 ) ; for ( i = y ; i < bound && y != 1 ; i = i * y ) powersOfY . add ( i ) ; i = 0 ; while ( true ) { int xPowI = ( int ) Math . pow ( ( double ) x , ( double ) i ) ; for ( int j = 0 ; j < powersOfY . size ( ) ; ++ j ) { int num = xPowI + powersOfY . get ( j ) ; if ( num <= bound ) s . add ( num ) ; else break ; } if ( xPowI >= bound x == 1 ) break ; i ++ ; } Iterator itr = s . iterator ( ) ; while ( itr . hasNext ( ) ) { System . out . print ( itr . next ( ) + " ▁ " ) ; } } public static void main ( String [ ] args ) { int x = 2 , y = 1 , bound = 10 ; powerfulIntegers ( x , y , bound ) ; } }


"Print all k | Java program to print all paths with sum k . ; utility function to print contents of a vector from index i to it 's end  ; binary tree node ; This function prints all paths that have sum k ; empty node ; add current node to the path ; check if there 's any k sum path   in the left sub-tree.  ; check if there 's any k sum path   in the right sub-tree.  ; check if there 's any k sum path that   terminates at this node   Traverse the entire path as   there can be negative elements too  ; If path sum is k , print the path ; Remove the current element from the path ; A wrapper over printKPathUtil ( ) ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { static void printVector ( Vector < Integer > v , int i ) { for ( int j = i ; j < v . size ( ) ; j ++ ) System . out . print ( v . get ( j ) + " ▁ " ) ; System . out . println ( ) ; } static class Node { int data ; Node left , right ; Node ( int x ) { data = x ; left = right = null ; } } ; static Vector < Integer > path = new Vector < Integer > ( ) ; static void printKPathUtil ( Node root , int k ) { if ( root == null ) return ; path . add ( root . data ) ; printKPathUtil ( root . left , k ) ; printKPathUtil ( root . right , k ) ; int f = 0 ; for ( int j = path . size ( ) - 1 ; j >= 0 ; j -- ) { f += path . get ( j ) ; if ( f == k ) printVector ( path , j ) ; } path . remove ( path . size ( ) - 1 ) ; } static void printKPath ( Node root , int k ) { path = new Vector < Integer > ( ) ; printKPathUtil ( root , k ) ; } public static void main ( String args [ ] ) { Node root = new Node ( 1 ) ; root . left = new Node ( 3 ) ; root . left . left = new Node ( 2 ) ; root . left . right = new Node ( 1 ) ; root . left . right . left = new Node ( 1 ) ; root . right = new Node ( - 1 ) ; root . right . left = new Node ( 4 ) ; root . right . left . left = new Node ( 1 ) ; root . right . left . right = new Node ( 2 ) ; root . right . right = new Node ( 5 ) ; root . right . right . right = new Node ( 2 ) ; int k = 5 ; printKPath ( root , k ) ; } }


"Print all leaf nodes of a Binary Tree from left to right | Java program to print leaf nodes from left to right ; A Binary Tree Node ; Function to print leaf nodes from left to right ; If node is null , return ; If node is leaf node , print its data ; If left child exists , check for leaf recursively ; If right child exists , check for leaf recursively ; Utility function to create a new tree node ; Driver code ; Let us create binary tree shown in above diagram ; Print leaf nodes of the given tree"
How can the above be solved in Java?

import java . util . * ; class GFG { static class Node { public int data ; public Node left , right ; } ; static void printLeafNodes ( Node root ) { if ( root == null ) return ; if ( root . left == null && root . right == null ) { System . out . print ( root . data + " ▁ " ) ; return ; } if ( root . left != null ) printLeafNodes ( root . left ) ; if ( root . right != null ) printLeafNodes ( root . right ) ; } static Node newNode ( int data ) { Node temp = new Node ( ) ; temp . data = data ; temp . left = null ; temp . right = null ; return temp ; } public static void main ( String [ ] args ) { Node root = newNode ( 1 ) ; root . left = newNode ( 2 ) ; root . right = newNode ( 3 ) ; root . left . left = newNode ( 4 ) ; root . right . left = newNode ( 5 ) ; root . right . right = newNode ( 8 ) ; root . right . left . left = newNode ( 6 ) ; root . right . left . right = newNode ( 7 ) ; root . right . right . left = newNode ( 9 ) ; root . right . right . right = newNode ( 10 ) ; printLeafNodes ( root ) ; } }


"Print all maximal increasing contiguous sub | Java Implementation to print all the Maximal Increasing Sub - array of array ; Function to print each of maximal contiguous increasing subarray ; Loop to iterate through the array and print the maximal contiguous increasing subarray . ; Condition to check whether the element at i , is greater than its next neighbouring element or not . ; Driver code"
How can the above be solved in Java?

 import java . util . * ; class GFG { static void printmaxSubseq ( int arr [ ] , int n ) { int i ; for ( i = 0 ; i < n ; i ++ ) { if ( i + 1 < n && arr [ i ] < arr [ i + 1 ] ) System . out . print ( arr [ i ] + " ▁ " ) ; else System . out . print ( arr [ i ] + "
"); } } public static void main ( String [ ] args ) { int arr [ ] = { 9 , 8 , 11 , 13 , 10 , 15 , 14 , 16 , 20 , 5 } ; int n = arr . length ; printmaxSubseq ( arr , n ) ; } }


"Print all multiplicative primes <= N | Java implementation of the approach ; Function to return the digit product of n ; Function to print all multiplicative primes <= n ; Create a boolean array " prime [ 0 . . n + 1 ] " . A value in prime [ i ] will finally be false if i is Not a prime , else true . ; If prime [ p ] is not changed , then it is a prime ; Update all multiples of p ; If i is prime and its digit sum is also prime i . e . i is a multiplicative prime ; Driver code"
How can the above be solved in Java?

import java . io . * ; class GFG { static int digitProduct ( int n ) { int prod = 1 ; while ( n > 0 ) { prod = prod * ( n % 10 ) ; n = n / 10 ; } return prod ; } static void printMultiplicativePrimes ( int n ) { boolean prime [ ] = new boolean [ n + 1 ] ; for ( int i = 0 ; i <= n ; i ++ ) prime [ i ] = true ; prime [ 0 ] = prime [ 1 ] = false ; for ( int p = 2 ; p * p <= n ; p ++ ) { if ( prime [ p ] ) { for ( int i = p * 2 ; i <= n ; i += p ) prime [ i ] = false ; } } for ( int i = 2 ; i <= n ; i ++ ) { if ( prime [ i ] && prime [ digitProduct ( i ) ] ) System . out . print ( i + " ▁ " ) ; } } public static void main ( String [ ] args ) { int n = 10 ; printMultiplicativePrimes ( n ) ; } }


"Print all n | Java program to print all n - digit numbers with absolute difference between sum of even and odd digits is 1 ; n -- > value of input out -- > output array index -- > index of next digit to be filled in output array evenSum , oddSum -- > sum of even and odd digits so far ; Base case ; If number becomes n - digit ; if absolute difference between sum of even and odd digits is 1 , print the number ; If current index is odd , then add it to odd sum and recurse ; else else add to even sum and recurse ; This is mainly a wrapper over findNDigitNumsUtil . It explicitly handles leading digit and calls findNDigitNumsUtil ( ) for remaining indexes ; output array to store n - digit numbers ; Initialize number index considered so far ; Initialize even and odd sums ; Explicitly handle first digit and call recursive function findNDigitNumsUtil for remaining indexes . Note that the first digit is considered to be present in even position ; Driver program"
How can the above be solved in Java?

import java . io . * ; import java . util . * ; class GFG { static void findNDigitNumsUtil ( int n , char out [ ] , int index , int evenSum , int oddSum ) { if ( index > n ) return ; if ( index == n ) { if ( Math . abs ( evenSum - oddSum ) == 1 ) { out [ index ] = ' ▁ ' ; System . out . print ( out ) ; } return ; } if ( index % 2 != 0 ) { for ( int i = 0 ; i <= 9 ; i ++ ) { out [ index ] = ( char ) ( i + '0' ) ; findNDigitNumsUtil ( n , out , index + 1 , evenSum , oddSum + i ) ; } } { for ( int i = 0 ; i <= 9 ; i ++ ) { out [ index ] = ( char ) ( i + '0' ) ; findNDigitNumsUtil ( n , out , index + 1 , evenSum + i , oddSum ) ; } } } static void findNDigitNums ( int n ) { char [ ] out = new char [ n + 1 ] ; int index = 0 ; int evenSum = 0 , oddSum = 0 ; for ( int i = 1 ; i <= 9 ; i ++ ) { out [ index ] = ( char ) ( i + '0' ) ; findNDigitNumsUtil ( n , out , index + 1 , evenSum + i , oddSum ) ; } } public static void main ( String [ ] args ) { int n = 3 ; findNDigitNums ( n ) ; } }


"Print all n | Java recursive program to print all n - digit numbers whose sum of digits equals to given sum ; n , sum -- > value of inputs out -- > output array index -- > index of next digit to be filled in output array ; Base case ; If number becomes N - digit ; if sum of its digits is equal to given sum , print it ; Traverse through every digit . Note that here we ' re ▁ considering ▁ leading ▁ 0' s as digits ; append current digit to number ; recurse for next digit with reduced sum ; This is mainly a wrapper over findNDigitNumsUtil . It explicitly handles leading digit ; output array to store N - digit numbers ; fill 1 st position by every digit from 1 to 9 and calls findNDigitNumsUtil ( ) for remaining positions ; driver program to test above function"
How can the above be solved in Java?

import java . io . * ; class GFG { static void findNDigitNumsUtil ( int n , int sum , char out [ ] , int index ) { if ( index > n sum < 0 ) return ; if ( index == n ) { if ( sum == 0 ) { out [ index ] = ' \0' ; System . out . print ( out ) ; System . out . print ( " ▁ " ) ; } return ; } for ( int i = 0 ; i <= 9 ; i ++ ) { out [ index ] = ( char ) ( i + '0' ) ; findNDigitNumsUtil ( n , sum - i , out , index + 1 ) ; } } static void findNDigitNums ( int n , int sum ) { char [ ] out = new char [ n + 1 ] ; for ( int i = 1 ; i <= 9 ; i ++ ) { out [ 0 ] = ( char ) ( i + '0' ) ; findNDigitNumsUtil ( n , sum - i , out , 1 ) ; } } public static void main ( String [ ] args ) { int n = 2 , sum = 3 ; findNDigitNums ( n , sum ) ; } }


"Print all nodes at distance k from a given node | A binary tree node ; Recursive function to print all the nodes at distance k in tree ( or subtree ) rooted with given root . ; Base Case ; If we reach a k distant node , print it ; Recur for left and right subtrees ; Prints all nodes at distance k from a given target node . The k distant nodes may be upward or downward . This function Returns distance of root from target node , it returns - 1 if target node is not present in tree rooted with root . ; Base Case 1 : If tree is empty , return - 1 ; If target is same as root . Use the downward function to print all nodes at distance k in subtree rooted with target or root ; Recur for left subtree ; Check if target node was found in left subtree ; If root is at distance k from target , print root Note that dl is Distance of root 's left child from  target ; Else go to right subtree and print all k - dl - 2 distant nodes Note that the right child is 2 edges away from left child ; Add 1 to the distance and return value for parent calls ; MIRROR OF ABOVE CODE FOR RIGHT SUBTREE Note that we reach here only when node was not found in left subtree ; If target was neither present in left nor in right subtree ; Driver program to test the above functions ; Let us construct the tree shown in above diagram"
How can the above be solved in Java?

class Node { int data ; Node left , right ; Node ( int item ) { data = item ; left = right = null ; } } class BinaryTree { Node root ; void printkdistanceNodeDown ( Node node , int k ) { if ( node == null k < 0 ) return ; if ( k == 0 ) { System . out . print ( node . data ) ; System . out . println ( " " ) ; return ; } printkdistanceNodeDown ( node . left , k - 1 ) ; printkdistanceNodeDown ( node . right , k - 1 ) ; } int printkdistanceNode ( Node node , Node target , int k ) { if ( node == null ) return - 1 ; if ( node == target ) { printkdistanceNodeDown ( node , k ) ; return 0 ; } int dl = printkdistanceNode ( node . left , target , k ) ; if ( dl != - 1 ) { if ( dl + 1 == k ) { System . out . print ( node . data ) ; System . out . println ( " " ) ; } else printkdistanceNodeDown ( node . right , k - dl - 2 ) ; return 1 + dl ; } int dr = printkdistanceNode ( node . right , target , k ) ; if ( dr != - 1 ) { if ( dr + 1 == k ) { System . out . print ( node . data ) ; System . out . println ( " " ) ; } else printkdistanceNodeDown ( node . left , k - dr - 2 ) ; return 1 + dr ; } return - 1 ; } public static void main ( String args [ ] ) { BinaryTree tree = new BinaryTree ( ) ; tree . root = new Node ( 20 ) ; tree . root . left = new Node ( 8 ) ; tree . root . right = new Node ( 22 ) ; tree . root . left . left = new Node ( 4 ) ; tree . root . left . right = new Node ( 12 ) ; tree . root . left . right . left = new Node ( 10 ) ; tree . root . left . right . right = new Node ( 14 ) ; Node target = tree . root . left . right ; tree . printkdistanceNode ( tree . root , target , 2 ) ; } }


"Print all nodes that are at distance k from a leaf node | A binary tree node ; Given a binary tree and a nuber k , print all nodes that are k distant from a leaf ; leaf node ; parent of left leaf ; parent of right leaf ; Driver program to test the above functions ; Let us construct the tree shown in above diagram"
How can the above be solved in Java?

class Node { int data ; Node left , right ; Node ( int item ) { data = item ; left = right = null ; } } class BinaryTree { Node root ; int printKDistantfromLeaf ( Node node , int k ) { if ( node == null ) return - 1 ; int lk = printKDistantfromLeaf ( node . left , k ) ; int rk = printKDistantfromLeaf ( node . right , k ) ; boolean isLeaf = lk == - 1 && lk == rk ; if ( lk == 0 || rk == 0 || ( isLeaf && k == 0 ) ) System . out . print ( " ▁ " + node . data ) ; if ( isLeaf && k > 0 ) return k - 1 ; if ( lk > 0 && lk < k ) return lk - 1 ; if ( rk > 0 && rk < k ) return rk - 1 ; return - 2 ; } 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 . right . left . right = new Node ( 8 ) ; System . out . println ( " ▁ Nodes ▁ at ▁ distance ▁ 2 ▁ are ▁ : " ) ; tree . printKDistantfromLeaf ( tree . root , 2 ) ; } }


"Print all nodes that are at distance k from a leaf node | Java program to print all nodes at a distance k from leaf A binary tree node ; This function prints all nodes that are distance k from a leaf node path [ ] -- > Store ancestors of a node visited [ ] -- > Stores true if a node is printed as output . A node may be k distance away from many leaves , we want to print it once ; Base case ; append this Node to the path array ; it 's a leaf, so print the ancestor at distance k only  if the ancestor is not already printed  ; If not leaf node , recur for left and right subtrees ; Given a binary tree and a nuber k , print all nodes that are k distant from a leaf ; Driver program to test the above functions ; Let us construct the tree shown in above diagram"
How can the above be solved in Java?

class Node { int data ; Node left , right ; Node ( int item ) { data = item ; left = right = null ; } } class BinaryTree { Node root ; void kDistantFromLeafUtil ( Node node , int path [ ] , boolean visited [ ] , int pathLen , int k ) { if ( node == null ) return ; path [ pathLen ] = node . data ; visited [ pathLen ] = false ; pathLen ++ ; if ( node . left == null && node . right == null && pathLen - k - 1 >= 0 && visited [ pathLen - k - 1 ] == false ) { System . out . print ( path [ pathLen - k - 1 ] + " ▁ " ) ; visited [ pathLen - k - 1 ] = true ; return ; } kDistantFromLeafUtil ( node . left , path , visited , pathLen , k ) ; kDistantFromLeafUtil ( node . right , path , visited , pathLen , k ) ; } void printKDistantfromLeaf ( Node node , int k ) { int path [ ] = new int [ 1000 ] ; boolean visited [ ] = new boolean [ 1000 ] ; kDistantFromLeafUtil ( node , path , visited , 0 , k ) ; } 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 . right . left . right = new Node ( 8 ) ; System . out . println ( " ▁ Nodes ▁ at ▁ distance ▁ 2 ▁ are ▁ : " ) ; tree . printKDistantfromLeaf ( tree . root , 2 ) ; } }


"Print all nodes that don 't have sibling | A binary tree node ; Function to print all non - root nodes that don 't have a sibling ; Base case ; If this is an internal node , recur for left and right subtrees ; If left child is NULL and right is not , print right child and recur for right child ; If right child is NULL and left is not , print left child and recur for left child ; Driver program to test the above functions ; Let us construct the tree shown in above diagram"
How can the above be solved in Java?

class Node { int data ; Node left , right ; Node ( int item ) { data = item ; left = right = null ; } } class BinaryTree { Node root ; void printSingles ( Node node ) { if ( node == null ) return ; if ( node . left != null && node . right != null ) { printSingles ( node . left ) ; printSingles ( node . right ) ; } else if ( node . right != null ) { System . out . print ( node . right . data + " ▁ " ) ; printSingles ( node . right ) ; } else if ( node . left != null ) { System . out . print ( node . left . data + " ▁ " ) ; printSingles ( node . left ) ; } } 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 . right = new Node ( 4 ) ; tree . root . right . left = new Node ( 5 ) ; tree . root . right . left . right = new Node ( 6 ) ; tree . printSingles ( tree . root ) ; } }


"Print all non | Java program to generate all non - increasing sequences of sum equals to x ; Utility function to print array arr [ 0. . n - 1 ] ; Recursive Function to generate all non - increasing sequences with sum x arr [ ] -- > Elements of current sequence curr_sum -- > Current Sum curr_idx -- > Current index in arr [ ] ; If current sum is equal to x , then we found a sequence ; Try placing all numbers from 1 to x - curr_sum at current index ; The placed number must also be smaller than previously placed numbers and it may be equal to the previous stored value , i . e . , arr [ curr_idx - 1 ] if there exists a previous number ; Place number at curr_idx ; Recur ; Try next number ; A wrapper over generateUtil ( ) ; Array to store sequences on by one ; Driver program"
How can the above be solved in Java?

class GFG { static void printArr ( int arr [ ] , int n ) { for ( int i = 0 ; i < n ; i ++ ) System . out . printf ( " % d ▁ " , arr [ i ] ) ; System . out . println ( " " ) ; } static void generateUtil ( int x , int arr [ ] , int curr_sum , int curr_idx ) { if ( curr_sum == x ) { printArr ( arr , curr_idx ) ; return ; } int num = 1 ; while ( num <= x - curr_sum && ( curr_idx == 0 num <= arr [ curr_idx - 1 ] ) ) { arr [ curr_idx ] = num ; generateUtil ( x , arr , curr_sum + num , curr_idx + 1 ) ; num ++ ; } } static void generate ( int x ) { int arr [ ] = new int [ x ] ; generateUtil ( x , arr , 0 , 0 ) ; } public static void main ( String [ ] args ) { int x = 5 ; generate ( x ) ; } }


"Print all numbers from a given range that are made up of consecutive digits | Java program for the above approach ; Function to find the consecutive digit numbers in the given range ; Initialize num as empty String ; Stores the resultant number ; Iterate over the range [ 1 , 9 ] ; Check if the current number is within range ; Iterate on the digits starting from i ; Checking the consecutive digits numbers starting from i and ending at j is within range or not ; Sort the numbers in the increasing order ; Driver Code ; Print the required numbers"
How can the above be solved in Java?

import java . util . * ; class GFG { static Vector < Integer > solve ( int start , int end ) { String num = " " ; Vector < Integer > ans = new Vector < > ( ) ; for ( int i = 1 ; i <= 9 ; i ++ ) { num = Integer . toString ( i ) ; int value = i ; if ( value >= start && value <= end ) { ans . add ( value ) ; } for ( int j = i + 1 ; j <= 9 ; j ++ ) { num += Integer . toString ( j ) ; value = Integer . valueOf ( num ) ; if ( value >= start && value <= end ) { ans . add ( value ) ; } } } Collections . sort ( ans ) ; ; return ans ; } public static void main ( String [ ] args ) { int L = 12 , R = 87 ; Vector < Integer > ans = solve ( L , R ) ; for ( int it : ans ) System . out . print ( it + " ▁ " ) ; } }


"Print all numbers less than N with at | Java program to print all the numbers less than N which have at most 2 unique digits ; Function to generate all possible numbers ; If the number is less than n ; If the number exceeds ; Check if it is not the same number ; Function to print all numbers ; All combination of digits ; Print all numbers ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { static Set < Integer > st = new HashSet < Integer > ( ) ; static void generateNumbers ( int n , int num , int a , int b ) { if ( num > 0 && num < n ) st . add ( num ) ; if ( num >= n ) return ; if ( num * 10 + a > num ) generateNumbers ( n , num * 10 + a , a , b ) ; generateNumbers ( n , num * 10 + b , a , b ) ; } static void printNumbers ( int n ) { for ( int i = 0 ; i <= 9 ; i ++ ) for ( int j = i + 1 ; j <= 9 ; j ++ ) generateNumbers ( n , 0 , i , j ) ; System . out . print ( " The ▁ numbers ▁ are : ▁ " ) ; System . out . print ( st ) ; st . clear ( ) ; } public static void main ( String args [ ] ) { int n = 12 ; printNumbers ( n ) ; } }


"Print all numbers that are divisors of N and are co | Java program for tha above approach ; Function to print all numbers that are divisors of N and are co - prime with the quotient of their division ; Iterate upto square root of N ; If divisors are equal and gcd is 1 , then print only one of them ; Otherwise print both ; Driver Code"
How can the above be solved in Java?

import java . util . * ; class GFG { static int gcd ( int a , int b ) { return b == 0 ? a : gcd ( b , a % b ) ; } static void printUnitaryDivisors ( int n ) { for ( int i = 1 ; i <= ( int ) Math . sqrt ( n ) ; i ++ ) { if ( n % i == 0 ) { if ( n / i == i && gcd ( i , n / i ) == 1 ) { System . out . print ( i + " ▁ " ) ; } else { if ( gcd ( i , n / i ) == 1 ) { System . out . print ( i + " ▁ " + n / i + " ▁ " ) ; } } } } } public static void main ( String [ ] args ) { int N = 12 ; printUnitaryDivisors ( N ) ; } }


"Print all numbers that can be obtained by adding A or B to N exactly M times | Java program for tha above approach ; Function to find all possible numbers that can be obtained by adding A or B to N exactly M times ; For maintaining increasing order ; Smallest number that can be achieved ; If A and B are equal , the only number that can be onbtained is N + M * A ; For finding other numbers , subtract A from number 1 time and add B to number 1 time ; Driver Code ; Given Input ; Function Call"
How can the above be solved in Java?

import java . util . * ; class GFG { static void possibleNumbers ( int N , int M , int A , int B ) { if ( A > B ) { int temp = A ; A = B ; B = temp ; } int number = N + M * A ; System . out . print ( number + " ▁ " ) ; if ( A != B ) { for ( int i = 0 ; i < M ; i ++ ) { number = number - A + B ; System . out . print ( number + " ▁ " ) ; } } } public static void main ( String [ ] args ) { int N = 5 , M = 3 , A = 4 , B = 6 ; possibleNumbers ( N , M , A , B ) ; } }


"Print all numbers that can be obtained by adding A or B to N exactly M times | Java program for tha above approach ; Function to find all possible numbers that can be obtained by adding A or B to N exactly M times ; For maintaining increasing order ; Smallest number that can be obtained ; If A and B are equal , then only one number can be obtained , i . e . N + M * A ; For finding others numbers , subtract A from number once and add B to number once ; Driver Code ; Given Input ; Function Call"
How can the above be solved in Java?


"Print all numbers that can be obtained by adding A or B to N exactly M times | Java program for the above approach ; Function to find all possible numbers that can be obtained by adding A or B to N exactly N times ; If number of steps is 0 and only possible number is N ; Add A to N and make a recursive call for M - 1 steps ; Add B to N and make a recursive call for M - 1 steps . ; Driver Code ; Given Inputs ; Stores all possible numbers ; Function call ; Print all possible numbers"
How can the above be solved in Java?

import java . util . * ; public class MyClass { static void possibleNumbers ( Set < Integer > numbers , int N , int M , int A , int B ) { if ( M == 0 ) { numbers . add ( N ) ; return ; } possibleNumbers ( numbers , N + A , M - 1 , A , B ) ; possibleNumbers ( numbers , N + B , M - 1 , A , B ) ; } public static void main ( String args [ ] ) { int N = 5 , M = 3 , A = 4 , B = 6 ; Set < Integer > numbers = new HashSet < Integer > ( ) ; possibleNumbers ( numbers , N , M , A , B ) ; Iterator < Integer > i = numbers . iterator ( ) ; while ( i . hasNext ( ) ) System . out . print ( i . next ( ) + " ▁ " ) ; } }