"Connect nodes at same level |  ; initialize queue to hold nodes at same level ; adding nodes to tehe queue ; initializing prev to null ; i > 0 because when i is 0 prev points the last node of previous level , so we skip it ; pointing last node of the nth level to null ; Driver program to test above functions ; Constructed binary tree is 10 / \ 8 2 / 3 ; Populates nextRight pointer in all nodes ; Let us check the values of nextRight pointers"
How can the above be solved in Java?

import java . util . * ; import java . io . * ; class Node { int data ; Node left , right , nextRight ; Node ( int item ) { data = item ; left = right = nextRight = null ; } } public class BinaryTree { Node root ; void connect ( Node p ) { Queue < Node > q = new LinkedList < > ( ) ; q . add ( root ) ; Node temp = null ; while ( ! q . isEmpty ( ) ) { int n = q . size ( ) ; for ( int i = 0 ; i < n ; i ++ ) { Node prev = temp ; temp = q . poll ( ) ; if ( i > 0 ) prev . nextRight = temp ; if ( temp . left != null ) q . add ( temp . left ) ; if ( temp . right != null ) q . add ( temp . right ) ; } temp . nextRight = null ; } } public static void main ( String args [ ] ) { BinaryTree tree = new BinaryTree ( ) ; tree . root = new Node ( 10 ) ; tree . root . left = new Node ( 8 ) ; tree . root . right = new Node ( 2 ) ; tree . root . left . left = new Node ( 3 ) ; tree . connect ( tree . root ) ; System . out . println ( " Following ▁ are ▁ populated ▁ nextRight ▁ pointers ▁ in ▁ " + " the ▁ tree " + " ( -1 ▁ is ▁ printed ▁ if ▁ there ▁ is ▁ no ▁ nextRight ) " ) ; int a = tree . root . nextRight != null ? tree . root . nextRight . data : - 1 ; System . out . println ( " nextRight ▁ of ▁ " + tree . root . data + " ▁ is ▁ " + a ) ; int b = tree . root . left . nextRight != null ? tree . root . left . nextRight . data : - 1 ; System . out . println ( " nextRight ▁ of ▁ " + tree . root . left . data + " ▁ is ▁ " + b ) ; int c = tree . root . right . nextRight != null ? tree . root . right . nextRight . data : - 1 ; System . out . println ( " nextRight ▁ of ▁ " + tree . root . right . data + " ▁ is ▁ " + c ) ; int d = tree . root . left . left . nextRight != null ? tree . root . left . left . nextRight . data : - 1 ; System . out . println ( " nextRight ▁ of ▁ " + tree . root . left . left . data + " ▁ is ▁ " + d ) ; } }


"Connect nodes at same level | A binary tree node ; Sets the nextRight of root and calls connectRecur ( ) for other nodes ; Set the nextRight for root ; Set the next right for rest of the nodes ( other than root ) ; Set next right of all descendents of p . Assumption : p is a compete binary tree ; Base case ; Set the nextRight pointer for p 's left child ; Set the nextRight pointer for p 's right child  p->nextRight will be NULL if p is the right most child  at its level ; Set nextRight for other nodes in pre order fashion ; Driver program to test above functions ; Constructed binary tree is 10 / \ 8 2 / 3 ; Populates nextRight pointer in all nodes ; Let us check the values of nextRight pointers"
How can the above be solved in Java?

class Node { int data ; Node left , right , nextRight ; Node ( int item ) { data = item ; left = right = nextRight = null ; } } class BinaryTree { Node root ; void connect ( Node p ) { p . nextRight = null ; connectRecur ( p ) ; } void connectRecur ( Node p ) { if ( p == null ) return ; if ( p . left != null ) p . left . nextRight = p . right ; if ( p . right != null ) p . right . nextRight = ( p . nextRight != null ) ? p . nextRight . left : null ; connectRecur ( p . left ) ; connectRecur ( p . right ) ; } public static void main ( String args [ ] ) { BinaryTree tree = new BinaryTree ( ) ; tree . root = new Node ( 10 ) ; tree . root . left = new Node ( 8 ) ; tree . root . right = new Node ( 2 ) ; tree . root . left . left = new Node ( 3 ) ; tree . connect ( tree . root ) ; System . out . println ( " Following ▁ are ▁ populated ▁ nextRight ▁ pointers ▁ in ▁ " + " the ▁ tree " + " ( -1 ▁ is ▁ printed ▁ if ▁ there ▁ is ▁ no ▁ nextRight ) " ) ; int a = tree . root . nextRight != null ? tree . root . nextRight . data : - 1 ; System . out . println ( " nextRight ▁ of ▁ " + tree . root . data + " ▁ is ▁ " + a ) ; int b = tree . root . left . nextRight != null ? tree . root . left . nextRight . data : - 1 ; System . out . println ( " nextRight ▁ of ▁ " + tree . root . left . data + " ▁ is ▁ " + b ) ; int c = tree . root . right . nextRight != null ? tree . root . right . nextRight . data : - 1 ; System . out . println ( " nextRight ▁ of ▁ " + tree . root . right . data + " ▁ is ▁ " + c ) ; int d = tree . root . left . left . nextRight != null ? tree . root . left . left . nextRight . data : - 1 ; System . out . println ( " nextRight ▁ of ▁ " + tree . root . left . left . data + " ▁ is ▁ " + d ) ; } }


"Connell Sequence | Java code to generate first ' n ' terms of Connell Sequence ; Function to generate a fixed number of even or odd terms . The size of r decides whether numbers to be generated even or odd . ; Generating the first ' n ' terms of Connell Sequence ; A dummy 0 is inserted at the beginning for consistency ; Calling function gen ( ) to generate ' k ' number of terms ; Checking if ' n ' terms are already generated ; Removing the previously inserted dummy 0 ; Driver Code"
How can the above be solved in Java?

import java . util . * ; class GFG { static Vector < Long > gen ( long n , Vector < Long > r ) { long a = r . get ( r . size ( ) - 1 ) ; a ++ ; for ( int i = 1 ; i <= n ; a += 2 , i ++ ) { r . add ( a ) ; } return r ; } static Vector < Long > conell ( long n ) { Vector < Long > res = new Vector < Long > ( ) ; long k = 1 ; res . add ( 0L ) ; while ( true ) { res = gen ( k , res ) ; k ++ ; int j = res . size ( ) - 1 ; while ( j != n && j + k > n ) { k -- ; } if ( j >= n ) { break ; } } res . remove ( 0 ) ; return res ; } public static void main ( String [ ] args ) { long n = 10 ; System . out . println ( " The ▁ first ▁ " + n + " ▁ terms ▁ are " ) ; Vector < Long > res = conell ( n ) ; for ( int i = 0 ; i < res . size ( ) ; i ++ ) { System . out . print ( res . get ( i ) + " ▁ " ) ; } System . out . println ( ) ; } }


"Consecutive Prime numbers greater than equal to given number . | Java program for the above approach ; Function to check prime . ; It means it is not a prime ; No factor other than 1 therefore prime number ; Function to find out the required consecutive primes . ; Finding first prime just less than sqrt ( n ) . ; Finding prime just greater than sqrt ( n ) . ; Product of both prime is greater than n then print it ; Finding prime greater than second ; Driver code"
How can the above be solved in Java?

import java . io . * ; import java . util . * ; class GFG { static boolean is_prime ( long n ) { if ( n == 1 ) { return false ; } for ( long i = 2 ; i <= ( long ) Math . sqrt ( n ) ; i ++ ) { if ( n % i == 0 ) { return false ; } } return true ; } static void consecutive_primes ( long n ) { long first = - 1 , second = - 1 ; for ( long i = ( long ) Math . sqrt ( n ) ; i >= 2 ; i -- ) { if ( is_prime ( i ) ) { first = i ; break ; } } for ( long i = ( long ) Math . sqrt ( n ) + 1 ; i <= n / 2 ; i ++ ) { if ( is_prime ( i ) ) { second = i ; break ; } } if ( first * second >= n ) { System . out . println ( first + " ▁ " + second ) ; } else { for ( long i = second + 1 ; i <= n ; i ++ ) { if ( is_prime ( i ) ) { System . out . println ( second + " ▁ " + i ) ; return ; } } } } public static void main ( String args [ ] ) { long n = 14 ; consecutive_primes ( n ) ; } }


"Consecutive sequenced numbers in a string | Java Program to check whether a String contains consecutive sequential numbers or not ; function to check consecutive sequential number ; variable to store starting number ; length of the input String ; find the number till half of the String ; new String containing the starting substring of input String ; converting starting substring into number ; backing up the starting number in start ; while loop until the new_String is smaller than input String ; next number ; concatenate the next number ; check if new String becomes equal to input String ; if String doesn 't contains consecutive numbers ; Driver Code"
How can the above be solved in Java?

 class GFG { static int isConsecutive ( String str ) { int start ; int length = str . length ( ) ; for ( int i = 0 ; i < length / 2 ; i ++ ) { String new_str = str . substring ( 0 , i + 1 ) ; int num = Integer . parseInt ( new_str ) ; start = num ; while ( new_str . length ( ) < length ) { num ++ ; new_str = new_str + String . valueOf ( num ) ; } if ( new_str . equals ( str ) ) return start ; } return - 1 ; } public static void main ( String [ ] args ) { String str = "99100" ; System . out . println ( " String : ▁ " + str ) ; int start = isConsecutive ( str ) ; if ( start != - 1 ) System . out . println ( "Yes
" + start); else System . out . println ( " No " ) ; String str1 = "121315" ; System . out . println ( " String : " + str1); start = isConsecutive ( str1 ) ; if ( start != - 1 ) System . out . println ( "Yes
" + start); else System . out . println ( " No " ) ; } }


"Consecutive steps to roof top | Java code to find maximum number of consecutive steps . ; Function to count consecutive steps ; count the number of consecutive increasing height building ; Driver code"
How can the above be solved in Java?

import java . io . * ; class GFG { static int find_consecutive_steps ( int arr [ ] , int len ) { int count = 0 ; int maximum = 0 ; for ( int index = 1 ; index < len ; index ++ ) { if ( arr [ index ] > arr [ index - 1 ] ) count ++ ; else { maximum = Math . max ( maximum , count ) ; count = 0 ; } } return Math . max ( maximum , count ) ; } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 2 , 3 , 4 } ; int len = arr . length ; System . out . println ( find_consecutive_steps ( arr , len ) ) ; } }


"Constant time range add operation on an array | Java program to get updated array after many array range add operation ; Utility method to add value val , to range [ lo , hi ] ; Utility method to get actual array from operation array ; convert array into prefix sum array ; method to print final updated array ; Driver code ; Range add Queries"
How can the above be solved in Java?

 import java . io . * ; class GFG { static void add ( int arr [ ] , int N , int lo , int hi , int val ) { arr [ lo ] += val ; if ( hi != N - 1 ) arr [ hi + 1 ] -= val ; } static void updateArray ( int arr [ ] , int N ) { for ( int i = 1 ; i < N ; i ++ ) arr [ i ] += arr [ i - 1 ] ; } static void printArr ( int arr [ ] , int N ) { updateArray ( arr , N ) ; for ( int i = 0 ; i < N ; i ++ ) System . out . print ( " " + arr [ i ] + " ▁ " ) ; System . out . print ( "
"); } public static void main ( String [ ] args ) { int N = 6 ; int arr [ ] = new int [ N ] ; add ( arr , N , 0 , 2 , 100 ) ; add ( arr , N , 1 , 5 , 100 ) ; add ( arr , N , 2 , 3 , 100 ) ; printArr ( arr , N ) ; } }


"Construct BST from given preorder traversal | Set 1 | Construct a BST from given pre - order traversal for example if the given traversal is { 10 , 5 , 1 , 7 , 40 , 50 } , then the output should be the root of the following tree . 10 / \ 5 40 / \ \ 1 7 50 ; This will create the BST ; A wrapper function of createNode ; A function to print BST in inorder ; Driver Code"
How can the above be solved in Java?

class Node { int data ; Node left , right ; Node ( int data ) { this . data = data ; this . left = this . right = null ; } } class CreateBSTFromPreorder { private static Node node ; public static Node createNode ( Node node , int data ) { if ( node == null ) node = new Node ( data ) ; if ( node . data > data ) node . left = createNode ( node . left , data ) ; if ( node . data < data ) node . right = createNode ( node . right , data ) ; return node ; } public static void create ( int data ) { node = createNode ( node , data ) ; } public static void inorderRec ( Node root ) { if ( root != null ) { inorderRec ( root . left ) ; System . out . println ( root . data ) ; inorderRec ( root . right ) ; } } public static void main ( String [ ] args ) { int [ ] nodeData = { 10 , 5 , 1 , 7 , 40 , 50 } ; for ( int i = 0 ; i < nodeData . length ; i ++ ) { create ( nodeData [ i ] ) ; } inorderRec ( node ) ; } }


"Construct BST from its given level order traversal | Java implementation to construct a BST from its level order traversal ; node of a BST ; function to get a new node ; Allocate memory ; put in the data ; function to construct a BST from its level order traversal ; function to print the inorder traversal ; Driver code"
How can the above be solved in Java?

class GFG { static class Node { int data ; Node left , right ; } ; static Node getNode ( int data ) { Node newNode = new Node ( ) ; newNode . data = data ; newNode . left = newNode . right = null ; return newNode ; } static Node LevelOrder ( Node root , int data ) { if ( root == null ) { root = getNode ( data ) ; return root ; } if ( data <= root . data ) root . left = LevelOrder ( root . left , data ) ; else root . right = LevelOrder ( root . right , data ) ; return root ; } static Node constructBst ( int arr [ ] , int n ) { if ( n == 0 ) return null ; Node root = null ; for ( int i = 0 ; i < n ; i ++ ) root = LevelOrder ( root , arr [ i ] ) ; return root ; } static void inorderTraversal ( Node root ) { if ( root == null ) return ; inorderTraversal ( root . left ) ; System . out . print ( root . data + " ▁ " ) ; inorderTraversal ( root . right ) ; } public static void main ( String args [ ] ) { int arr [ ] = { 7 , 4 , 12 , 3 , 6 , 8 , 1 , 5 , 10 } ; int n = arr . length ; Node root = constructBst ( arr , n ) ; System . out . print ( " Inorder ▁ Traversal : ▁ " ) ; inorderTraversal ( root ) ; } }


"Construct Binary Tree from String with bracket representation | Java program to cona binary tree from the given String ; A binary tree node has data , pointer to left child and a pointer to right child ; Helper function that allocates a new node ; This funtcion is here just to test ; function to return the index of close parenthesis ; Inbuilt stack ; if open parenthesis , push it ; if close parenthesis ; if stack is empty , this is the required index ; if not found return - 1 ; function to contree from String ; Base case ; new root ; if next char is ' ( ' find the index of its complement ' ) ' ; if index found ; call for left subtree ; call for right subtree ; Driver Code"
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 node = new Node ( ) ; node . data = data ; node . left = node . right = null ; return ( node ) ; } static void preOrder ( Node node ) { if ( node == null ) return ; System . out . printf ( " % d ▁ " , node . data ) ; preOrder ( node . left ) ; preOrder ( node . right ) ; } static int findIndex ( String str , int si , int ei ) { if ( si > ei ) return - 1 ; Stack < Character > s = new Stack < > ( ) ; for ( int i = si ; i <= ei ; i ++ ) { if ( str . charAt ( i ) == ' ( ' ) s . add ( str . charAt ( i ) ) ; else if ( str . charAt ( i ) == ' ) ' ) { if ( s . peek ( ) == ' ( ' ) { s . pop ( ) ; if ( s . isEmpty ( ) ) return i ; } } } return - 1 ; } static Node treeFromString ( String str , int si , int ei ) { if ( si > ei ) return null ; Node root = newNode ( str . charAt ( si ) - '0' ) ; int index = - 1 ; if ( si + 1 <= ei && str . charAt ( si + 1 ) == ' ( ' ) index = findIndex ( str , si + 1 , ei ) ; if ( index != - 1 ) { root . left = treeFromString ( str , si + 2 , index - 1 ) ; root . right = treeFromString ( str , index + 2 , ei - 1 ) ; } return root ; } public static void main ( String [ ] args ) { String str = "4(2(3 ) ( 1 ) ) (6(5 ) ) " ; Node root = treeFromString ( str , 0 , str . length ( ) - 1 ) ; preOrder ( root ) ; } }


"Construct Binary Tree from given Parent Array representation | A binary tree node ; Creates a node with key as ' i ' . If i is root , then it changes root . If parent of i is not created , then it creates parent first ; If this node is already created ; Create a new node and set created [ i ] ; If ' i ' is root , change root pointer and return ; If parent is not created , then create parent first ; Find parent pointer ; If this is first child of parent ; If second child ; Creates tree from parent [ 0. . n - 1 ] and returns root of the created tree ; Create an array created [ ] to keep track of created nodes , initialize all entries as NULL ; For adding new line in a program ; Utility function to do inorder traversal ; Driver method"
How can the above be solved in Java?

class Node { int key ; Node left , right ; public Node ( int key ) { this . key = key ; left = right = null ; } } class BinaryTree { Node root ; void createNode ( int parent [ ] , int i , Node created [ ] ) { if ( created [ i ] != null ) return ; created [ i ] = new Node ( i ) ; if ( parent [ i ] == - 1 ) { root = created [ i ] ; return ; } if ( created [ parent [ i ] ] == null ) createNode ( parent , parent [ i ] , created ) ; Node p = created [ parent [ i ] ] ; if ( p . left == null ) p . left = created [ i ] ; else p . right = created [ i ] ; } Node createTree ( int parent [ ] , int n ) { Node [ ] created = new Node [ n ] ; for ( int i = 0 ; i < n ; i ++ ) created [ i ] = null ; for ( int i = 0 ; i < n ; i ++ ) createNode ( parent , i , created ) ; return root ; } void newLine ( ) { System . out . println ( " " ) ; } void inorder ( Node node ) { if ( node != null ) { inorder ( node . left ) ; System . out . print ( node . key + " ▁ " ) ; inorder ( node . right ) ; } } public static void main ( String [ ] args ) { BinaryTree tree = new BinaryTree ( ) ; int parent [ ] = new int [ ] { - 1 , 0 , 0 , 1 , 1 , 3 , 5 } ; int n = parent . length ; Node node = tree . createTree ( parent , n ) ; System . out . println ( " Inorder ▁ traversal ▁ of ▁ constructed ▁ tree ▁ " ) ; tree . inorder ( node ) ; tree . newLine ( ) ; } }


"Construct Full Binary Tree from given preorder and postorder traversals | Java program for construction of full binary tree ; A binary tree node has data , pointer to left child and a pointer to right child ; A recursive function to construct Full from pre [ ] and post [ ] . preIndex is used to keep track of index in pre [ ] . l is low index and h is high index for the current subarray in post [ ] ; Base case ; The first node in preorder traversal is root . So take the node at preIndex from preorder and make it root , and increment preIndex ; If the current subarry has only one element , no need to recur or preIndex > size after incrementing ; Search the next element of pre [ ] in post [ ] ; Use the index of element found in postorder to divide postorder array in two parts . Left subtree and right subtree ; The main function to construct Full Binary Tree from given preorder and postorder traversals . This function mainly uses constructTreeUtil ( ) ; A utility function to print inorder traversal of a Binary Tree ; Driver program to test above functions"
How can the above be solved in Java?

public class fullbinarytreepostpre { static int preindex ; static class node { int data ; node left , right ; public node ( int data ) { this . data = data ; } } static node constructTreeUtil ( int pre [ ] , int post [ ] , int l , int h , int size ) { if ( preindex >= size l > h ) return null ; node root = new node ( pre [ preindex ] ) ; preindex ++ ; if ( l == h preindex >= size ) return root ; int i ; for ( i = l ; i <= h ; i ++ ) { if ( post [ i ] == pre [ preindex ] ) break ; } if ( i <= h ) { root . left = constructTreeUtil ( pre , post , l , i , size ) ; root . right = constructTreeUtil ( pre , post , i + 1 , h , size ) ; } return root ; } static node constructTree ( int pre [ ] , int post [ ] , int size ) { preindex = 0 ; return constructTreeUtil ( pre , post , 0 , size - 1 , size ) ; } static void printInorder ( node root ) { if ( root == null ) return ; printInorder ( root . left ) ; System . out . print ( root . data + " ▁ " ) ; printInorder ( root . right ) ; } public static void main ( String [ ] args ) { int pre [ ] = { 1 , 2 , 4 , 8 , 9 , 5 , 3 , 6 , 7 } ; int post [ ] = { 8 , 9 , 4 , 5 , 2 , 6 , 7 , 3 , 1 } ; int size = pre . length ; node root = constructTree ( pre , post , size ) ; System . out . println ( " Inorder ▁ traversal ▁ of ▁ the ▁ constructed ▁ tree : " ) ; printInorder ( root ) ; } }


"Construct Full Binary Tree using its Preorder traversal and Preorder traversal of its mirror tree | Java program to construct full binary tree using its preorder traversal and preorder traversal of its mirror tree ; A Binary Tree Node ; Utility function to create a new tree node ; A utility function to print inorder traversal of a Binary Tree ; A recursive function to con Full binary tree from pre [ ] and preM [ ] . preIndex is used to keep track of index in pre [ ] . l is low index and h is high index for the current subarray in preM [ ] ; Base case ; The first node in preorder traversal is root . So take the node at preIndex from preorder and make it root , and increment preIndex ; If the current subarry has only one element , no need to recur ; Search the next element of pre [ ] in preM [ ] ; con left and right subtrees recursively ; return root ; function to con full binary tree using its preorder traversal and preorder traversal of its mirror tree ; Driver code"
How can the above be solved in Java?

class GFG { static class Node { int data ; Node left , right ; } ; static class INT { int a ; INT ( int a ) { this . a = a ; } } static Node newNode ( int data ) { Node temp = new Node ( ) ; temp . data = data ; temp . left = temp . right = null ; return temp ; } static void printInorder ( Node node ) { if ( node == null ) return ; printInorder ( node . left ) ; System . out . printf ( " % d ▁ " , node . data ) ; printInorder ( node . right ) ; } static Node conBinaryTreeUtil ( int pre [ ] , int preM [ ] , INT preIndex , int l , int h , int size ) { if ( preIndex . a >= size l > h ) return null ; Node root = newNode ( pre [ preIndex . a ] ) ; ++ ( preIndex . a ) ; if ( l == h ) return root ; int i ; for ( i = l ; i <= h ; ++ i ) if ( pre [ preIndex . a ] == preM [ i ] ) break ; if ( i <= h ) { root . left = conBinaryTreeUtil ( pre , preM , preIndex , i , h , size ) ; root . right = conBinaryTreeUtil ( pre , preM , preIndex , l + 1 , i - 1 , size ) ; } return root ; } static void conBinaryTree ( Node root , int pre [ ] , int preMirror [ ] , int size ) { INT preIndex = new INT ( 0 ) ; int preMIndex = 0 ; root = conBinaryTreeUtil ( pre , preMirror , preIndex , 0 , size - 1 , size ) ; printInorder ( root ) ; } public static void main ( String args [ ] ) { int preOrder [ ] = { 1 , 2 , 4 , 5 , 3 , 6 , 7 } ; int preOrderMirror [ ] = { 1 , 3 , 7 , 6 , 2 , 5 , 4 } ; int size = preOrder . length ; Node root = new Node ( ) ; conBinaryTree ( root , preOrder , preOrderMirror , size ) ; } }


"Construct MEX array from the given array | Java program for the above approach ; Function to construct array B [ ] that stores MEX of array A [ ] excluding A [ i ] ; Stores elements present in arr [ ] ; Mark all values 1 , if present ; Initialize variable to store MEX ; Find MEX of arr [ ] ; Stores MEX for all indices ; Traverse the given array ; Update MEX ; MEX default ; Print the array B ; Driver Code ; Given array arr [ ] ; Size of array ; Function call"
How can the above be solved in Java?

import java . util . * ; class GFG { static int MAXN = 100001 ; static void constructMEX ( int arr [ ] , int N ) { int hash [ ] = new int [ MAXN ] ; for ( int i = 0 ; i < N ; i ++ ) { hash [ i ] = 0 ; } for ( int i = 0 ; i < N ; i ++ ) { hash [ arr [ i ] ] = 1 ; } int MexOfArr = 0 ; for ( int i = 1 ; i < MAXN ; i ++ ) { if ( hash [ i ] == 0 ) { MexOfArr = i ; break ; } } int B [ ] = new int [ N ] ; for ( int i = 0 ; i < N ; i ++ ) { if ( arr [ i ] < MexOfArr ) B [ i ] = arr [ i ] ; else B [ i ] = MexOfArr ; } for ( int i = 0 ; i < N ; i ++ ) System . out . print ( B [ i ] + " ▁ " ) ; } public static void main ( String [ ] args ) { int arr [ ] = { 2 , 1 , 5 , 3 } ; int N = arr . length ; constructMEX ( arr , N ) ; } }


"Construct Special Binary Tree from given Inorder traversal | A binary tree node has data , pointer to left child and a pointer to right child ; Recursive function to construct binary of size len from Inorder traversal inorder [ ] . Initial values of start and end should be 0 and len - 1. ; Find index of the maximum element from Binary Tree ; Pick the maximum value and make it root ; If this is the only element in inorder [ start . . end ] , then return it ; Using index in Inorder traversal , construct left and right subtress ; Function to find index of the maximum value in arr [ start ... end ] ; This funtcion is here just to test buildTree ( ) ; first recur on left child ; then print the data of node ; now recur on right child ; Driver code ; Assume that inorder traversal of following tree is given 40 / \ 10 30 / \ 5 28 ; Let us test the built tree by printing Inorder traversal"
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 ; Node buildTree ( int inorder [ ] , int start , int end , Node node ) { if ( start > end ) return null ; int i = max ( inorder , start , end ) ; node = new Node ( inorder [ i ] ) ; if ( start == end ) return node ; node . left = buildTree ( inorder , start , i - 1 , node . left ) ; node . right = buildTree ( inorder , i + 1 , end , node . right ) ; return node ; } int max ( int arr [ ] , int strt , int end ) { int i , max = arr [ strt ] , maxind = strt ; for ( i = strt + 1 ; i <= end ; i ++ ) { if ( arr [ i ] > max ) { max = arr [ i ] ; maxind = i ; } } return maxind ; } void printInorder ( Node node ) { if ( node == null ) return ; printInorder ( node . left ) ; System . out . print ( node . data + " ▁ " ) ; printInorder ( node . right ) ; } public static void main ( String args [ ] ) { BinaryTree tree = new BinaryTree ( ) ; int inorder [ ] = new int [ ] { 5 , 10 , 40 , 30 , 28 } ; int len = inorder . length ; Node mynode = tree . buildTree ( inorder , 0 , len - 1 , tree . root ) ; System . out . println ( " Inorder ▁ traversal ▁ of ▁ the ▁ constructed ▁ tree ▁ is ▁ " ) ; tree . printInorder ( mynode ) ; } }


"Construct Tree from given Inorder and Preorder traversals | A binary tree node has data , pointer to left child and a pointer to right child ; Recursive function to construct binary of size len from Inorder traversal in [ ] and Preorder traversal pre [ ] . Initial values of inStrt and inEnd should be 0 and len - 1. The function doesn 't do any error checking for cases where  inorder and preorder do not form a tree  ; Pick current node from Preorder traversal using preIndex and increment preIndex ; If this node has no children then return ; Else find the index of this node in Inorder traversal ; Using index in Inorder traversal , construct left and right subtress ; Function to find index of value in arr [ start ... end ] The function assumes that value is present in in [ ] ; This funtcion is here just to test buildTree ( ) ; first recur on left child ; then print the data of node ; now recur on right child ; driver program to test above functions ; building the tree by printing inorder traversal"
How can the above be solved in Java?

class Node { char data ; Node left , right ; Node ( char item ) { data = item ; left = right = null ; } } class BinaryTree { Node root ; static int preIndex = 0 ; Node buildTree ( char in [ ] , char pre [ ] , int inStrt , int inEnd ) { if ( inStrt > inEnd ) return null ; Node tNode = new Node ( pre [ preIndex ++ ] ) ; if ( inStrt == inEnd ) return tNode ; int inIndex = search ( in , inStrt , inEnd , tNode . data ) ; tNode . left = buildTree ( in , pre , inStrt , inIndex - 1 ) ; tNode . right = buildTree ( in , pre , inIndex + 1 , inEnd ) ; return tNode ; } int search ( char arr [ ] , int strt , int end , char value ) { int i ; for ( i = strt ; i <= end ; i ++ ) { if ( arr [ i ] == value ) return i ; } return i ; } void printInorder ( Node node ) { if ( node == null ) return ; printInorder ( node . left ) ; System . out . print ( node . data + " ▁ " ) ; printInorder ( node . right ) ; } public static void main ( String args [ ] ) { BinaryTree tree = new BinaryTree ( ) ; char in [ ] = new char [ ] { ' D ' , ' B ' , ' E ' , ' A ' , ' F ' , ' C ' } ; char pre [ ] = new char [ ] { ' A ' , ' B ' , ' D ' , ' E ' , ' C ' , ' F ' } ; int len = in . length ; Node root = tree . buildTree ( in , pre , 0 , len - 1 ) ; System . out . println ( " Inorder ▁ traversal ▁ of ▁ constructed ▁ tree ▁ is ▁ : ▁ " ) ; tree . printInorder ( root ) ; } }


"Construct Tree from given Inorder and Preorder traversals | Java program to construct a tree using inorder and preorder traversal ; Function to build tree using given traversal ; Function to print tree in Inorder ; first recur on left child ; then print the data of node ; now recur on right child ; driver program to test above functions"
How can the above be solved in Java?

import java . util . * ; public class TreeNode { int val ; TreeNode left ; TreeNode right ; TreeNode ( int x ) { val = x ; } } class BinaryTree { static Set < TreeNode > set = new HashSet < > ( ) ; static Stack < TreeNode > stack = new Stack < > ( ) ; public TreeNode buildTree ( int [ ] preorder , int [ ] inorder ) { TreeNode root = null ; for ( int pre = 0 , in = 0 ; pre < preorder . length ; ) { TreeNode node = null ; do { node = new TreeNode ( preorder [ pre ] ) ; if ( root == null ) { root = node ; } if ( ! stack . isEmpty ( ) ) { if ( set . contains ( stack . peek ( ) ) ) { set . remove ( stack . peek ( ) ) ; stack . pop ( ) . right = node ; } else { stack . peek ( ) . left = node ; } } stack . push ( node ) ; } while ( preorder [ pre ++ ] != inorder [ in ] && pre < preorder . length ) ; node = null ; while ( ! stack . isEmpty ( ) && in < inorder . length && stack . peek ( ) . val == inorder [ in ] ) { node = stack . pop ( ) ; in ++ ; } if ( node != null ) { set . add ( node ) ; stack . push ( node ) ; } } return root ; } void printInorder ( TreeNode node ) { if ( node == null ) return ; printInorder ( node . left ) ; System . out . print ( node . val + " ▁ " ) ; printInorder ( node . right ) ; } public static void main ( String args [ ] ) { BinaryTree tree = new BinaryTree ( ) ; int in [ ] = new int [ ] { 9 , 8 , 4 , 2 , 10 , 5 , 10 , 1 , 6 , 3 , 13 , 12 , 7 } ; int pre [ ] = new int [ ] { 1 , 2 , 4 , 8 , 9 , 5 , 10 , 10 , 3 , 6 , 7 , 12 , 13 } ; int len = in . length ; TreeNode root = tree . buildTree ( pre , in ) ; tree . printInorder ( root ) ; } }


"Construct Tree from given Inorder and Preorder traversals | Java program to construct tree using inorder and preorder traversals ; A binary tree node has data , pointer to left child and a pointer to right child ; Store indexes of all items so that we we can quickly find later ; Recursive function to construct binary of size len from Inorder traversal in [ ] and Preorder traversal pre [ ] . Initial values of inStrt and inEnd should be 0 and len - 1. The function doesn 't do any error  checking for cases where inorder and preorder  do not form a tree  ; Pick current node from Preorder traversal using preIndex and increment preIndex ; If this node has no children then return ; Else find the index of this node in Inorder traversal ; Using index in Inorder traversal , construct left and right subtress ; This function mainly creates an unordered_map , then calls buildTree ( ) ; This funtcion is here just to test buildTree ( ) ; Driver code ; Let us test the built tree by printing Insorder traversal"
How can the above be solved in Java?

import java . io . * ; import java . util . * ; class Node { char data ; Node left , right ; Node ( char item ) { data = item ; left = right = null ; } } class Tree { public static Node root ; static HashMap < Character , Integer > mp = new HashMap < > ( ) ; static int preIndex = 0 ; public static Node buildTree ( char [ ] in , char [ ] pre , int inStrt , int inEnd ) { if ( inStrt > inEnd ) { return null ; } char curr = pre [ preIndex ++ ] ; Node tNode ; tNode = new Node ( curr ) ; if ( inStrt == inEnd ) { return tNode ; } int inIndex = mp . get ( curr ) ; tNode . left = buildTree ( in , pre , inStrt , inIndex - 1 ) ; tNode . right = buildTree ( in , pre , inIndex + 1 , inEnd ) ; return tNode ; } public static Node buldTreeWrap ( char [ ] in , char [ ] pre , int len ) { for ( int i = 0 ; i < len ; i ++ ) { mp . put ( in [ i ] , i ) ; } return buildTree ( in , pre , 0 , len - 1 ) ; } static void printInorder ( Node node ) { if ( node == null ) { return ; } printInorder ( node . left ) ; System . out . print ( node . data + " ▁ " ) ; printInorder ( node . right ) ; } public static void main ( String [ ] args ) { char [ ] in = { ' D ' , ' B ' , ' E ' , ' A ' , ' F ' , ' C ' } ; char [ ] pre = { ' A ' , ' B ' , ' D ' , ' E ' , ' C ' , ' F ' } ; int len = in . length ; Tree . root = buldTreeWrap ( in , pre , len ) ; System . out . println ( " Inorder ▁ traversal ▁ of ▁ the ▁ constructed ▁ tree ▁ is " ) ; printInorder ( root ) ; } }


"Construct XOR tree by Given leaf nodes of Perfect Binary Tree | Java implementation of the above approach ; Maximum size for xor tree ; Allocating space to xor tree ; A recursive function that constructs xor tree for vector array [ start ... . . end ] . x is index of current node in XOR tree ; If there is one element in vector array , store it in current node of XOR tree ; System . out . print ( xor_tree [ x ] + " ▁ x " ; ; for left subtree ; for right subtree ; for getting the middle index from corner indexes . ; Build the left and the right subtrees by xor operation ; merge the left and right subtrees by XOR operation ; Function to conXOR tree from the given vector array . This function calls construct_Xor_Tree_Util ( ) to fill the allocated memory of xor_tree vector array ; Driver Code ; leaf nodes of Perfect Binary Tree ; Build the xor tree ; Height of xor tree ; Maximum size of xor tree ; Root node is at index 0 considering 0 - based indexing in XOR Tree ; print value at root node"
How can the above be solved in Java?

 class GFG { static int maxsize = 100005 ; static int [ ] xor_tree = new int [ maxsize ] ; static void construct_Xor_Tree_Util ( int [ ] current , int start , int end , int x ) { if ( start == end ) { xor_tree [ x ] = current [ start ] ; return ; } int left = x * 2 + 1 ; int right = x * 2 + 2 ; int mid = start + ( end - start ) / 2 ; construct_Xor_Tree_Util ( current , start , mid , left ) ; construct_Xor_Tree_Util ( current , mid + 1 , end , right ) ; xor_tree [ x ] = ( xor_tree [ left ] ^ xor_tree [ right ] ) ; } static void construct_Xor_Tree ( int [ ] arr , int n ) { construct_Xor_Tree_Util ( arr , 0 , n - 1 , 0 ) ; } public static void main ( String [ ] args ) { int [ ] leaf_nodes = { 40 , 32 , 12 , 1 , 4 , 3 , 2 , 7 } ; int n = leaf_nodes . length ; construct_Xor_Tree ( leaf_nodes , n ) ; int x = ( int ) ( Math . ceil ( Math . log ( n ) ) ) ; int max_size = 2 * ( int ) Math . pow ( 2 , x ) - 1 ; System . out . print ( "Nodes of the XOR Tree:
"); for ( int i = 0 ; i < max_size ; i ++ ) { System . out . print ( xor_tree [ i ] + " ▁ " ) ; } int root = 0 ; System . out . print ( " Root : " + xor_tree[root]); } }


"Construct a Binary Tree from Postorder and Inorder | A binary tree node has data , pointer to left child and a pointer to right child ; Recursive function to construct binary of size n from Inorder traversal in [ ] and Postrder traversal post [ ] . Initial values of inStrt and inEnd should be 0 and n - 1. The function doesn 't do any error  checking for cases where inorder and postorder  do not form a tree  ; Base case ; Pick current node from Postrder traversal using postIndex and decrement postIndex ; If this node has no children then return ; Else find the index of this node in Inorder traversal ; Using index in Inorder traversal , construct left and right subtress ; Function to find index of value in arr [ start ... end ] The function assumes that value is postsent in in [ ] ; This funtcion is here just to test ; Driver Code"
How can the above be solved in Java?

class Node { int data ; Node left , right ; public Node ( int data ) { this . data = data ; left = right = null ; } } class BinaryTree { Node buildUtil ( int in [ ] , int post [ ] , int inStrt , int inEnd , int postStrt , int postEnd ) { if ( inStrt > inEnd ) return null ; Node node = new Node ( post [ postEnd ] ) ; if ( inStrt == inEnd ) return node ; int iIndex = search ( in , inStrt , inEnd , node . data ) ; node . left = buildUtil ( in , post , inStrt , iIndex - 1 , postStrt , postStrt - inStrt + iIndex - 1 ) ; node . right = buildUtil ( in , post , iIndex + 1 , inEnd , postEnd - inEnd + iIndex , postEnd - 1 ) ; return node ; } int search ( int arr [ ] , int strt , int end , int value ) { int i ; for ( i = strt ; i <= end ; i ++ ) { if ( arr [ i ] == value ) break ; } return i ; } void preOrder ( Node node ) { if ( node == null ) return ; System . out . print ( node . data + " ▁ " ) ; preOrder ( node . left ) ; preOrder ( node . right ) ; } public static void main ( String [ ] args ) { BinaryTree tree = new BinaryTree ( ) ; int in [ ] = new int [ ] { 4 , 8 , 2 , 5 , 1 , 6 , 3 , 7 } ; int post [ ] = new int [ ] { 8 , 4 , 5 , 2 , 6 , 7 , 3 , 1 } ; int n = in . length ; Node root = tree . buildUtil ( in , post , 0 , n - 1 , 0 , n - 1 ) ; System . out . println ( " Preorder ▁ of ▁ the ▁ constructed ▁ tree ▁ : ▁ " ) ; tree . preOrder ( root ) ; } }


"Construct a Binary Tree from Postorder and Inorder | Java program for above approach ; Node class ; Constructor ; Tree building function ; Create Stack of type Node * ; Create HashSet of type Node * ; Initialise postIndex with n - 1 ; Initialise root with null ; Initialise node with NULL ; Run do - while loop ; Initialise node with new Node ( post [ p ] ) ; ; Check is root is equal to NULL ; If size of set is greater than 0 ; If st . peek ( ) is present in the set s ; If the stack is not empty and st . top ( ) . data is equal to in [ i ] ; Pop elements from stack ; If node not equal to NULL ; Return root ; For print preOrder Traversal ; Driver Code ; Function Call ; Function Call for preOrder"
How can the above be solved in Java?

 import java . io . * ; import java . util . * ; class GFG { static class Node { int data ; Node left , right ; Node ( int x ) { data = x ; left = right = null ; } } static Node buildTree ( int in [ ] , int post [ ] , int n ) { Stack < Node > st = new Stack < > ( ) ; HashSet < Node > s = new HashSet < > ( ) ; int postIndex = n - 1 ; Node root = null ; for ( int p = n - 1 , i = n - 1 ; p >= 0 { Node node = null ; do { node = new Node ( post [ p ] ) ; if ( root == null ) { root = node ; } if ( st . size ( ) > 0 ) { if ( s . contains ( st . peek ( ) ) ) { s . remove ( st . peek ( ) ) ; st . peek ( ) . left = node ; st . pop ( ) ; } else { st . peek ( ) . right = node ; } } st . push ( node ) ; } while ( post [ p -- ] != in [ i ] && p >= 0 ) ; node = null ; while ( st . size ( ) > 0 && i >= 0 && st . peek ( ) . data == in [ i ] ) { node = st . peek ( ) ; st . pop ( ) ; i -- ; } if ( node != null ) { s . add ( node ) ; st . push ( node ) ; } } return root ; } static void preOrder ( Node node ) { if ( node == null ) return ; System . out . printf ( " % d ▁ " , node . data ) ; preOrder ( node . left ) ; preOrder ( node . right ) ; } public static void main ( String [ ] args ) { int in [ ] = { 4 , 8 , 2 , 5 , 1 , 6 , 3 , 7 } ; int post [ ] = { 8 , 4 , 5 , 2 , 6 , 7 , 3 , 1 } ; int n = in . length ; Node root = buildTree ( in , post , n ) ; System . out . print ( "Preorder of the constructed tree :
"); preOrder ( root ) ; } }


"Construct a Binary Tree from Postorder and Inorder | Java program to contree using inorder and postorder traversals ; A binary tree node has data , pointer to left child and a pointer to right child ; Recursive function to conbinary of size n from Inorder traversal in [ ] and Postorder traversal post [ ] . Initial values of inStrt and inEnd should be 0 and n - 1. The function doesn 't do any error checking for cases where inorder and postorder do not form a tree  ; Base case ; Pick current node from Postorder traversal using postIndex and decrement postIndex ; If this node has no children then return ; Else find the index of this node in Inorder traversal ; Using index in Inorder traversal , con left and right subtress ; This function mainly creates an unordered_map , then calls buildTreeUtil ( ) ; Store indexes of all items so that we we can quickly find later ; Index in postorder ; Helper function that allocates a new node ; This funtcion is here just to test ; Driver code"
How can the above be solved in Java?

 import java . util . * ; class GFG { static class Node { int data ; Node left , right ; } ; static Node buildUtil ( int in [ ] , int post [ ] , int inStrt , int inEnd ) { if ( inStrt > inEnd ) return null ; int curr = post [ index ] ; Node node = newNode ( curr ) ; ( index ) -- ; if ( inStrt == inEnd ) return node ; int iIndex = mp . get ( curr ) ; node . right = buildUtil ( in , post , iIndex + 1 , inEnd ) ; node . left = buildUtil ( in , post , inStrt , iIndex - 1 ) ; return node ; } static HashMap < Integer , Integer > mp = new HashMap < Integer , Integer > ( ) ; static int index ; static Node buildTree ( int in [ ] , int post [ ] , int len ) { for ( int i = 0 ; i < len ; i ++ ) mp . put ( in [ i ] , i ) ; index = len - 1 ; return buildUtil ( in , post , 0 , len - 1 ) ; } static Node newNode ( int data ) { Node node = new Node ( ) ; node . data = data ; node . left = node . right = null ; return ( node ) ; } static void preOrder ( Node node ) { if ( node == null ) return ; System . out . printf ( " % d ▁ " , node . data ) ; preOrder ( node . left ) ; preOrder ( node . right ) ; } public static void main ( String [ ] args ) { int in [ ] = { 4 , 8 , 2 , 5 , 1 , 6 , 3 , 7 } ; int post [ ] = { 8 , 4 , 5 , 2 , 6 , 7 , 3 , 1 } ; int n = in . length ; Node root = buildTree ( in , post , n ) ; System . out . print ( "Preorder of the constructed tree :
"); preOrder ( root ) ; } }


"Construct a Doubly linked linked list from 2D Matrix | Java program to construct a Doubly linked linked list from 2D Matrix ; define dimension of matrix ; struct node of doubly linked list with four pointer next , prev , up , down ; function to create a new node ; function to construct the doubly linked list ; Create Node with value contain in matrix at index ( i , j ) ; Assign address of curr into the prev pointer of temp ; Assign address of curr into the up pointer of temp ; Recursive call for next pointer ; Recursive call for down pointer ; Return newly constructed node whose all four node connected at it 's appropriate position ; Function to construct the doubly linked list ; function call for construct the doubly linked list ; function for displaying doubly linked list data ; pointer to move right ; pointer to move down ; loop till node . down is not null ; loop till node . right is not null ; driver code ; initialise matrix"
How can the above be solved in Java?

 import java . util . * ; class GFG { static int dim = 3 ; static class Node { int data ; Node next ; Node prev ; Node up ; Node down ; } ; static Node createNode ( int data ) { Node temp = new Node ( ) ; temp . data = data ; temp . next = null ; temp . prev = null ; temp . up = null ; temp . down = null ; return temp ; } static Node constructDoublyListUtil ( int mtrx [ ] [ ] , int i , int j , Node curr ) { if ( i >= dim j >= dim ) { return null ; } Node temp = createNode ( mtrx [ i ] [ j ] ) ; temp . prev = curr ; temp . up = curr ; temp . next = constructDoublyListUtil ( mtrx , i , j + 1 , temp ) ; temp . down = constructDoublyListUtil ( mtrx , i + 1 , j , temp ) ; return temp ; } static Node constructDoublyList ( int mtrx [ ] [ ] ) { return constructDoublyListUtil ( mtrx , 0 , 0 , null ) ; } static void display ( Node head ) { Node rPtr ; Node dPtr = head ; while ( dPtr != null ) { rPtr = dPtr ; while ( rPtr != null ) { System . out . print ( rPtr . data + " ▁ " ) ; rPtr = rPtr . next ; } System . out . print ( "
"); dPtr = dPtr . down ; } } public static void main ( String args [ ] ) { int mtrx [ ] [ ] = { { 1 , 2 , 3 } , { 4 , 5 , 6 } , { 7 , 8 , 9 } } ; Node list = constructDoublyList ( mtrx ) ; display ( list ) ; } }


"Construct a List using the given Q XOR queries | Java program for the above approach ; Function to return required list after performing all the queries ; Store cumulative Bitwise XOR ; Initialize final list to return ; Perform each query ; The initial value of 0 ; Sort the list ; Return final list ; Driver Code ; Given Queries ; Function Call"
How can the above be solved in Java?

import java . util . * ; class GFG { static List < Integer > ConstructList ( int [ ] [ ] Q ) { int xor = 0 ; List < Integer > ans = new ArrayList < > ( ) ; for ( int i = Q . length - 1 ; i >= 0 ; i -- ) { if ( Q [ i ] [ 0 ] == 0 ) ans . add ( Q [ i ] [ 1 ] ^ xor ) ; else xor ^= Q [ i ] [ 1 ] ; } ans . add ( xor ) ; Collections . sort ( ans ) ; return ans ; } public static void main ( String [ ] args ) { int [ ] [ ] Q = { { 0 , 6 } , { 0 , 3 } , { 0 , 2 } , { 1 , 4 } , { 1 , 5 } } ; System . out . println ( ConstructList ( Q ) ) ; } }


"Construct a Matrix N x N with first N ^ 2 natural numbers for an input N | Java program for the above approach ; Function to print the desired matrix ; Iterate ove all [ 0 , N ] ; If is even ; If row number is even print the row in forward order ; If row number is odd print the row in reversed order ; Driver Code ; Given matrix size ; Function call"
How can the above be solved in Java?

public class Gfg { public static void UniqueMatrix ( int N ) { int element_value = 1 ; int i = 0 ; while ( i < N ) { if ( i % 2 == 0 ) { for ( int f = element_value ; f < element_value + N ; f ++ ) { System . out . print ( f + " ▁ " ) ; } element_value += N ; } else { for ( int k = element_value + N - 1 ; k > element_value - 1 ; k -- ) { System . out . print ( k + " ▁ " ) ; } element_value += N ; } System . out . println ( ) ; i = i + 1 ; } } public static void main ( String [ ] args ) { int N = 4 ; UniqueMatrix ( N ) ; } }


"Construct a Matrix such that each cell consists of sum of adjacent elements of respective cells in given Matrix | Java program for the above approach ; Initialize rows and columns ; Store all 8 directions ; Function to check if a cell ( i , j ) is valid or not ; Function to find sum of adjacent cells for cell ( i , j ) ; Initialize sum ; Visit all 8 directions ; Check if cell is valid ; Return sum ; Function to print sum of adjacent elements ; Stores the resultant matrix ; Iterate each elements of matrix ; Find adjacent sum ; Driver code ; Given matrix ; Size of matrix ; Function call"
How can the above be solved in Java?

import java . util . * ; import java . lang . * ; public class GFG { private static int r , c ; static int [ ] [ ] dir = { { 1 , 0 } , { - 1 , 0 } , { 0 , 1 } , { 0 , - 1 } , { - 1 , - 1 } , { - 1 , 1 } , { 1 , 1 } , { 1 , - 1 } } ; public static boolean valid ( int i , int j ) { if ( i >= 0 && j >= 0 && i < r && j < c ) return true ; return false ; } static int find ( int i , int j , int [ ] [ ] v ) { int s = 0 ; for ( int k = 0 ; k < 8 ; k ++ ) { int ni = i + dir [ k ] [ 0 ] , nj = j + dir [ k ] [ 1 ] ; if ( valid ( ni , nj ) ) s += v [ ni ] [ nj ] ; } return s ; } static void findsumofneighbors ( int [ ] [ ] M ) { int [ ] [ ] v = new int [ r ] ; for ( int i = 0 ; i < r ; i ++ ) { for ( int j = 0 ; j < c ; j ++ ) { v [ i ] [ j ] = find ( i , j , M ) ; System . out . print ( v [ i ] [ j ] + " ▁ " ) ; } System . out . println ( " " ) ; } } public static void main ( String [ ] args ) { int [ ] [ ] M = { { 1 , 4 , 1 } , { 2 , 4 , 5 } , { 3 , 1 , 2 } } ; r = M . length ; c = M [ 0 ] . length ; findsumofneighbors ( M ) ; } }


"Construct a Matrix with no element exceeding X and sum of two adjacent elements not exceeding Y | Java implementation of the above approach ; Function to print the required matrix ; For 1 * 1 matrix ; Greater number ; Smaller number ; Sets / Resets for alternate filling of the matrix ; Print the matrix ; If end of row is reached ; Driver Code"
How can the above be solved in Java?

 class GFG { static void FindMatrix ( int n , int m , int x , int y ) { int a , b , i , j ; if ( n * m == 1 ) { if ( x > y ) { System . out . print ( y + "
"); } else { System . out . print ( x + "
"); } return ; } a = Math . min ( x , y ) ; b = Math . min ( 2 * x , y ) - a ; boolean flag = true ; for ( i = 0 ; i < n ; i ++ ) { for ( j = 0 ; j < m ; j ++ ) { if ( flag ) System . out . print ( a + " ▁ " ) ; else System . out . print ( b + " ▁ " ) ; flag = ! flag ; } if ( ( ( n % 2 != 0 && m % 2 == 0 ) || ( n % 2 == 0 && m % 2 == 0 ) ) ) flag = ! flag ; System . out . print ( "
"); } } public static void main ( String [ ] args ) { int N , M , X , Y ; N = 3 ; M = 3 ; X = 5 ; Y = 3 ; FindMatrix ( N , M , X , Y ) ; } }


"Construct a Maximum Binary Tree from two given Binary Trees | A binary tree node has data , pointer to left child and a pointer to right child ; Helper method that allocates a new node with the given data and NULL left and right pointers . ; Given a binary tree , print its nodes in inorder ; first recur on left child ; then print the data of node ; now recur on right child ; Method to find the maximum binary tree from two binary trees ; Driver Code ; First Binary Tree 3 / \ 2 6 / 20 ; Second Binary Tree 5 / \ 1 8 \ \ 2 8"
How can the above be solved in Java?

class Node { int data ; Node left , right ; public Node ( int data , Node left , Node right ) { this . data = data ; this . left = left ; this . right = right ; } static Node newNode ( int data ) { return new Node ( data , null , null ) ; } static void inorder ( Node node ) { if ( node == null ) return ; inorder ( node . left ) ; System . out . printf ( " % d ▁ " , node . data ) ; inorder ( node . right ) ; } static Node MaximumBinaryTree ( Node t1 , Node t2 ) { if ( t1 == null ) return t2 ; if ( t2 == null ) return t1 ; t1 . data = Math . max ( t1 . data , t2 . data ) ; t1 . left = MaximumBinaryTree ( t1 . left , t2 . left ) ; t1 . right = MaximumBinaryTree ( t1 . right , t2 . right ) ; return t1 ; } public static void main ( String [ ] args ) { Node root1 = newNode ( 3 ) ; root1 . left = newNode ( 2 ) ; root1 . right = newNode ( 6 ) ; root1 . left . left = newNode ( 20 ) ; Node root2 = newNode ( 5 ) ; root2 . left = newNode ( 1 ) ; root2 . right = newNode ( 8 ) ; root2 . left . right = newNode ( 2 ) ; root2 . right . right = newNode ( 8 ) ; Node root3 = MaximumBinaryTree ( root1 , root2 ) ; inorder ( root3 ) ; } }


"Construct a Perfect Binary Tree from Preorder Traversal | Java program for the above approach ; Structure of the tree ; Function to create a new node with the value val ; Return the newly created node ; Function to create the Perfect Binary Tree ; If preStart > preEnd return NULL ; Initialize root as pre [ preStart ] ; If the only node is left , then return node ; Parameters for further recursion ; Recursive Call to build the subtree of root node ; Return the created root ; Function to build Perfect Binary Tree ; Function to print the Inorder of the given Tree ; Base Case ; Left Recursive Call ; Print the data ; Right Recursive Call ; Driver Code ; Function Call ; Print Inorder Traversal"
How can the above be solved in Java?

public class Main { static class Node { public int data ; public Node left , right ; public Node ( int val ) { data = val ; left = right = null ; } } static Node getNewNode ( int val ) { Node newNode = new Node ( val ) ; return newNode ; } static Node buildPerfectBT_helper ( int preStart , int preEnd , int [ ] pre ) { if ( preStart > preEnd ) return null ; Node root = getNewNode ( pre [ preStart ] ) ; if ( preStart == preEnd ) return root ; int leftPreStart = preStart + 1 ; int rightPreStart = leftPreStart + ( preEnd - leftPreStart + 1 ) / 2 ; int leftPreEnd = rightPreStart - 1 ; int rightPreEnd = preEnd ; root . left = buildPerfectBT_helper ( leftPreStart , leftPreEnd , pre ) ; root . right = buildPerfectBT_helper ( rightPreStart , rightPreEnd , pre ) ; return root ; } static Node buildPerfectBT ( int [ ] pre , int size ) { return buildPerfectBT_helper ( 0 , size - 1 , pre ) ; } static void printInorder ( Node root ) { if ( root == null ) return ; printInorder ( root . left ) ; System . out . print ( root . data + " ▁ " ) ; printInorder ( root . right ) ; } public static void main ( String [ ] args ) { int [ ] pre = { 1 , 2 , 4 , 5 , 3 , 6 , 7 } ; int N = pre . length ; Node root = buildPerfectBT ( pre , N ) ; System . out . print ( " Inorder ▁ traversal ▁ of ▁ the ▁ tree : ▁ " ) ; printInorder ( root ) ; } }


"Construct a Tree whose sum of nodes of all the root to leaf path is not divisible by the count of nodes in that path | Java program for the above approach ; Function to assign values to nodes of the tree s . t . sum of values of nodes of path between any 2 nodes is not divisible by length of path ; Stores the adjacency list ; Create a adjacency list ; Stores whether node is visited or not ; Stores the node values ; Variable used to assign values to the nodes alternatively to the parent child ; Declare a queue ; Push the 1 st node ; Assign K value to this node ; Dequeue the node ; Mark it as visited ; Upgrade the value of K ; Assign K to the child nodes ; If the child is unvisited ; Enqueue the child ; Assign K to the child ; Print the value assigned to the nodes ; Driver code ; Function Call"
How can the above be solved in Java?

import java . util . * ; class GFG { static void assignValues ( int Edges [ ] [ ] , int n ) { ArrayList < ArrayList < Integer > > tree = new ArrayList < > ( ) ; for ( int i = 0 ; i < n + 1 ; i ++ ) tree . add ( new ArrayList < > ( ) ) ; for ( int i = 0 ; i < n - 1 ; i ++ ) { int u = Edges [ i ] [ 0 ] ; int v = Edges [ i ] [ 1 ] ; tree . get ( u ) . add ( v ) ; tree . get ( v ) . add ( u ) ; } boolean [ ] visited = new boolean [ n + 1 ] ; int [ ] answer = new int [ n + 1 ] ; int K = 1 ; Queue < Integer > q = new LinkedList < > ( ) ; q . add ( 1 ) ; answer [ 1 ] = K ; while ( ! q . isEmpty ( ) ) { int node = q . peek ( ) ; q . poll ( ) ; visited [ node ] = true ; K = ( ( answer [ node ] == 1 ) ? 2 : 1 ) ; for ( Integer child : tree . get ( node ) ) { if ( ! visited [ child ] ) { q . add ( child ) ; answer [ child ] = K ; } } } for ( int i = 1 ; i <= n ; i ++ ) { System . out . print ( answer [ i ] + " ▁ " ) ; } } public static void main ( String [ ] args ) { int N = 11 ; int Edges [ ] [ ] = { { 1 , 2 } , { 1 , 3 } , { 1 , 4 } , { 1 , 5 } , { 2 , 6 } , { 2 , 10 } , { 10 , 11 } , { 3 , 7 } , { 4 , 8 } , { 5 , 9 } } ; assignValues ( Edges , N ) ; } }


"Construct a binary string following the given constraints | Java implementation of the approach ; Function to print a binary string which has ' a ' number of 0 ' s , ▁ ' b ' ▁ number ▁ of ▁ 1' s and there are at least ' x ' indices such that s [ i ] != s [ i + 1 ] ; Divide index value by 2 and store it into d ; If index value x is even and x / 2 is not equal to a ; Loop for d for each d print 10 ; subtract d from a and b ; Loop for b to print remaining 1 's ; Loop for a to print remaining 0 's ; Driver code"
How can the above be solved in Java?

class GFG { static void constructBinString ( int a , int b , int x ) { int d , i ; d = x / 2 ; if ( x % 2 == 0 && x / 2 != a ) { d -- ; System . out . print ( "0" ) ; a -- ; } for ( i = 0 ; i < d ; i ++ ) System . out . print ( "10" ) ; a = a - d ; b = b - d ; for ( i = 0 ; i < b ; i ++ ) { System . out . print ( "1" ) ; } for ( i = 0 ; i < a ; i ++ ) { System . out . print ( "0" ) ; } } public static void main ( String [ ] args ) { int a = 4 , b = 3 , x = 2 ; constructBinString ( a , b , x ) ; } }


"Construct a complete binary tree from given array in level order fashion | Java program to construct binary tree from given array in level order fashion ; Tree Node ; Function to insert nodes in level order ; Base case for recursion ; insert left child ; insert right child ; Function to print tree nodes in InOrder fashion ; Driver program to test above function"
How can the above be solved in Java?

public class Tree { Node root ; static class Node { int data ; Node left , right ; Node ( int data ) { this . data = data ; this . left = null ; this . right = null ; } } public Node insertLevelOrder ( int [ ] arr , Node root , int i ) { if ( i < arr . length ) { Node temp = new Node ( arr [ i ] ) ; root = temp ; root . left = insertLevelOrder ( arr , root . left , 2 * i + 1 ) ; root . right = insertLevelOrder ( arr , root . right , 2 * i + 2 ) ; } return root ; } public void inOrder ( Node root ) { if ( root != null ) { inOrder ( root . left ) ; System . out . print ( root . data + " ▁ " ) ; inOrder ( root . right ) ; } } public static void main ( String args [ ] ) { Tree t2 = new Tree ( ) ; int arr [ ] = { 1 , 2 , 3 , 4 , 5 , 6 , 6 , 6 , 6 } ; t2 . root = t2 . insertLevelOrder ( arr , t2 . root , 0 ) ; t2 . inOrder ( t2 . root ) ; } }


"Construct a graph from given degrees of all vertices | Java program to generate a graph for a given fixed degrees ; A function to print the adjacency matrix . ; n is number of vertices ; For each pair of vertex decrement the degree of both vertex . ; Print the result in specified format ; Driver Code"
How can the above be solved in Java?

 import java . util . * ; class GFG { static void printMat ( int degseq [ ] , int n ) { int [ ] [ ] mat = new int [ n ] [ n ] ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = i + 1 ; j < n ; j ++ ) { if ( degseq [ i ] > 0 && degseq [ j ] > 0 ) { degseq [ i ] -- ; degseq [ j ] -- ; mat [ i ] [ j ] = 1 ; mat [ j ] [ i ] = 1 ; } } } System . out . print ( " " ▁ + ▁ setw ( 3 ) ▁ + ▁ " "); for ( int i = 0 ; i < n ; i ++ ) System . out . print ( setw ( 3 ) + " ( " + i + " ) " ) ; System . out . print ( "
"); for ( int i = 0 ; i < n ; i ++ ) { System . out . print ( setw ( 4 ) + " ( " + i + " ) " ) ; for ( int j = 0 ; j < n ; j ++ ) System . out . print ( setw ( 5 ) + mat [ i ] [ j ] ) ; System . out . print ( "
"); } } static String setw ( int n ) { String space = " " ; while ( n -- > 0 ) space += " ▁ " ; return space ; } public static void main ( String [ ] args ) { int degseq [ ] = { 2 , 2 , 1 , 1 , 1 } ; int n = degseq . length ; printMat ( degseq , n ) ; } }


"Construct a graph using N vertices whose shortest distance between K pair of vertices is 2 | Java program to implement the above approach ; Function to construct the simple and connected graph such that the distance between exactly K pairs of vertices is 2 ; Stores maximum possible count of edges in a graph ; Base Case ; Stores edges of a graph ; Connect all vertices of pairs ( i , j ) ; Print first ( ( N - 1 ) + Max - K ) elements of edges [ ] ; Driver Code"
How can the above be solved in Java?

 import java . util . * ; class GFG { static class pair { int first , second ; public pair ( int first , int second ) { this . first = first ; this . second = second ; } } static void constGraphWithCon ( int N , int K ) { int Max = ( ( N - 1 ) * ( N - 2 ) ) / 2 ; if ( K > Max ) { System . out . print ( - 1 + "
"); return ; } Vector < pair > ans = new Vector < > ( ) ; for ( int i = 1 ; i < N ; i ++ ) { for ( int j = i + 1 ; j <= N ; j ++ ) { ans . add ( new pair ( i , j ) ) ; } } for ( int i = 0 ; i < ( N - 1 ) + Max - K ; i ++ ) { System . out . print ( ans . get ( i ) . first + " ▁ " + ans . get ( i ) . second + "
"); } } public static void main ( String [ ] args ) { int N = 5 , K = 3 ; constGraphWithCon ( N , K ) ; } }


"Construct a graph which does not contain any pair of adjacent nodes with same value | Java program for the above approach ; Function that prints the edges of the generated graph ; First print connections stored in store [ ] ; Check if there is more than one occurrence of 1 st unique element ; Print all other occurrence of 1 st unique element with second unique element ; Function to construct the graph such that the every adjacent nodes have different value ; Stores pair of edges formed ; Stores first unique occurrence ; Check for the second unique occurrence ; Store indices of 2 nd unique occurrence ; To check if arr has only 1 unique element or not ; Store the connections of all unique elements with Node 1 ; If value at node ( i + 1 ) is same as value at Node 1 then store its indices ; If count is zero then it 's not  possible to construct the graph ; If more than 1 unique element is present ; Print the edges ; Driver Code ; Given array having node values ; 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 printConnections ( Vector < pair > store , Vector < Integer > ind , int ind1 ) { for ( pair pr : store ) { System . out . print ( pr . first + " ▁ " + pr . second + "
"); } if ( ind . size ( ) != 0 ) { for ( int x : ind ) { System . out . print ( ind1 + " ▁ " + ( x + 1 ) + "
"); } } } static void constructGraph ( char arr [ ] , int N ) { Vector < Integer > ind = new Vector < > ( ) ; Vector < pair > store = new Vector < > ( ) ; char x = arr [ 0 ] ; int count = 0 ; int ind1 = - 1 ; for ( int i = 1 ; i <= N - 1 ; ++ i ) { if ( arr [ i ] != x ) { ind1 = i + 1 ; count ++ ; store . add ( new pair ( 1 , i + 1 ) ) ; } else { ind . add ( i ) ; } } if ( count == 0 ) { System . out . print ( " Not ▁ Possible " ) ; } else { System . out . print ( " Possible " + "
"); printConnections ( store , ind , ind1 ) ; } } public static void main ( String [ ] args ) { int N = 5 ; char arr [ ] = { ' a ' , ' b ' , ' a ' , ' b ' , ' c ' } ; constructGraph ( arr , N ) ; } }


"Construct a matrix such that union of ith row and ith column contains every element from 1 to 2 N | Java implementation of the above approach ; Function to find the square matrix ; For Matrix of order 1 , it will contain only 1 ; For Matrix of odd order , it is not possible ; For Matrix of even order ; All diagonal elements of the matrix can be N itself . ; Assign values at desired place in the matrix ; Loop to add N in the lower half of the matrix such that it contains elements from 1 to 2 * N - 1 ; Loop to print the matrix ; Driver Code"
How can the above be solved in Java?

class GFG { static int matrix [ ] [ ] = new int [ 100 ] [ 100 ] ; static void printRequiredMatrix ( int n ) { if ( n == 1 ) { System . out . println ( "1" ) ; } else if ( n % 2 != 0 ) { System . out . println ( " - 1" ) ; } else { for ( int i = 0 ; i < n ; i ++ ) { matrix [ i ] [ i ] = n ; } int u = n - 1 ; for ( int i = 0 ; i < n - 1 ; i ++ ) { matrix [ i ] [ u ] = i + 1 ; for ( int j = 1 ; j < n / 2 ; j ++ ) { int a = ( i + j ) % ( n - 1 ) ; int b = ( i - j + n - 1 ) % ( n - 1 ) ; if ( a < b ) { int temp = a ; a = b ; b = temp ; } matrix [ b ] [ a ] = i + 1 ; } } for ( int i = 0 ; i < n ; i ++ ) for ( int j = 0 ; j < i ; j ++ ) matrix [ i ] [ j ] = matrix [ j ] [ i ] + n ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = 0 ; j < n ; j ++ ) System . out . print ( matrix [ i ] [ j ] + " ▁ " ) ; System . out . println ( ) ; } } System . out . println ( ) ; } public static void main ( String [ ] args ) { int n = 1 ; printRequiredMatrix ( n ) ; n = 3 ; printRequiredMatrix ( n ) ; n = 6 ; printRequiredMatrix ( n ) ; } }


"Construct a sequence from given frequencies of N consecutive integers with unit adjacent difference | Java program for the above approach ; Function generates the sequence ; Map to store the frequency of numbers ; Sum of all frequencies ; Try all possibilities for the starting element ; If the frequency of current element is non - zero ; vector to store the answer ; Copy of the map for every possible starting element ; Decrement the frequency ; Push the starting element to the vector ; The last element inserted is i ; Try to fill the rest of the positions if possible ; If the frequency of last - 1 is non - zero ; Decrement the frequency of last - 1 ; Insert it into the sequence ; Update last number added to sequence ; Break from the inner loop ; If the size of the sequence vector is equal to sum of total frequqncies ; Return sequence ; If no such sequence if found return empty sequence ; Function call to print the sequence ; The required sequence ; If the size of sequence if zero it means no such sequence was found ; Otherwise print the sequence ; Driver Code ; Frequency of all elements from 0 to n - 1 ; Number of elements whose frequencies are given ; Function call"
How can the above be solved in Java?

import java . util . * ; class GFG { static Vector < Integer > generateSequence ( int [ ] freq , int n ) { HashMap < Integer , Integer > m = new HashMap < Integer , Integer > ( ) ; int total = 0 ; for ( int i = 0 ; i < n ; i ++ ) { m . put ( i , freq [ i ] ) ; total += freq [ i ] ; } for ( int i = 0 ; i < n ; i ++ ) { if ( m . containsKey ( i ) ) { Vector < Integer > sequence = new Vector < Integer > ( ) ; @ SuppressWarnings ( " unchecked " ) HashMap < Integer , Integer > mcopy = ( HashMap < Integer , Integer > ) m . clone ( ) ; if ( mcopy . containsKey ( i ) && mcopy . get ( i ) > 0 ) mcopy . put ( i , mcopy . get ( i ) - 1 ) ; sequence . add ( i ) ; int last = i ; for ( int i1 = 0 ; i1 < total - 1 ; i1 ++ ) { if ( mcopy . containsKey ( last - 1 ) && mcopy . get ( last - 1 ) > 0 ) { mcopy . put ( last - 1 , mcopy . get ( last - 1 ) - 1 ) ; sequence . add ( last - 1 ) ; last -- ; } else if ( mcopy . containsKey ( last + 1 ) ) { mcopy . put ( last + 1 , mcopy . get ( last + 1 ) - 1 ) ; sequence . add ( last + 1 ) ; last ++ ; } else break ; } if ( sequence . size ( ) == total ) { return sequence ; } } } Vector < Integer > empty = new Vector < Integer > ( ) ; return empty ; } static void PrintSequence ( int freq [ ] , int n ) { Vector < Integer > sequence = generateSequence ( freq , n ) ; if ( sequence . size ( ) == 0 ) { System . out . print ( " - 1" ) ; } else { for ( int i = 0 ; i < sequence . size ( ) ; i ++ ) { System . out . print ( sequence . get ( i ) + " ▁ " ) ; } } } public static void main ( String [ ] args ) { int freq [ ] = { 2 , 2 , 2 , 3 , 1 } ; int N = 5 ; PrintSequence ( freq , N ) ; } }


"Construct a special tree from given preorder traversal | A Binary Tree node ; A recursive function to create a Binary Tree from given pre [ ] preLN [ ] arrays . The function returns root of tree . index_ptr is used to update index values in recursive calls . index must be initially passed as 0 ; store the current value of index in pre [ ] ; Base Case : All nodes are constructed ; Allocate memory for this node and increment index for subsequent recursive calls ; If this is an internal node , construct left and right subtrees and link the subtrees ; A wrapper over constructTreeUtil ( ) ; Initialize index as 0. Value of index is used in recursion to maintain the current index in pre [ ] and preLN [ ] arrays . ; This function is used only for testing ; first recur on left child ; then print the data of node ; now recur on right child ; driver function to test the above functions"
How can the above be solved in Java?

class Node { int data ; Node left , right ; Node ( int item ) { data = item ; left = right = null ; } } class Index { int index = 0 ; } class BinaryTree { Node root ; Index myindex = new Index ( ) ; Node constructTreeUtil ( int pre [ ] , char preLN [ ] , Index index_ptr , int n , Node temp ) { int index = index_ptr . index ; if ( index == n ) return null ; temp = new Node ( pre [ index ] ) ; ( index_ptr . index ) ++ ; if ( preLN [ index ] == ' N ' ) { temp . left = constructTreeUtil ( pre , preLN , index_ptr , n , temp . left ) ; temp . right = constructTreeUtil ( pre , preLN , index_ptr , n , temp . right ) ; } return temp ; } Node constructTree ( int pre [ ] , char preLN [ ] , int n , Node node ) { int index = 0 ; return constructTreeUtil ( pre , preLN , myindex , n , node ) ; } void printInorder ( Node node ) { if ( node == null ) return ; printInorder ( node . left ) ; System . out . print ( node . data + " ▁ " ) ; printInorder ( node . right ) ; } public static void main ( String args [ ] ) { BinaryTree tree = new BinaryTree ( ) ; int pre [ ] = new int [ ] { 10 , 30 , 20 , 5 , 15 } ; char preLN [ ] = new char [ ] { ' N ' , ' N ' , ' L ' , ' L ' , ' L ' } ; int n = pre . length ; Node mynode = tree . constructTree ( pre , preLN , n , tree . root ) ; System . out . println ( " Following ▁ is ▁ Inorder ▁ Traversal ▁ of ▁ the " + " Constructed ▁ Binary ▁ Tree : ▁ " ) ; tree . printInorder ( mynode ) ; } }


"Construct a string of length L such that each substring of length X has exactly Y distinct letters | Java implementation to construct a string of length L such that each substring of length X has exactly Y distinct letters . ; Initialize p equal to the ASCII value of a ; Iterate till the length of the string ; Driver code"
How can the above be solved in Java?

public class GFG { static void string ( int l , int x , int y ) { int p = 97 ; for ( int j = 0 ; j < l ; j ++ ) { char ans = ( char ) ( p + ( j % y ) ) ; System . out . print ( ans ) ; } } public static void main ( String [ ] args ) { int l = 6 ; int x = 5 ; int y = 3 ; string ( l , x , y ) ; } }


"Construct a string that has exactly K subsequences from given string | Java program for the above approach ; Function that computes the String s ; Length of the given String str ; List that stores all the prime factors of given k ; Find the prime factors ; Initialize the count of each character position as 1 ; Loop until the list becomes empty ; Increase the character count by multiplying it with the prime factor ; If we reach end then again start from beginning ; Store the output ; Print the String ; Driver code ; Given String ; Function Call"
How can the above be solved in Java?

import java . util . * ; class GFG { static void printSubsequenceString ( String str , int k ) { int n = str . length ( ) ; int i ; Vector < Integer > factors = new Vector < Integer > ( ) ; for ( i = 2 ; i <= Math . sqrt ( k ) ; i ++ ) { while ( k % i == 0 ) { factors . add ( i ) ; k /= i ; } } if ( k > 1 ) factors . add ( k ) ; int [ ] count = new int [ n ] ; Arrays . fill ( count , 1 ) ; int index = 0 ; while ( factors . size ( ) > 0 ) { count [ index ++ ] *= factors . get ( factors . size ( ) - 1 ) ; factors . remove ( factors . get ( factors . size ( ) - 1 ) ) ; if ( index == n ) index = 0 ; } String s = " " ; for ( i = 0 ; i < n ; i ++ ) { while ( count [ i ] -- > 0 ) { s += str . charAt ( i ) ; } } System . out . print ( s ) ; } public static void main ( String [ ] args ) { String str = " code " ; int k = 20 ; printSubsequenceString ( str , k ) ; } }


"Construct an AP series consisting of A and B having minimum possible Nth term | Java program for the above approach ; Function to check if both a and b are present in the AP series or not ; Iterate over the array arr [ ] ; If a is present ; If b is present ; If both are present ; Otherwise ; Function to print all the elements of the Arithmetic Progression ; Function to construct AP series consisting of A and B with minimum Nth term ; Stores the resultant series ; Initialise ans [ i ] as INT_MAX ; Maintain a smaller than b ; swap ( a and b ) ; Difference between a and b ; Check for all possible combination of start and common difference d ; Initialise arr [ 0 ] as start ; Check if both a and b are present or not and the Nth term is the minimum or not ; Update the answer ; Print the resultant array ; Driver Code ; Function call"
How can the above be solved in Java?

import java . io . * ; class GFG { public static boolean check_both_present ( int [ ] arr , int N , int a , int b ) { boolean f1 = false , f2 = false ; for ( int i = 0 ; i < N ; i ++ ) { if ( arr [ i ] == a ) { f1 = true ; } if ( arr [ i ] == b ) { f2 = true ; } } if ( f1 && f2 ) { return true ; } else { return false ; } } public static void print_array ( int [ ] ans , int N ) { for ( int i = 0 ; i < N ; i ++ ) { System . out . print ( ans [ i ] + " ▁ " ) ; } } public static void build_AP ( int N , int a , int b ) { int [ ] arr = new int [ N ] ; int [ ] ans = new int [ N ] ; for ( int i = 0 ; i < N ; i ++ ) ans [ i ] = Integer . MAX_VALUE ; int flag = 0 ; if ( a > b ) { a += ( b - ( b = a ) ) ; } int diff = b - a ; for ( int start = 1 ; start <= a ; start ++ ) { for ( int d = 1 ; d <= diff ; d ++ ) { arr [ 0 ] = start ; for ( int i = 1 ; i < N ; i ++ ) { arr [ i ] = arr [ i - 1 ] + d ; } if ( check_both_present ( arr , N , a , b ) && arr [ N - 1 ] < ans [ N - 1 ] ) { for ( int i = 0 ; i < N ; i ++ ) { ans [ i ] = arr [ i ] ; } } } } print_array ( ans , N ) ; } public static void main ( String [ ] args ) { int N = 5 , A = 20 , B = 50 ; build_AP ( N , A , B ) ; } }


"Construct an Array of Strings having Longest Common Prefix specified by the given Array | Java Program to implement the above approach ; Function to find the array of strings ; Marks the ( N + 1 ) th string ; To generate remaining N strings ; Check if current character is b ; Find i - th string using ( i + 1 ) - th string ; Otherwise ; Insert the string ; Return the answer ; Driver Code ; Print the strings"
How can the above be solved in Java?

import java . util . * ; class GFG { static Vector < String > solve ( int n , int arr [ ] ) { String s = " aaa " ; Vector < String > ans = new Vector < String > ( ) ; ans . add ( s ) ; for ( int i = n - 1 ; i >= 0 ; i -- ) { if ( s . length ( ) - 1 >= arr [ i ] ) { char ch = s . charAt ( arr [ i ] ) ; if ( ch == ' b ' ) ch = ' a ' ; else ch = ' b ' ; char [ ] myNameChars = s . toCharArray ( ) ; myNameChars [ arr [ i ] ] = ch ; s = String . valueOf ( myNameChars ) ; } ans . add ( s ) ; } return ans ; } public static void main ( String [ ] args ) { int [ ] arr = { 2 , 0 , 3 } ; int n = arr . length ; Vector < String > ans = solve ( n , arr ) ; for ( int i = ans . size ( ) - 1 ; i >= 0 ; i -- ) { System . out . println ( ans . get ( i ) ) ; } } }


"Construct an Array of size N in which sum of odd elements is equal to sum of even elements | Java program to Create an array of size N consisting of distinct elements where sum of odd elements is equal to sum of even elements ; Function to construct the required array ; To confirst half , distinct even numbers ; To consecond half , distinct odd numbers ; Calculate the last number of second half so as to make both the halves equal ; Function to construct the required array ; check if size is multiple of 4 then array exist ; function call to conarray ; Driver code"
How can the above be solved in Java?

 class GFG { static void arrayConstruct ( int N ) { for ( int i = 2 ; i <= N ; i = i + 2 ) System . out . print ( i + " ▁ " ) ; for ( int i = 1 ; i < N - 1 ; i = i + 2 ) System . out . print ( i + " ▁ " ) ; System . out . print ( N - 1 + ( N / 2 ) + "
"); } static void createArray ( int N ) { if ( N % 4 == 0 ) arrayConstruct ( N ) ; else System . out . print ( - 1 + "
"); } public static void main ( String [ ] args ) { int N = 8 ; createArray ( N ) ; } }


"Construct an Array of size N whose sum of cube of all elements is a perfect square | Java implementation of the above approach ; Function to construct an array of size N ; Prints the first N natural numbers ; Driver Code"
How can the above be solved in Java?

class GFG { public static void constructArray ( int N ) { for ( int i = 1 ; i <= N ; i ++ ) { System . out . print ( i + " ▁ " ) ; } } public static void main ( String [ ] args ) { int N = 5 ; constructArray ( N ) ; } }


"Construct an array from XOR of all elements of array except element at same index | Java program to construct array from XOR of elements of given array ; function to construct new array ; calculate xor of array ; update array ; Driver code ; print result"
How can the above be solved in Java?

class GFG { static void constructXOR ( int A [ ] , int n ) { int XOR = 0 ; for ( int i = 0 ; i < n ; i ++ ) XOR ^= A [ i ] ; for ( int i = 0 ; i < n ; i ++ ) A [ i ] = XOR ^ A [ i ] ; } public static void main ( String [ ] args ) { int A [ ] = { 2 , 4 , 1 , 3 , 5 } ; int n = A . length ; constructXOR ( A , n ) ; for ( int i = 0 ; i < n ; i ++ ) System . out . print ( A [ i ] + " ▁ " ) ; } }


"Construct an array from its pair |  ; Fills element in arr [ ] from its pair sum array pair [ ] . n is size of arr [ ] ; Driver program to test above function"
How can the above be solved in Java?

import java . io . * ; class PairSum { static void constructArr ( int arr [ ] , int pair [ ] , int n ) { arr [ 0 ] = ( pair [ 0 ] + pair [ 1 ] - pair [ n - 1 ] ) / 2 ; for ( int i = 1 ; i < n ; i ++ ) arr [ i ] = pair [ i - 1 ] - arr [ 0 ] ; } public static void main ( String [ ] args ) { int pair [ ] = { 15 , 13 , 11 , 10 , 12 , 10 , 9 , 8 , 7 , 5 } ; int n = 5 ; int [ ] arr = new int [ n ] ; constructArr ( arr , pair , n ) ; for ( int i = 0 ; i < n ; i ++ ) System . out . print ( arr [ i ] + " ▁ " ) ; } }


"Construct an array from its pair | Java implementation of the approach ; Utility function to print the array ; Function to generate the original array from the pair - product array ; First element of the resulting array ; Find all the other elements ; Print the elements of the generated array ; Driver code"
How can the above be solved in Java?

class GFG { static void printArr ( int arr [ ] , int n ) { for ( int i = 0 ; i < n ; i ++ ) System . out . print ( arr [ i ] + " ▁ " ) ; } static void constructArr ( int pair [ ] , int n ) { int size = ( 1 + ( int ) Math . sqrt ( 1 + 8 * n ) ) / 2 ; int [ ] arr = new int [ size ] ; arr [ 0 ] = ( int ) Math . sqrt ( ( pair [ 0 ] * pair [ 1 ] ) / pair [ size - 1 ] ) ; for ( int i = 1 ; i < size ; i ++ ) arr [ i ] = pair [ i - 1 ] / arr [ 0 ] ; printArr ( arr , size ) ; } public static void main ( String [ ] args ) { int pair [ ] = { 48 , 18 , 24 , 24 , 32 , 12 } ; int n = pair . length ; constructArr ( pair , n ) ; } }


"Construct an array of first N natural numbers such that every adjacent pair is coprime | Java program to implement the above approach ; Function to construct an arrary with adjacent elements as co - prime numbers ; Iterate over the range [ 1 , N ] ; Print i ; Driver Code"
How can the above be solved in Java?

class GFG { static void ConstArrayAdjacentCoprime ( int N ) { for ( int i = 1 ; i <= N ; i ++ ) { System . out . print ( i + " ▁ " ) ; } } public static void main ( String [ ] args ) { int N = 6 ; ConstArrayAdjacentCoprime ( N ) ; } }


"Construct an array whose Prefix XOR array starting from X is an N | Java program for the above approach ; Function to print the required array ; Iteratie from 1 to N ; Print the i - th element ; Update prev_xor to i ; Driver Code ; Given Input ; Function Call"
How can the above be solved in Java?

class GFG { static void GenerateArray ( int N , int X ) { int prev_xor = X ; for ( int i = 1 ; i <= N ; i ++ ) { System . out . print ( i ^ prev_xor ) ; if ( i != N ) { System . out . print ( " ▁ " ) ; } prev_xor = i ; } } public static void main ( String args [ ] ) { int N = 4 , X = 3 ; System . out . print ( " The ▁ generated ▁ array ▁ is ▁ " ) ; GenerateArray ( N , X ) ; } }


"Construct array with sum of product of same indexed elements in the given array equal to zero | Java program to implement the above approach ; Function to generate a new array with product of same indexed elements with arr [ ] equal to 0 ; Stores sum of same indexed array elements of arr and new array ; Traverse the array ; If i is an even number ; Insert arr [ i + 1 ] into the new array newArr [ ] ; Insert - arr [ i - 1 ] into the new array newArr [ ] ; Print new array elements ; Driver Code"
How can the above be solved in Java?

import java . util . * ; class GFG { static void constructNewArraySumZero ( int arr [ ] , int N ) { int newArr [ ] = new int [ N ] ; for ( int i = 0 ; i < N ; i ++ ) { if ( i % 2 == 0 ) { newArr [ i ] = arr [ i + 1 ] ; } else { newArr [ i ] = - arr [ i - 1 ] ; } } for ( int i = 0 ; i < N ; i ++ ) { System . out . print ( newArr [ i ] + " ▁ " ) ; } } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 2 , 3 , - 5 , - 6 , 8 } ; int N = arr . length ; constructNewArraySumZero ( arr , N ) ; } }


"Construct binary palindrome by repeated appending and trimming | JAVA code to form binary palindrome ; function to apply DFS ; set the parent marked ; if the node has not been visited set it and its children marked ; link which digits must be equal ; connect the two indices ; set everything connected to first character as 1 ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { static void dfs ( int parent , int ans [ ] , Vector < Integer > connectchars [ ] ) { ans [ parent ] = 1 ; for ( int i = 0 ; i < connectchars [ parent ] . size ( ) ; i ++ ) { if ( ans [ connectchars [ parent ] . get ( i ) ] != 1 ) dfs ( connectchars [ parent ] . get ( i ) , ans , connectchars ) ; } } static void printBinaryPalindrome ( int n , int k ) { int [ ] arr = new int [ n ] ; int [ ] ans = new int [ n ] ; Vector < Integer > [ ] connectchars = new Vector [ k ] ; for ( int i = 0 ; i < k ; i ++ ) connectchars [ i ] = new Vector < Integer > ( ) ; for ( int i = 0 ; i < n ; i ++ ) arr [ i ] = i % k ; for ( int i = 0 ; i < n / 2 ; i ++ ) { connectchars [ arr [ i ] ] . add ( arr [ n - i - 1 ] ) ; connectchars [ arr [ n - i - 1 ] ] . add ( arr [ i ] ) ; } dfs ( 0 , ans , connectchars ) ; for ( int i = 0 ; i < n ; i ++ ) System . out . print ( ans [ arr [ i ] ] ) ; } public static void main ( String [ ] args ) { int n = 10 , k = 4 ; printBinaryPalindrome ( n , k ) ; } }


"Construct lexicographically smallest palindrome | Java for constructing smallest palindrome ; function for printing palindrome ; iterate till i < j ; continue if str [ i ] == str [ j ] ; update str [ i ] = str [ j ] = ' a ' if both are ' * ' ; update str [ i ] = str [ j ] if only str [ i ] = ' * ' ; update str [ j ] = str [ i ] if only str [ j ] = ' * ' ; else print not possible and return ; Driver code"
How can the above be solved in Java?

class GFG { static String constructPalin ( char [ ] str , int len ) { int i = 0 , j = len - 1 ; for ( ; i < j ; i ++ , j -- ) { if ( str [ i ] == str [ j ] && str [ i ] != ' * ' ) continue ; else if ( str [ i ] == str [ j ] && str [ i ] == ' * ' ) { str [ i ] = ' a ' ; str [ j ] = ' a ' ; continue ; } else if ( str [ i ] == ' * ' ) { str [ i ] = str [ j ] ; continue ; } else if ( str [ j ] == ' * ' ) { str [ j ] = str [ i ] ; continue ; } System . out . println ( " Not ▁ Possible " ) ; return " " ; } return String . valueOf ( str ) ; } public static void main ( String [ ] args ) { String str = " bca * xc * * b " ; int len = str . length ( ) ; System . out . println ( constructPalin ( str . toCharArray ( ) , len ) ) ; } }


"Construct longest possible sequence of unique elements with given LCM | Java program to implement the above approach ; Function to construct an array of unique elements whose LCM is N ; Stores array elements whose LCM is N ; Iterate over the range [ 1 , sqrt ( N ) ] ; If N is divisible by i ; Insert i into newArr [ ] ; If N is not perfect square ; Sort the array newArr [ ] ; Print array elements ; Driver Code ; Given N ; Function Call"
How can the above be solved in Java?

import java . util . Arrays ; class GFG { static void constructArrayWithGivenLCM ( int N ) { int newArr [ ] = new int [ N ] ; int j = 0 ; for ( int i = 1 ; i * i <= N ; i ++ ) { if ( N % i == 0 ) { newArr [ j ] = i ; j ++ ; if ( N / i != i ) { newArr [ j ] = N / i ; j ++ ; } } } Arrays . sort ( newArr ) ; for ( int i = j ; i < N ; i ++ ) { System . out . print ( newArr [ i ] + " ▁ " ) ; } } public static void main ( String [ ] args ) { int N = 12 ; constructArrayWithGivenLCM ( N ) ; } }


"Construct the Array using given bitwise AND , OR and XOR | Java program for the above approach ; Function to find the array ; Loop through all bits in number ; If bit is set in AND then set it in every element of the array ; If bit is not set in AND ; But set in b ( OR ) ; Set bit position in first element ; If bit is not set in c then set it in second element to keep xor as zero for bit position ; Calculate AND , OR and XOR of array ; Check if values are equal or not ; If not , then array is not possible ; Driver code ; Given Bitwise AND , OR , and XOR ; Function Call"
How can the above be solved in Java?

import java . io . * ; class GFG { static void findArray ( int n , int a , int b , int c ) { int arr [ ] = new int [ n + 1 ] ; for ( int bit = 30 ; bit >= 0 ; bit -- ) { int set = a & ( 1 << bit ) ; if ( set != 0 ) { for ( int i = 0 ; i < n ; i ++ ) arr [ i ] |= set ; } else { if ( ( b & ( 1 << bit ) ) != 0 ) { arr [ 0 ] |= ( 1 << bit ) ; if ( ( c & ( 1 << bit ) ) == 0 ) { arr [ 1 ] |= ( 1 << bit ) ; } } } } int aa = Integer . MAX_VALUE , bb = 0 , cc = 0 ; for ( int i = 0 ; i < n ; i ++ ) { aa &= arr [ i ] ; bb |= arr [ i ] ; cc ^= arr [ i ] ; } if ( a == aa && b == bb && c == cc ) { for ( int i = 0 ; i < n ; i ++ ) System . out . print ( arr [ i ] + " ▁ " ) ; } else System . out . println ( " - 1" ) ; } public static void main ( String [ ] args ) { int n = 3 , a = 4 , b = 6 , c = 6 ; findArray ( n , a , b , c ) ; } }


"Construct the Cypher string based on the given conditions | Java program for the above approach ; Function to check whether a number is prime or not ; Function to check if a prime number can be expressed as sum of two Prime Numbers ; If the N && ( N - 2 ) is Prime ; Function to check semiPrime ; Loop from 2 to Math . sqrt ( num ) ; Increment the count of prime numbers ; If num is greater than 1 , then add 1 to it ; Return '1' if count is 2 else return '0' ; Function to make the Cypher String ; Resultant String ; Make String for the number N ; Check for semiPrime ; Traverse to make Cypher String ; If index is odd add the current character ; Else current character is changed ; Check for sum of two primes ; Traverse to make Cypher String ; If index is odd then current character is changed ; Else add the current character ; If the resultant String is " " then print - 1 ; Else print the resultant String ; Driver Code ; Given Number ; Function Call"
How can the above be solved in Java?

import java . util . * ; class GFG { static boolean isPrime ( int n ) { if ( n <= 1 ) return false ; for ( int i = 2 ; i <= Math . sqrt ( n ) ; i ++ ) { if ( n % i == 0 ) return false ; } return true ; } static boolean isPossibleSum ( int N ) { if ( isPrime ( N ) && isPrime ( N - 2 ) ) { return true ; } else { return false ; } } static boolean checkSemiprime ( int num ) { int cnt = 0 ; for ( int i = 2 ; cnt < 2 && i * i <= num ; ++ i ) { while ( num % i == 0 ) { num /= i ; ++ cnt ; } } if ( num > 1 ) { ++ cnt ; } return cnt == 2 ; } static void makeCypherString ( int N ) { String semiPrime = " " ; String sumOfPrime = " " ; String str = String . valueOf ( N ) ; if ( checkSemiprime ( N ) ) { for ( int i = 0 ; i < str . length ( ) ; i ++ ) { if ( i % 2 == 1 ) { semiPrime += str . charAt ( i ) ; } else { semiPrime += ( char ) ( str . charAt ( i ) - '0' + 65 ) ; } } } if ( isPossibleSum ( N ) ) { for ( int i = 0 ; i < str . length ( ) ; i ++ ) { if ( i % 2 == 1 ) { sumOfPrime += ( char ) ( str . charAt ( i ) - '0' + 65 ) ; } else { sumOfPrime += str . charAt ( i ) ; } } } if ( semiPrime + sumOfPrime == " " ) { System . out . print ( " - 1" ) ; } else { System . out . print ( semiPrime + sumOfPrime ) ; } } public static void main ( String [ ] args ) { int N = 1011243 ; makeCypherString ( N ) ; } }


"Construct the full k | Java program to build full k - ary tree from its preorder traversal and to print the postorder traversal of the tree . ; Structure of a node of an n - ary tree ; Utility function to create a new tree node with k children ; Function to build full k - ary tree ; For null tree ; For adding k children to a node ; Check if ind is in range of array Check if height of the tree is greater than 1 ; Recursively add each child ; Function to find the height of the tree ; Function to print postorder traversal of the tree ; Driver Code"
How can the above be solved in Java?

import java . util . * ; class GFG { static class Node { int key ; Vector < Node > child ; } ; static Node newNode ( int value ) { Node nNode = new Node ( ) ; nNode . key = value ; nNode . child = new Vector < Node > ( ) ; return nNode ; } static int ind ; static Node BuildKaryTree ( int A [ ] , int n , int k , int h ) { if ( n <= 0 ) return null ; Node nNode = newNode ( A [ ind ] ) ; if ( nNode == null ) { System . out . println ( " Memory ▁ error " ) ; return null ; } for ( int i = 0 ; i < k ; i ++ ) { if ( ind < n - 1 && h > 1 ) { ind ++ ; nNode . child . add ( BuildKaryTree ( A , n , k , h - 1 ) ) ; } else { nNode . child . add ( null ) ; } } return nNode ; } static Node BuildKaryTree_1 ( int [ ] A , int n , int k , int in ) { int height = ( int ) Math . ceil ( Math . log ( ( double ) n * ( k - 1 ) + 1 ) / Math . log ( ( double ) k ) ) ; ind = in ; return BuildKaryTree ( A , n , k , height ) ; } static void postord ( Node root , int k ) { if ( root == null ) return ; for ( int i = 0 ; i < k ; i ++ ) postord ( root . child . get ( i ) , k ) ; System . out . print ( root . key + " ▁ " ) ; } public static void main ( String args [ ] ) { int ind = 0 ; int k = 3 , n = 10 ; int preorder [ ] = { 1 , 2 , 5 , 6 , 7 , 3 , 8 , 9 , 10 , 4 } ; Node root = BuildKaryTree_1 ( preorder , n , k , ind ) ; System . out . println ( " Postorder ▁ traversal ▁ of ▁ " + " constructed ▁ full ▁ k - ary ▁ tree ▁ is : ▁ " ) ; postord ( root , k ) ; System . out . println ( ) ; } }


"Construct the largest number whose sum of cost of digits is K | Java program for the above approach ; Function to find the maximum number among the two numbers S and T ; If "0" exists in the string S ; If "0" exists in the string T ; Else return the maximum number formed ; Recursive function to find maximum number formed such that the sum of cost of digits of formed number is K ; Base Case ; Return the stored state ; Including the digit ( idx + 1 ) ; Excluding the digit ( idx + 1 ) ; Store the result and return ; Function to find the maximum number formed such that the sum of the cost digits in the formed number is K ; Stores all Dp - states ; Recursive Call ; Return the result ; Driver Code"
How can the above be solved in Java?

import java . util . * ; public class Main { static String getMaximum ( String S , String T ) { if ( S . indexOf ( "0" ) > - 1 ) return T ; if ( T . indexOf ( "0" ) > - 1 ) return S ; return S . length ( ) > T . length ( ) ? S : T ; } static String recursion ( int [ ] arr , int idx , int N , int K , Vector < Vector < String > > dp ) { if ( K == 0 ) { return " " ; } if ( K < 0 idx == N ) { return "0" ; } if ( dp . get ( idx ) . get ( K ) != " - 1" ) return dp . get ( idx ) . get ( K ) ; String include = String . valueOf ( idx + 1 ) + recursion ( arr , 0 , N , K - arr [ idx ] , dp ) ; String exclude = recursion ( arr , idx + 1 , N , K , dp ) ; dp . get ( idx ) . set ( K , getMaximum ( include , exclude ) ) ; return dp . get ( idx ) . get ( K ) ; } static String largestNumber ( int [ ] arr , int N , int K ) { Vector < Vector < String > > dp = new Vector < Vector < String > > ( ) ; for ( int i = 0 ; i < N + 1 ; i ++ ) { dp . add ( new Vector < String > ( ) ) ; for ( int j = 0 ; j < K + 1 ; j ++ ) { dp . get ( i ) . add ( " - 1" ) ; } } String ans = recursion ( arr , 0 , N , K , dp ) ; return ans == " " ? "0" : ans ; } public static void main ( String [ ] args ) { int [ ] arr = { 3 , 12 , 9 , 5 , 3 , 4 , 6 , 5 , 10 } ; int K = 14 ; int N = arr . length ; System . out . print ( largestNumber ( arr , N , K ) ) ; } }


"Construct the smallest possible Array with given Sum and XOR | Java program implementation of the approach ; Function to find array ; Array not possible ; Array possible with exactly 1 or no element ; Checking array with two elements possible or not . ; Driver code ; Given sum and value of Bitwise XOR ; Function call"
How can the above be solved in Java?

import java . util . * ; import java . io . * ; class GFG { static void findArray ( int sum , int xorr ) { if ( xorr > sum sum % 2 != xorr % 2 ) { System . out . println ( " No ▁ Array ▁ Possible " ) ; return ; } if ( sum == xorr ) { if ( sum == 0 ) System . out . println ( " Array ▁ is ▁ empty ▁ " + " with ▁ size ▁ 0" ) ; else System . out . println ( " Array ▁ size ▁ is ▁ " + 1 ) ; System . out . println ( " Array ▁ is ▁ " + sum ) ; return ; } int mid = ( sum - xorr ) / 2 ; if ( xorr == 1 && mid == 1 ) { System . out . println ( " Array ▁ size ▁ is ▁ " + 3 ) ; System . out . println ( " Array ▁ is ▁ " + xorr + " ▁ " + mid + " ▁ " + mid ) ; } else { System . out . println ( " Array ▁ size ▁ is ▁ " + 2 ) ; System . out . println ( " Array ▁ is ▁ " + ( xorr + mid ) + " ▁ " + mid ) ; } } public static void main ( String [ ] args ) { int sum = 4 , xorr = 2 ; findArray ( sum , xorr ) ; } }


"Construction of Longest Increasing Subsequence ( LIS ) and printing LIS sequence |  ;  ; Compare previous highest subsequence ; Print list"
How can the above be solved in Java?

package BIT ; import java . util . ArrayList ; import java . util . Iterator ; public class LongestIncreasingSubsequence { public static void main ( String [ ] args ) { int array [ ] = { 10 , 9 , 8 , 6 , 5 , 4 } ; ArrayList list = new ArrayList ( ) ; ArrayList longestList = new ArrayList ( ) ; int currentMax ; int highestCount = 0 ; for ( int i = 0 ; i < array . length ; i ++ ) { currentMax = Integer . MIN_VALUE ; for ( int j = i ; j < array . length ; j ++ ) { if ( array [ j ] > currentMax ) { list . add ( array [ j ] ) ; currentMax = array [ j ] ; } } if ( highestCount < list . size ( ) ) { highestCount = list . size ( ) ; longestList = new ArrayList ( list ) ; } list . clear ( ) ; } System . out . println ( ) ; Iterator itr = longestList . iterator ( ) ; System . out . println ( " The ▁ Longest ▁ subsequence " ) ; while ( itr . hasNext ( ) ) { System . out . print ( itr . next ( ) + " ▁ " ) ; } System . out . println ( ) ; System . out . println ( " Length ▁ of ▁ LIS : ▁ " + highestCount ) ; } }


"Construction of Longest Increasing Subsequence ( LIS ) and printing LIS sequence | Dynamic Programming solution to conLongest Increasing Subsequence ; Utility function to print LIS ; Function to conand print Longest Increasing Subsequence ; L [ i ] - The longest increasing sub - sequence ends with arr [ i ] ; L [ 0 ] is equal to arr [ 0 ] ; Start from index 1 ; Do for every j less than i ; L [ i ] = { Max ( L [ j ] ) } + arr [ i ] where j < i and arr [ j ] < arr [ i ] ; L [ i ] ends with arr [ i ] ; L [ i ] now stores increasing sub - sequence of arr [ 0. . i ] that ends with arr [ i ] ; LIS will be max of all increasing sub - sequences of arr ; max will contain LIS ; Driver function ; construct and print LIS of arr"
How can the above be solved in Java?

import java . util . * ; class GFG { static void printLIS ( Vector < Integer > arr ) { for ( int x : arr ) System . out . print ( x + " ▁ " ) ; System . out . println ( ) ; } static void constructPrintLIS ( int arr [ ] , int n ) { Vector < Integer > L [ ] = new Vector [ n ] ; for ( int i = 0 ; i < L . length ; i ++ ) L [ i ] = new Vector < Integer > ( ) ; L [ 0 ] . add ( arr [ 0 ] ) ; for ( int i = 1 ; i < n ; i ++ ) { for ( int j = 0 ; j < i ; j ++ ) { if ( ( arr [ i ] > arr [ j ] ) && ( L [ i ] . size ( ) < L [ j ] . size ( ) + 1 ) ) L [ i ] = L [ j ] ; } L [ i ] . add ( arr [ i ] ) ; } Vector < Integer > max = L [ 0 ] ; for ( Vector < Integer > x : L ) if ( x . size ( ) > max . size ( ) ) max = x ; printLIS ( max ) ; } public static void main ( String [ ] args ) { int arr [ ] = { 3 , 2 , 4 , 5 , 1 } ; int n = arr . length ; constructPrintLIS ( arr , n ) ; } }


"Construction of Longest Increasing Subsequence ( N log N ) | Java implementation to find longest increasing subsequence in O ( n Log n ) time . ; Binary search ; Add boundary case , when array n is zero Depend on smart pointers ; initialized with - 1 ; it will always point to empty location ; new smallest value ; arr [ i ] wants to extend largest subsequence ; arr [ i ] wants to be a potential condidate of future subsequence It will replace ceil value in tailIndices ; Driver code"
How can the above be solved in Java?

 import java . util . Arrays ; class GFG { static int GetCeilIndex ( int arr [ ] , int T [ ] , int l , int r , int key ) { while ( r - l > 1 ) { int m = l + ( r - l ) / 2 ; if ( arr [ T [ m ] ] >= key ) r = m ; else l = m ; } return r ; } static int LongestIncreasingSubsequence ( int arr [ ] , int n ) { int tailIndices [ ] = new int [ n ] ; Arrays . fill ( tailIndices , 0 ) ; int prevIndices [ ] = new int [ n ] ; Arrays . fill ( prevIndices , - 1 ) ; int len = 1 ; for ( int i = 1 ; i < n ; i ++ ) { if ( arr [ i ] < arr [ tailIndices [ 0 ] ] ) tailIndices [ 0 ] = i ; else if ( arr [ i ] > arr [ tailIndices [ len - 1 ] ] ) { prevIndices [ i ] = tailIndices [ len - 1 ] ; tailIndices [ len ++ ] = i ; } else { int pos = GetCeilIndex ( arr , tailIndices , - 1 , len - 1 , arr [ i ] ) ; prevIndices [ i ] = tailIndices [ pos - 1 ] ; tailIndices [ pos ] = i ; } } System . out . println ( " LIS ▁ of ▁ given ▁ input " ) ; for ( int i = tailIndices [ len - 1 ] ; i >= 0 ; i = prevIndices [ i ] ) System . out . print ( arr [ i ] + " ▁ " ) ; System . out . println ( ) ; return len ; } public static void main ( String [ ] args ) { int arr [ ] = { 2 , 5 , 3 , 7 , 11 , 8 , 10 , 13 , 6 } ; int n = arr . length ; System . out . print ( "LIS size
" + LongestIncreasingSubsequence(arr, n)); } }


"Container with Most Water | Java code for Max Water Container ; Calculating the max area ; Driver code"
How can the above be solved in Java?

 import java . util . * ; class Area { public static int maxArea ( int A [ ] , int len ) { int l = 0 ; int r = len - 1 ; int area = 0 ; while ( l < r ) { area = Math . max ( area , Math . min ( A [ l ] , A [ r ] ) * ( r - l ) ) ; if ( A [ l ] < A [ r ] ) l += 1 ; else r -= 1 ; } return area ; } public static void main ( String [ ] args ) { int a [ ] = { 1 , 5 , 4 , 3 } ; int b [ ] = { 3 , 1 , 2 , 4 , 5 } ; int len1 = 4 ; System . out . print ( maxArea ( a , len1 ) + "
" ); int len2 = 5 ; System . out . print ( maxArea ( b , len2 ) ) ; } }


import java . io . * ; class GFG { public static int maxArea ( int [ ] a ) { int Area = 0 ; for ( int i = 0 ; i < a . length ; i ++ ) { for ( int j = i + 1 ; j < a . length ; j ++ ) { Area = Math . max ( Area , Math . min ( a [ i ] , a [ j ] ) * ( j - i ) ) ; } } return Area ; } public static void main ( String [ ] args ) { int a [ ] = { 1 , 5 , 4 , 3 } ; int b [ ] = { 3 , 1 , 2 , 4 , 5 } ; System . out . println ( maxArea ( a ) ) ; System . out . println ( maxArea ( b ) ) ; } }


"Content of a Polynomial | Java implementation to find the content of the polynomial ; Function to find the content of the polynomial ; Loop to iterate over the elements of the array ; __gcd ( a , b ) is a inbuilt function for Greatest Common Divisor ; Driver Code ; Function call"
How can the above be solved in Java?

class GFG { static int findContent ( int arr [ ] , int n ) { int content = arr [ 0 ] ; for ( int i = 1 ; i < n ; i ++ ) { content = __gcd ( content , arr [ i ] ) ; } return content ; } static int __gcd ( int a , int b ) { return b == 0 ? a : __gcd ( b , a % b ) ; } public static void main ( String [ ] args ) { int n = 3 ; int arr [ ] = { 9 , 6 , 12 } ; System . out . print ( findContent ( arr , n ) ) ; } }