codeparrot/xlcost-text-to-code huggingface dataset:
Count distinct regular bracket sequences which are not N periodic | Java program for above approach ; Function that finds the value of Binomial Coefficient C ( n , k ) ; Since C ( n , k ) = C ( n , n - k ) ; Calculate the value of [ n * ( n - 1 ) * -- - * ( n - k + 1 ) ] / [ k * ( k - 1 ) * -- - * 1 ] ; Return the C ( n , k ) ; Binomial coefficient based function to find nth catalan number in O ( n ) time ; Calculate value of 2 nCn ; Return C ( 2 n , n ) / ( n + 1 ) ; Function to find possible ways to put balanced parenthesis in an expression of length n ; If n is odd , not possible to create any valid parentheses ; Otherwise return n / 2 th Catalan Number ; Difference between counting ways of 2 * N and N is the result ; Driver code ; Given value of N ; Function call
import java . io . * ; class GFG { static long binomialCoeff ( int n , int k ) { long res = 1 ; if ( k > n - k ) k = n - k ; for ( int i = 0 ; i < k ; ++ i ) { res *= ( n - i ) ; res /= ( i + 1 ) ; } return res ; } static long catalan ( int n ) { long c = binomialCoeff ( 2 * n , n ) ; return c / ( n + 1 ) ; } static long findWays ( int n ) { if ( ( n & 1 ) == 1 ) return 0 ; return catalan ( n / 2 ) ; } static void countNonNPeriodic ( int N ) { System . out . println ( findWays ( 2 * N ) - findWays ( N ) ) ; } public static void main ( String [ ] args ) { int N = 4 ; countNonNPeriodic ( N ) ; } }
Check if two elements of a matrix are on the same diagonal or not | Java implementation of the above approach ; Function to check if two integers are on the same diagonal of the matrix ; Storing indexes of x in I , J ; Storing Indexes of y in P , Q ; Condition to check if the both the elements are in same diagonal of a matrix ; Driver Code ; Dimensions of Matrix ; Given Matrix ; Elements to be checked ; Function call
class GFG { static void checkSameDiag ( int li [ ] [ ] , int x , int y , int m , int n ) { int I = 0 , J = 0 ; int P = 0 , Q = 0 ; for ( int i = 0 ; i < m ; i ++ ) { for ( int j = 0 ; j < n ; j ++ ) { if ( li [ i ] [ j ] == x ) { I = i ; J = j ; } if ( li [ i ] [ j ] == y ) { P = i ; Q = j ; } } } if ( P - Q == I - J P + Q == I + J ) { System . out . println ( " YES " ) ; } else System . out . println ( " NO " ) ; } public static void main ( String [ ] args ) { int m = 6 ; int n = 5 ; int [ ] [ ] li = { { 32 , 94 , 99 , 26 , 82 } , { 51 , 69 , 52 , 63 , 17 } , { 90 , 36 , 88 , 55 , 33 } , { 93 , 42 , 73 , 39 , 28 } , { 81 , 31 , 83 , 53 , 10 } , { 12 , 29 , 85 , 80 , 87 } } ; int x = 42 ; int y = 80 ; checkSameDiag ( li , x , y , m , n ) ; } }
Count of decrement operations required to obtain K in N steps | Java program for the above approach ; Function to check whether m number of steps of type 1 are valid or not ; If m and n are the count of operations of type 1 and type 2 respectively , then n - m operations are performed ; Find the value of S after step 2 ; If m steps of type 1 is valid ; Function to find the number of operations of type 1 required ; Iterate over the range ; Find the value of mid ; Check if m steps of type 1 are valid or not ; If mid is the valid number of steps ; If no valid number of steps exist ; Driver Code ; Given and N , K ; Function call
import java . util . * ; class GFG { static int isValid ( int n , int m , int k ) { int step2 = n - m ; int cnt = ( step2 * ( step2 + 1 ) ) / 2 ; if ( cnt - m == k ) return 0 ; if ( cnt - m > k ) return 1 ; return - 1 ; } static void countOfOperations ( int n , int k ) { int start = 0 , end = n ; boolean ok = true ; while ( start <= end ) { int mid = ( start + end ) / 2 ; int temp = isValid ( n , mid , k ) ; if ( temp == 0 ) { ok = false ; System . out . print ( mid ) ; break ; } else if ( temp == 1 ) { start = mid + 1 ; } else { end = mid - 1 ; } } if ( ok ) System . out . print ( " - 1" ) ; } public static void main ( String [ ] args ) { int N = 5 , K = 4 ; countOfOperations ( N , K ) ; } }
Print all Possible Decodings of a given Digit Sequence | Java program for the above approach ; Function to check if all the characters are lowercase or not ; Traverse the string ; If any character is not found to be in lowerCase ; Function to print the decodings ; If all characters are not in lowercase ; Function to return the character corresponding to given integer ; Function to return the decodings ; Base case ; Recursive call ; Stores the characters of two digit numbers ; Extract first digit and first two digits ; Check if it lies in the range of alphabets ; Next recursive call ; Combine both the output in a single final output array ; Index of final output array ; Store the elements of output1 in final output array ; Store the elements of output2 in final output array ; Result the result ; Driver Code ; Function call ; Print function call
import java . io . * ; class GFG { public static boolean nonLower ( String s ) { for ( int i = 0 ; i < s . length ( ) ; i ++ ) { if ( ! Character . isLowerCase ( s . charAt ( i ) ) ) { return true ; } } return false ; } public static void printCodes ( String output [ ] ) { for ( int i = 0 ; i < output . length ; i ++ ) { if ( nonLower ( output [ i ] ) ) continue ; System . out . println ( output [ i ] ) ; } } public static char getChar ( int n ) { return ( char ) ( n + 96 ) ; } public static String [ ] getCode ( String str ) { if ( str . length ( ) == 0 ) { String ans [ ] = { " " } ; return ans ; } String output1 [ ] = getCode ( str . substring ( 1 ) ) ; String output2 [ ] = new String [ 0 ] ; int firstDigit = ( str . charAt ( 0 ) - '0' ) ; int firstTwoDigit = 0 ; if ( str . length ( ) >= 2 ) { firstTwoDigit = ( str . charAt ( 0 ) - '0' ) * 10 + ( str . charAt ( 1 ) - '0' ) ; if ( firstTwoDigit >= 10 && firstTwoDigit <= 26 ) { output2 = getCode ( str . substring ( 2 ) ) ; } } String output [ ] = new String [ output1 . length + output2 . length ] ; int k = 0 ; for ( int i = 0 ; i < output1 . length ; i ++ ) { char ch = getChar ( firstDigit ) ; output [ i ] = ch + output1 [ i ] ; k ++ ; } for ( int i = 0 ; i < output2 . length ; i ++ ) { char ch = getChar ( firstTwoDigit ) ; output [ k ] = ch + output2 [ i ] ; k ++ ; } return output ; } public static void main ( String [ ] args ) { String input = "101" ; String output [ ] = getCode ( input ) ; printCodes ( output ) ; } }
Count prime numbers that can be expressed as sum of consecutive prime numbers | Java program for the above approach ; Function to check if a number is prime or not ; Base Case ; Iterate till [ 5 , Math . sqrt ( N ) ] to detect primality of numbers ; If N is divisible by i or i + 2 ; Return 1 if N is prime ; Function to count the prime numbers which can be expressed as sum of consecutive prime numbers ; Initialize count as 0 ; Stores prime numbers ; If i is prime ; Initialize the sum ; Find all required primes upto N ; Add it to the sum ; Return the final count ; Driver Code ; Given number N ; Function Call
import java . util . * ; class GFG { static int isprm ( int n ) { if ( n <= 1 ) return 0 ; if ( n <= 3 ) return 1 ; if ( n % 2 == 0 n % 3 == 0 ) return 0 ; for ( int i = 5 ; i * i <= n ; i = i + 6 ) { if ( n % i == 0 || n % ( i + 2 ) == 0 ) return 0 ; } return 1 ; } static int countprime ( int n ) { int count = 0 ; Vector < Integer > primevector = new Vector < > ( ) ; for ( int i = 2 ; i <= n ; i ++ ) { if ( isprm ( i ) == 1 ) { primevector . add ( i ) ; } } int sum = primevector . elementAt ( 0 ) ; for ( int i = 1 ; i < primevector . size ( ) ; i ++ ) { sum += primevector . elementAt ( i ) ; if ( sum > n ) break ; if ( isprm ( sum ) == 1 ) { count ++ ; } } return count ; } public static void main ( String [ ] args ) { int N = 45 ; System . out . print ( countprime ( N ) ) ; } }
Find a subarray of size K whose sum is a perfect square | Java program for the above approach ; Function to check if a given number is a perfect square or not ; Find square root of n ; Check if the square root is an integer or not ; Function to print the subarray whose sum is a perfect square ; Sum of first K elements ; If the first k elements have a sum as perfect square ; Iterate through the array ; If sum is perfect square ; If subarray not found ; Driver Code ; Given array ; Given subarray size K ; Function Call
class GFG { static class pair { int first , second ; } static boolean isPerfectSquare ( int n ) { double sr = Math . sqrt ( n ) ; return ( ( sr - Math . floor ( sr ) ) == 0 ) ; } static void SubarrayHavingPerfectSquare ( int [ ] arr , int k ) { pair ans = new pair ( ) ; int sum = 0 , i ; for ( i = 0 ; i < k ; i ++ ) { sum += arr [ i ] ; } boolean found = false ; if ( isPerfectSquare ( sum ) ) { ans . first = 0 ; ans . second = i - 1 ; } else { for ( int j = i ; j < arr . length ; j ++ ) { sum = sum + arr [ j ] - arr [ j - k ] ; if ( isPerfectSquare ( sum ) ) { found = true ; ans . first = j - k + 1 ; ans . second = j ; } } for ( int k1 = ans . first ; k1 <= ans . second ; k1 ++ ) { System . out . print ( arr [ k1 ] + " ▁ " ) ; } } if ( found == false ) { System . out . print ( " - 1" ) ; } } public static void main ( String [ ] args ) { int [ ] arr = { 20 , 34 , 51 , 10 , 99 , 87 , 23 , 45 } ; int K = 3 ; SubarrayHavingPerfectSquare ( arr , K ) ; } }
Check if any permutation of a number without any leading zeros is a power of 2 or not | Java program for the above approach ; Function to update the frequency array such that freq [ i ] stores the frequency of digit i to n ; While there are digits left to process ; Update the frequency of the current digit ; Remove the last digit ; Function that returns true if a and b are anagrams of each other ; To store the frequencies of the digits in a and b ; Update the frequency of the digits in a ; Update the frequency of the digits in b ; Match the frequencies of the common digits ; If frequency differs for any digit then the numbers are not anagrams of each other ; Function to check if any permutation of a number is a power of 2 or not ; Iterate over all possible perfect power of 2 ; Print that number ; Driver Code ; Given number N ; Function call
import java . util . * ; class GFG { static int TEN = 10 ; static void updateFreq ( int n , int freq [ ] ) { while ( n > 0 ) { int digit = n % TEN ; freq [ digit ] ++ ; n /= TEN ; } } static boolean areAnagrams ( int a , int b ) { int freqA [ ] = new int [ TEN ] ; int freqB [ ] = new int [ TEN ] ; updateFreq ( a , freqA ) ; updateFreq ( b , freqB ) ; for ( int i = 0 ; i < TEN ; i ++ ) { if ( freqA [ i ] != freqB [ i ] ) return false ; } return true ; } static boolean isPowerOf2 ( int N ) { for ( int i = 0 ; i < 32 ; i ++ ) { if ( areAnagrams ( 1 << i , N ) ) { System . out . print ( ( 1 << i ) ) ; return true ; } } return false ; } public static void main ( String [ ] args ) { int N = 46 ; if ( ! isPowerOf2 ( N ) ) { System . out . print ( " No " ) ; } } }
Count number of triangles possible with length of sides not exceeding N | Java implementation of the above approach ; Function to count total number of right angled triangle ; Initialise count with 0 ; Run three nested loops and check all combinations of sides ; Condition for right angled triangle ; Increment count ; Driver code ; Given N ; Function call
import java . io . * ; class GFG { static int right_angled ( int n ) { int count = 0 ; for ( int z = 1 ; z <= n ; z ++ ) { for ( int y = 1 ; y <= z ; y ++ ) { for ( int x = 1 ; x <= y ; x ++ ) { if ( ( x * x ) + ( y * y ) == ( z * z ) ) { count ++ ; } } } } return count ; } public static void main ( String [ ] args ) { int n = 5 ; System . out . println ( right_angled ( n ) ) ; } }
Check if the given two matrices are mirror images of one another | Java implementation of the above approach ; Function to check whether the two matrices are mirror of each other ; Initialising row and column of second matrix ; Iterating over the matrices ; Check row of first matrix with reversed row of second matrix ; If the element is not equal ; Increment column ; Reset column to 0 for new row ; Increment row ; Driver code ; Given 2 matrices ; Function Call
import java . util . * ; class GFG { static void mirrorMatrix ( int mat1 [ ] [ ] , int mat2 [ ] [ ] , int N ) { int row = 0 ; int col = 0 ; boolean isMirrorImage = true ; for ( int i = 0 ; i < N ; i ++ ) { for ( int j = N - 1 ; j >= 0 ; j -- ) { if ( mat2 [ row ] [ col ] != mat1 [ i ] [ j ] ) { isMirrorImage = false ; } col ++ ; } col = 0 ; row ++ ; } if ( isMirrorImage ) System . out . print ( " Yes " ) ; else System . out . print ( " No " ) ; } public static void main ( String [ ] args ) { int N = 4 ; int mat1 [ ] [ ] = { { 1 , 2 , 3 , 4 } , { 0 , 6 , 7 , 8 } , { 9 , 10 , 11 , 12 } , { 13 , 14 , 15 , 16 } } ; int mat2 [ ] [ ] = { { 4 , 3 , 2 , 1 } , { 8 , 7 , 6 , 0 } , { 12 , 11 , 10 , 9 } , { 16 , 15 , 14 , 13 } } ; mirrorMatrix ( mat1 , mat2 , N ) ; } }
Calculate number of nodes between two vertices in an acyclic Graph by DFS method | Java program for the above approach ; Function to return the count of nodes in the path from source to destination ; Mark the node visited ; If dest is reached ; Traverse all adjacent nodes ; If not already visited ; If there is path , then include the current node ; Return 0 if there is no path between src and dest through the current node ; Function to return the count of nodes between two given vertices of the acyclic Graph ; Initialize an adjacency list ; Populate the edges in the list ; Mark all the nodes as not visited ; Count nodes in the path from src to dest ; Return the nodes between src and dest ; Driver Code ; Given number of vertices and edges ; Given source and destination vertices ; Given edges
import java . util . Vector ; class GFG { static int dfs ( int src , int dest , int [ ] vis , Vector < Integer > [ ] adj ) { vis [ src ] = 1 ; if ( src == dest ) { return 1 ; } for ( int u : adj [ src ] ) { if ( vis [ u ] == 0 ) { int temp = dfs ( u , dest , vis , adj ) ; if ( temp != 0 ) { return temp + 1 ; } } } return 0 ; } static int countNodes ( int V , int E , int src , int dest , int edges [ ] [ ] ) { Vector < Integer > [ ] adj = new Vector [ V + 1 ] ; for ( int i = 0 ; i < adj . length ; i ++ ) adj [ i ] = new Vector < Integer > ( ) ; for ( int i = 0 ; i < E ; i ++ ) { adj [ edges [ i ] [ 0 ] ] . add ( edges [ i ] [ 1 ] ) ; adj [ edges [ i ] [ 1 ] ] . add ( edges [ i ] [ 0 ] ) ; } int vis [ ] = new int [ V + 1 ] ; int count = dfs ( src , dest , vis , adj ) ; return count - 2 ; } public static void main ( String [ ] args ) { int V = 8 , E = 7 ; int src = 5 , dest = 2 ; int edges [ ] [ ] = { { 1 , 4 } , { 4 , 5 } , { 4 , 2 } , { 2 , 6 } , { 6 , 3 } , { 2 , 7 } , { 3 , 8 } } ; System . out . print ( countNodes ( V , E , src , dest , edges ) ) ; } }
Check if all array elements are pairwise co | Java program for the above approach ; Function to calculate GCD ; Function to calculate LCM ; Function to check if all elements in the array are pairwise coprime ; Initialize variables ; Iterate over the array ; Calculate product of array elements ; Calculate LCM of array elements ; If the product of array elements is equal to LCM of the array ; Driver Code ; Function call
import java . util . * ; import java . lang . * ; class GFG { static long GCD ( long a , long b ) { if ( a == 0 ) return b ; return GCD ( b % a , a ) ; } static long LCM ( long a , long b ) { return ( a * b ) / GCD ( a , b ) ; } static void checkPairwiseCoPrime ( int A [ ] , int n ) { long prod = 1 ; long lcm = 1 ; for ( int i = 0 ; i < n ; i ++ ) { prod *= A [ i ] ; lcm = LCM ( A [ i ] , lcm ) ; } if ( prod == lcm ) System . out . println ( " Yes " ) ; else System . out . println ( " No " ) ; } public static void main ( String [ ] args ) { int A [ ] = { 2 , 3 , 5 } ; int n = A . length ; checkPairwiseCoPrime ( A , n ) ; } }
Partition a set into two non | Java Program for above approach ; Function to return the maximum difference between the subset sums ; Stores the total sum of the array ; Checks for positive and negative elements ; Stores the minimum element from the given array ; Traverse the array ; Calculate total sum ; Mark positive element present in the set ; Mark negative element present in the set ; Find the minimum element of the set ; If the array contains both positive and negative elements ; Otherwise ; Driver Code ; Given the array ; Length of the array ; Function Call
import java . util . * ; import java . lang . * ; class GFG { static int maxDiffSubsets ( int [ ] arr ) { int totalSum = 0 ; boolean pos = false , neg = false ; int min = Integer . MAX_VALUE ; for ( int i = 0 ; i < arr . length ; i ++ ) { totalSum += Math . abs ( arr [ i ] ) ; if ( arr [ i ] > 0 ) pos = true ; if ( arr [ i ] < 0 ) neg = true ; if ( arr [ i ] < min ) min = arr [ i ] ; } if ( pos && neg ) return totalSum ; else return totalSum - 2 * min ; } public static void main ( String [ ] args ) { int [ ] S = { 1 , 2 , 1 } ; int N = S . length ; if ( N < 2 ) System . out . println ( " Not ▁ Possible " ) ; else System . out . println ( maxDiffSubsets ( S ) ) ; } }
Split array into two subarrays such that difference of their sum is minimum | Java Program for above approach ; Function to return minimum difference between two subarray sums ; To store prefix sums ; Generate prefix sum array ; To store suffix sums ; Generate suffix sum array ; Stores the minimum difference ; Traverse the given array ; Calculate the difference ; Update minDiff ; Return minDiff ; Driver Code ; Given array ; Length of the array
import java . util . * ; import java . lang . * ; class GFG { static int minDiffSubArray ( int arr [ ] , int n ) { int [ ] prefix_sum = new int [ n ] ; prefix_sum [ 0 ] = arr [ 0 ] ; for ( int i = 1 ; i < n ; i ++ ) prefix_sum [ i ] = prefix_sum [ i - 1 ] + arr [ i ] ; int [ ] suffix_sum = new int [ n ] ; suffix_sum [ n - 1 ] = arr [ n - 1 ] ; for ( int i = n - 2 ; i >= 0 ; i -- ) suffix_sum [ i ] = suffix_sum [ i + 1 ] + arr [ i ] ; int minDiff = Integer . MAX_VALUE ; for ( int i = 0 ; i < n - 1 ; i ++ ) { int diff = Math . abs ( prefix_sum [ i ] - suffix_sum [ i + 1 ] ) ; if ( diff < minDiff ) minDiff = diff ; } return minDiff ; } public static void main ( String [ ] args ) { int [ ] arr = { 7 , 9 , 5 , 10 } ; int n = arr . length ; System . out . println ( minDiffSubArray ( arr , n ) ) ; } }
Count of days remaining for the next day with higher temperature | Java program for the above approach ; Function to determine how many days required to wait for the next warmer temperature ; To store the answer ; Traverse all the temperatures ; Check if current index is the next warmer temperature of any previous indexes ; Pop the element ; Push the current index ; Print waiting days ; Driver Code ; Given temperatures ; Function call
import java . util . * ; import java . lang . * ; class GFG { static void dailyTemperatures ( int [ ] T ) { int n = T . length ; int [ ] daysOfWait = new int [ n ] ; Arrays . fill ( daysOfWait , - 1 ) ; Stack < Integer > s = new Stack < > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { while ( ! s . isEmpty ( ) && T [ s . peek ( ) ] < T [ i ] ) { daysOfWait [ s . peek ( ) ] = i - s . peek ( ) ; s . pop ( ) ; } s . push ( i ) ; } for ( int i = 0 ; i < n ; i ++ ) { System . out . print ( daysOfWait [ i ] + " ▁ " ) ; } } public static void main ( String [ ] args ) { int [ ] arr = { 73 , 74 , 75 , 71 , 69 , 72 , 76 , 73 } ; dailyTemperatures ( arr ) ; } }
Check if an array contains only one distinct element | Java program for the above approach ; Function to find if the array contains only one distinct element ; Create a set ; Traversing the array ; Compare and print the result ; Driver Code ; Function call
import java . util . * ; public class Main { public static void uniqueElement ( int arr [ ] ) { Set < Integer > set = new HashSet < > ( ) ; for ( int i = 0 ; i < arr . length ; i ++ ) { set . add ( arr [ i ] ) ; } if ( set . size ( ) == 1 ) System . out . println ( " Yes " ) ; else System . out . println ( " No " ) ; } public static void main ( String args [ ] ) { int arr [ ] = { 9 , 9 , 9 , 9 , 9 , 9 , 9 } ; uniqueElement ( arr ) ; } }
Maximum cost of splitting given Binary Tree into two halves | Java program for the above approach ; To store the results and sum of all nodes in the array ; To create adjacency list ; Function to add edges into the adjacency list ; Recursive function that calculate the value of the cost of splitting the tree recursively ; Fetch the child of node - r ; Neglect if cur node is parent ; Add all values of nodes which are decendents of r ; The two trees formed are rooted at ' r ' with its decendents ; Check and replace if current product t1 * t2 is large ; Function to find the maximum cost after splitting the tree in 2 halves ; Find sum of values in all nodes ; Traverse edges to create adjacency list ; Function Call ; Driver Code ; Values in each node ; Given Edges
import java . util . * ; class GFG { static int ans = 0 , allsum = 0 ; static Vector < Integer > [ ] edges = new Vector [ 100001 ] ; static void addedge ( int a , int b ) { edges [ a ] . add ( b ) ; edges [ b ] . add ( a ) ; } static void findCost ( int r , int p , int arr [ ] ) { int i , cur ; for ( i = 0 ; i < edges [ r ] . size ( ) ; i ++ ) { cur = edges [ r ] . get ( i ) ; if ( cur == p ) continue ; findCost ( cur , r , arr ) ; arr [ r ] += arr [ cur ] ; } int t1 = arr [ r ] ; int t2 = allsum - t1 ; if ( t1 * t2 > ans ) { ans = t1 * t2 ; } } static void maximumCost ( int r , int p , int N , int M , int arr [ ] , int Edges [ ] [ ] ) { for ( int i = 0 ; i < N ; i ++ ) { allsum += arr [ i ] ; } for ( int i = 0 ; i < M ; i ++ ) { addedge ( Edges [ i ] [ 0 ] , Edges [ i ] [ 1 ] ) ; } findCost ( r , p , arr ) ; } public static void main ( String [ ] args ) { int a , b , N = 6 ; int arr [ ] = { 13 , 8 , 7 , 4 , 5 , 9 } ; int M = 5 ; int Edges [ ] [ ] = { { 0 , 1 } , { 1 , 2 } , { 1 , 4 } , { 3 , 4 } , { 4 , 5 } } ; for ( int i = 0 ; i < edges . length ; i ++ ) edges [ i ] = new Vector < Integer > ( ) ; maximumCost ( 1 , - 1 , N , M , arr , Edges ) ; System . out . print ( ans ) ; } }
Diameters for each node of Tree after connecting it with given disconnected component | Java Program to implement the above approach ; Keeps track of the farthest end of the diameter ; Keeps track of the length of the diameter ; Stores the nodes which are at ends of the diameter ; Perform DFS on the given tree ; Update diameter and X ; If current node is an end of diameter ; Traverse its neighbors ; Function to call DFS for the required purposes ; DFS from a random node and find the node farthest from it ; DFS from X to calculate diameter ; DFS from farthest_node to find the farthest node ( s ) from it ; DFS from X ( other end of diameter ) and check the farthest node ( s ) from it ; If node i is the end of a diameter ; Increase diameter by 1 ; Otherwise ; Remains unchanged ; Driver Code ; constructed tree is 1 / \ 2 3 7 / | \ / | \ 4 5 6 ; creating undirected edges
import java . util . * ; class GFG { static int X = 1 ; static int diameter = 0 ; static HashMap < Integer , Boolean > mp = new HashMap < > ( ) ; static void dfs ( int current_node , int prev_node , int len , boolean add_to_map , Vector < Integer > [ ] adj ) { if ( len > diameter ) { diameter = len ; X = current_node ; } if ( add_to_map && len == diameter ) { mp . put ( current_node , true ) ; } for ( int it : adj [ current_node ] ) { if ( it != prev_node ) dfs ( it , current_node , len + 1 , add_to_map , adj ) ; } } static void dfsUtility ( Vector < Integer > [ ] adj ) { dfs ( 1 , - 1 , 0 , false , adj ) ; int farthest_node = X ; dfs ( farthest_node , - 1 , 0 , false , adj ) ; dfs ( farthest_node , - 1 , 0 , true , adj ) ; dfs ( X , - 1 , 0 , true , adj ) ; } static void printDiameters ( Vector < Integer > [ ] adj ) { dfsUtility ( adj ) ; for ( int i = 1 ; i <= 6 ; i ++ ) { if ( mp . containsKey ( i ) && mp . get ( i ) == true ) System . out . print ( diameter + 1 + " , ▁ " ) ; else System . out . print ( diameter + " , ▁ " ) ; } } public static void main ( String [ ] args ) { Vector < Integer > [ ] adj = new Vector [ 7 ] ; for ( int i = 0 ; i < adj . length ; i ++ ) adj [ i ] = new Vector < Integer > ( ) ; adj [ 1 ] . add ( 2 ) ; adj [ 2 ] . add ( 1 ) ; adj [ 1 ] . add ( 3 ) ; adj [ 3 ] . add ( 1 ) ; adj [ 2 ] . add ( 4 ) ; adj [ 4 ] . add ( 2 ) ; adj [ 2 ] . add ( 5 ) ; adj [ 5 ] . add ( 2 ) ; adj [ 2 ] . add ( 6 ) ; adj [ 6 ] . add ( 2 ) ; printDiameters ( adj ) ; } }