codeparrot/xlcost-text-to-code huggingface dataset:
Check if all substrings of length K of a Binary String has equal count of 0 s and 1 s | Java program for the above approach ; Function to check if the substring of length K has equal 0 and 1 ; Traverse the String ; Check if every K - th character is the same or not ; Traverse subString of length K ; If current character is 0 ; Increment count ; Otherwise ; Decrement count ; Check for equal 0 s and 1 s ; Driver code
import java . util . * ; class GFG { static boolean check ( String s , int k ) { int n = s . length ( ) ; for ( int i = 0 ; i < k ; i ++ ) { for ( int j = i ; j < n ; j += k ) { if ( s . charAt ( i ) != s . charAt ( j ) ) return false ; } } int c = 0 ; for ( int i = 0 ; i < k ; i ++ ) { if ( s . charAt ( i ) == '0' ) c ++ ; else c -- ; } if ( c == 0 ) return true ; else return false ; } public static void main ( String [ ] args ) { String s = "101010" ; int k = 2 ; if ( check ( s , k ) ) System . out . print ( " Yes " + "NEW_LINE"); else System . out . print ( " No " + "NEW_LINE"); } }
Check if characters of a given string can be used to form any N equal strings | Java program for the above approach ; Function to check if the freq of any character is divisible by N ; Stores the frequency of characters ; If frequency of a character is not divisible by n ; If no character has frequency at least N ; Driver Code ; Function Call
import java . util . * ; class GFG { static boolean isSame ( String str , int n ) { HashMap < Integer , Integer > mp = new HashMap < Integer , Integer > ( ) ; for ( int i = 0 ; i < str . length ( ) ; i ++ ) { if ( mp . containsKey ( str . charAt ( i ) - ' a ' ) ) { mp . put ( str . charAt ( i ) - ' a ' , mp . get ( str . charAt ( i ) - ' a ' ) + 1 ) ; } else { mp . put ( str . charAt ( i ) - ' a ' , 1 ) ; } } for ( Map . Entry < Integer , Integer > it : mp . entrySet ( ) ) { if ( ( it . getValue ( ) ) >= n ) { return true ; } } return false ; } public static void main ( String [ ] args ) { String str = " ccabcba " ; int n = 4 ; if ( isSame ( str , n ) ) { System . out . print ( " Yes " ) ; } else { System . out . print ( " No " ) ; } } }
Find the root of given non decreasing function between A and B | Java program for the above approach ; Given function ; Function to find the root of the given non - decreasing Function ; To get the minimum possible answer for the root ; Find mid ; Search in [ low , x ] ; Search in [ x , high ] ; Return the required answer ; Function to find the roots of the given equation within range [ a , b ] ; If root doesn 't exists ; Else find the root upto 4 decimal places ; Driver Code ; Given range ; Function call
import java . util . * ; import java . lang . * ; class GFG { static final double eps = 1e-6 ; static double func ( double a , double b , double c , double x ) { return a * x * x + b * x + c ; } static double findRoot ( double a , double b , double c , double low , double high ) { double x = - 1 ; while ( Math . abs ( high - low ) > eps ) { x = ( low + high ) / 2 ; if ( func ( a , b , c , low ) * func ( a , b , c , x ) <= 0 ) { high = x ; } else { low = x ; } } return x ; } static void solve ( double a , double b , double c , double A , double B ) { if ( func ( a , b , c , A ) * func ( a , b , c , B ) > 0 ) { System . out . println ( " No ▁ solution " ) ; } else { System . out . format ( " % .4f " , findRoot ( a , b , c , A , B ) ) ; } } public static void main ( String [ ] args ) { double a = 2 , b = - 3 , c = - 2 , A = 0 , B = 3 ; solve ( a , b , c , A , B ) ; } }
Median of difference of all pairs from an Array | Java program to implement the above approach ; Function check if mid can be median index of the difference array ; Size of the array ; Total possible no of pair possible ; The index of the element in the difference of all pairs from the array ; Count the number of pairs having difference <= mid ; If the difference between end and first element is less then or equal to mid ; Checking for the no of element less than or equal to mid is greater than median or not ; Function to calculate the median of differences of all pairs from the array ; Size of the array ; Initialising the low and high ; Binary search ; Calculate mid ; If mid can be the median of the array ; Returning the median of the differences of pairs from the array ; Driver code
import java . util . * ; class GFG { static boolean possible ( long mid , int [ ] a ) { long n = a . length ; long total = ( n * ( n - 1 ) ) / 2 ; long need = ( total + 1 ) / 2 ; long count = 0 ; long start = 0 , end = 1 ; while ( end < n ) { if ( a [ ( int ) end ] - a [ ( int ) start ] <= mid ) { end ++ ; } else { count += ( end - start - 1 ) ; start ++ ; } } if ( end == n && start < end && a [ ( int ) end - 1 ] - a [ ( int ) start ] <= mid ) { long t = end - start - 1 ; count += ( t * ( t + 1 ) / 2 ) ; } if ( count >= need ) return true ; else return false ; } static long findMedian ( int [ ] a ) { long n = a . length ; long low = 0 , high = a [ ( int ) n - 1 ] - a [ 0 ] ; while ( low <= high ) { long mid = ( low + high ) / 2 ; if ( possible ( mid , a ) ) high = mid - 1 ; else low = mid + 1 ; } return high + 1 ; } public static void main ( String [ ] args ) { int [ ] a = { 1 , 7 , 5 , 2 } ; Arrays . sort ( a ) ; System . out . println ( findMedian ( a ) ) ; } }
Print all Strings from array A [ ] having all strings from array B [ ] as subsequence | Java program to implement the above approach ; Function to find strings from A [ ] having all strings in B [ ] as subsequence ; Calculate respective sizes ; Stores the answer ; Stores the frequency of each character in strings of A [ ] ; Compute the frequencies of characters of all strings ; Stores the frequency of each character in strings of B [ ] each character of a string in B [ ] ; If the frequency of a character in B [ ] exceeds that in A [ ] ; A string exists in B [ ] which is not a proper subset of A [ i ] ; If all strings in B [ ] are proper subset of A [ ] ; Push the string in resultant vector ; If any string is found ; Print those strings ; Otherwise ; Driver code
import java . util . * ; class GFG { static void UniversalSubset ( List < String > A , List < String > B ) { int n1 = A . size ( ) ; int n2 = B . size ( ) ; List < String > res = new ArrayList < > ( ) ; int [ ] [ ] A_fre = new int [ n1 ] [ 26 ] ; for ( int i = 0 ; i < n1 ; i ++ ) { for ( int j = 0 ; j < 26 ; j ++ ) A_fre [ i ] [ j ] = 0 ; } for ( int i = 0 ; i < n1 ; i ++ ) { for ( int j = 0 ; j < A . get ( i ) . length ( ) ; j ++ ) { A_fre [ i ] [ A . get ( i ) . charAt ( j ) - ' a ' ] ++ ; } } int [ ] B_fre = new int [ 26 ] ; for ( int i = 0 ; i < n2 ; i ++ ) { int [ ] arr = new int [ 26 ] ; for ( int j = 0 ; j < B . get ( i ) . length ( ) ; j ++ ) { arr [ B . get ( i ) . charAt ( j ) - ' a ' ] ++ ; B_fre [ B . get ( i ) . charAt ( j ) - ' a ' ] = Math . max ( B_fre [ B . get ( i ) . charAt ( j ) - ' a ' ] , arr [ B . get ( i ) . charAt ( j ) - ' a ' ] ) ; } } for ( int i = 0 ; i < n1 ; i ++ ) { int flag = 0 ; for ( int j = 0 ; j < 26 ; j ++ ) { if ( A_fre [ i ] [ j ] < B_fre [ j ] ) { flag = 1 ; break ; } } if ( flag == 0 ) res . add ( A . get ( i ) ) ; } if ( res . size ( ) != 0 ) { for ( int i = 0 ; i < res . size ( ) ; i ++ ) { for ( int j = 0 ; j < res . get ( i ) . length ( ) ; j ++ ) System . out . print ( res . get ( i ) . charAt ( j ) ) ; } System . out . print ( " ▁ " ) ; } else System . out . print ( " - 1" ) ; } public static void main ( String [ ] args ) { List < String > A = Arrays . asList ( " geeksforgeeks " , " topcoder " , " leetcode " ) ; List < String > B = Arrays . asList ( " geek " , " ee " ) ; UniversalSubset ( A , B ) ; } }
Closest pair in an Array such that one number is multiple of the other | Java program for the above approach ; Function to find the minimum distance pair where one is the multiple of the other ; Initialize the variables ; Iterate for all the elements ; Loop to make pairs ; Check for minimum distance ; Check if one is a multiple of other ; Update the distance ; Store indexes ; If no such pair exists ; Print the answer ; Driver Code ; Given array arr [ ] ; Function Call
import java . util . * ; class GFG { public static void findPair ( int a [ ] , int n ) { int min_dist = Integer . MAX_VALUE ; int index_a = - 1 , index_b = - 1 ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = i + 1 ; j < n ; j ++ ) { if ( j - i < min_dist ) { if ( a [ i ] % a [ j ] == 0 a [ j ] % a [ i ] == 0 ) { min_dist = j - i ; index_a = i ; index_b = j ; } } } } if ( index_a == - 1 ) { System . out . println ( " - 1" ) ; } else { System . out . print ( " ( " + a [ index_a ] + " , ▁ " + a [ index_b ] + " ) " ) ; } } public static void main ( String [ ] args ) { int a [ ] = { 2 , 3 , 4 , 5 , 6 } ; int n = a . length ; findPair ( a , n ) ; } }
Print all numbers in given range having digits in strictly increasing order | Java program for the above approach ; Function to print all numbers in the range [ L , R ] having digits in strictly increasing order ; Iterate over the range ; Iterate over the digits ; Check if the current digit is >= the previous digit ; If the digits are in ascending order ; Driver code ; Given range L and R ; Function call
import java . util . * ; class GFG { static void printNum ( int L , int R ) { for ( int i = L ; i <= R ; i ++ ) { int temp = i ; int c = 10 ; int flag = 0 ; while ( temp > 0 ) { if ( temp % 10 >= c ) { flag = 1 ; break ; } c = temp % 10 ; temp /= 10 ; } if ( flag == 0 ) System . out . print ( i + " ▁ " ) ; } } public static void main ( String [ ] args ) { int L = 10 , R = 15 ; printNum ( L , R ) ; } }
Find the missing number in unordered Arithmetic Progression | Java program for the above approach ; Function to find the missing element ; Fix left and right boundary for binary search ; Find index of middle element ; Check if the element just after the middle element is missing ; Check if the element just before mid is missing ; Check if the elements till mid follow the AP , then recur for right half ; Else recur for left half ; Function to find the missing element in AP series ; Sort the array arr [ ] ; Calculate Common Difference ; Binary search for the missing ; Driver Code ; Given array arr [ ] ; Function Call
import java . util . Arrays ; class GFG { static int findMissing ( int arr [ ] , int left , int right , int diff ) { if ( right <= left ) return 0 ; int mid = left + ( right - left ) / 2 ; if ( arr [ mid + 1 ] - arr [ mid ] != diff ) return ( arr [ mid ] + diff ) ; if ( mid > 0 && arr [ mid ] - arr [ mid - 1 ] != diff ) return ( arr [ mid - 1 ] + diff ) ; if ( arr [ mid ] == arr [ 0 ] + mid * diff ) return findMissing ( arr , mid + 1 , right , diff ) ; return findMissing ( arr , left , mid - 1 , diff ) ; } static int missingElement ( int arr [ ] , int n ) { Arrays . sort ( arr ) ; int diff = ( arr [ n - 1 ] - arr [ 0 ] ) / n ; return findMissing ( arr , 0 , n - 1 , diff ) ; } public static void main ( String [ ] args ) { int arr [ ] = new int [ ] { 2 , 8 , 6 , 10 } ; int n = arr . length ; System . out . println ( missingElement ( arr , n ) ) ; } }
Floor value Kth root of a number using Recursive Binary Search | Java program for the above approach ; Function to calculate x raised to the power y in O ( logn ) ; Function to find the Kth root of the number N using BS ; If the range is still valid ; Find the mid - value of range ; Base Case ; Condition to check if the left search space is useless ; Driver Code ; Given N and K ; Function Call
class GFG { static int power ( int x , int y ) { int temp ; if ( y == 0 ) return 1 ; temp = power ( x , y / 2 ) ; if ( y % 2 == 0 ) return temp * temp ; else return x * temp * temp ; } static int nthRootSearch ( int low , int high , int N , int K ) { if ( low <= high ) { int mid = ( low + high ) / 2 ; if ( ( power ( mid , K ) <= N ) && ( power ( mid + 1 , K ) > N ) ) { return mid ; } else if ( power ( mid , K ) < N ) { return nthRootSearch ( mid + 1 , high , N , K ) ; } else { return nthRootSearch ( low , mid - 1 , N , K ) ; } } return low ; } public static void main ( String s [ ] ) { int N = 16 , K = 4 ; System . out . println ( nthRootSearch ( 0 , N , N , K ) ) ; } }
Count of subsets having sum of min and max element less than K | Java program to print count of subsets S such that Math . min ( S ) + Math . max ( S ) < K ; Function that return the count of subset such that Math . min ( S ) + Math . max ( S ) < K ; Sorting the array ; ans stores total number of subsets ; Add all possible subsets between i and j ; Decrease the sum ; Driver code
import java . util . * ; class GFG { static int get_subset_count ( int arr [ ] , int K , int N ) { Arrays . sort ( arr ) ; int left , right ; left = 0 ; right = N - 1 ; int ans = 0 ; while ( left <= right ) { if ( arr [ left ] + arr [ right ] < K ) { ans += 1 << ( right - left ) ; left ++ ; } else { right -- ; } } return ans ; } public static void main ( String [ ] args ) { int arr [ ] = { 2 , 4 , 5 , 7 } ; int K = 8 ; int N = arr . length ; System . out . print ( get_subset_count ( arr , K , N ) ) ; } }
Minimize the maximum difference of adjacent elements after at most K insertions | Java program to find the minimum of maximum difference between adjacent elements after at most K insertions ; Calculate the maximum adjacent difference ; If the maximum adjacent difference is already zero ; best and worst specifies range of the maximum adjacent difference ; To store the no of insertions required for respective values of mid ; If the number of insertions required exceeds K ; Otherwise ; Driver code
import java . util . * ; class GFG { static int minMaxDiff ( int arr [ ] , int n , int k ) { int max_adj_dif = Integer . MIN_VALUE ; for ( int i = 0 ; i < n - 1 ; i ++ ) max_adj_dif = Math . max ( max_adj_dif , Math . abs ( arr [ i ] - arr [ i + 1 ] ) ) ; if ( max_adj_dif == 0 ) return 0 ; int best = 1 ; int worst = max_adj_dif ; int mid , required ; while ( best < worst ) { mid = ( best + worst ) / 2 ; required = 0 ; for ( int i = 0 ; i < n - 1 ; i ++ ) { required += ( Math . abs ( arr [ i ] - arr [ i + 1 ] ) - 1 ) / mid ; } if ( required > k ) best = mid + 1 ; else worst = mid ; } return worst ; } public static void main ( String [ ] args ) { int arr [ ] = { 3 , 12 , 25 , 50 } ; int n = arr . length ; int k = 7 ; System . out . println ( minMaxDiff ( arr , n , k ) ) ; } }
Check if minimum element in array is less than or equals half of every other element | Java implementation to check if the minimum element in the array is greater than or equal to half of every other elements ; Function to Check if the minimum element in the array is greater than or equal to half of every other elements ; Initialise the variables to store smallest and second smallest ; Check if current element is smaller than smallest , the current smallest will become secondSmallest and current element will be the new smallest ; Check if current element is smaller than secondSmallest simply update the latter ; Driver code
import java . util . * ; class GFG { static void checkMin ( int arr [ ] , int len ) { int smallest = Integer . MAX_VALUE ; int secondSmallest = Integer . MAX_VALUE ; for ( int i = 0 ; i < len ; i ++ ) { if ( arr [ i ] < smallest ) { secondSmallest = smallest ; smallest = arr [ i ] ; } else if ( arr [ i ] < secondSmallest ) { secondSmallest = arr [ i ] ; } } if ( 2 * smallest <= secondSmallest ) System . out . print ( " Yes " ) ; else System . out . print ( " No " ) ; } public static void main ( String [ ] args ) { int arr [ ] = { 2 , 3 , 4 , 5 } ; int len = arr . length ; checkMin ( arr , len ) ; } }
Largest and smallest Fibonacci numbers in an Array | Java program to find minimum and maximum fibonacci number in given array ; Function to create hash table to check Fibonacci numbers ; Insert initial two numbers in the hash table ; Sum of previous two numbers ; Update the variable each time ; Function to find minimum and maximum fibonacci number in given array ; Find maximum value in the array ; Creating a set containing all Fibonacci numbers up to maximum value in the array ; For storing the Minimum and Maximum Fibonacci number ; Check if current element is a fibonacci number ; Update the maximum and minimum accordingly ; Driver code
import java . util . * ; class GFG { static void createHash ( HashSet < Integer > hash , int maxElement ) { int prev = 0 , curr = 1 ; hash . add ( prev ) ; hash . add ( curr ) ; while ( curr <= maxElement ) { int temp = curr + prev ; hash . add ( temp ) ; prev = curr ; curr = temp ; } } static void fibonacci ( int arr [ ] , int n ) { int max_val = Arrays . stream ( arr ) . max ( ) . getAsInt ( ) ; HashSet < Integer > hash = new HashSet < Integer > ( ) ; createHash ( hash , max_val ) ; int minimum = Integer . MAX_VALUE ; int maximum = Integer . MIN_VALUE ; for ( int i = 0 ; i < n ; i ++ ) { if ( hash . contains ( arr [ i ] ) ) { minimum = Math . min ( minimum , arr [ i ] ) ; maximum = Math . max ( maximum , arr [ i ] ) ; } } System . out . print ( minimum + " , ▁ " + maximum + "NEW_LINE"); } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 2 , 3 , 4 , 5 , 6 , 7 } ; int n = arr . length ; fibonacci ( arr , n ) ; } }
Longest substring with K unique characters using Binary Search | Java implementation of the approach ; Function that returns true if there is a subString of length len with <= k unique characters ; Size of the String ; Map to store the characters and their frequency ; Update the map for the first subString ; Check for the rest of the subStrings ; Add the new character ; Remove the first character of the previous window ; Update the map ; Function to return the length of the longest subString which has K unique characters ; Check if the complete String contains K unique characters ; Size of the String ; Apply binary search ; Driver code
import java . util . * ; class GFG { static boolean isValidLen ( String s , int len , int k ) { int n = s . length ( ) ; Map < Character , Integer > mp = new HashMap < Character , Integer > ( ) ; int right = 0 ; while ( right < len ) { if ( mp . containsKey ( s . charAt ( right ) ) ) { mp . put ( s . charAt ( right ) , mp . get ( s . charAt ( right ) ) + 1 ) ; } else { mp . put ( s . charAt ( right ) , 1 ) ; } right ++ ; } if ( mp . size ( ) <= k ) return true ; while ( right < n ) { if ( mp . containsKey ( s . charAt ( right ) ) ) { mp . put ( s . charAt ( right ) , mp . get ( s . charAt ( right ) ) + 1 ) ; } else { mp . put ( s . charAt ( right ) , 1 ) ; } if ( mp . containsKey ( s . charAt ( right - len ) ) ) { mp . put ( s . charAt ( right - len ) , mp . get ( s . charAt ( right - len ) ) - 1 ) ; } if ( mp . get ( s . charAt ( right - len ) ) == 0 ) mp . remove ( s . charAt ( right - len ) ) ; if ( mp . size ( ) <= k ) return true ; right ++ ; } return mp . size ( ) <= k ; } static int maxLenSubStr ( String s , int k ) { Set < Character > uni = new HashSet < Character > ( ) ; for ( Character x : s . toCharArray ( ) ) uni . add ( x ) ; if ( uni . size ( ) < k ) return - 1 ; int n = s . length ( ) ; int lo = - 1 , hi = n + 1 ; while ( hi - lo > 1 ) { int mid = lo + hi >> 1 ; if ( isValidLen ( s , mid , k ) ) lo = mid ; else hi = mid ; } return lo ; } public static void main ( String [ ] args ) { String s = " aabacbebebe " ; int k = 3 ; System . out . print ( maxLenSubStr ( s , k ) ) ; } }
Largest area square in an array when elements can be shuffled | Java implementation of the approach ; Function that returns true if it is possible to make a square with side equal to l ; To store the count of elements greater than or equal to l ; Increment the count ; If the count becomes greater than or equal to l ; Function to return the maximum area of the square that can be obtained ; If square is possible with side length m ; Try to find a square with smaller side length ; Return the area ; Driver code
class GFG { static boolean isSquarePossible ( int arr [ ] , int n , int l ) { int cnt = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( arr [ i ] >= l ) cnt ++ ; if ( cnt >= l ) return true ; } return false ; } static int maxArea ( int arr [ ] , int n ) { int l = 0 , r = n ; int len = 0 ; while ( l <= r ) { int m = l + ( ( r - l ) / 2 ) ; if ( isSquarePossible ( arr , n , m ) ) { len = m ; l = m + 1 ; } else r = m - 1 ; } return ( len * len ) ; } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 3 , 4 , 5 , 5 } ; int n = arr . length ; System . out . println ( maxArea ( arr , n ) ) ; } }
Check duplicates in a stream of strings | Java implementation of the approach ; Function to insert the names and check whether they appear for the first time ; To store the names of the employees ; If current name is appearing for the first time ; Driver code
import java . util . * ; class GFG { static void insertNames ( String arr [ ] , int n ) { HashSet < String > set = new HashSet < String > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( ! set . contains ( arr [ i ] ) ) { System . out . print ( "NoNEW_LINE"); set . add ( arr [ i ] ) ; } else { System . out . print ( "YesNEW_LINE"); } } } public static void main ( String [ ] args ) { String arr [ ] = { " geeks " , " for " , " geeks " } ; int n = arr . length ; insertNames ( arr , n ) ; } }
Count the triplets such that A [ i ] < B [ j ] < C [ k ] | Java implementation of the approach ; Function to return the count of elements in arr [ ] which are less than the given key ; Modified binary search ; Function to return the count of elements in arr [ ] which are greater than the given key ; Modified binary search ; Function to return the count of the required triplets ; Sort all three arrays ; Iterate for all the elements of array B ; Count of elements in A [ ] which are less than the chosen element from B [ ] ; Count of elements in C [ ] which are greater than the chosen element from B [ ] ; Update the count ; Driver code
import java . util . * ; class GFG { static int countLessThan ( int arr [ ] , int n , int key ) { int l = 0 , r = n - 1 ; int index = - 1 ; while ( l <= r ) { int m = ( l + r ) / 2 ; if ( arr [ m ] < key ) { l = m + 1 ; index = m ; } else { r = m - 1 ; } } return ( index + 1 ) ; } static int countGreaterThan ( int arr [ ] , int n , int key ) { int l = 0 , r = n - 1 ; int index = - 1 ; while ( l <= r ) { int m = ( l + r ) / 2 ; if ( arr [ m ] <= key ) { l = m + 1 ; } else { r = m - 1 ; index = m ; } } if ( index == - 1 ) return 0 ; return ( n - index ) ; } static int countTriplets ( int n , int a [ ] , int b [ ] , int c [ ] ) { Arrays . sort ( a ) ; Arrays . sort ( b ) ; Arrays . sort ( c ) ; int count = 0 ; for ( int i = 0 ; i < n ; ++ i ) { int current = b [ i ] ; int low = countLessThan ( a , n , current ) ; int high = countGreaterThan ( c , n , current ) ; count += ( low * high ) ; } return count ; } public static void main ( String args [ ] ) { int a [ ] = { 1 , 5 } ; int b [ ] = { 2 , 4 } ; int c [ ] = { 3 , 6 } ; int size = a . length ; System . out . println ( countTriplets ( size , a , b , c ) ) ; } }
Cost to Balance the parentheses | Java code to calculate the minimum cost to make the given parentheses balanced ; To store absolute count of balanced and unbalanced parenthesis ; o ( open bracket ) stores count of ' ( ' and c ( close bracket ) stores count of ' ) ' ; Driver code
import java . io . * ; class GFG { static int costToBalance ( String s ) { if ( s . length ( ) == 0 ) System . out . println ( 0 ) ; int ans = 0 ; int o = 0 , c = 0 ; for ( int i = 0 ; i < s . length ( ) ; i ++ ) { if ( s . charAt ( i ) == ' ( ' ) o ++ ; if ( s . charAt ( i ) == ' ) ' ) c ++ ; } if ( o != c ) return - 1 ; int [ ] a = new int [ s . length ( ) ] ; if ( s . charAt ( 0 ) == ' ( ' ) a [ 0 ] = 1 ; else a [ 0 ] = - 1 ; if ( a [ 0 ] < 0 ) ans += Math . abs ( a [ 0 ] ) ; for ( int i = 1 ; i < s . length ( ) ; i ++ ) { if ( s . charAt ( i ) == ' ( ' ) a [ i ] = a [ i - 1 ] + 1 ; else a [ i ] = a [ i - 1 ] - 1 ; if ( a [ i ] < 0 ) ans += Math . abs ( a [ i ] ) ; } return ans ; } public static void main ( String args [ ] ) { String s ; s = " ) ) ) ( ( ( " ; System . out . println ( costToBalance ( s ) ) ; s = " ) ) ( ( " ; System . out . println ( costToBalance ( s ) ) ; } }