codeparrot/xlcost-text-to-code huggingface dataset:
Iterative method to check if two trees are mirror of each other | Java implementation to check whether the two binary tress are mirrors of each other or not ; structure of a node in binary tree ; Utility function to create and return a new node for a binary tree ; function to check whether the two binary trees are mirrors of each other or not ; iterative inorder traversal of 1 st tree and reverse inoder traversal of 2 nd tree ; if the corresponding nodes in the two traversal have different data values , then they are not mirrors of each other . ; if at any point one root becomes null and the other root is not null , then they are not mirrors . This condition verifies that structures of tree are mirrors of each other . ; we have visited the node and its left subtree . Now , it ' s ▁ right ▁ subtree ' s turn ; we have visited the node and its right subtree . Now , it ' s ▁ left ▁ subtree ' s turn ; both the trees have been completely traversed ; tress are mirrors of each other ; Driver program to test above ; 1 st binary tree formation ; 1 ; / \ ; 3 2 ; / \ ; 2 nd binary tree formation ; 1 ; / \ ; 2 3 ; / \ ; 4 5
import java . util . * ; class GfG { static class Node { int data ; Node left , right ; } static Node newNode ( int data ) { Node temp = new Node ( ) ; temp . data = data ; temp . left = null ; temp . right = null ; return temp ; } static String areMirrors ( Node root1 , Node root2 ) { Stack < Node > st1 = new Stack < Node > ( ) ; Stack < Node > st2 = new Stack < Node > ( ) ; while ( true ) { while ( root1 != null && root2 != null ) { if ( root1 . data != root2 . data ) return " No " ; st1 . push ( root1 ) ; st2 . push ( root2 ) ; root1 = root1 . left ; root2 = root2 . right ; } if ( ! ( root1 == null && root2 == null ) ) return " No " ; if ( ! st1 . isEmpty ( ) && ! st2 . isEmpty ( ) ) { root1 = st1 . peek ( ) ; root2 = st2 . peek ( ) ; st1 . pop ( ) ; st2 . pop ( ) ; root1 = root1 . right ; root2 = root2 . left ; } else break ; } return " Yes " ; } public static void main ( String [ ] args ) { Node root1 = newNode ( 1 ) ; root1 . left = newNode ( 3 ) ; root1 . right = newNode ( 2 ) ; root1 . right . left = newNode ( 5 ) ; root1 . right . right = newNode ( 4 ) ; Node root2 = newNode ( 1 ) ; root2 . left = newNode ( 2 ) ; root2 . right = newNode ( 3 ) ; root2 . left . left = newNode ( 4 ) ; root2 . left . right = newNode ( 5 ) ; System . out . println ( areMirrors ( root1 , root2 ) ) ; } }
Maximum score assigned to a subsequence of numerically consecutive and distinct array elements | Java program for the above approach ; Function to find the maximum score possible ; Base Case ; If previously occurred subproblem occurred ; Check if lastpicked element differs by 1 from the current element ; Calculate score by including the current element ; Calculate score by excluding the current element ; Return maximum score from the two possibilities ; Function to print maximum score ; DP array to store results ; Initialise dp with - 1 ; Function call ; Driver Code ; Given arrays ; Function Call
import java . util . * ; class GFG { public static int maximumSum ( int [ ] a , int [ ] b , int n , int index , int lastpicked , int [ ] [ ] dp ) { if ( index == n ) return 0 ; if ( dp [ index ] [ lastpicked + 1 ] != - 1 ) return dp [ index ] [ lastpicked + 1 ] ; int option1 = 0 , option2 = 0 ; if ( lastpicked == - 1 a [ lastpicked ] != a [ index ] ) { option1 = b [ index ] + maximumSum ( a , b , n , index + 1 , index , dp ) ; } option2 = maximumSum ( a , b , n , index + 1 , lastpicked , dp ) ; return dp [ index ] [ lastpicked + 1 ] = Math . max ( option1 , option2 ) ; } public static void maximumPoints ( int arr [ ] , int brr [ ] , int n ) { int index = 0 , lastPicked = - 1 ; int dp [ ] [ ] = new int [ n + 5 ] [ n + 5 ] ; for ( int i [ ] : dp ) Arrays . fill ( i , - 1 ) ; System . out . println ( maximumSum ( arr , brr , n , index , lastPicked , dp ) ) ; } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 2 , 3 , 3 , 3 , 1 } ; int brr [ ] = { - 1 , 2 , 10 , 20 , - 10 , - 9 } ; int N = arr . length ; maximumPoints ( arr , brr , N ) ; } }
Maximum possible sum of a window in an array such that elements of same window in other array are unique | Java program to find the maximum possible sum of a window in one array such that elements in same window of other array are unique . ; Function to return maximum sum of window in A [ ] according to given constraints . ; Map is used to store elements and their counts . ; Initialize result ; calculating the maximum possible sum for each subarray containing unique elements . ; Remove all duplicate instances of A [ i ] in current window . ; Add current instance of A [ i ] to map and to current sum . ; Update result if current sum is more . ; Driver Code to test above method
import java . util . HashSet ; import java . util . Set ; public class MaxPossibleSuminWindow { static int returnMaxSum ( int A [ ] , int B [ ] , int n ) { Set < Integer > mp = new HashSet < Integer > ( ) ; int result = 0 ; int curr_sum = 0 , curr_begin = 0 ; for ( int i = 0 ; i < n ; ++ i ) { while ( mp . contains ( A [ i ] ) ) { mp . remove ( A [ curr_begin ] ) ; curr_sum -= B [ curr_begin ] ; curr_begin ++ ; } mp . add ( A [ i ] ) ; curr_sum += B [ i ] ; result = Integer . max ( result , curr_sum ) ; } return result ; } public static void main ( String [ ] args ) { int A [ ] = { 0 , 1 , 2 , 3 , 0 , 1 , 4 } ; int B [ ] = { 9 , 8 , 1 , 2 , 3 , 4 , 5 } ; int n = A . length ; System . out . println ( returnMaxSum ( A , B , n ) ) ; } }
Length of second longest sequence of consecutive 1 s in a binary array | Java implementation of the above approach ; Function to find maximum and second maximum length ; Initialise maximum length ; Initialise second maximum length ; Initialise count ; Iterate over the array ; If sequence ends ; Reset count ; Otherwise ; Increase length of current sequence ; Update maximum ; Traverse the given array ; If sequence continues ; Increase length of current sequence ; Update second max ; Reset count when 0 is found ; Print the result ; Driver code ; Given array ; Function Call
import java . io . * ; import java . util . * ; class GFG { static void FindMax ( int arr [ ] , int N ) { int maxi = - 1 ; int maxi2 = - 1 ; int count = 0 ; for ( int i = 0 ; i < N ; ++ i ) { if ( arr [ i ] == 0 ) count = 0 ; else { count ++ ; maxi = Math . max ( maxi , count ) ; } } for ( int i = 0 ; i < N ; i ++ ) { if ( arr [ i ] == 1 ) { count ++ ; if ( count > maxi2 && count < maxi ) { maxi2 = count ; } } if ( arr [ i ] == 0 ) count = 0 ; } maxi = Math . max ( maxi , 0 ) ; maxi2 = Math . max ( maxi2 , 0 ) ; System . out . println ( maxi2 ) ; } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 1 , 1 , 0 , 0 , 1 , 1 } ; int n = arr . length ; FindMax ( arr , n ) ; } }
Count nodes from all lower levels smaller than minimum valued node of current level for every level in a Binary Tree | Java program of the above approach ; Stores the nodes to be deleted ; Structure of a Tree node ; Function to create a new node ; Function to find the min value of node for each level ; Count is used to diffentiate each level of the tree ; Function to check whether the nodes in the level below it are smaller by performing post order traversal ; Traverse the left subtree ; Traverse right subtree ; Check from minimum values computed at each level ; Function to print count of nodes from all lower levels having values less than the the nodes in the current level ; Stores the number of levels ; Stores the required count of nodes for each level ; Driver Code ; 4 / \ 3 5 / \ / \ 10 2 3 1
import java . util . * ; class GFG { static Map < Integer , Boolean > mp = new HashMap < Integer , Boolean > ( ) ; static class Node { int key ; Node left , right ; } ; static Node newNode ( int key ) { Node temp = new Node ( ) ; temp . key = key ; temp . left = temp . right = null ; return ( temp ) ; } static void calculateMin ( Node root , Vector < Integer > levelMin ) { Queue < Node > qt = new LinkedList < > ( ) ; qt . add ( root ) ; int count = 1 ; int min_v = Integer . MAX_VALUE ; while ( ! qt . isEmpty ( ) ) { Node temp = qt . peek ( ) ; min_v = Math . min ( min_v , temp . key ) ; qt . remove ( ) ; if ( temp . left != null ) { qt . add ( temp . left ) ; } if ( temp . right != null ) { qt . add ( temp . right ) ; } count -- ; if ( count == 0 ) { levelMin . add ( min_v ) ; min_v = Integer . MAX_VALUE ; count = qt . size ( ) ; } } } static void findNodes ( Node root , Vector < Integer > levelMin , int [ ] levelResult , int level ) { if ( root == null ) return ; findNodes ( root . left , levelMin , levelResult , level + 1 ) ; findNodes ( root . right , levelMin , levelResult , level + 1 ) ; for ( int i = 0 ; i < level ; i ++ ) { if ( root . key <= levelMin . get ( i ) ) { levelResult [ i ] += 1 ; } } } static void printNodes ( Node root ) { Vector < Integer > levelMin = new Vector < Integer > ( ) ; calculateMin ( root , levelMin ) ; int numLevels = levelMin . size ( ) ; int [ ] levelResult = new int [ numLevels ] ; findNodes ( root , levelMin , levelResult , 0 ) ; for ( int i = 0 ; i < numLevels ; i ++ ) { System . out . print ( levelResult [ i ] + " ▁ " ) ; } } public static void main ( String [ ] args ) { Node root = newNode ( 4 ) ; root . left = newNode ( 3 ) ; root . right = newNode ( 5 ) ; root . right . left = newNode ( 3 ) ; root . right . right = newNode ( 1 ) ; root . left . left = newNode ( 10 ) ; root . left . right = newNode ( 2 ) ; printNodes ( root ) ; } }
Design a data structure that supports insert , delete , search and getRandom in constant time | Java program to design a data structure that support following operations in Theta ( n ) time a ) Insert b ) Delete c ) Search d ) getRandom ; class to represent the required data structure ; Constructor ( creates arr [ ] and hash ) ; A resizable array ; A hash where keys are array elements and values are indexes in arr [ ] ; A Theta ( 1 ) function to add an element to MyDS data structure ; If element is already present , then nothing to do ; Else put element at the end of arr [ ] ; And put in hash also ; A Theta ( 1 ) function to remove an element from MyDS data structure ; Check if element is present ; If present , then remove element from hash ; Swap element with last element so that remove from arr [ ] can be done in O ( 1 ) time ; Remove last element ( This is O ( 1 ) ) ; Update hash table for new index of last element ; Returns a random element from MyDS ; Find a random index from 0 to size - 1 Choose a different seed ; Return element at randomly picked index ; Returns index of element if element is present , otherwise null ; Driver class
import java . util . * ; class MyDS { public MyDS ( ) { arr = new ArrayList < Integer > ( ) ; hash = new HashMap < Integer , Integer > ( ) ; } ArrayList < Integer > arr ; HashMap < Integer , Integer > hash ; void add ( int x ) { if ( hash . get ( x ) != null ) return ; int s = arr . size ( ) ; arr . add ( x ) ; hash . put ( x , s ) ; } void remove ( int x ) { Integer index = hash . get ( x ) ; if ( index == null ) return ; hash . remove ( x ) ; int size = arr . size ( ) ; Integer last = arr . get ( size - 1 ) ; Collections . swap ( arr , index , size - 1 ) ; arr . remove ( size - 1 ) ; hash . put ( last , index ) ; } int getRandom ( ) { Random rand = new Random ( ) ; int index = rand . nextInt ( arr . size ( ) ) ; return arr . get ( index ) ; } Integer search ( int x ) { return hash . get ( x ) ; } } class Main { public static void main ( String [ ] args ) { MyDS ds = new MyDS ( ) ; ds . add ( 10 ) ; ds . add ( 20 ) ; ds . add ( 30 ) ; ds . add ( 40 ) ; System . out . println ( ds . search ( 30 ) ) ; ds . remove ( 20 ) ; ds . add ( 50 ) ; System . out . println ( ds . search ( 50 ) ) ; System . out . println ( ds . getRandom ( ) ) ; } }
Count subarrays which contains both the maximum and minimum array element | Java program for the above approach ; Function to count subarray containing both maximum and minimum array elements ; If the length of the array is less than 2 ; Find the index of maximum element ; Find the index of minimum element ; If i > j , then swap the value of i and j ; Return the answer ; Function to return max_element index ; Function to return min_element index ; Driver Code ; Function call
import java . util . * ; import java . lang . * ; class GFG { static int countSubArray ( int arr [ ] , int n ) { if ( n < 2 ) return n ; int i = max_element ( arr ) ; int j = min_element ( arr ) ; if ( i > j ) { int tmp = arr [ i ] ; arr [ i ] = arr [ j ] ; arr [ j ] = tmp ; } return ( i + 1 ) * ( n - j ) ; } static int max_element ( int [ ] arr ) { int idx = 0 ; int max = arr [ 0 ] ; for ( int i = 1 ; i < arr . length ; i ++ ) { if ( max < arr [ i ] ) { max = arr [ i ] ; idx = i ; } } return idx ; } static int min_element ( int [ ] arr ) { int idx = 0 ; int min = arr [ 0 ] ; for ( int i = 1 ; i < arr . length ; i ++ ) { if ( arr [ i ] < min ) { min = arr [ i ] ; idx = i ; } } return idx ; } public static void main ( String [ ] args ) { int arr [ ] = { 4 , 1 , 2 , 3 } ; int n = arr . length ; System . out . println ( countSubArray ( arr , n ) ) ; } }
Count pairs of leaf nodes in a Binary Tree which are at most K distance apart | Structure of a Node ; Constructor of the class ; Stores the count of required pairs ; Function to perform dfs to find pair of leaf nodes at most K distance apart ; Return empty array if node is null ; If node is a leaf node and return res ; Traverse to the left ; Traverse to the right ; Update the distance between left and right leaf node ; Count all pair of leaf nodes which are at most K distance apart ; Return res to parent node ; Driver Code ; 1 / \ 2 3 / 4 ; Given distance K ; Function Call
class Node { int data ; Node left , right ; public Node ( int item ) { data = item ; left = right = null ; } } public class GFG { Node root ; static int result ; static int [ ] dfs ( Node root , int distance ) { if ( root == null ) return new int [ distance + 1 ] ; if ( root . left == null && root . right == null ) { int res [ ] = new int [ distance + 1 ] ; res [ 1 ] ++ ; return res ; } int [ ] left = dfs ( root . left , distance ) ; int [ ] right = dfs ( root . right , distance ) ; int res [ ] = new int [ distance + 1 ] ; for ( int i = res . length - 2 ; i >= 1 ; i -- ) { res [ i + 1 ] = left [ i ] + right [ i ] ; } for ( int l = 1 ; l < left . length ; l ++ ) { for ( int r = 0 ; r < right . length ; r ++ ) { if ( l + r <= distance ) { result += left [ l ] * right [ r ] ; } } } return res ; } public static void main ( String [ ] args ) { GFG tree = new GFG ( ) ; tree . root = new Node ( 1 ) ; tree . root . left = new Node ( 2 ) ; tree . root . right = new Node ( 3 ) ; tree . root . left . left = new Node ( 4 ) ; result = 0 ; int K = 3 ; dfs ( tree . root , K ) ; System . out . println ( result ) ; } }
Count number of triangles possible with length of sides not exceeding N | Java implementation of the above approach ; First member of pair ; Second member of pair ; Function to count total number of right angled triangle ; Consider a set to store the three sides ; Find possible third side ; Condition for a right angled triangle ; Check if the third side is an integer ; Push the three sides ; Add the three sides in the set to find unique triangles ; Return the size of set ; Driver code ; Given N ; Function call
import java . util . * ; class Pair < F , S > { private F first ; private S second ; public Pair ( F first , S second ) { this . first = first ; this . second = second ; } } class GFG { public static int right_angled ( int n ) { Set < Pair < Integer , Pair < Integer , Integer > > > s = new HashSet < Pair < Integer , Pair < Integer , Integer > > > ( ) ; for ( int x = 1 ; x <= n ; x ++ ) { for ( int y = 1 ; y <= n ; y ++ ) { if ( x * x + y * y <= n * n ) { int z = ( int ) Math . sqrt ( x * x + y * y ) ; if ( z * z != ( x * x + y * y ) ) continue ; Vector < Integer > v = new Vector < Integer > ( ) ; v . add ( x ) ; v . add ( y ) ; v . add ( ( int ) Math . sqrt ( x * x + y * y ) ) ; Collections . sort ( v ) ; s . add ( new Pair < Integer , Pair < Integer , Integer > > ( v . get ( 0 ) , new Pair < Integer , Integer > ( v . get ( 1 ) , v . get ( 2 ) ) ) ) ; } else break ; } } return s . size ( ) - 1 ; } public static void main ( String [ ] args ) { int n = 5 ; System . out . println ( right_angled ( n ) ) ; } }
Maximum absolute difference between any two level sum in a N | Java program for the above approach ; Function to find the maximum absolute difference of level sum ; Create the adjacency list ; Initialize value of maximum and minimum level sum ; Do Level order traversal keeping track of nodes at every level ; Get the size of queue when the level order traversal for one level finishes ; Iterate for all the nodes in the queue currently ; Dequeue an node from queue ; Enqueue the children of dequeued node ; Update the maximum level sum value ; Update the minimum level sum value ; Return the result ; Driver Code ; Number of nodes and edges ; Edges of the N - ary tree ; Given cost ; Function call
import java . util . * ; class GFG { static void maxAbsDiffLevelSum ( int N , int M , int [ ] cost , int Edges [ ] [ ] ) { @ SuppressWarnings ( " unchecked " ) Vector < Integer > [ ] adj = new Vector [ N ] ; for ( int i = 0 ; i < adj . length ; i ++ ) adj [ i ] = new Vector < Integer > ( ) ; for ( int i = 0 ; i < M ; i ++ ) { int u = Edges [ i ] [ 0 ] ; int v = Edges [ i ] [ 1 ] ; adj [ u ] . add ( v ) ; } int maxSum = cost [ 0 ] , minSum = cost [ 0 ] ; Queue < Integer > q = new LinkedList < Integer > ( ) ; q . add ( 0 ) ; while ( ! q . isEmpty ( ) ) { int count = q . size ( ) ; int sum = 0 ; while ( count -- > 0 ) { int temp = q . peek ( ) ; q . remove ( ) ; sum = sum + cost [ temp ] ; for ( int i = 0 ; i < adj [ temp ] . size ( ) ; i ++ ) { q . add ( adj [ temp ] . get ( i ) ) ; } } maxSum = Math . max ( sum , maxSum ) ; minSum = Math . min ( sum , minSum ) ; } System . out . print ( Math . abs ( maxSum - minSum ) ) ; } public static void main ( String [ ] args ) { int N = 10 , M = 9 ; int Edges [ ] [ ] = { { 0 , 1 } , { 0 , 2 } , { 0 , 3 } , { 1 , 4 } , { 1 , 5 } , { 3 , 6 } , { 6 , 7 } , { 6 , 8 } , { 6 , 9 } } ; int [ ] cost = { 1 , 2 , - 1 , 3 , 4 , 5 , 8 , 6 , 12 , 7 } ; maxAbsDiffLevelSum ( N , M , cost , Edges ) ; } }
Split array into subarrays at minimum cost by minimizing count of repeating elements in each subarray | Java program for the above approach ; Function to find the minimum cost of splitting the array into subarrays ; Get the maximum element ; dp [ ] will store the minimum cost upto index i ; Initialize the result array ; Initialise the first element ; Create the frequency array ; Update the frequency ; Counting the cost of the duplicate element ; Minimum cost of operation from 0 to j ; Total cost of the array ; Driver Code ; Given cost K ; Function Call
import java . util . * ; class GFG { static long findMinCost ( int [ ] a , int k , int n ) { int max_ele = Arrays . stream ( a ) . max ( ) . getAsInt ( ) ; long [ ] dp = new long [ n + 1 ] ; for ( int i = 1 ; i <= n ; ++ i ) dp [ i ] = Integer . MAX_VALUE ; dp [ 0 ] = 0 ; for ( int i = 0 ; i < n ; ++ i ) { int [ ] freq = new int [ max_ele + 1 ] ; for ( int j = i ; j < n ; ++ j ) { freq [ a [ j ] ] ++ ; int cost = 0 ; for ( int x = 0 ; x <= max_ele ; ++ x ) { cost += ( freq [ x ] == 1 ) ? 0 : freq [ x ] ; } dp [ j + 1 ] = Math . min ( dp [ i ] + cost + k , dp [ j + 1 ] ) ; } } return dp [ n ] ; } public static void main ( String [ ] args ) { int [ ] arr = { 1 , 2 , 1 , 1 , 1 } ; int K = 2 ; int n = arr . length ; System . out . print ( findMinCost ( arr , K , n ) ) ; } }
Find subarray with given sum | Set 2 ( Handles Negative Numbers ) | Java program to print subarray with sum as given sum ; Function to print subarray with sum as given sum ; cur_sum to keep track of cummulative sum till that point ; check whether cur_sum - sum = 0 , if 0 it means the sub array is starting from index 0 - so stop ; if hashMap already has the value , means we already have subarray with the sum - so stop ; if value is not present then add to hashmap ; if end is - 1 : means we have reached end without the sum ; Driver code
import java . util . * ; class GFG { public static void subArraySum ( int [ ] arr , int n , int sum ) { int cur_sum = 0 ; int start = 0 ; int end = - 1 ; HashMap < Integer , Integer > hashMap = new HashMap < > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { cur_sum = cur_sum + arr [ i ] ; if ( cur_sum - sum == 0 ) { start = 0 ; end = i ; break ; } if ( hashMap . containsKey ( cur_sum - sum ) ) { start = hashMap . get ( cur_sum - sum ) + 1 ; end = i ; break ; } hashMap . put ( cur_sum , i ) ; } if ( end == - 1 ) { System . out . println ( " No ▁ subarray ▁ with ▁ given ▁ sum ▁ exists " ) ; } else { System . out . println ( " Sum ▁ found ▁ between ▁ indexes ▁ " + start + " ▁ to ▁ " + end ) ; } } public static void main ( String [ ] args ) { int [ ] arr = { 10 , 2 , - 2 , - 20 , 10 } ; int n = arr . length ; int sum = - 10 ; subArraySum ( arr , n , sum ) ; } }
Write Code to Determine if Two Trees are Identical | A binary tree node ; Given two trees , return true if they are structurally identical ; 1. both empty ; 2. both non - empty -> compare them ; 3. one empty , one not -> false ; Driver program to test identicalTrees ( ) function
class Node { int data ; Node left , right ; Node ( int item ) { data = item ; left = right = null ; } } class BinaryTree { Node root1 , root2 ; boolean identicalTrees ( Node a , Node b ) { if ( a == null && b == null ) return true ; if ( a != null && b != null ) return ( a . data == b . data && identicalTrees ( a . left , b . left ) && identicalTrees ( a . right , b . right ) ) ; return false ; } public static void main ( String [ ] args ) { BinaryTree tree = new BinaryTree ( ) ; tree . root1 = new Node ( 1 ) ; tree . root1 . left = new Node ( 2 ) ; tree . root1 . right = new Node ( 3 ) ; tree . root1 . left . left = new Node ( 4 ) ; tree . root1 . left . right = new Node ( 5 ) ; tree . root2 = new Node ( 1 ) ; tree . root2 . left = new Node ( 2 ) ; tree . root2 . right = new Node ( 3 ) ; tree . root2 . left . left = new Node ( 4 ) ; tree . root2 . left . right = new Node ( 5 ) ; if ( tree . identicalTrees ( tree . root1 , tree . root2 ) ) System . out . println ( " Both ▁ trees ▁ are ▁ identical " ) ; else System . out . println ( " Trees ▁ are ▁ not ▁ identical " ) ; } }