"Print first k digits of 1 / n where n is a positive integer | Java code to Print first k digits of 1 / n where n is a positive integer ; Function to print first k digits after dot in value of 1 / n . n is assumed to be a positive integer . ; Initialize remainder ; Run a loop k times to print k digits ; The next digit can always be obtained as doing ( 10 * rem ) / 10 ; Update remainder ; Driver program"
How can the above be solved in Java?

import java . io . * ; class GFG { static void print ( int n , int k ) { int rem = 1 ; for ( int i = 0 ; i < k ; i ++ ) { System . out . print ( ( 10 * rem ) / n ) ; rem = ( 10 * rem ) % n ; } } public static void main ( String [ ] args ) { int n = 7 , k = 3 ; print ( n , k ) ; System . out . println ( ) ; n = 21 ; k = 4 ; print ( n , k ) ; } }


"Print first n Fibonacci Numbers using direct formula | Java code to print fibonacci numbers till n using direct formula . ; Function to calculate fibonacci using recurrence relation formula ; Using direct formula ; Driver code"
How can the above be solved in Java?

class GFG { static void fibonacci ( double n ) { double fib ; for ( double i = 0 ; i < n ; i ++ ) { fib = ( Math . pow ( ( 1 + Math . sqrt ( 5 ) ) , i ) - Math . pow ( ( 1 - Math . sqrt ( 5 ) ) , i ) ) / ( Math . pow ( 2 , i ) * Math . sqrt ( 5 ) ) ; System . out . print ( ( int ) fib + " ▁ " ) ; } } public static void main ( String [ ] args ) { double n = 8 ; fibonacci ( n ) ; } }


"Print first n numbers with exactly two set bits | Java program to print first n numbers with exactly two set bits ; Function to print first n numbers with two set bits ; Initialize higher of two sets bits ; Keep reducing n for every number with two set bits ; Consider all lower set bits for current higher set bit ; Print current number ; If we have found n numbers ; Consider next lower bit for current higher bit . ; Increment higher set bit ; Driver program"
How can the above be solved in Java?

import java . io . * ; class GFG { static void printTwoSetBitNums ( int n ) { int x = 1 ; while ( n > 0 ) { int y = 0 ; while ( y < x ) { System . out . print ( ( ( 1 << x ) + ( 1 << y ) ) + " ▁ " ) ; n -- ; if ( n == 0 ) return ; y ++ ; } x ++ ; } } public static void main ( String [ ] args ) { int n = 4 ; printTwoSetBitNums ( n ) ; } }


"Print given sentence into its equivalent ASCII form | Java implementation for converting a string into it 's ASCII equivalent sentence ; Function to compute the ASCII value of each character one by one ; Driver function"
How can the above be solved in Java?

import java . util . * ; import java . lang . * ; class GeeksforGeeks { static void ASCIISentence ( String str ) { int l = str . length ( ) ; int convert ; for ( int i = 0 ; i < l ; i ++ ) { convert = str . charAt ( i ) ; System . out . print ( convert ) ; } } public static void main ( String args [ ] ) { String str = " GeeksforGeeks " ; System . out . println ( " ASCII ▁ Sentence : " ) ; ASCIISentence ( str ) ; } }


"Print indices in non | package whatever do not write package name here ; Function to print the order of array elements generating non - decreasing quotient after division by X ; Stores the quotient and the order ; Traverse the array ; Sort the vector ; Print the order ; Driver Code"
How can the above be solved in Java?

import java . io . * ; import java . util . * ; class GFG { static void printOrder ( int order [ ] , int N , int X ) { ArrayList < int [ ] > vect = new ArrayList < > ( ) ; for ( int i = 0 ; i < N ; i ++ ) { if ( order [ i ] % X == 0 ) { vect . add ( new int [ ] { order [ i ] / X , i + 1 } ) ; } else { vect . add ( new int [ ] { order [ i ] / X + 1 , i + 1 } ) ; } } Collections . sort ( vect , ( a , b ) -> a [ 0 ] - b [ 0 ] ) ; for ( int i = 0 ; i < N ; i ++ ) { System . out . print ( vect . get ( i ) [ 1 ] + " ▁ " ) ; } System . out . println ( ) ; } public static void main ( String args [ ] ) { int N = 3 , X = 3 ; int order [ ] = { 2 , 7 , 4 } ; printOrder ( order , N , X ) ; } }


"Print indices of pair of array elements required to be removed to split array into 3 equal sum subarrays | Java program for the above approach ; Function to check if array can be split into three equal sum subarrays by removing a pair ; Stores prefix sum array ; Copy array elements ; Traverse the array ; Stores sums of all three subarrays ; Sum of left subarray ; Sum of middle subarray ; Sum of right subarray ; Check if sum of subarrays are equal ; Print the possible pair ; If no such pair exists , print - 1 ; Driver Code ; Given array ; Size of the array"
How can the above be solved in Java?

 import java . util . * ; class GFG { static void findSplit ( int arr [ ] , int N ) { int [ ] sum = new int [ N ] ; for ( int i = 0 ; i < N ; i ++ ) { sum [ i ] = arr [ i ] ; } for ( int i = 1 ; i < N ; i ++ ) { sum [ i ] += sum [ i - 1 ] ; } for ( int l = 1 ; l <= N - 4 ; l ++ ) { for ( int r = l + 2 ; r <= N - 2 ; r ++ ) { int lsum = 0 , rsum = 0 , msum = 0 ; lsum = sum [ l - 1 ] ; msum = sum [ r - 1 ] - sum [ l ] ; rsum = sum [ N - 1 ] - sum [ r ] ; if ( lsum == rsum && rsum == msum ) { System . out . print ( l + " ▁ " + r + "
"); return ; } } } System . out . print ( - 1 + "
"); } public static void main ( String [ ] args ) { int arr [ ] = { 2 , 5 , 12 , 7 , 19 , 4 , 3 } ; int N = arr . length ; findSplit ( arr , N ) ; } }


"Print indices of pair of array elements required to be removed to split array into 3 equal sum subarrays | Java program for the above approach ; Function to check if array can be split into three equal sum subarrays by removing a pair ; Two pointers l and r ; Stores prefix sum array ; Traverse the array ; Two pointer approach ; Sum of left subarray ; Sum of middle subarray ; Sum of right subarray ; Print split indices if sum is equal ; Move left pointer if lsum < rsum ; Move right pointer if rsum > lsum ; Move both pointers if lsum = rsum but they are not equal to msum ; If no possible pair exists , print - 1 ; Driver Code ; Given array ; Size of the array"
How can the above be solved in Java?

public class GFG { static void findSplit ( int [ ] arr , int N ) { int l = 1 , r = N - 2 ; int lsum , msum , rsum ; int sum [ ] = new int [ N ] ; sum [ 0 ] = arr [ 0 ] ; for ( int i = 1 ; i < N ; i ++ ) { sum [ i ] = sum [ i - 1 ] + arr [ i ] ; } while ( l < r ) { lsum = sum [ l - 1 ] ; msum = sum [ r - 1 ] - sum [ l ] ; rsum = sum [ N - 1 ] - sum [ r ] ; if ( lsum == msum && msum == rsum ) { System . out . println ( l + " ▁ " + r ) ; return ; } if ( lsum < rsum ) l ++ ; else if ( lsum > rsum ) r -- ; else { l ++ ; r -- ; } } System . out . println ( - 1 ) ; } public static void main ( String [ ] args ) { int [ ] arr = { 2 , 5 , 12 , 7 , 19 , 4 , 3 } ; int N = arr . length ; findSplit ( arr , N ) ; } }


"Print indices of pair of array elements required to be removed to split array into 3 equal sum subarrays | Java program for the above approach ; Function to check if array can be split into three equal sum subarrays by removing two elements ; Stores sum of all three subarrays ; Sum of left subarray ; Sum of middle subarray ; Sum of right subarray ; Check if sum of subarrays are equal ; Print the possible pair ; If no pair exists , print - 1 ; Driver Code ; Given array ; Size of the array"
How can the above be solved in Java?

import java . util . * ; class GFG { static void findSplit ( int arr [ ] , int N ) { for ( int l = 1 ; l <= N - 4 ; l ++ ) { for ( int r = l + 2 ; r <= N - 2 ; r ++ ) { int lsum = 0 , rsum = 0 , msum = 0 ; for ( int i = 0 ; i <= l - 1 ; i ++ ) { lsum += arr [ i ] ; } for ( int i = l + 1 ; i <= r - 1 ; i ++ ) { msum += arr [ i ] ; } for ( int i = r + 1 ; i < N ; i ++ ) { rsum += arr [ i ] ; } if ( lsum == rsum && rsum == msum ) { System . out . println ( l + " ▁ " + r ) ; return ; } } } System . out . print ( - 1 ) ; } public static void main ( String [ ] args ) { int arr [ ] = { 2 , 5 , 12 , 7 , 19 , 4 , 3 } ; int N = arr . length ; findSplit ( arr , N ) ; } }


"Print k different sorted permutations of a given array | Java implementation of the approach ; Utility function to print the original indices of the elements of the array ; Used for sorting in ascending order ; Function to print the required permutations ; To keep track of original indices ; Sort the array ; Count the number of swaps that can be made ; Cannot generate 3 permutations ; Print the first permutation ; Find an index to swap and create second permutation ; Print the last permutation ; Driver code ; Function call"
How can the above be solved in Java?

import java . util . * ; class GFG { static int next_pos = 1 ; static class pair { int first , second ; pair ( ) { first = 0 ; second = 0 ; } } static void printIndices ( int n , pair a [ ] ) { for ( int i = 0 ; i < n ; i ++ ) System . out . print ( a [ i ] . second + " ▁ " ) ; System . out . println ( ) ; } static class sort implements Comparator < pair > { public int compare ( pair a , pair b ) { return a . first < b . first ? - 1 : 1 ; } } static void printPermutations ( int n , int a [ ] , int k ) { pair arr [ ] = new pair [ n ] ; for ( int i = 0 ; i < n ; i ++ ) { arr [ i ] = new pair ( ) ; arr [ i ] . first = a [ i ] ; arr [ i ] . second = i ; } Arrays . sort ( arr , new sort ( ) ) ; int count = 1 ; for ( int i = 1 ; i < n ; i ++ ) if ( arr [ i ] . first == arr [ i - 1 ] . first ) count ++ ; if ( count < k ) { System . out . print ( " - 1" ) ; return ; } for ( int i = 0 ; i < k - 1 ; i ++ ) { printIndices ( n , arr ) ; for ( int j = next_pos ; j < n ; j ++ ) { if ( arr [ j ] . first == arr [ j - 1 ] . first ) { pair t = arr [ j ] ; arr [ j ] = arr [ j - 1 ] ; arr [ j - 1 ] = t ; next_pos = j + 1 ; break ; } } } printIndices ( n , arr ) ; } public static void main ( String arsg [ ] ) { int a [ ] = { 1 , 3 , 3 , 1 } ; int n = a . length ; int k = 3 ; printPermutations ( n , a , k ) ; } }


"Print k numbers where all pairs are divisible by m | Java program to find a list of k elements from an array such that difference between all of them is divisible by m . ; function to generate k numbers whose difference is divisible by m ; Using an adjacency list like representation to store numbers that lead to same remainder . ; stores the modulus when divided by m ; If we found k elements which have same remainder . ; If we could not find k elements ; Driver Code"
How can the above be solved in Java?

import java . util . * ; class GFG { static void print_result ( int a [ ] , int n , int k , int m ) { Vector < Vector < Integer > > v = new Vector < Vector < Integer > > ( m ) ; for ( int i = 0 ; i < m ; i ++ ) v . add ( new Vector < Integer > ( ) ) ; for ( int i = 0 ; i < n ; i ++ ) { int rem = a [ i ] % m ; v . get ( rem ) . add ( a [ i ] ) ; if ( v . get ( rem ) . size ( ) == k ) { for ( int j = 0 ; j < k ; j ++ ) System . out . print ( v . get ( rem ) . get ( j ) + " ▁ " ) ; return ; } } System . out . print ( " - 1" ) ; } public static void main ( String [ ] args ) { int a [ ] = { 1 , 8 , 4 } ; int n = a . length ; print_result ( a , n , 2 , 3 ) ; } }


"Print last character of each word in a string | Java implementation of the approach ; Function to print the last character of each word in the given string ; Now , last word is also followed by a space ; If current character is a space ; Then previous character must be the last character of some word ; Driver code"
How can the above be solved in Java?

class GFG { static void printLastChar ( String str ) { str = str + " ▁ " ; for ( int i = 1 ; i < str . length ( ) ; i ++ ) { if ( str . charAt ( i ) == ' ▁ ' ) System . out . print ( str . charAt ( i - 1 ) + " ▁ " ) ; } } public static void main ( String s [ ] ) { String str = " Geeks ▁ for ▁ Geeks " ; printLastChar ( str ) ; } }


"Print last k digits of a ^ b ( a raised to power b ) | Java code to find last k digits of a ^ b ; Iterative Function to calculate ( x ^ y ) % p in O ( log y ) ; Initialize result ; 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 ; Method to print last k digits of a ^ b ; Generating 10 ^ k ; Calling modular exponentiation ; Printing leftmost zeros . Since ( a ^ b ) % k can have digits less then k . In that case we need to print zeros ; If temp is not zero then print temp If temp is zero then already printed ; Driver Method"
How can the above be solved in Java?

public class GFG { static int power ( long x , long y , long p ) { long res = 1 ; while ( y > 0 ) { if ( ( y & 1 ) != 0 ) res = ( res * x ) % p ; x = ( x * x ) % p ; } return ( int ) res ; } static void printLastKDigits ( int a , int b , int k ) { System . out . print ( " Last ▁ " + k + " ▁ digits ▁ of ▁ " + a + " ^ " + b + " ▁ = ▁ " ) ; int temp = 1 ; for ( int i = 1 ; i <= k ; i ++ ) temp *= 10 ; temp = power ( a , b , temp ) ; for ( int i = 0 ; i < k - Integer . toString ( temp ) . length ( ) ; i ++ ) System . out . print ( 0 ) ; if ( temp != 0 ) System . out . print ( temp ) ; } public static void main ( String [ ] args ) { int a = 11 ; int b = 3 ; int k = 2 ; printLastKDigits ( a , b , k ) ; } }


"Print left rotation of array in O ( n ) time and O ( 1 ) space | JAVA implementation of left rotation of an array K number of times ; Function to leftRotate array multiple times ; To get the starting point of rotated array ; Prints the rotated array from start position ; Driver code ; Function Call ; Function Call ; Function Call"
How can the above be solved in Java?

import java . util . * ; import java . lang . * ; import java . io . * ; class arr_rot { static void leftRotate ( int arr [ ] , int n , int k ) { int mod = k % n ; for ( int i = 0 ; i < n ; ++ i ) System . out . print ( arr [ ( i + mod ) % n ] + " ▁ " ) ; System . out . println ( ) ; } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 3 , 5 , 7 , 9 } ; int n = arr . length ; int k = 2 ; leftRotate ( arr , n , k ) ; k = 3 ; leftRotate ( arr , n , k ) ; k = 4 ; leftRotate ( arr , n , k ) ; } }


"Print left rotation of array in O ( n ) time and O ( 1 ) space | Java implementation for print left rotation of any array K times ; Function for the k times left rotation ; In Collection class rotate function takes two parameters - the name of array and the position by which it should be rotated The below function will be rotating the array left in linear time Collections . rotate ( ) rotate the array from right hence n - k ; Print the rotated array from start position ; Driver code ; Function call"
How can the above be solved in Java?

import java . io . * ; import java . util . * ; class GFG { static void leftRotate ( Integer arr [ ] , int k , int n ) { Collections . rotate ( Arrays . asList ( arr ) , n - k ) ; for ( int i = 0 ; i < n ; i ++ ) System . out . print ( arr [ i ] + " ▁ " ) ; } public static void main ( String [ ] args ) { Integer arr [ ] = { 1 , 3 , 5 , 7 , 9 } ; int n = arr . length ; int k = 2 ; leftRotate ( arr , k , n ) ; } }


"Print leftmost and rightmost nodes of a Binary Tree | Java program to print corner node at each level in a binary tree ; A binary tree node has key , pointer to left child and a pointer to right child ; Function to print corner node at each level ; star node is for keeping track of levels ; pushing root node and star node ; Do level order traversal of Binary Tree ; n is the no of nodes in current Level ; If it is leftmost corner value or rightmost corner value then print it ; push the left and right children of the temp node ; Driver program to test above functions"
How can the above be solved in Java?

import java . util . * ; class Node { int key ; Node left , right ; public Node ( int key ) { this . key = key ; left = right = null ; } } class BinaryTree { Node root ; void printCorner ( Node root ) { Queue < Node > q = new LinkedList < Node > ( ) ; q . add ( root ) ; while ( ! q . isEmpty ( ) ) { int n = q . size ( ) ; for ( int i = 0 ; i < n ; i ++ ) { Node temp = q . peek ( ) ; q . poll ( ) ; if ( i == 0 i == n - 1 ) System . out . print ( temp . key + " ▁ " ) ; if ( temp . left != null ) q . add ( temp . left ) ; if ( temp . right != null ) q . add ( temp . right ) ; } } } public static void main ( String [ ] args ) { BinaryTree tree = new BinaryTree ( ) ; tree . root = new Node ( 15 ) ; tree . root . left = new Node ( 10 ) ; tree . root . right = new Node ( 20 ) ; tree . root . left . left = new Node ( 8 ) ; tree . root . left . right = new Node ( 12 ) ; tree . root . right . left = new Node ( 16 ) ; tree . root . right . right = new Node ( 25 ) ; tree . printCorner ( tree . root ) ; } }


"Print list items containing all characters of a given word | Java program to print all strings that contain all characters of a word ; prints list items having all characters of word ; * Since calloc is used , map [ ] is initialized as 0 ; Set the values in map ; Get the length ( ) of given word ; * Check each item of list if has all characters of word ; * unset the bit so that strings like sss not printed ; Set the values in map for next item ; Driver code"
How can the above be solved in Java?

class GFG { static final int NO_OF_CHARS = 256 ; static void print ( String [ ] list , String word , int list_size ) { int [ ] map = new int [ NO_OF_CHARS ] ; int i , j , count , word_size ; for ( i = 0 ; i < word . length ( ) ; i ++ ) map [ word . charAt ( i ) ] = 1 ; word_size = word . length ( ) ; for ( i = 0 ; i < list_size ; i ++ ) { for ( j = 0 , count = 0 ; j < list [ i ] . length ( ) ; j ++ ) { if ( map [ list [ i ] . charAt ( j ) ] > 0 ) { count ++ ; map [ list [ i ] . charAt ( j ) ] = 0 ; } } if ( count == word_size ) System . out . println ( list [ i ] ) ; for ( j = 0 ; j < word . length ( ) ; j ++ ) map [ word . charAt ( j ) ] = 1 ; } } public static void main ( String [ ] args ) { String str = " sun " ; String [ ] list = { " geeksforgeeks " , " unsorted " , " sunday " , " just " , " sss " } ; print ( list , str , 5 ) ; } }


"Print longest palindrome word in a sentence | Java program to print longest palindrome word in a sentence and its length ; Function to check if a word is palindrome ; making the check case case insensitive ; loop to check palindrome ; Function to find longest palindrome word ; to check last word for palindrome ; to store each word ; extracting each word ; Driver code"
How can the above be solved in Java?

public class GFG { static boolean checkPalin ( String word ) { int n = word . length ( ) ; word = word . toLowerCase ( ) ; for ( int i = 0 ; i < n ; i ++ , n -- ) if ( word . charAt ( i ) != word . charAt ( n - 1 ) ) return false ; return true ; } static String longestPalin ( String str ) { str = str + " ▁ " ; String longestword = " " , word = " " ; int length , length1 = 0 ; for ( int i = 0 ; i < str . length ( ) ; i ++ ) { char ch = str . charAt ( i ) ; if ( ch != ' ▁ ' ) word = word + ch ; else { length = word . length ( ) ; if ( checkPalin ( word ) && length > length1 ) { length1 = length ; longestword = word ; } word = " " ; } } return longestword ; } public static void main ( String args [ ] ) { String s = new String ( " My ▁ name ▁ is ▁ ava ▁ " + " and ▁ i ▁ love ▁ Geeksforgeeks " ) ; if ( longestPalin ( s ) == " " ) System . out . println ( " No ▁ Palindrome " + " ▁ Word " ) ; else System . out . println ( longestPalin ( s ) ) ; } }


"Print matrix after applying increment operations in M ranges | Java implementation of the approach ; Function to update and print the matrix after performing queries ; Add 1 to the first element of the sub - matrix ; If there is an element after the last element of the sub - matrix then decrement it by 1 ; Calculate the running sum ; Print the updated element ; Next line ; Driver code ; Size of the matrix ; Queries"
How can the above be solved in Java?

public class GFG { static void updateMatrix ( int n , int q [ ] [ ] , int mat [ ] [ ] ) { int i , j ; for ( i = 0 ; i < q . length ; i ++ ) { int X1 = q [ i ] [ 0 ] ; int Y1 = q [ i ] [ 1 ] ; int X2 = q [ i ] [ 2 ] ; int Y2 = q [ i ] [ 3 ] ; mat [ X1 ] [ Y1 ] ++ ; if ( Y2 + 1 < n ) mat [ X2 ] [ Y2 + 1 ] -- ; else if ( X2 + 1 < n ) mat [ X2 + 1 ] [ 0 ] -- ; } int sum = 0 ; for ( i = 0 ; i < n ; i ++ ) { for ( j = 0 ; j < n ; j ++ ) { sum += mat [ i ] [ j ] ; System . out . print ( sum + " ▁ " ) ; } System . out . println ( ) ; } } public static void main ( String [ ] args ) { int n = 5 ; int mat [ ] [ ] = new int [ n ] [ n ] ; int q [ ] [ ] = { { 0 , 0 , 1 , 2 } , { 1 , 2 , 3 , 4 } , { 1 , 4 , 3 , 4 } } ; updateMatrix ( n , q , mat ) ; } }


"Print matrix elements from top | Java program for the above approach ; Function to traverse the matrix diagonally upwards ; Store the number of rows ; Initialize queue ; Push the index of first element i . e . , ( 0 , 0 ) ; Get the front element ; Pop the element at the front ; Insert the element below if the current element is in first column ; Insert the right neighbour if it exists ; Driver Code ; Given vector of vectors arr ; Function call"
How can the above be solved in Java?

import java . util . * ; class GFG { static class pair { int first , second ; public pair ( int first , int second ) { this . first = first ; this . second = second ; } } static void printDiagonalTraversal ( int [ ] [ ] nums ) { int m = nums . length ; Queue < pair > q = new LinkedList < > ( ) ; q . add ( new pair ( 0 , 0 ) ) ; while ( ! q . isEmpty ( ) ) { pair p = q . peek ( ) ; q . remove ( ) ; System . out . print ( nums [ p . first ] [ p . second ] + " ▁ " ) ; if ( p . second == 0 && p . first + 1 < m ) { q . add ( new pair ( p . first + 1 , p . second ) ) ; } if ( p . second + 1 < nums [ p . first ] . length ) q . add ( new pair ( p . first , p . second + 1 ) ) ; } } public static void main ( String [ ] args ) { int [ ] [ ] arr = { { 1 , 2 , 3 } , { 4 , 5 , 6 } , { 7 , 8 , 9 } } ; printDiagonalTraversal ( arr ) ; } }


"Print matrix elements from top | Java program for the above approach ; Function to traverse the matrix diagonally upwards ; Stores the maximum size of vector from all row of matrix nums [ ] [ ] ; Store elements in desired order ; Store every element on the basis of sum of index ( i + j ) ; Print the stored result ; Print in reverse order ; Driver Code ; Given vector of vectors arr ; Function Call"
How can the above be solved in Java?

import java . util . * ; class GFG { static void printDiagonalTraversal ( int [ ] [ ] nums ) { int max_size = nums [ 0 ] . length ; ArrayList < ArrayList < Integer > > v = new ArrayList < ArrayList < Integer > > ( ) ; for ( int i = 0 ; i < 2 * max_size - 1 ; i ++ ) { v . add ( new ArrayList < Integer > ( ) ) ; } for ( int i = 0 ; i < nums [ 0 ] . length ; i ++ ) { for ( int j = 0 ; j < nums [ 0 ] . length ; j ++ ) { v . get ( i + j ) . add ( nums [ i ] [ j ] ) ; } } for ( int i = 0 ; i < v . size ( ) ; i ++ ) { for ( int j = v . get ( i ) . size ( ) - 1 ; j >= 0 ; j -- ) { System . out . print ( v . get ( i ) . get ( j ) + " ▁ " ) ; } } } public static void main ( String [ ] args ) { int [ ] [ ] arr = { { 1 , 2 , 3 } , { 4 , 5 , 6 } , { 7 , 8 , 9 } } ; printDiagonalTraversal ( arr ) ; } }


"Print matrix elements using DFS traversal | Java program for the above approach ; Direction vectors ; Function to check if curruent position is valid or not ; Check if the cell is out of bounds ; Check if the cell is visited ; Function to print the matrix elements ; Stores if a position in the matrix been visited or not ; Initialize stack to implement DFS ; Push the first position of grid [ ] [ ] in the stack ; Mark the cell ( 0 , 0 ) visited ; Stores top element of stack ; Delete the top ( ) element of stack ; Print element at the cell ; Traverse in all four adjacent sides of current positions ; Check if x and y is valid position and then push the position of current cell in the stack ; Push the current cell ; Mark current cell visited ; Driver Code ; Given matrix ; Row of the matrix ; Column of the matrix"
How can the above be solved in Java?

import java . util . * ; public class Main { public static class Pair { int Item1 , Item2 ; public Pair ( int Item1 , int Item2 ) { this . Item1 = Item1 ; this . Item2 = Item2 ; } } static int [ ] dRow = { - 1 , 0 , 1 , 0 } ; static int [ ] dCol = { 0 , 1 , 0 , - 1 } ; static Vector < Vector < Boolean > > vis ; static boolean isValid ( int row , int col , int COL , int ROW ) { if ( row < 0 col < 0 col > COL - 1 row > ROW - 1 ) return false ; if ( vis . get ( row ) . get ( col ) == true ) return false ; return true ; } static void DFS_iterative ( int [ ] [ ] grid , int M , int N ) { vis = new Vector < Vector < Boolean > > ( ) ; for ( int i = 0 ; i < M + 5 ; i ++ ) { vis . add ( new Vector < Boolean > ( ) ) ; for ( int j = 0 ; j < N + 5 ; j ++ ) { vis . get ( i ) . add ( false ) ; } } Vector < Pair > st = new Vector < Pair > ( ) ; st . add ( new Pair ( 0 , 0 ) ) ; vis . get ( 0 ) . set ( 0 , true ) ; while ( st . size ( ) > 0 ) { Pair p = st . get ( st . size ( ) - 1 ) ; st . remove ( st . size ( ) - 1 ) ; int row = p . Item1 ; int col = p . Item2 ; System . out . print ( grid [ row ] [ col ] + " ▁ " ) ; for ( int i = 0 ; i < 4 ; i ++ ) { int x = row + dRow [ i ] ; int y = col + dCol [ i ] ; if ( isValid ( x , y , M , N ) ) { st . add ( new Pair ( x , y ) ) ; vis . get ( x ) . set ( y , true ) ; } } } } public static void main ( String [ ] args ) { int [ ] [ ] grid = { { 1 , 2 , 3 , 4 } , { 5 , 6 , 7 , 8 } , { 9 , 10 , 11 , 12 } , { 13 , 14 , 15 , 16 } } ; int M = 4 ; int N = 4 ; DFS_iterative ( grid , M , N ) ; } }


"Print matrix elements using DFS traversal | Java program to implement the above approach ; Direction vectors ; Function to check if current position is valid or not ; Check if the cell is out of bounds ; Check if the cell is visited or not ; Utility function to print matrix elements using DFS Traversal ; Mark the current cell visited ; Print the element at the cell ; Traverse all four adjacent cells of the current element ; Check if x and y is valid index or not ; Function to print the matrix elements ; Initialize a visiting matrix ; Function call to print matrix elements by DFS traversal ; Driver Code ; Given matrix ; Row of the matrix ; Column of the matrix"
How can the above be solved in Java?

import java . util . * ; class GFG { static int dRow [ ] = { - 1 , 0 , 1 , 0 } ; static int dCol [ ] = { 0 , 1 , 0 , - 1 } ; static boolean isValid ( boolean [ ] [ ] vis , int row , int col , int COL , int ROW ) { if ( row < 0 col < 0 col > COL - 1 row > ROW - 1 ) return false ; if ( vis [ row ] [ col ] == true ) return false ; return true ; } static void DFSUtil ( int row , int col , int [ ] [ ] grid , boolean [ ] [ ] vis , int M , int N ) { vis [ row ] [ col ] = true ; System . out . print ( grid [ row ] [ col ] + " ▁ " ) ; for ( int i = 0 ; i < 4 ; i ++ ) { int x = row + dRow [ i ] ; int y = col + dCol [ i ] ; if ( isValid ( vis , x , y , M , N ) ) DFSUtil ( x , y , grid , vis , M , N ) ; } } static void DFS ( int row , int col , int [ ] [ ] grid , int M , int N ) { boolean [ ] [ ] vis = new boolean [ M + 1 ] [ N + 1 ] ; for ( int i = 0 ; i < M + 1 ; i ++ ) { for ( int j = 0 ; j < N + 1 ; j ++ ) { vis [ i ] [ j ] = false ; } } DFSUtil ( 0 , 0 , grid , vis , M , N ) ; } public static void main ( String args [ ] ) { int [ ] [ ] grid = { { 1 , 2 , 3 , 4 } , { 5 , 6 , 7 , 8 } , { 9 , 10 , 11 , 12 } , { 13 , 14 , 15 , 16 } } ; int M = grid . length ; int N = grid [ 0 ] . length ; DFS ( 0 , 0 , grid , M , N ) ; } }


"Print matrix in antispiral form | Java Code for Print matrix in antispiral form ; k - starting row index m - ending row index l - starting column index n - ending column index i - iterator ; Print the first row from the remaining rows ; Print the last column from the remaining columns ; Print the last row from the remaining rows ; Print the first column from the remaining columns ; Driver program to test above function"
How can the above be solved in Java?

import java . util . * ; class GFG { public static void antiSpiralTraversal ( int m , int n , int a [ ] [ ] ) { int i , k = 0 , l = 0 ; Stack < Integer > stk = new Stack < Integer > ( ) ; while ( k <= m && l <= n ) { for ( i = l ; i <= n ; ++ i ) stk . push ( a [ k ] [ i ] ) ; k ++ ; for ( i = k ; i <= m ; ++ i ) stk . push ( a [ i ] [ n ] ) ; n -- ; if ( k <= m ) { for ( i = n ; i >= l ; -- i ) stk . push ( a [ m ] [ i ] ) ; m -- ; } if ( l <= n ) { for ( i = m ; i >= k ; -- i ) stk . push ( a [ i ] [ l ] ) ; l ++ ; } } while ( ! stk . empty ( ) ) { System . out . print ( stk . peek ( ) + " ▁ " ) ; stk . pop ( ) ; } } public static void main ( String [ ] args ) { int mat [ ] [ ] = { { 1 , 2 , 3 , 4 , 5 } , { 6 , 7 , 8 , 9 , 10 } , { 11 , 12 , 13 , 14 , 15 } , { 16 , 17 , 18 , 19 , 20 } } ; antiSpiralTraversal ( mat . length - 1 , mat [ 0 ] . length - 1 , mat ) ; } }


"Print matrix in diagonal pattern | Java program to print matrix in diagonal order ; Driver code ; Initialize matrix ; n - size mode - switch to derive up / down traversal it - iterator count - increases until it reaches n and then decreases ; 2 n will be the number of iterations"
How can the above be solved in Java?

public class MatrixDiag { public static void main ( String [ ] args ) { int [ ] [ ] mat = { { 1 , 2 , 3 , 4 } , { 5 , 6 , 7 , 8 } , { 9 , 10 , 11 , 12 } , { 13 , 14 , 15 , 16 } } ; int n = 4 , mode = 0 , it = 0 , lower = 0 ; for ( int t = 0 ; t < ( 2 * n - 1 ) ; t ++ ) { int t1 = t ; if ( t1 >= n ) { mode ++ ; t1 = n - 1 ; it -- ; lower ++ ; } else { lower = 0 ; it ++ ; } for ( int i = t1 ; i >= lower ; i -- ) { if ( ( t1 + mode ) % 2 == 0 ) { System . out . println ( mat [ i ] [ t1 + lower - i ] ) ; } else { System . out . println ( mat [ t1 + lower - i ] [ i ] ) ; } } } } }


"Print matrix in diagonal pattern | Java program to print matrix in diagonal order ; Initialize indexes of element to be printed next ; Direction is initially from down to up ; Traverse the matrix till all elements get traversed ; If isUp = true then traverse from downward to upward ; Set i and j according to direction ; If isUp = 0 then traverse up to down ; Set i and j according to direction ; Revert the isUp to change the direction ; Driver code"
How can the above be solved in Java?

class GFG { static final int MAX = 100 ; static void printMatrixDiagonal ( int mat [ ] [ ] , int n ) { int i = 0 , j = 0 ; boolean isUp = true ; for ( int k = 0 ; k < n * n ; ) { if ( isUp ) { for ( ; i >= 0 && j < n ; j ++ , i -- ) { System . out . print ( mat [ i ] [ j ] + " ▁ " ) ; k ++ ; } if ( i < 0 && j <= n - 1 ) i = 0 ; if ( j == n ) { i = i + 2 ; j -- ; } } else { for ( ; j >= 0 && i < n ; i ++ , j -- ) { System . out . print ( mat [ i ] [ j ] + " ▁ " ) ; k ++ ; } if ( j < 0 && i <= n - 1 ) j = 0 ; if ( i == n ) { j = j + 2 ; i -- ; } } isUp = ! isUp ; } } public static void main ( String [ ] args ) { int mat [ ] [ ] = { { 1 , 2 , 3 } , { 4 , 5 , 6 } , { 7 , 8 , 9 } } ; int n = 3 ; printMatrixDiagonal ( mat , n ) ; } }


"Print modified array after executing the commands of addition and subtraction | Java program to find modified array after executing m commands / queries ; Update function for every command ; If q == 0 , add ' k ' and ' - k ' to ' l - 1' and ' r ' index ; If q == 1 , add ' - k ' and ' k ' to ' l - 1' and ' r ' index ; Function to generate the final array after executing all commands ; Generate final array with the help of DP concept ; driver code ; Generate final array ; Printing the final modified array"
How can the above be solved in Java?

import java . util . Arrays ; class GFG { static void updateQuery ( int arr [ ] , int n , int q , int l , int r , int k ) { if ( q == 0 ) { arr [ l - 1 ] += k ; arr [ r ] += - k ; } else { arr [ l - 1 ] += - k ; arr [ r ] += k ; } return ; } static void generateArray ( int arr [ ] , int n ) { for ( int i = 1 ; i < n ; ++ i ) arr [ i ] += arr [ i - 1 ] ; } public static void main ( String arg [ ] ) { int n = 5 ; int arr [ ] = new int [ n + 1 ] ; Arrays . fill ( arr , 0 ) ; int q = 0 , l = 1 , r = 3 , k = 2 ; updateQuery ( arr , n , q , l , r , k ) ; q = 1 ; l = 3 ; r = 5 ; k = 3 ; updateQuery ( arr , n , q , l , r , k ) ; q = 0 ; l = 2 ; r = 5 ; k = 1 ; updateQuery ( arr , n , q , l , r , k ) ; generateArray ( arr , n ) ; for ( int i = 0 ; i < n ; ++ i ) System . out . print ( arr [ i ] + " ▁ " ) ; } }


"Print modified array after multiple array range increment operations | Java implementation to increment values in the given range by a value d for multiple queries ; structure to store the ( start , end ) index pair for each query ; function to increment values in the given range by a value d for multiple queries ; for each ( start , end ) index pair , perform the following operations on ' sum [ ] ' ; increment the value at index ' start ' by the given value ' d ' in ' sum [ ] ' ; if the index ' ( end + 1 ) ' exists then decrement the value at index ' ( end + 1 ) ' by the given value ' d ' in ' sum [ ] ' ; Now , perform the following operations : accumulate values in the ' sum [ ] ' array and then add them to the corresponding indexes in ' arr [ ] ' ; function to print the elements of the given array ; Driver code ; modifying the array for multiple queries"
How can the above be solved in Java?

class GFG { static class query { int start , end ; query ( int start , int end ) { this . start = start ; this . end = end ; } } public static void incrementByD ( int [ ] arr , query [ ] q_arr , int n , int m , int d ) { int [ ] sum = new int [ n ] ; for ( int i = 0 ; i < m ; i ++ ) { sum [ q_arr [ i ] . start ] += d ; if ( ( q_arr [ i ] . end + 1 ) < n ) sum [ q_arr [ i ] . end + 1 ] -= d ; } arr [ 0 ] += sum [ 0 ] ; for ( int i = 1 ; i < n ; i ++ ) { sum [ i ] += sum [ i - 1 ] ; arr [ i ] += sum [ i ] ; } } public static void printArray ( int [ ] arr , int n ) { for ( int i = 0 ; i < n ; i ++ ) System . out . print ( arr [ i ] + " ▁ " ) ; } public static void main ( String [ ] args ) { int [ ] arr = { 3 , 5 , 4 , 8 , 6 , 1 } ; query [ ] q_arr = new query [ 5 ] ; q_arr [ 0 ] = new query ( 0 , 3 ) ; q_arr [ 1 ] = new query ( 4 , 5 ) ; q_arr [ 2 ] = new query ( 1 , 4 ) ; q_arr [ 3 ] = new query ( 0 , 1 ) ; q_arr [ 4 ] = new query ( 2 , 5 ) ; int n = arr . length ; int m = q_arr . length ; int d = 2 ; System . out . println ( " Original ▁ Array : " ) ; printArray ( arr , n ) ; incrementByD ( arr , q_arr , n , m , d ) ; System . out . println ( " Modified Array : "); printArray ( arr , n ) ; } }


"Print n 0 s and m 1 s such that no two 0 s and no three 1 s are together | Java implementation of the above approach ; Function to print the required pattern ; When condition fails ; When m = n - 1 ; Driver code"
How can the above be solved in Java?

class GFG { static void printPattern ( int n , int m ) { if ( m > 2 * ( n + 1 ) m < n - 1 ) { System . out . print ( " - 1" ) ; } else if ( Math . abs ( n - m ) <= 1 ) { while ( n > 0 && m > 0 ) { System . out . print ( "01" ) ; n -- ; m -- ; } if ( n != 0 ) { System . out . print ( "0" ) ; } if ( m != 0 ) { System . out . print ( "1" ) ; } } else { while ( m - n > 1 && n > 0 ) { System . out . print ( "110" ) ; m = m - 2 ; n = n - 1 ; } while ( n > 0 ) { System . out . print ( "10" ) ; n -- ; m -- ; } while ( m > 0 ) { System . out . print ( "1" ) ; m -- ; } } } public static void main ( String [ ] args ) { int n = 4 , m = 8 ; printPattern ( n , m ) ; } }


"Print n numbers such that their sum is a perfect square | Java implementation of the approach ; Function to print n numbers such that their sum is a perfect square ; Print ith odd number ; Driver code"
How can the above be solved in Java?

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


"Print n terms of Newman | Java Program to print n terms of Newman - Conway Sequence ; Function to find the n - th element ; Declare array to store sequence ; Driver code"
How can the above be solved in Java?

class GFG { public static void sequence ( int n ) { int f [ ] = new int [ n + 1 ] ; f [ 0 ] = 0 ; f [ 1 ] = 1 ; f [ 2 ] = 1 ; System . out . print ( f [ 1 ] + " ▁ " + f [ 2 ] + " ▁ " ) ; for ( int i = 3 ; i <= n ; i ++ ) { f [ i ] = f [ f [ i - 1 ] ] + f [ i - f [ i - 1 ] ] ; System . out . print ( f [ i ] + " ▁ " ) ; } } public static void main ( String [ ] args ) { int n = 13 ; sequence ( n ) ; } }


"Print n x n spiral matrix using O ( 1 ) extra space | Java program to print a n x n spiral matrix in clockwise direction using O ( 1 ) space ; Prints spiral matrix of size n x n containing numbers from 1 to n x n ; x stores the layer in which ( i , j ) th element lies ; Finds minimum of four inputs ; For upper right half ; for lower left half ; Driver code ; print a n x n spiral matrix in O ( 1 ) space"
How can the above be solved in Java?

import java . io . * ; import java . util . * ; class GFG { static void printSpiral ( int n ) { for ( int i = 0 ; i < n ; i ++ ) { for ( int j = 0 ; j < n ; j ++ ) { int x ; x = Math . min ( Math . min ( i , j ) , Math . min ( n - 1 - i , n - 1 - j ) ) ; if ( i <= j ) System . out . print ( ( n - 2 * x ) * ( n - 2 * x ) - ( i - x ) - ( j - x ) + " 	 " ) ; else System . out . print ( ( n - 2 * x - 2 ) * ( n - 2 * x - 2 ) + ( i - x ) + ( j - x ) + " 	 " ) ; } System . out . println ( ) ; } } public static void main ( String args [ ] ) { int n = 5 ; printSpiral ( n ) ; } }


"Print negative weight cycle in a Directed Graph | Java program for the above approach ; Structure to represent a weighted edge in graph ; Structure to represent a directed and weighted graph ; V . Number of vertices , E . Number of edges ; Graph is represented as an array of edges . ; Creates a new graph with V vertices and E edges ; Function runs Bellman - Ford algorithm and prints negative cycle ( if present ) ; Initialize distances from src to all other vertices as INFINITE and all parent as - 1 ; Relax all edges | V | - 1 times . ; Check for negative - weight cycles ; Store one of the vertex of the negative weight cycle ; To store the cycle vertex ; Reverse cycle [ ] ; Printing the negative cycle ; Driver Code ; Number of vertices in graph ; Number of edges in graph ; Given Graph ; Function Call"
How can the above be solved in Java?

import java . util . ArrayList ; import java . util . Collections ; class GFG { static class Edge { int src , dest , weight ; } static class Graph { int V , E ; Edge [ ] edge ; } static Graph createGraph ( int V , int E ) { Graph graph = new Graph ( ) ; graph . V = V ; graph . E = E ; graph . edge = new Edge [ graph . E ] ; for ( int i = 0 ; i < graph . E ; i ++ ) { graph . edge [ i ] = new Edge ( ) ; } return graph ; } static void NegCycleBellmanFord ( Graph graph , int src ) { int V = graph . V ; int E = graph . E ; int [ ] dist = new int [ V ] ; int [ ] parent = new int [ V ] ; for ( int i = 0 ; i < V ; i ++ ) { dist [ i ] = 1000000 ; parent [ i ] = - 1 ; } dist [ src ] = 0 ; for ( int i = 1 ; i <= V - 1 ; i ++ ) { for ( int j = 0 ; j < E ; j ++ ) { int u = graph . edge [ j ] . src ; int v = graph . edge [ j ] . dest ; int weight = graph . edge [ j ] . weight ; if ( dist [ u ] != 1000000 && dist [ u ] + weight < dist [ v ] ) { dist [ v ] = dist [ u ] + weight ; parent [ v ] = u ; } } } int C = - 1 ; for ( int i = 0 ; i < E ; i ++ ) { int u = graph . edge [ i ] . src ; int v = graph . edge [ i ] . dest ; int weight = graph . edge [ i ] . weight ; if ( dist [ u ] != 1000000 && dist [ u ] + weight < dist [ v ] ) { C = v ; break ; } } if ( C != - 1 ) { for ( int i = 0 ; i < V ; i ++ ) C = parent [ C ] ; ArrayList < Integer > cycle = new ArrayList < > ( ) ; for ( int v = C ; ; v = parent [ v ] ) { cycle . add ( v ) ; if ( v == C && cycle . size ( ) > 1 ) break ; } Collections . reverse ( cycle ) ; for ( int v : cycle ) System . out . print ( v + " ▁ " ) ; System . out . println ( ) ; } else System . out . println ( - 1 ) ; } public static void main ( String [ ] args ) { int V = 5 ; int E = 5 ; Graph graph = createGraph ( V , E ) ; graph . edge [ 0 ] . src = 0 ; graph . edge [ 0 ] . dest = 1 ; graph . edge [ 0 ] . weight = 1 ; graph . edge [ 1 ] . src = 1 ; graph . edge [ 1 ] . dest = 2 ; graph . edge [ 1 ] . weight = 2 ; graph . edge [ 2 ] . src = 2 ; graph . edge [ 2 ] . dest = 3 ; graph . edge [ 2 ] . weight...


"Print nodes at k distance from root | A binary tree node has data , pointer to left child and a pointer to right child ; Driver program to test above functions ; Constructed binary tree is 1 / \ 2 3 / \ / 4 5 8"
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 printKDistant ( Node node , int k ) { if ( node == null k < 0 ) return ; if ( k == 0 ) { System . out . print ( node . data + " ▁ " ) ; return ; } printKDistant ( node . left , k - 1 ) ; printKDistant ( node . right , k - 1 ) ; } 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 ( 8 ) ; tree . printKDistant ( tree . root , 2 ) ; } }


"Print nodes at k distance from root | Iterative | Java program to print all nodes of level k iterative approach ; Node of binary tree ; Function to add a new node ; Function to print nodes of given level ; extra null is added to keep track of all the nodes to be added before level is incremented by 1 ; print when level is equal to k ; break the loop if level exceeds the given level number ; Driver code ; create a binary tree"
How can the above be solved in Java?

 import java . util . * ; class GFG { static class Node { int data ; Node left , right ; } static Node newNode ( int data ) { Node newnode = new Node ( ) ; newnode . data = data ; newnode . left = newnode . right = null ; return newnode ; } static boolean printKDistant ( Node root , int klevel ) { Queue < Node > q = new LinkedList < > ( ) ; int level = 1 ; boolean flag = false ; q . add ( root ) ; q . add ( null ) ; while ( q . size ( ) > 0 ) { Node temp = q . peek ( ) ; if ( level == klevel && temp != null ) { flag = true ; System . out . print ( temp . data + " ▁ " ) ; } q . remove ( ) ; if ( temp == null ) { if ( q . peek ( ) != null ) q . add ( null ) ; level += 1 ; if ( level > klevel ) break ; } else { if ( temp . left != null ) q . add ( temp . left ) ; if ( temp . right != null ) q . add ( temp . right ) ; } } System . out . println ( ) ; return flag ; } public static void main ( String srga [ ] ) { Node root = newNode ( 20 ) ; root . left = newNode ( 10 ) ; root . right = newNode ( 30 ) ; root . left . left = newNode ( 5 ) ; root . left . right = newNode ( 15 ) ; root . left . right . left = newNode ( 12 ) ; root . right . left = newNode ( 25 ) ; root . right . right = newNode ( 40 ) ; System . out . print ( " data ▁ at ▁ level ▁ 1 ▁ : ▁ " ) ; boolean ret = printKDistant ( root , 1 ) ; if ( ret == false ) System . out . print ( " Number ▁ exceeds ▁ total ▁ " + "number of levels
"); System . out . print ( " data ▁ at ▁ level ▁ 2 ▁ : ▁ " ) ; ret = printKDistant ( root , 2 ) ; if ( ret == false ) System . out . print ( " Number ▁ exceeds ▁ total ▁ " + "number of levels
"); System . out . print ( " data ▁ at ▁ level ▁ 3 ▁ : ▁ " ) ; ret = printKDistant ( root , 3 ) ; if ( ret == false ) System . out . print ( " Number ▁ exceeds ▁ total ▁ " + "number of levels
"); System . out . print ( " data ▁ at ▁ level ▁ 6 ▁ : ▁ " ) ; ret = printKDistant ( root , 6 ) ; if ( ret == false ) System . out . print ( " Number ▁ exceeds ▁ total " + "number of levels
"); } }


"Print nodes between two given level numbers of a binary tree | Java program to print Nodes level by level between given two levels ; A binary tree Node has key , pointer to left and right children ; Given a binary tree , print nodes from level number ' low ' to level number ' high ' ; Marker node to indicate end of level ; Initialize level number ; Enqueue the only first level node and marker node for end of level ; Simple level order traversal loop ; Remove the front item from queue ; Check if end of level is reached ; print a new line and increment level number ; Check if marker node was last node in queue or level number is beyond the given upper limit ; Enqueue the marker for end of next level ; If this is marker , then we don 't need print it  and enqueue its children ; If level is equal to or greater than given lower level , print it ; Enqueue children of non - marker node ; Driver program to test for above functions"
How can the above be solved in Java?

import java . util . LinkedList ; import java . util . Queue ; class Node { int data ; Node left , right ; public Node ( int item ) { data = item ; left = right = null ; } } class BinaryTree { Node root ; void printLevels ( Node node , int low , int high ) { Queue < Node > Q = new LinkedList < > ( ) ; Node marker = new Node ( 4 ) ; int level = 1 ; Q . add ( node ) ; Q . add ( marker ) ; while ( Q . isEmpty ( ) == false ) { Node n = Q . peek ( ) ; Q . remove ( ) ; if ( n == marker ) { System . out . println ( " " ) ; level ++ ; if ( Q . isEmpty ( ) == true level > high ) break ; Q . add ( marker ) ; continue ; } if ( level >= low ) System . out . print ( n . data + " ▁ " ) ; if ( n . left != null ) Q . add ( n . left ) ; if ( n . right != null ) Q . add ( n . right ) ; } } 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 ) ; System . out . print ( " Level ▁ Order ▁ traversal ▁ between ▁ given ▁ two ▁ levels ▁ is ▁ " ) ; tree . printLevels ( tree . root , 2 , 3 ) ; } }


"Print number in ascending order which contains 1 , 2 and 3 in their digits . | Java program to print all number containing 1 , 2 and 3 in any order . ; prints all the number containing 1 , 2 , 3 in any order ; check if the number contains 1 , 2 & 3 in any order ; sort all the numbers ; convert the number to string and find if it contains 1 , 2 & 3. ; Driver Code"
How can the above be solved in Java?

import java . io . FileNotFoundException ; import java . util . ArrayList ; import java . util . Collections ; import java . util . Iterator ; class GFG { private static String printNumbers ( int [ ] numbers ) { ArrayList < Integer > array = new ArrayList < > ( ) ; for ( int number : numbers ) { if ( findContainsOneTwoThree ( number ) ) array . add ( number ) ; } Collections . sort ( array ) ; StringBuffer strbuf = new StringBuffer ( ) ; Iterator it = array . iterator ( ) ; while ( it . hasNext ( ) ) { int value = ( int ) it . next ( ) ; if ( strbuf . length ( ) > 0 ) strbuf . append ( " , ▁ " ) ; strbuf . append ( Integer . toString ( value ) ) ; } return ( strbuf . length ( ) > 0 ) ? strbuf . toString ( ) : " - 1" ; } private static boolean findContainsOneTwoThree ( int number ) { String str = Integer . toString ( number ) ; return ( str . contains ( "1" ) && str . contains ( "2" ) && str . contains ( "3" ) ) ; } public static void main ( String [ ] args ) { int [ ] numbers = { 123 , 1232 , 456 , 234 , 32145 } ; System . out . println ( printNumbers ( numbers ) ) ; } }


"Print numbers in descending order along with their frequencies | Java program to print the elements in descending along with their frequencies ; Function to print the elements in descending along with their frequencies ; Sorts the element in decreasing order ; traverse the array elements ; Prints the number and count ; Prints the last step ; Driver Code"
How can the above be solved in Java?

 import java . util . * ; class GFG { static void printElements ( int a [ ] , int n ) { Arrays . sort ( a ) ; a = reverse ( a ) ; int cnt = 1 ; for ( int i = 0 ; i < n - 1 ; i ++ ) { if ( a [ i ] != a [ i + 1 ] ) { System . out . print ( a [ i ] + " ▁ occurs ▁ " + cnt + " times
"); cnt = 1 ; } else cnt += 1 ; } System . out . print ( a [ n - 1 ] + " ▁ occurs ▁ " + cnt + " times
"); } static int [ ] reverse ( int a [ ] ) { int i , n = a . length , t ; for ( i = 0 ; i < n / 2 ; i ++ ) { t = a [ i ] ; a [ i ] = a [ n - i - 1 ] ; a [ n - i - 1 ] = t ; } return a ; } public static void main ( String [ ] args ) { int a [ ] = { 1 , 1 , 1 , 2 , 3 , 4 , 9 , 9 , 10 } ; int n = a . length ; printElements ( a , n ) ; } }


"Print numbers in the range 1 to n having bits in alternate pattern | Java implementation to print numbers in the range 1 to n having bits in alternate pattern ; function to print numbers in the range 1 to n having bits in alternate pattern ; first number having bits in alternate pattern ; display ; loop until n < curr_num ; generate next number having alternate bit pattern ; if true then break ; display ; generate next number having alternate bit pattern ; if true then break ; display ; Driver code"
How can the above be solved in Java?

import java . io . * ; import java . util . * ; class GFG { public static void printNumHavingAltBitPatrn ( int n ) { int curr_num = 1 , i = 1 ; System . out . print ( curr_num + " ▁ " ) ; while ( i != 0 ) { i ++ ; curr_num <<= 1 ; if ( n < curr_num ) break ; System . out . print ( curr_num + " ▁ " ) ; curr_num = ( ( curr_num ) << 1 ) ^ 1 ; if ( n < curr_num ) break ; System . out . print ( curr_num + " ▁ " ) ; } } public static void main ( String [ ] args ) { int n = 50 ; printNumHavingAltBitPatrn ( n ) ; } }


"Print numbers such that no two consecutive numbers are co | Java implementation of the approach ; Function for Sieve of Eratosthenes ; Function to print the required sequence ; Store only the required primes ; Base condition ; First integer in the list ; Second integer in the list ; Third integer in the list ; Generate ( N - 1 ) th term ; Generate Nth term ; Modify first term ; Print the sequence ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { static int MAX = 620000 ; static int [ ] prime = new int [ MAX ] ; static void Sieve ( ) { for ( int i = 2 ; i < MAX ; i ++ ) { if ( prime [ i ] == 0 ) { for ( int j = 2 * i ; j < MAX ; j += i ) { prime [ j ] = 1 ; } } } } static void printSequence ( int n ) { Sieve ( ) ; Vector < Integer > v = new Vector < Integer > ( ) ; Vector < Integer > u = new Vector < Integer > ( ) ; for ( int i = 13 ; i < MAX ; i ++ ) { if ( prime [ i ] == 0 ) { v . add ( i ) ; } } if ( n == 3 ) { System . out . print ( 6 + " ▁ " + 10 + " ▁ " + 15 ) ; return ; } int k ; for ( k = 0 ; k < n - 2 ; k ++ ) { if ( k % 3 == 0 ) { u . add ( v . get ( k ) * 6 ) ; } else if ( k % 3 == 1 ) { u . add ( v . get ( k ) * 15 ) ; } else { u . add ( v . get ( k ) * 10 ) ; } } k -- ; u . add ( v . get ( k ) * 7 ) ; u . add ( 7 * 11 ) ; u . set ( 0 , u . get ( 0 ) * 11 ) ; for ( int i = 0 ; i < u . size ( ) ; i ++ ) { System . out . print ( u . get ( i ) + " ▁ " ) ; } } public static void main ( String [ ] args ) { int n = 4 ; printSequence ( n ) ; } }


"Print numbers such that no two consecutive numbers are co | Java implementation of the approach ; Function to generate Sieve of Eratosthenes ; If prime [ p ] is not changed , then it is a prime ; Add the prime numbers to the array b ; Function to return the gcd of a and b ; Function to print the required sequence of integers ; Including the primes in a series of primes which will be later multiplied ; This is done to mark a product as existing ; Maximum number of primes that we consider ; For different interval ; For different starting index of jump ; For storing the numbers ; Checking for occurrence of a product . Also checking for the same prime occurring consecutively ; Including the primes in a series of primes which will be later multiplied ; Driver Code"
How can the above be solved in Java?

import java . util . * ; class GFG { static int limit = 1000000000 ; static int MAX_PRIME = 2000000 ; static int MAX = 1000000 ; static int I_MAX = 50000 ; static HashMap < Integer , Integer > mp = new HashMap < Integer , Integer > ( ) ; static int [ ] b = new int [ MAX ] ; static int [ ] p = new int [ MAX ] ; static int j = 0 ; static boolean [ ] prime = new boolean [ MAX_PRIME + 1 ] ; static void SieveOfEratosthenes ( int n ) { for ( int i = 0 ; i < MAX_PRIME + 1 ; i ++ ) prime [ i ] = true ; for ( int p = 2 ; p * p <= n ; p ++ ) { if ( prime [ p ] == true ) { for ( int i = p * p ; i <= n ; i += p ) prime [ i ] = false ; } } for ( int p = 2 ; p <= n ; p ++ ) { if ( prime [ p ] ) { b [ j ++ ] = p ; } } } static int gcd ( int a , int b ) { if ( b == 0 ) return a ; return gcd ( b , a % b ) ; } static void printSeries ( int n ) { SieveOfEratosthenes ( MAX_PRIME ) ; int i , g , k , l , m , d ; int [ ] ar = new int [ I_MAX + 2 ] ; for ( i = 0 ; i < j ; i ++ ) { if ( ( b [ i ] * b [ i + 1 ] ) > limit ) break ; p [ i ] = b [ i ] ; mp . put ( b [ i ] * b [ i + 1 ] , 1 ) ; } d = 550 ; boolean flag = false ; for ( k = 2 ; ( k < d - 1 ) && ! flag ; k ++ ) { for ( m = 2 ; ( m < d ) && ! flag ; m ++ ) { for ( l = m + k ; l < d ; l += k ) { if ( ( ( b [ l ] * b [ l + k ] ) < limit ) && mp . containsKey ( b [ l ] * b [ l + k ] ) && mp . containsKey ( p [ i - 1 ] * b [ l ] ) && ( l + k ) < d && p [ i - 1 ] != b [ l + k ] && p [ i - 1 ] != b [ l ] && mp . get ( b [ l ] * b [ l + k ] ) != 1 ) { if ( mp . get ( p [ i - 1 ] * b [ l ] ) != 1 ) { p [ i ] = b [ l ] ; mp . put ( p [ i - 1 ] * b [ l ] , 1 ) ; i ++ ; } } if ( i >= I_MAX ) { flag = true ; break ; } } } } for ( i = 0 ; i < n ; i ++ ) ar [ i ] = p [ i ] * p [ i + 1 ] ; for ( i = 0 ; i < n - 1 ; i ++ ) System . out . print ( ar [ i ] + " ▁ " ) ; g = gcd ( ar [ n - 1 ] , ar [ n - 2 ] ) ; System . out . print ( g * 2 ) ; } public static void main ( String [ ] args ) { int n = 4 ; printSeries ( n ) ; } }


"Print pair with maximum AND value in an array | Java Program to find pair with maximum AND value ; Utility function to check number of elements having set msb as of pattern ; Function for finding maximum and value pair ; iterate over total of 30 bits from msb to lsb ; find the count of element having set msb ; if count >= 2 set particular bit in result ; Find the elements ; print the pair of elements ; inc count value after printing element ; return the result value ; Driver code"
How can the above be solved in Java?

import java . util . * ; import java . io . * ; class GFG { static int checkBit ( int pattern , int arr [ ] , int n ) { int count = 0 ; for ( int i = 0 ; i < n ; i ++ ) if ( ( pattern & arr [ i ] ) == pattern ) count ++ ; return count ; } static int maxAND ( int arr [ ] , int n ) { int res = 0 , count ; for ( int bit = 31 ; bit >= 0 ; bit -- ) { count = checkBit ( res | ( 1 << bit ) , arr , n ) ; if ( count >= 2 ) res |= ( 1 << bit ) ; } if ( res == 0 ) System . out . println ( " Not ▁ Possible " ) ; else { System . out . print ( " Pair ▁ = ▁ " ) ; count = 0 ; for ( int i = 0 ; i < n && count < 2 ; i ++ ) { if ( ( arr [ i ] & res ) == res ) { count ++ ; System . out . print ( arr [ i ] + " ▁ " ) ; } } System . out . println ( ) ; } return res ; } public static void main ( String args [ ] ) { int arr [ ] = { 4 , 8 , 6 , 2 } ; int n = arr . length ; System . out . println ( " Maximum ▁ AND ▁ Value ▁ = ▁ " + maxAND ( arr , n ) ) ; } }


"Print path from a node to root of given Complete Binary Tree | Java program for the above approach ; Function to print the path from node to root ; Iterate until root is reached ; Print the value of the current node ; Move to parent of the current node ; Driver Code"
How can the above be solved in Java?

import java . util . * ; class GFG { static void path_to_root ( int node ) { while ( node >= 1 ) { System . out . print ( node + " ▁ " ) ; node /= 2 ; } } public static void main ( String [ ] args ) { int N = 7 ; path_to_root ( N ) ; } }


"Print path from given Source to Destination in 2 | Java program for printing a path from given source to destination ; Function to print the path ; Base condition ; Pop stores elements ; Recursive call for printing stack In reverse order ; Function to store the path into The stack , if path exist ; Base condition ; Push current elements ; Condition to check whether reach to the Destination or not ; Increment ' x ' ordinate of source by ( 2 * x + y ) Keeping ' y ' constant ; Increment ' y ' ordinate of source by ( 2 * y + x ) Keeping ' x ' constant ; Pop current elements form stack ; If no path exists ; Utility function to check whether path exist or not ; To store x co - ordinate ; To store y co - ordinate ; Function to find the path ; Print - 1 , if path doesn 't exist ; Driver code ; Function call"
How can the above be solved in Java?

import java . util . * ; class GFG { static void printExistPath ( Stack < Integer > sx , Stack < Integer > sy , int last ) { if ( sx . isEmpty ( ) || sy . isEmpty ( ) ) { return ; } int x = sx . peek ( ) ; int y = sy . peek ( ) ; sx . pop ( ) ; sy . pop ( ) ; printExistPath ( sx , sy , last ) ; if ( sx . size ( ) == last - 1 ) { System . out . print ( " ( " + x + " , ▁ " + y + " ) " ) ; } else { System . out . print ( " ( " + x + " , ▁ " + y + " ) - > " ) ; } } static boolean storePath ( int srcX , int srcY , int destX , int destY , Stack < Integer > sx , Stack < Integer > sy ) { if ( srcX > destX srcY > destY ) { return false ; } sx . add ( srcX ) ; sy . add ( srcY ) ; if ( srcX == destX && srcY == destY ) { printExistPath ( sx , sy , sx . size ( ) ) ; return true ; } if ( storePath ( ( 2 * srcX ) + srcY , srcY , destX , destY , sx , sy ) ) { return true ; } if ( storePath ( srcX , ( 2 * srcY ) + srcX , destX , destY , sx , sy ) ) { return true ; } sx . pop ( ) ; sy . pop ( ) ; return false ; } static boolean isPathExist ( int srcX , int srcY , int destX , int destY ) { Stack < Integer > sx = new Stack < Integer > ( ) ; Stack < Integer > sy = new Stack < Integer > ( ) ; return storePath ( srcX , srcY , destX , destY , sx , sy ) ; } static void printPath ( int srcX , int srcY , int destX , int destY ) { if ( ! isPathExist ( srcX , srcY , destX , destY ) ) { System . out . print ( " - 1" ) ; } } public static void main ( String [ ] args ) { int srcX = 5 , srcY = 8 ; int destX = 83 , destY = 21 ; printPath ( srcX , srcY , destX , destY ) ; } }


"Print path from root to a given node in a binary tree | Java implementation to print the path from root to a given node in a binary tree ; A node of binary tree ; Returns true if there is a path from root to the given node . It also populates ' arr ' with the given path ; if root is NULL there is no path ; push the node ' s ▁ value ▁ in ▁ ' arr '  ; if it is the required node return true ; else check whether the required node lies in the left subtree or right subtree of the current node ; required node does not lie either in the left or right subtree of the current node Thus , remove current node ' s ▁ value ▁ from ▁ ▁ ▁ ' arr 'and then return false  ; function to print the path from root to the given node if the node lies in the binary tree ; ArrayList to store the path ; if required node ' x ' is present then print the path ; ' x ' is not present in the binary tree ; Driver program to test above ; binary tree formation"
How can the above be solved in Java?

import java . util . ArrayList ; public class PrintPath { class Node { int data ; Node left , right ; Node ( int data ) { this . data = data ; left = right = null ; } } ; public static boolean hasPath ( Node root , ArrayList < Integer > arr , int x ) { if ( root == null ) return false ; arr . add ( root . data ) ; if ( root . data == x ) return true ; if ( hasPath ( root . left , arr , x ) || hasPath ( root . right , arr , x ) ) return true ; arr . remove ( arr . size ( ) - 1 ) ; return false ; } public static void printPath ( Node root , int x ) { ArrayList < Integer > arr = new ArrayList < > ( ) ; if ( hasPath ( root , arr , x ) ) { for ( int i = 0 ; i < arr . size ( ) - 1 ; i ++ ) System . out . print ( arr . get ( i ) + " - > " ) ; System . out . print ( arr . get ( arr . size ( ) - 1 ) ) ; } else System . out . print ( " No ▁ Path " ) ; } 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 ) ; int x = 5 ; printPath ( root , x ) ; } }


"Print prime factors of a given integer in decreasing order using Stack | Java program for the above approach ; Function to print prime factors of N in decreasing order ; Stores prime factors of N in decreasing order ; Insert i into stack ; Update N ; Update i ; Print value of stack st ; Driver Code ; Function Call"
How can the above be solved in Java?

import java . util . * ; class GFG { static void PrimeFactors ( int N ) { Stack < Integer > st = new Stack < > ( ) ; int i = 2 ; while ( N != 1 ) { if ( N % i == 0 ) { st . push ( i ) ; while ( N % i == 0 ) { N = N / i ; } } i ++ ; } while ( ! st . isEmpty ( ) ) { System . out . println ( st . peek ( ) ) ; st . pop ( ) ; } } public static void main ( String [ ] args ) { int N = 8 ; PrimeFactors ( N ) ; ; } }


"Print prime numbers from 1 to N in reverse order | Java program to print all primes between 1 to N in reverse order using Sieve of Eratosthenes ; Create a boolean array " prime [ 0 . . n ] " and initialize all entries it as true . A value in prime [ i ] will finally be false if i is Not a prime , else true . ; If prime [ p ] is not changed , then it is a prime ; Update all multiples of p ; Print all prime numbers ; Driver Program to test above function ; static input ; To display ; reverseorder ( N ) ; calling the function"
How can the above be solved in Java?

import java . io . * ; import java . util . * ; class GFG { static void reverseorder ( int n ) { boolean prime [ ] = new boolean [ n + 1 ] ; for ( int i = 0 ; i < n ; i ++ ) prime [ i ] = true ; for ( int p = 2 ; p * p <= n ; p ++ ) { if ( prime [ p ] == true ) { for ( int i = p * 2 ; i <= n ; i += p ) prime [ i ] = false ; } } for ( int i = n ; i >= 2 ; i -- ) if ( prime [ i ] == true ) System . out . print ( i + " ▁ " ) ; } public static void main ( String args [ ] ) { int N = 25 ; System . out . println ( " Prime ▁ number ▁ in ▁ reverse ▁ order " ) ; if ( N == 1 ) System . out . println ( " No ▁ prime ▁ no ▁ exist ▁ in ▁ this ▁ range " ) ; else } }


"Print prime numbers with prime sum of digits in an array | Java implementation of the above approach ; Function to store the primes ; Function to return the sum of digits ; Function to print additive primes ; If the number is prime ; Check if it 's digit sum is prime ; Driver code"
How can the above be solved in Java?

import java . util . Arrays ; class GFG { static void sieve ( int maxEle , int prime [ ] ) { prime [ 0 ] = prime [ 1 ] = 1 ; for ( int i = 2 ; i * i <= maxEle ; i ++ ) { if ( prime [ i ] == 0 ) { for ( int j = 2 * i ; j <= maxEle ; j += i ) prime [ j ] = 1 ; } } } static int digitSum ( int n ) { int sum = 0 ; while ( n > 0 ) { sum += n % 10 ; n = n / 10 ; } return sum ; } static void printAdditivePrime ( int arr [ ] , int n ) { int maxEle = Arrays . stream ( arr ) . max ( ) . getAsInt ( ) ; int prime [ ] = new int [ maxEle + 1 ] ; sieve ( maxEle , prime ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( prime [ arr [ i ] ] == 0 ) { int sum = digitSum ( arr [ i ] ) ; if ( prime [ sum ] == 0 ) System . out . print ( arr [ i ] + " ▁ " ) ; } } } public static void main ( String [ ] args ) { int a [ ] = { 2 , 4 , 6 , 11 , 12 , 18 , 7 } ; int n = a . length ; printAdditivePrime ( a , n ) ; } }


"Print rectangular pattern with given center | Java program for the above approach ; Function to print the matrix filled with rectangle pattern having center coordinates are c1 , c2 ; Iterate in the range [ 0 , n - 1 ] ; Iterate in the range [ 0 , n - 1 ] ; Driver code ; Given Input ; Function Call"
How can the above be solved in Java?

import java . io . * ; class GFG { static void printRectPattern ( int c1 , int c2 , int n ) { for ( int i = 0 ; i < n ; i ++ ) { for ( int j = 0 ; j < n ; j ++ ) { System . out . print ( ( Math . max ( Math . abs ( c1 - i ) , Math . abs ( c2 - j ) ) ) + " ▁ " ) ; } System . out . println ( ) ; } } public static void main ( String [ ] args ) { int c1 = 2 ; int c2 = 2 ; int n = 5 ; printRectPattern ( c1 , c2 , n ) ; } }


"Print root to leaf paths without using recursion | Java program to Print root to leaf path WITHOUT using recursion ; A binary tree node ; Function to print root to leaf path for a leaf using parent nodes stored in map ; start from leaf node and keep on pushing nodes into stack till root node is reached ; Start popping nodes from stack and print them ; An iterative function to do preorder traversal of binary tree and print root to leaf path without using recursion ; Corner Case ; Create an empty stack and push root to it ; Create a map to store parent pointers of binary tree nodes ; parent of root is NULL ; Pop all items one by one . Do following for every popped item a ) push its right child and set its parent pointer b ) push its left child and set its parent pointer Note that right child is pushed first so that left is processed first ; Pop the top item from stack ; If leaf node encountered , print Top To Bottom path ; Push right & left children of the popped node to stack . Also set their parent pointer in the map ; Driver program to test above functions ; Constructed binary tree is 10 / \ 8 2 / \ / 3 5 2"
How can the above be solved in Java?

import java . util . Stack ; import java . util . HashMap ; public class PrintPath { class Node { int data ; Node left , right ; Node ( int data ) { left = right = null ; this . data = data ; } } ; public static void printTopToBottomPath ( Node curr , HashMap < Node , Node > parent ) { Stack < Node > stk = new Stack < > ( ) ; while ( curr != null ) { stk . push ( curr ) ; curr = parent . get ( curr ) ; } while ( ! stk . isEmpty ( ) ) { curr = stk . pop ( ) ; System . out . print ( curr . data + " ▁ " ) ; } System . out . println ( ) ; } public static void printRootToLeaf ( Node root ) { if ( root == null ) return ; Stack < Node > nodeStack = new Stack < > ( ) ; nodeStack . push ( root ) ; HashMap < Node , Node > parent = new HashMap < > ( ) ; parent . put ( root , null ) ; while ( ! nodeStack . isEmpty ( ) ) { Node current = nodeStack . pop ( ) ; if ( current . left == null && current . right == null ) printTopToBottomPath ( current , parent ) ; if ( current . right != null ) { parent . put ( current . right , current ) ; nodeStack . push ( current . right ) ; } if ( current . left != null ) { parent . put ( current . left , current ) ; nodeStack . push ( current . left ) ; } } } public static void main ( String args [ ] ) { Node root = new Node ( 10 ) ; root . left = new Node ( 8 ) ; root . right = new Node ( 2 ) ; root . left . left = new Node ( 3 ) ; root . left . right = new Node ( 5 ) ; root . right . left = new Node ( 2 ) ; printRootToLeaf ( root ) ; } }


"Print siblings of a given Node in N | Java program for the above approach ; Structure of a node of N - ary tree ; Function to create a new node ; Function to find the siblings of the node / value ; Stores nodes level wise ; Push the root ; Continue until all levels are traversed ; Stores current node ; Enqueue all children of the current node ; If node value is found ; Print all children of current node except value as the answer ; Push the child nodes of temp into the queue ; Driver Code ; Stores root of the constructed tree ; Print siblings of Node X"
How can the above be solved in Java?

import java . util . * ; class GFG { static class Node { int key ; Vector < Node > child = new Vector < > ( ) ; } ; static Node newNode ( int key ) { Node temp = new Node ( ) ; temp . key = key ; return temp ; } static void Siblings ( Node root , int value ) { int flag = 0 ; if ( root == null ) return ; Queue < Node > q = new LinkedList < > ( ) ; q . add ( root ) ; while ( ! q . isEmpty ( ) ) { Node temp = q . peek ( ) ; q . remove ( ) ; for ( int i = 0 ; i < temp . child . size ( ) ; i ++ ) { if ( temp . child . get ( i ) . key == value ) { flag = 1 ; for ( int j = 0 ; j < temp . child . size ( ) ; j ++ ) { if ( value != temp . child . get ( j ) . key ) System . out . print ( temp . child . get ( j ) . key + " ▁ " ) ; } break ; } q . add ( temp . child . get ( i ) ) ; } } if ( flag == 0 ) System . out . print ( " No ▁ siblings ! ! " ) ; } static Node constructTree ( ) { Node root = newNode ( 10 ) ; ( root . child ) . add ( newNode ( 20 ) ) ; ( root . child ) . add ( newNode ( 30 ) ) ; ( root . child ) . add ( newNode ( 40 ) ) ; ( root . child . get ( 0 ) . child ) . add ( newNode ( 50 ) ) ; ( root . child . get ( 0 ) . child ) . add ( newNode ( 60 ) ) ; ( root . child . get ( 1 ) . child ) . add ( newNode ( 70 ) ) ; ( root . child . get ( 1 ) . child ) . add ( newNode ( 80 ) ) ; ( root . child . get ( 2 ) . child ) . add ( newNode ( 90 ) ) ; ( root . child . get ( 2 ) . child ) . add ( newNode ( 100 ) ) ; ( root . child . get ( 2 ) . child ) . add ( newNode ( 110 ) ) ; return root ; } public static void main ( String [ ] args ) { Node root = constructTree ( ) ; int X = 30 ; Siblings ( root , X ) ; } }


"Print steps to make a number in form of 2 ^ X | Java program to implement the above approach ; Function to find the leftmost unset bit in a number . ; Function that perform the step ; Find the leftmost unset bit ; If the number has no bit unset , it means it is in form 2 ^ x - 1 ; Count the steps ; Iterate till number is of form 2 ^ x - 1 ; At even step increase by 1 ; Odd step xor with any 2 ^ m - 1 ; Find the leftmost unset bit ; 2 ^ m - 1 ; Perform the step ; Increase the steps ; Driver code"
How can the above be solved in Java?

class GFG { static int find_leftmost_unsetbit ( int n ) { int ind = - 1 ; int i = 1 ; while ( n > 0 ) { if ( ( n % 2 ) != 1 ) { ind = i ; } i ++ ; n >>= 1 ; } return ind ; } static void perform_steps ( int n ) { int left = find_leftmost_unsetbit ( n ) ; if ( left == - 1 ) { System . out . print ( " No ▁ steps ▁ required " ) ; return ; } int step = 1 ; while ( find_leftmost_unsetbit ( n ) != - 1 ) { if ( step % 2 == 0 ) { n += 1 ; System . out . println ( " Step " + step + " : ▁ Increase ▁ by ▁ 1" ) ; } else { int m = find_leftmost_unsetbit ( n ) ; int num = ( int ) ( Math . pow ( 2 , m ) - 1 ) ; n = n ^ num ; System . out . println ( " Step " + step + " : ▁ Xor ▁ with ▁ " + num ) ; } step += 1 ; } } public static void main ( String [ ] args ) { int n = 39 ; perform_steps ( n ) ; } }


"Print string after removing all ( “ 10 ” or “ 01 ” ) from the binary string | Java program to print the final String after removing all the occurrences of "10" and "01" from the given binary String ; Function to print the final String after removing all the occurrences of "10" and "01" from the given binary String ; Variables to store the count of 1 ' s ▁ and ▁ 0' s ; Variable left will store whether 0 ' s ▁ or ▁ 1' s is left in the final String ; Length of the String ; For loop to count the occurrences of 1 ' s ▁ and ▁ 0' s in the String ; To check if the count of 1 ' s ▁ is ▁ ▁ greater ▁ than ▁ the ▁ count ▁ of ▁ 0' s or not . If x is greater , then those many 1 's  are printed. ; Length of the final remaining String after removing all the occurrences ; Printing the final String ; Driver Code"
How can the above be solved in Java?

import java . util . * ; class GFG { static void finalString ( String str ) { int x = 0 , y = 0 ; int left ; int n = str . length ( ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( str . charAt ( i ) == '1' ) x ++ ; else y ++ ; } if ( x > y ) left = 1 ; else left = 0 ; int length = n - 2 * Math . min ( x , y ) ; for ( int i = 0 ; i < length ; i ++ ) { System . out . print ( left ) ; } } public static void main ( String [ ] args ) { String str = "010110100100000" ; finalString ( str ) ; } }


"Print string of odd length in ' X ' format | Java program to print cross pattern ; Function to print given string in cross pattern ; i and j are the indexes of characters to be displayed in the ith iteration i = 0 initially and go upto length of string j = length of string initially in each iteration of i , we increment i and decrement j , we print character only of k == i or k == j ; driver code"
How can the above be solved in Java?

class GFG { static void pattern ( String str , int len ) { for ( int i = 0 ; i < len ; i ++ ) { int j = len - 1 - i ; for ( int k = 0 ; k < len ; k ++ ) { if ( k == i k == j ) System . out . print ( str . charAt ( k ) ) ; else System . out . print ( " ▁ " ) ; } System . out . println ( " " ) ; } } public static void main ( String [ ] args ) { String str = " geeksforgeeks " ; int len = str . length ( ) ; pattern ( str , len ) ; } }


"Print string of odd length in ' X ' format | Java program to print the given pattern ; Function to print the given string in respective pattern ; Print characters at corresponding places satisfying the two conditions ; Print blank space at rest of places ; Driver code"
How can the above be solved in Java?

import java . io . * ; class GFG { static void printPattern ( String str , int len ) { for ( int i = 0 ; i < len ; i ++ ) { for ( int j = 0 ; j < len ; j ++ ) { if ( ( i == j ) || ( i + j == len - 1 ) ) System . out . print ( str . charAt ( j ) ) ; else System . out . print ( " ▁ " ) ; } System . out . println ( ) ; } } public static void main ( String [ ] args ) { String str = " geeksforgeeks " ; int len = str . length ( ) ; printPattern ( str , len ) ; } }


"Print the DFS traversal step | Java program to print the complete DFS - traversal of graph using back - tracking ; Function to print the complete DFS - traversal ; Check if all th node is visited or not and count unvisited nodes ; If all the node is visited return ; ; Mark not visited node as visited ; Track the current edge ; Print the node ; Check for not visited node and proceed with it . ; call the DFs function if not visited ; Backtrack through the last visited nodes ; Function to call the DFS function which prints the DFS - traversal stepwise ; Create a array of visited node ; Vector to track last visited road ; Initialize all the node with false ; call the function ; Function to insert edges in Graph ; Driver Code ; number of nodes and edges in the graph ; Function call to create the graph ; Call the function to print"
How can the above be solved in Java?

import java . io . * ; import java . util . * ; class GFG { static int N = 1000 ; static ArrayList < ArrayList < Integer > > adj = new ArrayList < ArrayList < Integer > > ( ) ; static void dfsUtil ( int u , int node , boolean visited [ ] , ArrayList < ArrayList < Integer > > road_used , int parent , int it ) { int c = 0 ; for ( int i = 0 ; i < node ; i ++ ) if ( visited [ i ] ) c ++ ; if ( c == node ) return ; visited [ u ] = true ; road_used . add ( new ArrayList < Integer > ( Arrays . asList ( parent , u ) ) ) ; System . out . print ( u + " ▁ " ) ; for ( int x : adj . get ( u ) ) { if ( ! visited [ x ] ) { dfsUtil ( x , node , visited , road_used , u , it + 1 ) ; } } for ( int y = 0 ; y < road_used . size ( ) ; y ++ ) { if ( road_used . get ( y ) . get ( 1 ) == u ) { dfsUtil ( road_used . get ( y ) . get ( 0 ) , node , visited , road_used , u , it + 1 ) ; } } } static void dfs ( int node ) { boolean [ ] visited = new boolean [ node ] ; ArrayList < ArrayList < Integer > > road_used = new ArrayList < ArrayList < Integer > > ( ) ; for ( int i = 0 ; i < node ; i ++ ) { visited [ i ] = false ; } dfsUtil ( 0 , node , visited , road_used , - 1 , 0 ) ; } static void insertEdge ( int u , int v ) { adj . get ( u ) . add ( v ) ; adj . get ( v ) . add ( u ) ; } public static void main ( String [ ] args ) { int node = 11 , edge = 13 ; for ( int i = 0 ; i < N ; i ++ ) { adj . add ( new ArrayList < Integer > ( ) ) ; } insertEdge ( 0 , 1 ) ; insertEdge ( 0 , 2 ) ; insertEdge ( 1 , 5 ) ; insertEdge ( 1 , 6 ) ; insertEdge ( 2 , 4 ) ; insertEdge ( 2 , 9 ) ; insertEdge ( 6 , 7 ) ; insertEdge ( 6 , 8 ) ; insertEdge ( 7 , 8 ) ; insertEdge ( 2 , 3 ) ; insertEdge ( 3 , 9 ) ; insertEdge ( 3 , 10 ) ; insertEdge ( 9 , 10 ) ; dfs ( node ) ; } }


"Print the Forests of a Binary Tree after removal of given Nodes | Java Program to implement the above approach ; Stores the nodes to be deleted ; Structure of a Tree node ; Function to create a new node ; Function to check whether the node needs to be deleted or not ; Function to perform tree pruning by performing post order traversal ; If the node needs to be deleted ; Store the its subtree ; Perform Inorder Traversal ; Function to print the forests ; Stores the remaining nodes ; Print the inorder traversal of Forests ; Driver Code"
How can the above be solved in Java?

import java . util . * ; class GFG { static HashMap < Integer , Boolean > mp = new HashMap < > ( ) ; 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 boolean deleteNode ( int nodeVal ) { return mp . containsKey ( nodeVal ) ; } static Node treePruning ( Node root , Vector < Node > result ) { if ( root == null ) return null ; root . left = treePruning ( root . left , result ) ; root . right = treePruning ( root . right , result ) ; if ( deleteNode ( root . key ) ) { if ( root . left != null ) { result . add ( root . left ) ; } if ( root . right != null ) { result . add ( root . right ) ; } return null ; } return root ; } static void printInorderTree ( Node root ) { if ( root == null ) return ; printInorderTree ( root . left ) ; System . out . print ( root . key + " ▁ " ) ; printInorderTree ( root . right ) ; } static void printForests ( Node root , int arr [ ] , int n ) { for ( int i = 0 ; i < n ; i ++ ) { mp . put ( arr [ i ] , true ) ; } Vector < Node > result = new Vector < > ( ) ; if ( treePruning ( root , result ) != null ) result . add ( root ) ; for ( int i = 0 ; i < result . size ( ) ; i ++ ) { printInorderTree ( result . get ( i ) ) ; System . out . println ( ) ; } } public static void main ( String [ ] args ) { Node root = newNode ( 1 ) ; root . left = newNode ( 12 ) ; root . right = newNode ( 13 ) ; root . right . left = newNode ( 14 ) ; root . right . right = newNode ( 15 ) ; root . right . left . left = newNode ( 21 ) ; root . right . left . right = newNode ( 22 ) ; root . right . right . left = newNode ( 23 ) ; root . right . right . right = newNode ( 24 ) ; int arr [ ] = { 14 , 23 , 1 } ; int n = arr . length ; printForests ( root , arr , n ) ; } }


"Print the Maximum Subarray Sum | Java program for the above approach ; Function to print the elements of Subarray with maximum sum ; Initialize currMax and globalMax with first value of nums ; Initialize endIndex startIndex , globalStartIndex ; Iterate for all the elemensts of the array ; Update currMax and startIndex ; startIndex = i ; update the new startIndex ; Update currMax ; Update globalMax anf globalMaxStartIndex ; Printing the elements of subarray with max sum ; Driver Code ; Given array arr [ ] ; Function call"
How can the above be solved in Java?

import java . util . * ; class GFG { static void SubarrayWithMaxSum ( Vector < Integer > nums ) { int currMax = nums . get ( 0 ) , globalMax = nums . get ( 0 ) ; int endIndex = 0 ; int startIndex = 0 , globalMaxStartIndex = 0 ; for ( int i = 1 ; i < nums . size ( ) ; ++ i ) { if ( nums . get ( i ) > nums . get ( i ) + currMax ) { currMax = nums . get ( i ) ; } else if ( nums . get ( i ) < nums . get ( i ) + currMax ) { currMax = nums . get ( i ) + currMax ; } if ( currMax > globalMax ) { globalMax = currMax ; endIndex = i ; globalMaxStartIndex = startIndex ; } } for ( int i = globalMaxStartIndex ; i <= endIndex ; ++ i ) { System . out . print ( nums . get ( i ) + " ▁ " ) ; } } public static void main ( String [ ] args ) { Vector < Integer > arr = new Vector < Integer > ( ) ; arr . add ( - 2 ) ; arr . add ( - 5 ) ; arr . add ( 6 ) ; arr . add ( - 2 ) ; arr . add ( - 3 ) ; arr . add ( 1 ) ; arr . add ( 5 ) ; arr . add ( - 6 ) ; SubarrayWithMaxSum ( arr ) ; } }


"Print the Maximum Subarray Sum | Java program for the above approach ; Function to print the elements of Subarray with maximum sum ; Initialize currMax and globalMax with first value of nums ; Iterate for all the elemensts of the array ; Update currMax ; Check if currMax is greater than globalMax ; Traverse in left direction to find start Index of subarray ; Decrement the start index ; Printing the elements of subarray with max sum ; Driver Code ; Given array arr [ ] ; Function call"
How can the above be solved in Java?

import java . util . * ; class GFG { static void SubarrayWithMaxSum ( Vector < Integer > nums ) { int endIndex = 0 , currMax = nums . get ( 0 ) ; int globalMax = nums . get ( 0 ) ; for ( int i = 1 ; i < nums . size ( ) ; ++ i ) { currMax = Math . max ( nums . get ( i ) , nums . get ( i ) + currMax ) ; if ( currMax > globalMax ) { globalMax = currMax ; endIndex = i ; } } int startIndex = endIndex ; while ( startIndex >= 0 ) { globalMax -= nums . get ( startIndex ) ; if ( globalMax == 0 ) break ; startIndex -- ; } for ( int i = startIndex ; i <= endIndex ; ++ i ) { System . out . print ( nums . get ( i ) + " ▁ " ) ; } } public static void main ( String [ ] args ) { Vector < Integer > arr = new Vector < Integer > ( ) ; arr . add ( - 2 ) ; arr . add ( - 5 ) ; arr . add ( 6 ) ; arr . add ( - 2 ) ; arr . add ( - 3 ) ; arr . add ( 1 ) ; arr . add ( 5 ) ; arr . add ( - 6 ) ; SubarrayWithMaxSum ( arr ) ; } }


"Print the arranged positions of characters to make palindrome | JAVA program to print original positions of characters in a String after rearranging and forming a palindrome ; Maximum number of characters ; Insert all positions of every character in the given String . ; find the number of odd elements . Takes O ( n ) ; A palindrome cannot contain more than 1 odd characters ; Print positions in first half of palindrome ; Consider one instance odd character ; Print positions in second half of palindrome ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { static int MAX = 256 ; static void printPalindromePos ( String str ) { Vector < Integer > [ ] pos = new Vector [ MAX ] ; for ( int i = 0 ; i < MAX ; i ++ ) pos [ i ] = new Vector < Integer > ( ) ; int n = str . length ( ) ; for ( int i = 0 ; i < n ; i ++ ) pos [ str . charAt ( i ) ] . add ( i + 1 ) ; int oddCount = 0 ; char oddChar = 0 ; for ( int i = 0 ; i < MAX ; i ++ ) { if ( pos [ i ] . size ( ) % 2 != 0 ) { oddCount ++ ; oddChar = ( char ) i ; } } if ( oddCount > 1 ) System . out . print ( " NO ▁ PALINDROME " ) ; for ( int i = 0 ; i < MAX ; i ++ ) { int mid = pos [ i ] . size ( ) / 2 ; for ( int j = 0 ; j < mid ; j ++ ) System . out . print ( pos [ i ] . get ( j ) + " ▁ " ) ; } if ( oddCount > 0 ) { int last = pos [ oddChar ] . size ( ) - 1 ; System . out . print ( pos [ oddChar ] . get ( last ) + " ▁ " ) ; pos [ oddChar ] . remove ( pos [ oddChar ] . size ( ) - 1 ) ; } for ( int i = MAX - 1 ; i >= 0 ; i -- ) { int count = pos [ i ] . size ( ) ; for ( int j = count / 2 ; j < count ; j ++ ) System . out . print ( pos [ i ] . get ( j ) + " ▁ " ) ; } } public static void main ( String [ ] args ) { String s = " geeksgk " ; printPalindromePos ( s ) ; } }


"Print the balanced bracket expression using given brackets | Java implementation of the above approach ; Function to print balanced bracket expression if it is possible ; If the condition is met ; Print brackets of type - 1 ; Print brackets of type - 3 ; Print brackets of type - 4 ; Print brackets of type - 2 ; If the condition is not met ; Driver code"
How can the above be solved in Java?

class GFG { static void printBalancedExpression ( int a , int b , int c , int d ) { if ( ( ( a == d ) && ( a != 0 ) ) || ( ( a == 0 ) && ( c == 0 ) && ( d == 0 ) ) ) { for ( int i = 1 ; i <= a ; i ++ ) System . out . print ( " ( ( " ) ; for ( int i = 1 ; i <= c ; i ++ ) System . out . print ( " ) ( " ) ; for ( int i = 1 ; i <= d ; i ++ ) System . out . print ( " ) ) " ) ; for ( int i = 1 ; i <= b ; i ++ ) System . out . print ( " ( ) " ) ; } else System . out . print ( - 1 ) ; } public static void main ( String args [ ] ) { int a = 3 , b = 1 , c = 4 , d = 3 ; printBalancedExpression ( a , b , c , d ) ; } }


"Print the final string when minimum value strings get concatenated in every operation | Java implementation of the approach ; Class that represents a pair ; Function that prints the final string ; Add all the strings and their corresponding values to the priority queue ; Take those two strings from the priority queue whose corresponding integer values are smaller and add them up as well as their values and add them back to the priority queue while there are more than a single element in the queue ; Get the minimum valued string ; Get the second minimum valued string ; Updated integer value ; Create new entry for the queue ; Add to the queue ; Print the only remaining string ; Driver code"
How can the above be solved in Java?

import java . util . * ; import java . lang . * ; class Priority { String s ; int count ; } class PQ implements Comparator < Priority > { public int compare ( Priority a , Priority b ) { if ( a . count > b . count ) return 1 ; else if ( a . count < b . count ) return - 1 ; return 0 ; } } class GFG { static void FindString ( String str [ ] , int num [ ] , int n ) { Comparator < Priority > comparator = new PQ ( ) ; PriorityQueue < Priority > p = new PriorityQueue < Priority > ( comparator ) ; for ( int i = 0 ; i < n ; i ++ ) { Priority x = new Priority ( ) ; x . s = str [ i ] ; x . count = num [ i ] ; p . add ( x ) ; } while ( p . size ( ) > 1 ) { Priority x = p . poll ( ) ; p . remove ( x ) ; Priority y = p . poll ( ) ; p . remove ( y ) ; int temp = x . count + y . count ; String sb = x . s + y . s ; Priority z = new Priority ( ) ; z . count = temp ; z . s = sb ; p . add ( z ) ; } Priority z = p . poll ( ) ; System . out . println ( z . s ) ; } public static void main ( String [ ] args ) { String str [ ] = { " Geeks " , " For " , " Geeks " } ; int num [ ] = { 2 , 3 , 7 } ; int n = num . length ; FindString ( str , num , n ) ; } }


"Print the first N terms of the series 6 , 28 , 66 , 120 , 190 , 276 , ... | Java program for the above approach ; Function to print the series ; Initialise the value of k with 2 ; Iterate from 1 to n ; Print each number ; Increment the value of K by 2 for next number ; Driver code ; Given number N ; Function Call"
How can the above be solved in Java?

class GFG { static void printSeries ( int n ) { int k = 2 ; for ( int i = 0 ; i < n ; i ++ ) { System . out . print ( k * ( 2 * k - 1 ) + " ▁ " ) ; k += 2 ; } System . out . println ( ) ; } public static void main ( String args [ ] ) { int N = 12 ; printSeries ( N ) ; } }


"Print the first and last character of each word in a String | Java program to print the first and last character of each word in a String ; Function to print the first and last character of each word . ; If it is the first word of the string then print it . ; If it is the last word of the string then also print it . ; If there is a space print the successor and predecessor to space . ; Driver code"
How can the above be solved in Java?

class GFG { static void FirstAndLast ( String str ) { int i ; for ( i = 0 ; i < str . length ( ) ; i ++ ) { if ( i == 0 ) System . out . print ( str . charAt ( i ) ) ; if ( i == str . length ( ) - 1 ) System . out . print ( str . charAt ( i ) ) ; if ( str . charAt ( i ) == ' ▁ ' ) { System . out . print ( str . charAt ( i - 1 ) + " ▁ " + str . charAt ( i + 1 ) ) ; } } } public static void main ( String args [ ] ) { String str = " Geeks ▁ for ▁ Geeks " ; FirstAndLast ( str ) ; } }


"Print the frequency of each character in Alphabetical order | Java implementation of the approach ; Function to print the frequency of each of the characters of s in alphabetical order ; To store the frequency of the characters ; Update the frequency array ; Print the frequency in alphatecial order ; If the current alphabet doesn 't  appear in the string ; Driver code"
How can the above be solved in Java?

class GFG { static int MAX = 26 ; static void compressString ( String s , int n ) { int freq [ ] = new int [ MAX ] ; for ( int i = 0 ; i < n ; i ++ ) { freq [ s . charAt ( i ) - ' a ' ] ++ ; } for ( int i = 0 ; i < MAX ; i ++ ) { if ( freq [ i ] == 0 ) continue ; System . out . print ( ( char ) ( i + ' a ' ) + " " + freq [ i ] ) ; } } public static void main ( String [ ] args ) { String s = " geeksforgeeks " ; int n = s . length ( ) ; compressString ( s , n ) ; } }


"Print the indices for every row of a grid from which escaping from the grid is possible | Java program for the above approach ; Function to find the row index for every row of a matrix from which one can exit the grid after entering from left ; Iterate over the range [ 0 , M - 1 ] ; Stores the direction from which a person enters a cell ; Row index from which one enters the grid ; Column index from which one enters the grid ; Iterate until j is atleast N - 1 ; If Mat [ i ] [ j ] is equal to 1 ; If entry is from left cell ; Decrement i by 1 ; Assign ' D ' to dir ; If entry is from upper cell ; Decrement j by 1 ; Assign ' R ' to dir ; If entry is from right cell ; Increment i by 1 ; Assign ' U ' to dir ; If entry is from bottom cell ; Increment j by 1 ; Assign ' L ' to dir ; Otherwise , ; If entry is from left cell ; Increment i by 1 ; Assign ' U ' to dir ; If entry is from upper cell ; Increment j by 1 ; Assign ' L ' to dir ; If entry is from right cell ; Decrement i by 1 ; Assign ' D ' to dir ; If entry is from lower cell ; Decrement j by 1 ; Assign ' R ' to dir ; If i or j is less than 0 or i is equal to M or j is equal to N ; If j is equal to N ; Otherwise ; Driver Code ; Input ; Function call"
How can the above be solved in Java?

import java . util . * ; class GFG { static void findPath ( int [ ] [ ] arr , int M , int N ) { for ( int row = 0 ; row < M ; row ++ ) { char dir = ' L ' ; int i = row ; int j = 0 ; while ( j < N ) { if ( arr [ i ] [ j ] == 1 ) { if ( dir == ' L ' ) { i -- ; dir = ' D ' ; } else if ( dir == ' U ' ) { j -- ; dir = ' R ' ; } else if ( dir == ' R ' ) { i ++ ; dir = ' U ' ; } else if ( dir == ' D ' ) { j ++ ; dir = ' L ' ; } } else { if ( dir == ' L ' ) { i ++ ; dir = ' U ' ; } else if ( dir == ' U ' ) { j ++ ; dir = ' L ' ; } else if ( dir == ' R ' ) { i -- ; dir = ' D ' ; } else if ( dir == ' D ' ) { j -- ; dir = ' R ' ; } } if ( i < 0 i == M j < 0 j == N ) break ; } if ( j == N ) System . out . print ( i + " ▁ " ) ; else System . out . print ( - 1 + " ▁ " ) ; } } public static void main ( String [ ] args ) { int [ ] [ ] arr = { { 1 , 1 , 0 , 1 } , { 1 , 1 , 0 , 0 } , { 1 , 0 , 0 , 0 } , { 1 , 1 , 0 , 1 } , { 0 , 1 , 0 , 1 } } ; int M = arr . length ; int N = arr [ 0 ] . length ; findPath ( arr , M , N ) ; } }


"Print the kth common factor of two numbers | Java program to find kth common factor of two numbers ; Returns k 'th common factor of x and y. ; Find smaller of two numbers ; Count common factors until we either reach small or count becomes k . ; If we reached small ; Driver code"
How can the above be solved in Java?

import java . lang . * ; class GFG { static int findKHCF ( int x , int y , int k ) { int small = Math . min ( x , y ) ; int count = 1 ; for ( int i = 2 ; i <= small ; i ++ ) { if ( x % i == 0 && y % i == 0 ) count ++ ; if ( count == k ) return i ; } return - 1 ; } public static void main ( String [ ] args ) { int x = 4 , y = 24 , k = 3 ; System . out . print ( findKHCF ( x , y , k ) ) ; } }


"Print the longest common substring | Java implementation to print the longest common substring ; function to find and print the longest common substring of X [ 0. . m - 1 ] and Y [ 0. . n - 1 ] ; Create a table to store lengths of longest common suffixes of substrings . Note that LCSuff [ i ] [ j ] contains length of longest common suffix of X [ 0. . i - 1 ] and Y [ 0. . j - 1 ] . The first row and first column entries have no logical meaning , they are used only for simplicity of program ; To store length of the longest common substring ; To store the index of the cell which contains the maximum value . This cell 's index helps in building  up the longest common substring from right to left. ; Following steps build LCSuff [ m + 1 ] [ n + 1 ] in bottom up fashion . ; if true , then no common substring exists ; allocate space for the longest common substring ; traverse up diagonally form the ( row , col ) cell until LCSuff [ row ] [ col ] != 0 ; resultStr = X . charAt ( row - 1 ) + resultStr ; or Y [ col - 1 ] ; move diagonally up to previous cell ; required longest common substring ; Driver program to test above function"
How can the above be solved in Java?

public class Longest_common_substr { static void printLCSubStr ( String X , String Y , int m , int n ) { int [ ] [ ] LCSuff = new int [ m + 1 ] [ n + 1 ] ; int len = 0 ; int row = 0 , col = 0 ; for ( int i = 0 ; i <= m ; i ++ ) { for ( int j = 0 ; j <= n ; j ++ ) { if ( i == 0 j == 0 ) LCSuff [ i ] [ j ] = 0 ; else if ( X . charAt ( i - 1 ) == Y . charAt ( j - 1 ) ) { LCSuff [ i ] [ j ] = LCSuff [ i - 1 ] [ j - 1 ] + 1 ; if ( len < LCSuff [ i ] [ j ] ) { len = LCSuff [ i ] [ j ] ; row = i ; col = j ; } } else LCSuff [ i ] [ j ] = 0 ; } } if ( len == 0 ) { System . out . println ( " No ▁ Common ▁ Substring " ) ; return ; } String resultStr = " " ; while ( LCSuff [ row ] [ col ] != 0 ) { -- len ; row -- ; col -- ; } System . out . println ( resultStr ) ; } public static void main ( String args [ ] ) { String X = " OldSite : GeeksforGeeks . org " ; String Y = " NewSite : GeeksQuiz . com " ; int m = X . length ( ) ; int n = Y . length ( ) ; printLCSubStr ( X , Y , m , n ) ; } }


"Print the longest leaf to leaf path in a Binary tree | Java program to print the longest leaf to leaf path ; Tree node structure used in the program ; Function to find height of a tree ; update the answer , because diameter of a tree is nothing but maximum value of ( left_height + right_height + 1 ) for each node ; save the root , this will help us finding the left and the right part of the diameter ; save the height of left & right subtree as well . ; prints the root to leaf path ; print left part of the path in reverse order ; this function finds out all the root to leaf paths ; append this node to the path array ; If it 's a leaf, so print the path that led to here ; print only one path which is equal to the height of the tree . ; otherwise try both subtrees ; Computes the diameter of a binary tree with given root . ; lh will store height of left subtree rh will store height of right subtree ; f is a flag whose value helps in printing left & right part of the diameter only once ; print the left part of the diameter ; print the right part of the diameter ; Driver code ; Enter the binary tree ... 1 / \ 2 3 / \ 4 5 \ / \ 8 6 7 / 9"
How can the above be solved in Java?

import java . io . * ; class Node { int data ; Node left , right ; Node ( int val ) { data = val ; left = right = null ; } } class GFG { static int ans , lh , rh , f ; static Node k ; public static Node Root ; static int height ( Node root ) { if ( root == null ) return 0 ; int left_height = height ( root . left ) ; int right_height = height ( root . right ) ; if ( ans < 1 + left_height + right_height ) { ans = 1 + left_height + right_height ; k = root ; lh = left_height ; rh = right_height ; } return 1 + Math . max ( left_height , right_height ) ; } static void printArray ( int [ ] ints , int len ) { int i ; if ( f == 0 ) { for ( i = len - 1 ; i >= 0 ; i -- ) { System . out . print ( ints [ i ] + " ▁ " ) ; } } else if ( f == 1 ) { for ( i = 0 ; i < len ; i ++ ) { System . out . print ( ints [ i ] + " ▁ " ) ; } } } static void printPathsRecur ( Node node , int [ ] path , int pathLen , int max ) { if ( node == null ) return ; path [ pathLen ] = node . data ; pathLen ++ ; if ( node . left == null && node . right == null ) { if ( pathLen == max && ( f == 0 f == 1 ) ) { printArray ( path , pathLen ) ; f = 2 ; } } else { printPathsRecur ( node . left , path , pathLen , max ) ; printPathsRecur ( node . right , path , pathLen , max ) ; } } static void diameter ( Node root ) { if ( root == null ) return ; ans = Integer . MIN_VALUE ; lh = 0 ; rh = 0 ; f = 0 ; int height_of_tree = height ( root ) ; int [ ] lPath = new int [ 100 ] ; int pathlen = 0 ; printPathsRecur ( k . left , lPath , pathlen , lh ) ; System . out . print ( k . data + " ▁ " ) ; int [ ] rPath = new int [ 100 ] ; f = 1 ; printPathsRecur ( k . right , rPath , pathlen , rh ) ; } public static void main ( String [ ] args ) { GFG . Root = new Node ( 1 ) ; GFG . Root . left = new Node ( 2 ) ; GFG . Root . right = new Node ( 3 ) ; GFG . Root . left . left = new Node ( 4 ) ; GFG . Root . left . right = new Node ( 5 ) ; GFG . Root . left . right . left = new Node ( 6 ) ; GFG . Root . left . right . right = new Node ( 7 ) ; GFG . Root . left . left . right = new...


"Print the longest palindromic prefix of a given string | Java program for the above approach ; Function to find the longest prefix which is palindromic ; Find the length of the given String ; For storing the length of longest prefix palindrome ; Loop to check the subString of all length from 1 to N which is palindrome ; String of length i ; To store the reversed of temp ; Reversing String temp2 ; If String temp is palindromic then update the length ; Print the palindromic String of max_len ; Driver Code ; Given String ; Function Call"
How can the above be solved in Java?

import java . util . * ; class GFG { static void LongestPalindromicPrefix ( String s ) { int n = s . length ( ) ; int max_len = 0 ; for ( int len = 1 ; len <= n ; len ++ ) { String temp = s . substring ( 0 , len ) ; String temp2 = temp ; temp2 = reverse ( temp2 ) ; if ( temp . equals ( temp2 ) ) { max_len = len ; } } System . out . print ( s . substring ( 0 , max_len ) ) ; } static String reverse ( String input ) { char [ ] a = input . toCharArray ( ) ; int l , r = a . length - 1 ; for ( l = 0 ; l < r ; l ++ , r -- ) { char temp = a [ l ] ; a [ l ] = a [ r ] ; a [ r ] = temp ; } return String . valueOf ( a ) ; } public static void main ( String [ ] args ) { String str = " abaab " ; LongestPalindromicPrefix ( str ) ; } }