codeparrot/xlcost-text-to-code huggingface dataset:
Rearrange characters in a string such that no two adjacent are same | Java program to rearrange characters in a string so that no two adjacent characters are same . ; Overriding compare ( ) method of Comparator ; store frequency of character ; Function to rearrange character of a string so that no char repeat twice ; Store frequencies of all characters in string ; Insert all characters with their frequencies into a priority_queue ; ' str ' that will store resultant value ; work as the previous visited element initial previous element be . ( ' # ' and it ' s ▁ frequency ▁ ' - 1 ' ) ; traverse queue ; pop top element from queue and add it to string . ; If frequency of previous character is less than zero that means it is useless , we need not to push it ; make current character as the previous ' char ' decrease frequency by ' one ' ; If length of the resultant string and original string is not same then string is not valid ; valid string ; Driver program to test above function
import java . io . * ; import java . util . * ; class KeyComparator implements Comparator < Key > { public int compare ( Key k1 , Key k2 ) { if ( k1 . freq < k2 . freq ) return 1 ; else if ( k1 . freq > k2 . freq ) return - 1 ; return 0 ; } } class Key { int freq ; char ch ; Key ( int val , char c ) { freq = val ; ch = c ; } } class GFG { static int MAX_CHAR = 26 ; static void rearrangeString ( String str ) { int n = str . length ( ) ; int [ ] count = new int [ MAX_CHAR ] ; for ( int i = 0 ; i < n ; i ++ ) count [ str . charAt ( i ) - ' a ' ] ++ ; PriorityQueue < Key > pq = new PriorityQueue < > ( new KeyComparator ( ) ) ; for ( char c = ' a ' ; c <= ' z ' ; c ++ ) { int val = c - ' a ' ; if ( count [ val ] > 0 ) pq . add ( new Key ( count [ val ] , c ) ) ; } str = " " ; Key prev = new Key ( - 1 , ' # ' ) ; while ( pq . size ( ) != 0 ) { Key k = pq . peek ( ) ; pq . poll ( ) ; str = str + k . ch ; if ( prev . freq > 0 ) pq . add ( prev ) ; ( k . freq ) -- ; prev = k ; } if ( n != str . length ( ) ) System . out . println ( " ▁ Not ▁ valid ▁ String ▁ " ) ; else System . out . println ( str ) ; } public static void main ( String args [ ] ) { String str = " bbbaa " ; rearrangeString ( str ) ; } }
Find ( a ^ b ) % m where ' a ' is very large | Java program to find ( a ^ b ) mod m for a large ' a ' ; utility function to calculate a % m ; ( s [ i ] - '0' ) gives the digit value and form the number ; Returns find ( a ^ b ) % m ; Find a % m ; now multiply ans by b - 1 times and take mod with m ; Driver code
public class GFG { static int aModM ( String s , int mod ) { int number = 0 ; for ( int i = 0 ; i < s . length ( ) ; i ++ ) { number = ( number * 10 ) ; int x = Character . getNumericValue ( s . charAt ( i ) ) ; number = number + x ; number %= mod ; } return number ; } static int ApowBmodM ( String a , int b , int m ) { int ans = aModM ( a , m ) ; int mul = ans ; for ( int i = 1 ; i < b ; i ++ ) ans = ( ans * mul ) % m ; return ans ; } public static void main ( String args [ ] ) { String a = "987584345091051645734583954832576" ; int b = 3 , m = 11 ; System . out . println ( ApowBmodM ( a , b , m ) ) ; } }
Lagrange 's Interpolation | Java program for implementation of Lagrange 's Interpolation ; To represent a data point corresponding to x and y = f ( x ) ; function to interpolate the given data points using Lagrange 's formula xi corresponds to the new data point whose value is to be obtained n represents the number of known data points ; double result = 0 ; Initialize result ; Compute individual terms of above formula ; Add current term to result ; Driver code ; creating an array of 4 known data points ; Using the interpolate function to obtain a data point corresponding to x = 3
import java . util . * ; class GFG { static class Data { int x , y ; public Data ( int x , int y ) { super ( ) ; this . x = x ; this . y = y ; } } ; static double interpolate ( Data f [ ] , int xi , int n ) { for ( int i = 0 ; i < n ; i ++ ) { double term = f [ i ] . y ; for ( int j = 0 ; j < n ; j ++ ) { if ( j != i ) term = term * ( xi - f [ j ] . x ) / ( f [ i ] . x - f [ j ] . x ) ; } result += term ; } return result ; } public static void main ( String [ ] args ) { Data f [ ] = { new Data ( 0 , 2 ) , new Data ( 1 , 3 ) , new Data ( 2 , 12 ) , new Data ( 5 , 147 ) } ; System . out . print ( " Value ▁ of ▁ f ( 3 ) ▁ is ▁ : ▁ " + ( int ) interpolate ( f , 3 , 4 ) ) ; } }
Sieve of Sundaram to print all primes smaller than n | Java program to print primes smaller than n using Sieve of Sundaram . ; Prints all prime numbers smaller ; In general Sieve of Sundaram , produces primes smaller than ( 2 * x + 2 ) for a number given number x . Since we want primes smaller than n , we reduce n to half ; This array is used to separate numbers of the form i + j + 2 ij from others where 1 <= i <= j ; Initialize all elements as not marked ; Main logic of Sundaram . Mark all numbers of the form i + j + 2 ij as true where 1 <= i <= j ; Since 2 is a prime number ; Print other primes . Remaining primes are of the form 2 * i + 1 such that marked [ i ] is false . ; Driver code
import java . util . Arrays ; class GFG { static int SieveOfSundaram ( int n ) { int nNew = ( n - 1 ) / 2 ; boolean marked [ ] = new boolean [ nNew + 1 ] ; Arrays . fill ( marked , false ) ; for ( int i = 1 ; i <= nNew ; i ++ ) for ( int j = i ; ( i + j + 2 * i * j ) <= nNew ; j ++ ) marked [ i + j + 2 * i * j ] = true ; if ( n > 2 ) System . out . print ( 2 + " ▁ " ) ; for ( int i = 1 ; i <= nNew ; i ++ ) if ( marked [ i ] == false ) System . out . print ( 2 * i + 1 + " ▁ " ) ; return - 1 ; } public static void main ( String [ ] args ) { int n = 20 ; SieveOfSundaram ( n ) ; } }
Construct original array starting with K from an array of XOR of all elements except elements at same index | Java program for the above approach ; Function to construct an array with each element equal to XOR of all array elements except the element at the same index ; Original array ; Stores Bitwise XOR of array ; Calculate XOR of all array elements ; Print the original array B [ ] ; Driver Code ; Function Call
class GFG { static void constructArray ( int A [ ] , int N , int K ) { int B [ ] = new int [ N ] ; int totalXOR = A [ 0 ] ^ K ; for ( int i = 0 ; i < N ; i ++ ) B [ i ] = totalXOR ^ A [ i ] ; for ( int i = 0 ; i < N ; i ++ ) { System . out . print ( B [ i ] + " ▁ " ) ; } } public static void main ( String [ ] args ) { int A [ ] = { 13 , 14 , 10 , 6 } , K = 2 ; int N = A . length ; constructArray ( A , N , K ) ; } }
Find extra element in the second array | Java implementation of the approach ; Function to return the extra element in B [ ] ; To store the result ; Find the XOR of all the element of array A [ ] and array B [ ] ; Driver code
class GFG { static int extraElement ( int A [ ] , int B [ ] , int n ) { int ans = 0 ; for ( int i = 0 ; i < n ; i ++ ) ans ^= A [ i ] ; for ( int i = 0 ; i < n + 1 ; i ++ ) ans ^= B [ i ] ; return ans ; } public static void main ( String [ ] args ) { int A [ ] = { 10 , 15 , 5 } ; int B [ ] = { 10 , 100 , 15 , 5 } ; int n = A . length ; System . out . println ( extraElement ( A , B , n ) ) ; } }
Hamming distance between two Integers | Java implementation of above approach ; Function to calculate hamming distance ; Driver code
class GFG { static int hammingDistance ( int n1 , int n2 ) { int x = n1 ^ n2 ; int setBits = 0 ; while ( x > 0 ) { setBits += x & 1 ; x >>= 1 ; } return setBits ; } public static void main ( String [ ] args ) { int n1 = 9 , n2 = 14 ; System . out . println ( hammingDistance ( n1 , n2 ) ) ; } }
Print bitwise AND set of a number N | JAVA program to print all bitwise subsets of N ( Naive approach ) ; function to find bitwise subsets Naive approach ; Driver function
class GFG { static void printSubsets ( int n ) { for ( int i = 0 ; i <= n ; i ++ ) if ( ( n & i ) == i ) System . out . print ( i + " ▁ " ) ; } public static void main ( String [ ] args ) { int n = 9 ; printSubsets ( n ) ; } }
Find most significant set bit of a number | Java program to find MSB number for given n . ; To find the position of the most significant set bit ; To return the the value of the number with set bit at k - th position ; Driver code
class GFG { static int setBitNumber ( int n ) { int k = ( int ) ( Math . log ( n ) / Math . log ( 2 ) ) ; return 1 << k ; } public static void main ( String arg [ ] ) { int n = 273 ; System . out . print ( setBitNumber ( n ) ) ; } }
Minimum number of subsets with distinct elements | A sorting based solution to find the minimum number of subsets of a set such that every subset contains distinct elements . ; Function to count subsets such that all subsets have distinct elements . ; Take input and initialize res = 0 ; Sort the array ; Traverse the input array and find maximum frequency ; For each number find its repetition / frequency ; Update res ; Driver function
import java . util . * ; import java . lang . * ; public class GfG { public static int subset ( int ar [ ] , int n ) { int res = 0 ; Arrays . sort ( ar ) ; for ( int i = 0 ; i < n ; i ++ ) { int count = 1 ; for ( ; i < n - 1 ; i ++ ) { if ( ar [ i ] == ar [ i + 1 ] ) count ++ ; else break ; } res = Math . max ( res , count ) ; } return res ; } public static void main ( String argc [ ] ) { int arr [ ] = { 5 , 6 , 9 , 3 , 4 , 3 , 4 } ; int n = 7 ; System . out . println ( subset ( arr , n ) ) ; } }
Minimum number of subsets with distinct elements | A hashing based solution to find the minimum number of subsets of a set such that every subset contains distinct elements . ; Function to count subsets such that all subsets have distinct elements . ; Traverse the input array and store frequencies of elements ; Find the maximum value in map . ; Driver code
import java . util . HashMap ; import java . util . Map ; class GFG { static int subset ( int arr [ ] , int n ) { HashMap < Integer , Integer > mp = new HashMap < > ( ) ; for ( int i = 0 ; i < n ; i ++ ) mp . put ( arr [ i ] , mp . get ( arr [ i ] ) == null ? 1 : mp . get ( arr [ i ] ) + 1 ) ; int res = 0 ; for ( Map . Entry < Integer , Integer > entry : mp . entrySet ( ) ) res = Math . max ( res , entry . getValue ( ) ) ; return res ; } public static void main ( String [ ] args ) { int arr [ ] = { 5 , 6 , 9 , 3 , 4 , 3 , 4 } ; int n = arr . length ; System . out . println ( subset ( arr , n ) ) ; } }
Count ways to represent a number as sum of perfect squares | Java program for the above approach ; Store perfect squares less than or equal to N ; Utility function to calculate perfect squares less than or equal to N ; Function to find the number of ways to represent a number as sum of perfect squares ; Handle the base cases ; Include the i - th index element ; Exclude the i - th index element ; Return the result ; Driver Code ; Given Input ; Precalculate perfect squares <= N ; Function Call
import java . io . * ; import java . lang . * ; import java . util . * ; public class GFG { static ArrayList < Integer > psquare = new ArrayList < > ( ) ; static void calcPsquare ( int N ) { for ( int i = 1 ; i * i <= N ; i ++ ) psquare . add ( i * i ) ; } static int countWays ( int index , int target ) { if ( target == 0 ) return 1 ; if ( index < 0 target < 0 ) return 0 ; int inc = countWays ( index , target - psquare . get ( index ) ) ; int exc = countWays ( index - 1 , target ) ; return inc + exc ; } public static void main ( String [ ] args ) { int N = 9 ; calcPsquare ( N ) ; System . out . print ( countWays ( psquare . size ( ) - 1 , N ) ) ; } }
Sum of distances of all nodes from a given node | Java program for the above approach ; Structure of a binary tree node ; Function that allocates a new node with the given data and null to its left and right pointers ; Return newly created node ; Function to count the number of nodes in the left and right subtrees ; Initialize a pair that stores the pair { number of nodes , depth } ; Finding the number of nodes in the left subtree ; Find the number of nodes in the right subtree ; Filling up size field ; Stores the sum of distances of all nodes from the given node ; Function to find the total distance ; If target node matches with the current node ; If root . left is not null ; Update sum ; Recur for the left subtree ; If root . right is not null ; Apply the formula given in the approach ; Recur for the right subtree ; Driver Code ; Input tree ; Total number of nodes ; Print the sum of distances
import java . util . * ; class GFG { static class pair { int first , second ; public pair ( int first , int second ) { this . first = first ; this . second = second ; } } static class TreeNode { int data , size ; TreeNode left ; TreeNode right ; } ; static TreeNode newNode ( int data ) { TreeNode Node = new TreeNode ( ) ; Node . data = data ; Node . left = null ; Node . right = null ; return ( Node ) ; } static pair sumofsubtree ( TreeNode root ) { pair p = new pair ( 1 , 0 ) ; if ( root . left != null ) { pair ptemp = sumofsubtree ( root . left ) ; p . second += ptemp . first + ptemp . second ; p . first += ptemp . first ; } if ( root . right != null ) { pair ptemp = sumofsubtree ( root . right ) ; p . second += ptemp . first + ptemp . second ; p . first += ptemp . first ; } root . size = p . first ; return p ; } static int sum = 0 ; static void distance ( TreeNode root , int target , int distancesum , int n ) { if ( root . data == target ) { sum = distancesum ; } if ( root . left != null ) { int tempsum = distancesum - root . left . size + ( n - root . left . size ) ; distance ( root . left , target , tempsum , n ) ; } if ( root . right != null ) { int tempsum = distancesum - root . right . size + ( n - root . right . size ) ; distance ( root . right , target , tempsum , n ) ; } } public static void main ( String [ ] args ) { TreeNode root = newNode ( 1 ) ; root . left = newNode ( 2 ) ; root . right = newNode ( 3 ) ; root . left . left = newNode ( 4 ) ; root . left . right = newNode ( 5 ) ; root . right . left = newNode ( 6 ) ; root . right . right = newNode ( 7 ) ; root . left . left . left = newNode ( 8 ) ; root . left . left . right = newNode ( 9 ) ; int target = 3 ; pair p = sumofsubtree ( root ) ; int totalnodes = p . first ; distance ( root , target , p . second , totalnodes ) ; System . out . print ( sum + "NEW_LINE"); } }
Rearrange array such that sum of same indexed elements is atmost K | Java program for the above approach ; Reverse array ; Function to rearrange array such that sum of similar indexed elements does not exceed K ; Sort the array B [ ] in descending order ; If condition fails ; Print the array ; Driver Code ; Given arrays
import java . util . * ; class GFG { static int [ ] reverse ( int a [ ] ) { int i , n = a . length , t ; for ( i = 0 ; i < n / 2 ; i ++ ) { t = a [ i ] ; a [ i ] = a [ n - i - 1 ] ; a [ n - i - 1 ] = t ; } return a ; } static void rearrangeArray ( int A [ ] , int B [ ] , int N , int K ) { Arrays . sort ( B ) ; B = reverse ( B ) ; boolean flag = true ; for ( int i = 0 ; i < N ; i ++ ) { if ( A [ i ] + B [ i ] > K ) { flag = false ; break ; } } if ( ! flag ) { System . out . print ( " - 1" + "NEW_LINE"); } else { for ( int i = 0 ; i < N ; i ++ ) { System . out . print ( B [ i ] + " ▁ " ) ; } } } public static void main ( String [ ] args ) { int A [ ] = { 1 , 2 , 3 , 4 , 2 } ; int B [ ] = { 1 , 2 , 3 , 1 , 1 } ; int N = A . length ; int K = 5 ; rearrangeArray ( A , B , N , K ) ; } }
Count rows with sum exceeding sum of the remaining Matrix | Java program to implement the above approach ; Function to count the number of rows whose sum exceeds the sum of elements of the remaining matrix ; Stores the matrix dimensions ; To store the result ; Stores the total sum of the matrix elements ; Calculate the total sum ; Traverse to check for each row ; Stores the sum of elements of the current row ; Calculate the sum of elements of the current row ; If sum of current row exceeds the sum of rest of the matrix ; Increase count ; Print the result ; Driver Code ; Given matrix ; Function Call
import java . io . * ; class GFG { static void countRows ( int [ ] [ ] mat ) { int n = mat . length ; int m = mat [ 0 ] . length ; int count = 0 ; int totalSum = 0 ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = 0 ; j < m ; j ++ ) { totalSum += mat [ i ] [ j ] ; } } for ( int i = 0 ; i < n ; i ++ ) { int currSum = 0 ; for ( int j = 0 ; j < m ; j ++ ) { currSum += mat [ i ] [ j ] ; } if ( currSum > totalSum - currSum ) count ++ ; } System . out . println ( count ) ; } public static void main ( String [ ] args ) { int [ ] [ ] mat = { { 2 , - 1 , 5 } , { - 3 , 0 , - 2 } , { 5 , 1 , 2 } } ; countRows ( mat ) ; } }
Check if array contains contiguous integers with duplicates allowed | Sorting based Java implementation to check whether the array contains a set of contiguous integers ; function to check whether the array contains a set of contiguous integers ; Sort the array ; After sorting , check if current element is either same as previous or is one more . ; Driver program to test above function
import java . util . * ; class GFG { static boolean areElementsContiguous ( int arr [ ] , int n ) { Arrays . sort ( arr ) ; for ( int i = 1 ; i < n ; i ++ ) if ( arr [ i ] - arr [ i - 1 ] > 1 ) return false ; return true ; } public static void main ( String [ ] args ) { int arr [ ] = { 5 , 2 , 3 , 6 , 4 , 4 , 6 , 6 } ; int n = arr . length ; if ( areElementsContiguous ( arr , n ) ) System . out . println ( " Yes " ) ; else System . out . println ( " No " ) ; } }
Check if array contains contiguous integers with duplicates allowed | Java implementation to check whether the array contains a set of contiguous integers ; function to check whether the array contains a set of contiguous integers ; Find maximum and minimum elements . ; There should be at least m elements in aaray to make them contiguous . ; Create a visited array and initialize false . ; Mark elements as true . ; If any element is not marked , all elements are not contiguous . ; Driver program
import java . util . * ; class GFG { static boolean areElementsContiguous ( int arr [ ] , int n ) { int max = Integer . MIN_VALUE ; int min = Integer . MAX_VALUE ; for ( int i = 0 ; i < n ; i ++ ) { max = Math . max ( max , arr [ i ] ) ; min = Math . min ( min , arr [ i ] ) ; } int m = max - min + 1 ; if ( m > n ) return false ; boolean visited [ ] = new boolean [ n ] ; for ( int i = 0 ; i < n ; i ++ ) visited [ arr [ i ] - min ] = true ; for ( int i = 0 ; i < m ; i ++ ) if ( visited [ i ] == false ) return false ; return true ; } public static void main ( String [ ] args ) { int arr [ ] = { 5 , 2 , 3 , 6 , 4 , 4 , 6 , 6 } ; int n = arr . length ; if ( areElementsContiguous ( arr , n ) ) System . out . println ( " Yes " ) ; else System . out . println ( " No " ) ; } }
Check if array contains contiguous integers with duplicates allowed | Java implementation to check whether the array contains a set of contiguous integers ; Function to check whether the array contains a set of contiguous integers ; Storing elements of ' arr [ ] ' in a hash table ' us ' ; As arr [ 0 ] is present in ' us ' ; Starting with previous smaller element of arr [ 0 ] ; If ' curr _ ele ' is present in ' us ' ; increment count ; update 'curr_ele" ; Starting with next greater element of arr [ 0 ] ; If ' curr _ ele ' is present in ' us ' ; increment count ; update 'curr_ele" ; Returns true if array contains a set of contiguous integers else returns false ; Driver Code
import java . io . * ; import java . util . * ; class GFG { static Boolean areElementsContiguous ( int arr [ ] , int n ) { HashSet < Integer > us = new HashSet < Integer > ( ) ; for ( int i = 0 ; i < n ; i ++ ) us . add ( arr [ i ] ) ; int count = 1 ; int curr_ele = arr [ 0 ] - 1 ; while ( us . contains ( curr_ele ) == true ) { count ++ ; curr_ele -- ; } curr_ele = arr [ 0 ] + 1 ; while ( us . contains ( curr_ele ) == true ) { count ++ ; curr_ele ++ ; } return ( count == ( us . size ( ) ) ) ; } public static void main ( String [ ] args ) { int arr [ ] = { 5 , 2 , 3 , 6 , 4 , 4 , 6 , 6 } ; int n = arr . length ; if ( areElementsContiguous ( arr , n ) ) System . out . println ( " Yes " ) ; else System . out . println ( " No " ) ; } }
Longest subarray not having more than K distinct elements | Java program to find longest subarray with k or less distinct elements . ; function to print the longest sub - array ; mark the element visited ; if its visited first time , then increase the counter of distinct elements by 1 ; When the counter of distinct elements increases from k , then reduce it to k ; from the left , reduce the number of time of visit ; if the reduced visited time element is not present in further segment then decrease the count of distinct elements ; increase the subsegment mark ; check length of longest sub - segment when greater then previous best then change it ; print the longest sub - segment ; Driver code
import java . util . * ; class GFG { static void longest ( int a [ ] , int n , int k ) { int [ ] freq = new int [ 7 ] ; int start = 0 , end = 0 , now = 0 , l = 0 ; for ( int i = 0 ; i < n ; i ++ ) { freq [ a [ i ] ] ++ ; if ( freq [ a [ i ] ] == 1 ) now ++ ; while ( now > k ) { freq [ a [ l ] ] -- ; if ( freq [ a [ l ] ] == 0 ) now -- ; l ++ ; } if ( i - l + 1 >= end - start + 1 ) { end = i ; start = l ; } } for ( int i = start ; i <= end ; i ++ ) System . out . print ( a [ i ] + " ▁ " ) ; } public static void main ( String args [ ] ) { int a [ ] = { 6 , 5 , 1 , 2 , 3 , 2 , 1 , 4 , 5 } ; int n = a . length ; int k = 3 ; longest ( a , n , k ) ; } }
Check if any K ranges overlap at any point | Java implementation of the approach ; Function that returns true if any k segments overlap at any point ; Vector to store the starting point and the ending point ; Starting points are marked by - 1 and ending points by + 1 ; Sort the vector by first element ; Comparator to sort the vector of pairs ; Stack to store the overlaps ; Get the current element ; If it is the starting point ; Push it in the stack ; It is the ending point ; Pop an element from stack ; If more than k ranges overlap ; Driver code
import java . util . ArrayList ; import java . util . Collections ; import java . util . Comparator ; import java . util . Stack ; class GFG { static class Pair { int first , second ; public Pair ( int first , int second ) { this . first = first ; this . second = second ; } } static boolean kOverlap ( ArrayList < Pair > pairs , int k ) { ArrayList < Pair > vec = new ArrayList < > ( ) ; for ( int i = 0 ; i < pairs . size ( ) ; i ++ ) { vec . add ( new Pair ( pairs . get ( i ) . first , - 1 ) ) ; vec . add ( new Pair ( pairs . get ( i ) . second , + 1 ) ) ; } Collections . sort ( vec , new Comparator < Pair > ( ) { public int compare ( Pair a , Pair b ) { if ( a . first != b . first ) return a . first - b . first ; return ( a . second - b . second ) ; } } ) ; Stack < Pair > st = new Stack < > ( ) ; for ( int i = 0 ; i < vec . size ( ) ; i ++ ) { Pair cur = vec . get ( i ) ; if ( cur . second == - 1 ) { st . push ( cur ) ; } else { st . pop ( ) ; } if ( st . size ( ) >= k ) { return true ; } } return false ; } public static void main ( String [ ] args ) { ArrayList < Pair > pairs = new ArrayList < > ( ) ; pairs . add ( new Pair ( 1 , 3 ) ) ; pairs . add ( new Pair ( 2 , 4 ) ) ; pairs . add ( new Pair ( 3 , 5 ) ) ; pairs . add ( new Pair ( 7 , 10 ) ) ; int n = pairs . size ( ) , k = 3 ; if ( kOverlap ( pairs , k ) ) System . out . println ( " Yes " ) ; else System . out . println ( " No " ) ; } }