codeparrot/xlcost-text-to-code huggingface dataset:
Kth Smallest Element in a sorted array formed by reversing subarrays from a random index | Java program for the above approach ; Function to find the Kth element in a sorted and rotated array at random point ; Set the boundaries for binary search ; Apply binary search to find R ; Initialize the middle element ; Check in the right side of mid ; Else check in the left side ; Random point either l or h ; Return the kth smallest element ; Driver Code ; Given Input ; Function Call
class GFG { public static int findkthElement ( int arr [ ] , int n , int K ) { int l = 0 ; int h = n - 1 , r ; while ( l + 1 < h ) { int mid = ( l + h ) / 2 ; if ( arr [ l ] >= arr [ mid ] ) l = mid ; else h = mid ; } if ( arr [ l ] < arr [ h ] ) r = l ; else r = h ; if ( K <= r + 1 ) return arr [ r + 1 - K ] ; else return arr [ n - ( K - ( r + 1 ) ) ] ; } public static void main ( String args [ ] ) { int [ ] arr = { 10 , 8 , 6 , 5 , 2 , 1 , 13 , 12 } ; int n = arr . length ; int K = 3 ; System . out . println ( findkthElement ( arr , n , K ) ) ; } }
Find all pairs ( a , b ) in an array such that a % b = k | Java implementation to find such pairs ; method to find pair such that ( a % b = k ) ; Consider each and every pair ; Print if their modulo equals to k ; Driver method
class Test { static boolean printPairs ( int arr [ ] , int n , int k ) { boolean isPairFound = true ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = 0 ; j < n ; j ++ ) { if ( i != j && arr [ i ] % arr [ j ] == k ) { System . out . print ( " ( " + arr [ i ] + " , ▁ " + arr [ j ] + " ) " + " ▁ " ) ; isPairFound = true ; } } } return isPairFound ; } public static void main ( String args [ ] ) { int arr [ ] = { 2 , 3 , 5 , 4 , 7 } ; int k = 3 ; if ( printPairs ( arr , arr . length , k ) == false ) System . out . println ( " No ▁ such ▁ pair ▁ exists " ) ; } }
Find all pairs ( a , b ) in an array such that a % b = k | Java program to find all pairs such that a % b = k . ; Utility method to find the divisors of n and store in vector v [ ] ; Vector is used to store the divisors ; If n is a square number , push only one occurrence ; method to find pairs such that ( a % b = k ) ; Store all the elements in the map to use map as hash for finding elements in O ( 1 ) time . ; Print all the pairs with ( a , b ) as ( k , numbers greater than k ) as k % ( num ( > k ) ) = k i . e . 2 % 4 = 2 ; Now check for the current element as ' a ' how many b exists such that a % b = k ; find all the divisors of ( arr [ i ] - k ) ; Check for each divisor i . e . arr [ i ] % b = k or not , if yes then print that pair . ; Clear vector ; Driver method
import java . util . HashMap ; import java . util . Vector ; class Test { static Vector < Integer > findDivisors ( int n ) { Vector < Integer > v = new Vector < > ( ) ; for ( int i = 1 ; i <= Math . sqrt ( n ) ; i ++ ) { if ( n % i == 0 ) { if ( n / i == i ) v . add ( i ) ; else { v . add ( i ) ; v . add ( n / i ) ; } } } return v ; } static boolean printPairs ( int arr [ ] , int n , int k ) { HashMap < Integer , Boolean > occ = new HashMap < > ( ) ; for ( int i = 0 ; i < n ; i ++ ) occ . put ( arr [ i ] , true ) ; boolean isPairFound = false ; for ( int i = 0 ; i < n ; i ++ ) { if ( occ . get ( k ) && k < arr [ i ] ) { System . out . print ( " ( " + k + " , ▁ " + arr [ i ] + " ) ▁ " ) ; isPairFound = true ; } if ( arr [ i ] >= k ) { Vector < Integer > v = findDivisors ( arr [ i ] - k ) ; for ( int j = 0 ; j < v . size ( ) ; j ++ ) { if ( arr [ i ] % v . get ( j ) == k && arr [ i ] != v . get ( j ) && occ . get ( v . get ( j ) ) ) { System . out . print ( " ( " + arr [ i ] + " , ▁ " + v . get ( j ) + " ) ▁ " ) ; isPairFound = true ; } } v . clear ( ) ; } } return isPairFound ; } public static void main ( String args [ ] ) { int arr [ ] = { 3 , 1 , 2 , 5 , 4 } ; int k = 2 ; if ( printPairs ( arr , arr . length , k ) == false ) System . out . println ( " No ▁ such ▁ pair ▁ exists " ) ; } }
Sum of nodes in a Binary Search Tree with values from a given range | Java program for the above approach ; Class for node of the Tree ; Function to create a new BST node ; Return the newly created node ; Stores the sum of all nodes lying in the range [ L , R ] ; Function to perform level order traversal on the Tree and calculate the required sum ; Base Case ; Stores the nodes while performing level order traversal ; Push the root node into the queue ; Iterate until queue is empty ; Stores the front node of the queue ; If the value of the node lies in the given range ; Add it to sum ; If the left child is not null and exceeds low ; Insert into queue ; If the right child is not null and exceeds low ; Insert into queue ; Return the resultant sum ; Function to insert a new node into the Binary Search Tree ; Base Case ; If the data is less than the value of the current node ; Recur for left subtree ; Otherwise ; Recur for the right subtree ; Return the node ; Driver Code ; Let us create following BST 10 / \ 5 15 / \ \ 3 7 18
import java . util . * ; class GFG { static class Node { int val ; Node left , right ; } ; static Node newNode ( int item ) { Node temp = new Node ( ) ; temp . val = item ; temp . left = temp . right = null ; return temp ; } static int sum = 0 ; static int rangeSumBST ( Node root , int low , int high ) { if ( root == null ) return 0 ; Queue < Node > q = new LinkedList < Node > ( ) ; q . add ( root ) ; while ( q . isEmpty ( ) == false ) { Node curr = q . peek ( ) ; q . remove ( ) ; if ( curr . val >= low && curr . val <= high ) { sum += curr . val ; } if ( curr . left != null && curr . val > low ) q . add ( curr . left ) ; if ( curr . right != null && curr . val < high ) q . add ( curr . right ) ; } return sum ; } static Node insert ( Node node , int data ) { if ( node == null ) return newNode ( data ) ; if ( data <= node . val ) node . left = insert ( node . left , data ) ; else node . right = insert ( node . right , data ) ; return node ; } public static void main ( String [ ] args ) { Node root = null ; root = insert ( root , 10 ) ; insert ( root , 5 ) ; insert ( root , 15 ) ; insert ( root , 3 ) ; insert ( root , 7 ) ; insert ( root , 18 ) ; int L = 7 , R = 15 ; System . out . print ( rangeSumBST ( root , L , R ) ) ; } }
Convert an array to reduced form | Set 1 ( Simple and Hashing ) | Java Program to convert an Array to reduced form ; Create a temp array and copy contents of arr [ ] to temp ; Sort temp array ; Create a hash table . ; One by one insert elements of sorted temp [ ] and assign them values from 0 to n - 1 ; Convert array by taking positions from umap ; Driver code
import java . util . * ; class GFG { public static void convert ( int arr [ ] , int n ) { int temp [ ] = arr . clone ( ) ; Arrays . sort ( temp ) ; HashMap < Integer , Integer > umap = new HashMap < > ( ) ; int val = 0 ; for ( int i = 0 ; i < n ; i ++ ) umap . put ( temp [ i ] , val ++ ) ; for ( int i = 0 ; i < n ; i ++ ) arr [ i ] = umap . get ( arr [ i ] ) ; } public static void printArr ( int arr [ ] , int n ) { for ( int i = 0 ; i < n ; i ++ ) System . out . print ( arr [ i ] + " ▁ " ) ; } public static void main ( String [ ] args ) { int arr [ ] = { 10 , 20 , 15 , 12 , 11 , 50 } ; int n = arr . length ; System . out . println ( " Given ▁ Array ▁ is ▁ " ) ; printArr ( arr , n ) ; convert ( arr , n ) ; System . out . println ( " Converted Array is "); printArr ( arr , n ) ; } }
Check if count of substrings in S with string S1 as prefix and S2 as suffix is equal to that with S2 as prefix and S1 as suffix | Java program for the above approach ; Function to count number of substrings that starts with string S1 and ends with string S2 ; Stores the length of each string ; Stores the count of prefixes as S1 and suffixes as S2 ; Traverse string S ; Find the prefix at index i ; Find the suffix at index i ; If the prefix is S1 ; If the suffix is S2 ; Return the count of substrings ; Function to check if the number of substrings starts with S1 and ends with S2 and vice - versa is same or not ; Count the number of substrings ; Print the result ; Driver Code
class GFG { static int countSubstrings ( String S , String S1 , String S2 ) { int N = S . length ( ) ; int N1 = S1 . length ( ) ; int N2 = S2 . length ( ) ; int count = 0 , totalcount = 0 ; for ( int i = 0 ; i < N ; i ++ ) { String prefix = S . substring ( i , ( i + N1 < N ) ? ( i + N1 ) : N ) ; String suffix = S . substring ( i , ( i + N2 < N ) ? ( i + N2 ) : N ) ; if ( S1 . equals ( prefix ) ) count ++ ; if ( S2 . equals ( suffix ) ) totalcount += count ; } return totalcount ; } static void checkSubstrings ( String S , String S1 , String S2 ) { int x = countSubstrings ( S , S1 , S2 ) ; int y = countSubstrings ( S , S2 , S1 ) ; if ( x == y ) System . out . println ( " Yes " ) ; else System . out . println ( " No " ) ; } public static void main ( String [ ] args ) { String S = " opencloseopencloseopen " ; String S1 = " open " ; String S2 = " close " ; checkSubstrings ( S , S1 , S2 ) ; } }
Return maximum occurring character in an input string | Java program to output the maximum occurring character in a string ; Create array to keep the count of individual characters and initialize the array as 0 ; Construct character count array from the input string . ; Initialize max count ; Initialize result ; Traversing through the string and maintaining the count of each character ; Driver Method
public class GFG { static final int ASCII_SIZE = 256 ; static char getMaxOccuringChar ( String str ) { int count [ ] = new int [ ASCII_SIZE ] ; int len = str . length ( ) ; for ( int i = 0 ; i < len ; i ++ ) count [ str . charAt ( i ) ] ++ ; int max = - 1 ; char result = ' ▁ ' ; for ( int i = 0 ; i < len ; i ++ ) { if ( max < count [ str . charAt ( i ) ] ) { max = count [ str . charAt ( i ) ] ; result = str . charAt ( i ) ; } } return result ; } public static void main ( String [ ] args ) { String str = " sample ▁ string " ; System . out . println ( " Max ▁ occurring ▁ character ▁ is ▁ " + getMaxOccuringChar ( str ) ) ; } }
Group words with same set of characters | Java program to print all words that have the same unique character set ; Generates a key from given string . The key contains all unique characters of given string in sorted order consisting of only distinct elements . ; store all unique characters of current word in key ; Print all words together with same character sets . ; Stores indexes of all words that have same set of unique characters . unordered_map < string , vector < int > > Hash ; ; Traverse all words ; if the key is already in the map then get its corresponding value and update the list and put it in the map ; if key is not present in the map then create a new list and add both key and the list ; print all words that have the same unique character set ; Driver program to test above function
import java . util . ArrayList ; import java . util . Arrays ; import java . util . HashMap ; import java . util . Map . Entry ; public class GFG { static final int MAX_CHAR = 26 ; static String getKey ( String str ) { boolean [ ] visited = new boolean [ MAX_CHAR ] ; Arrays . fill ( visited , false ) ; for ( int j = 0 ; j < str . length ( ) ; j ++ ) visited [ str . charAt ( j ) - ' a ' ] = true ; String key = " " ; for ( int j = 0 ; j < MAX_CHAR ; j ++ ) if ( visited [ j ] ) key = key + ( char ) ( ' a ' + j ) ; return key ; } static void wordsWithSameCharSet ( String words [ ] , int n ) { HashMap < String , ArrayList < Integer > > Hash = new HashMap < > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { String key = getKey ( words [ i ] ) ; if ( Hash . containsKey ( key ) ) { ArrayList < Integer > get_al = Hash . get ( key ) ; get_al . add ( i ) ; Hash . put ( key , get_al ) ; } else { ArrayList < Integer > new_al = new ArrayList < > ( ) ; new_al . add ( i ) ; Hash . put ( key , new_al ) ; } } for ( Entry < String , ArrayList < Integer > > it : Hash . entrySet ( ) ) { ArrayList < Integer > get = it . getValue ( ) ; for ( Integer v : get ) System . out . print ( words [ v ] + " , ▁ " ) ; System . out . println ( ) ; } } public static void main ( String args [ ] ) { String words [ ] = { " may " , " student " , " students " , " dog " , " studentssess " , " god " , " cat " , " act " , " tab " , " bat " , " flow " , " wolf " , " lambs " , " amy " , " yam " , " balms " , " looped " , " poodle " } ; int n = words . length ; wordsWithSameCharSet ( words , n ) ; } }
Second most repeated word in a sequence | Java program to find out the second most repeated word ; Method to find the word ; Store all the words with its occurrence ; find the second largest occurrence ; Return string with occurrence equals to sec_max ; Driver method
import java . util . * ; class GFG { static String secMostRepeated ( Vector < String > seq ) { HashMap < String , Integer > occ = new HashMap < String , Integer > ( seq . size ( ) ) { @ Override public Integer get ( Object key ) { return containsKey ( key ) ? super . get ( key ) : 0 ; } } ; for ( int i = 0 ; i < seq . size ( ) ; i ++ ) occ . put ( seq . get ( i ) , occ . get ( seq . get ( i ) ) + 1 ) ; int first_max = Integer . MIN_VALUE , sec_max = Integer . MIN_VALUE ; Iterator < Map . Entry < String , Integer > > itr = occ . entrySet ( ) . iterator ( ) ; while ( itr . hasNext ( ) ) { Map . Entry < String , Integer > entry = itr . next ( ) ; int v = entry . getValue ( ) ; if ( v > first_max ) { sec_max = first_max ; first_max = v ; } else if ( v > sec_max && v != first_max ) sec_max = v ; } itr = occ . entrySet ( ) . iterator ( ) ; while ( itr . hasNext ( ) ) { Map . Entry < String , Integer > entry = itr . next ( ) ; int v = entry . getValue ( ) ; if ( v == sec_max ) return entry . getKey ( ) ; } return null ; } public static void main ( String [ ] args ) { String arr [ ] = { " ccc " , " aaa " , " ccc " , " ddd " , " aaa " , " aaa " } ; List < String > seq = Arrays . asList ( arr ) ; System . out . println ( secMostRepeated ( new Vector < > ( seq ) ) ) ; } }
Check if a Binary Tree ( not BST ) has duplicate values | Java Program to check duplicates in Binary Tree ; Function that used HashSet to find presence of duplicate nodes ; If tree is empty , there are no duplicates . ; If current node 's data is already present.  ; Insert current node ; Recursively check in left and right subtrees . ; To check if tree has duplicates ; A binary tree Node has data , pointer to left child and a pointer to right child
import java . util . HashSet ; public class CheckDuplicateValues { public static boolean checkDupUtil ( Node root , HashSet < Integer > s ) { if ( root == null ) return false ; if ( s . contains ( root . data ) ) return true ; s . add ( root . data ) ; return checkDupUtil ( root . left , s ) || checkDupUtil ( root . right , s ) ; } public static boolean checkDup ( Node root ) { HashSet < Integer > s = new HashSet < > ( ) ; return checkDupUtil ( root , s ) ; } public static void main ( String args [ ] ) { Node root = new Node ( 1 ) ; root . left = new Node ( 2 ) ; root . right = new Node ( 2 ) ; root . left . left = new Node ( 3 ) ; if ( checkDup ( root ) ) System . out . print ( " Yes " ) ; else System . out . print ( " No " ) ; } } class Node { int data ; Node left , right ; Node ( int data ) { this . data = data ; } } ;
Expression Tree | Java program to construct an expression tree ; Java program for expression tree ; A utility function to check if ' c ' is an operator ; Utility function to do inorder traversal ; Returns root of constructed tree for given postfix expression ; Traverse through every character of input expression ; If operand , simply push into stack ; operator ; Pop two top nodes Store top Remove top ; make them children ; System . out . println ( t1 + " " + t2 ) ; Add this subexpression to stack ; only element will be root of expression tree ; Driver program to test above
import java . util . Stack ; class Node { char value ; Node left , right ; Node ( char item ) { value = item ; left = right = null ; } } class ExpressionTree { boolean isOperator ( char c ) { if ( c == ' + ' c == ' - ' c == ' * ' c == ' / ' c == ' ^ ' ) { return true ; } return false ; } void inorder ( Node t ) { if ( t != null ) { inorder ( t . left ) ; System . out . print ( t . value + " ▁ " ) ; inorder ( t . right ) ; } } Node constructTree ( char postfix [ ] ) { Stack < Node > st = new Stack < Node > ( ) ; Node t , t1 , t2 ; for ( int i = 0 ; i < postfix . length ; i ++ ) { if ( ! isOperator ( postfix [ i ] ) ) { t = new Node ( postfix [ i ] ) ; st . push ( t ) ; } else { t = new Node ( postfix [ i ] ) ; t1 = st . pop ( ) ; t2 = st . pop ( ) ; t . right = t1 ; t . left = t2 ; st . push ( t ) ; } } t = st . peek ( ) ; st . pop ( ) ; return t ; } public static void main ( String args [ ] ) { ExpressionTree et = new ExpressionTree ( ) ; String postfix = " ab + ef * g * - " ; char [ ] charArray = postfix . toCharArray ( ) ; Node root = et . constructTree ( charArray ) ; System . out . println ( " infix ▁ expression ▁ is " ) ; et . inorder ( root ) ; } }
Queries to count sum of rows and columns of a Matrix present in given ranges | Java program for the above approach ; Function to preprocess the matrix to execute the queries ; Stores the sum of each row ; Stores the sum of each col ; Traverse the matrix and calculate sum of each row and column ; Insert all row sums in sum_list ; Insert all column sums in sum_list ; Sort the array in ascending order ; Traverse the array queries [ ] [ ] ; Search the leftmost index of L ; Search the rightmost index of R ; Function to search for the leftmost index of given number ; Initialize low , high and ans ; Stores mid ; If A [ mid ] >= num ; Function to search for the rightmost index of given number ; Initialise low , high and ans ; Stores mid ; If A [ mid ] <= num ; Update ans ; Update mid ; Update high ; Driver Code ; Given dimensions of matrix ; Given matrix ; Given number of queries ; Given queries ; Function call to count the number row - sums and column - sums present in the given ranges
import java . io . * ; import java . util . * ; class GFG { static void totalCount ( int [ ] [ ] A , int N , int M , int [ ] [ ] queries , int Q ) { int row_sum [ ] = new int [ N ] ; int col_sum [ ] = new int [ M ] ; for ( int i = 0 ; i < N ; i ++ ) { for ( int j = 0 ; j < M ; j ++ ) { row_sum [ i ] += A [ i ] [ j ] ; col_sum [ j ] += A [ i ] [ j ] ; } } ArrayList < Integer > sum_list = new ArrayList < > ( ) ; for ( int i = 0 ; i < N ; i ++ ) sum_list . add ( row_sum [ i ] ) ; for ( int i = 0 ; i < M ; i ++ ) sum_list . add ( col_sum [ i ] ) ; Collections . sort ( sum_list ) ; for ( int i = 0 ; i < Q ; i ++ ) { int L = queries [ i ] [ 0 ] ; int R = queries [ i ] [ 1 ] ; int l = left_search ( sum_list , L ) ; int r = right_search ( sum_list , R ) ; System . out . print ( r - l + 1 + " ▁ " ) ; } } static int left_search ( ArrayList < Integer > A , int num ) { int low = 0 , high = A . size ( ) - 1 ; int ans = 0 ; while ( low <= high ) { int mid = low + ( high - low ) / 2 ; if ( A . get ( mid ) >= num ) { ans = mid ; high = mid - 1 ; } else { low = mid + 1 ; } } return ans ; } static int right_search ( ArrayList < Integer > A , int num ) { int low = 0 , high = A . size ( ) - 1 ; int ans = high ; while ( low <= high ) { int mid = low + ( high - low ) / 2 ; if ( A . get ( mid ) <= num ) { ans = mid ; low = mid + 1 ; } else { high = mid - 1 ; } } return ans ; } public static void main ( String [ ] args ) { int N = 3 , M = 2 ; int A [ ] [ ] = { { 13 , 3 } , { 9 , 4 } , { 6 , 10 } } ; int Q = 2 ; int queries [ ] [ ] = { { 10 , 20 } , { 25 , 35 } } ; totalCount ( A , N , M , queries , Q ) ; } }
Smallest element repeated exactly ‘ k ’ times ( not limited to small range ) | Java program to find the smallest element with frequency exactly k . ; Map is used to store the count of elements present in the array ; Traverse the map and find minimum element with frequency k . ; Driver program to test above function
import java . util . * ; class GFG { public static int smallestKFreq ( int a [ ] , int n , int k ) { HashMap < Integer , Integer > m = new HashMap < Integer , Integer > ( ) ; for ( int i = 0 ; i < n ; i ++ ) if ( m . containsKey ( a [ i ] ) ) m . put ( a [ i ] , m . get ( a [ i ] ) + 1 ) ; else m . put ( a [ i ] , 1 ) ; int res = Integer . MAX_VALUE ; Set < Integer > s = m . keySet ( ) ; for ( int temp : s ) if ( m . get ( temp ) == k ) res = Math . min ( res , temp ) ; return ( res != Integer . MAX_VALUE ) ? res : - 1 ; } public static void main ( String [ ] args ) { int arr [ ] = { 2 , 2 , 1 , 3 , 1 } ; int k = 2 ; System . out . println ( smallestKFreq ( arr , arr . length , k ) ) ; } }
Maximize profit that can be earned by selling an item among N buyers | Java program for the above approach ; Function to find the maximum profit earned by selling an item among N buyers ; Stores the maximum profit ; Stores the price of the item ; Sort the array ; Traverse the array ; Count of buyers with budget >= arr [ i ] ; Update the maximum profit ; Return the maximum possible price ; Driver Code
import java . util . * ; class GFG { public static int maximumProfit ( int arr [ ] ) { int ans = Integer . MIN_VALUE ; int price = 0 ; Arrays . sort ( arr ) ; int N = arr . length ; for ( int i = 0 ; i < N ; i ++ ) { int count = ( N - i ) ; if ( ans < count * arr [ i ] ) { price = arr [ i ] ; ans = count * arr [ i ] ; } } return price ; } public static void main ( String [ ] args ) { int arr [ ] = { 22 , 87 , 9 , 50 , 56 , 43 } ; System . out . print ( maximumProfit ( arr ) ) ; } }
Lexicographically smallest permutation of the array possible by at most one swap | Java program for the above approach ; Function to print the elements of the array arr [ ] ; Traverse the array arr [ ] ; Function to convert given array to lexicographically smallest permutation possible by swapping at most one pair ; Stores the index of the first element which is not at its correct position ; Checks if any such array element exists or not ; Traverse the given array ; If element is found at i ; If the first array is not in correct position ; Store the index of the first elements ; Store the index of the first element ; Swap the pairs ; Print the array ; Driver Code ; Given array ; Store the size of the array
import java . io . * ; class GFG { static void print ( int arr [ ] ) { for ( int element : arr ) { System . out . print ( element + " ▁ " ) ; } } static void makeLexicographically ( int arr [ ] , int length ) { int index = 0 ; int temp = 0 ; int check = 0 ; int condition = 0 ; int element = 0 ; for ( int i = 0 ; i < length ; ++ i ) { if ( element == arr [ i ] ) { check = i ; break ; } else if ( arr [ i ] != i + 1 && check == 0 ) { index = i ; check = 1 ; condition = - 1 ; element = i + 1 ; } } if ( condition == - 1 ) { temp = arr [ index ] ; arr [ index ] = arr [ check ] ; arr [ check ] = temp ; } print ( arr ) ; } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 2 , 3 , 4 } ; int N = arr . length ; makeLexicographically ( arr , N ) ; } }