codeparrot/xlcost-text-to-code huggingface dataset:
Minimum Cost Path in a directed graph via given set of intermediate nodes | Java program to implement the above approach ; Stores minimum - cost of path from source ; Function to Perform BFS on graph g starting from vertex v ; If destination is reached ; Set flag to true ; Visit all the intermediate nodes ; If any intermediate node is not visited ; If all intermediate nodes are visited ; Update the minSum ; Mark the current node visited ; Traverse adjacent nodes ; Mark the neighbour visited ; Find minimum cost path considering the neighbour as the source ; Mark the neighbour unvisited ; Mark the source unvisited ; Driver code ; Stores the graph ; Number of nodes ; Source ; Destination ; Keeps a check on visited and unvisited nodes ; Stores intemediate nodes ; If no path is found
import java . util . * ; class GFG { static class pair { int first , second ; pair ( int f , int s ) { this . first = f ; this . second = s ; } } static int minSum = Integer . MAX_VALUE ; static void getMinPathSum ( Map < Integer , ArrayList < pair > > graph , boolean [ ] visited , ArrayList < Integer > necessary , int source , int dest , int currSum ) { if ( src == dest ) { boolean flag = true ; for ( int i : necessary ) { if ( ! visited [ i ] ) { flag = false ; break ; } } if ( flag ) minSum = Math . min ( minSum , currSum ) ; return ; } else { visited [ src ] = true ; for ( pair node : graph . get ( src ) ) { if ( ! visited [ node . first ] ) { visited [ node . first ] = true ; getMinPathSum ( graph , visited , necessary , node . first , dest , currSum + node . second ) ; visited [ node . first ] = false ; } } visited [ src ] = false ; } } public static void main ( String [ ] args ) { Map < Integer , ArrayList < pair > > graph = new HashMap < > ( ) ; for ( int i = 0 ; i <= 6 ; i ++ ) graph . put ( i , new ArrayList < pair > ( ) ) ; graph . get ( 0 ) . add ( new pair ( 1 , 2 ) ) ; graph . get ( 0 ) . add ( new pair ( 2 , 3 ) ) ; graph . get ( 0 ) . add ( new pair ( 3 , 2 ) ) ; graph . get ( 1 ) . add ( new pair ( 4 , 4 ) ) ; graph . get ( 1 ) . add ( new pair ( 0 , 1 ) ) ; graph . get ( 2 ) . add ( new pair ( 4 , 5 ) ) ; graph . get ( 2 ) . add ( new pair ( 5 , 6 ) ) ; graph . get ( 3 ) . add ( new pair ( 5 , 7 ) ) ; graph . get ( 3 ) . add ( new pair ( 0 , 1 ) ) ; graph . get ( 4 ) . add ( new pair ( 6 , 4 ) ) ; graph . get ( 5 ) . add ( new pair ( 4 , 2 ) ) ; graph . get ( 6 ) . add ( new pair ( 7 , 11 ) ) ; int n = 7 ; int source = 0 ; int dest = 6 ; boolean [ ] visited = new boolean [ n ] ; ArrayList < Integer > necessary = new ArrayList < > ( Arrays . asList ( 2 , 4 ) ) ; getMinPathSum ( graph , visited , necessary , source , dest , 0 ) ; if ( minSum == Integer . MAX_VALUE ) System . out . println ( - 1 ) ; else System . out . println ( minSum ) ; } }
Unique subsequences of length K with given sum | Java program for the above approach ; Function to find all the subsequences of a given length and having sum S ; Termination condition ; Add value to sum ; Check if the resultant sum equals to target sum ; If true ; Print resultant array ; End this recursion stack ; Check all the combinations using backtracking ; Check all the combinations using backtracking ; Driver Code ; Given array ; To store the subsequence ; Function Call
import java . util . * ; class GFG { static void comb ( int [ ] arr , int len , int r , int ipos , int [ ] op , int opos , int sum ) { if ( opos == r ) { int sum2 = 0 ; for ( int i = 0 ; i < opos ; i ++ ) { sum2 = sum2 + op [ i ] ; } if ( sum == sum2 ) { for ( int i = 0 ; i < opos ; i ++ ) System . out . print ( op [ i ] + " , ▁ " ) ; System . out . println ( ) ; } return ; } if ( ipos < len ) { comb ( arr , len , r , ipos + 1 , op , opos , sum ) ; op [ opos ] = arr [ ipos ] ; comb ( arr , len , r , ipos + 1 , op , opos + 1 , sum ) ; } } public static void main ( String [ ] args ) { int arr [ ] = { 4 , 6 , 8 , 2 , 12 } ; int K = 3 ; int S = 20 ; int N = arr . length ; int op [ ] = new int [ N ] ; comb ( arr , N , K , 0 , op , 0 , S ) ; } }
Traverse the matrix in Diagonally Bottum | Java implementation to traverse the matrix in the bottom - up fashion using recursion ; Static variable for changing row and column ; Flag variable for handling bottum up diagonal traversing ; Recursive function to traverse the matrix diagonally bottom - up ; Base Condition ; Condition when to traverse Bottom Diagonal of the matrix ; Print matrix cell value ; Recursive function to traverse The matrix diagonally ; Recursive function to change diagonal ; Driver Code ; Initialize the 5 x 5 matrix ; Function call for traversing matrix
class GFG { static int k1 = 0 , k2 = 0 ; static boolean flag = true ; static boolean traverseMatrixDiagonally ( int m [ ] [ ] , int i , int j , int row , int col ) { if ( i >= row j >= col ) { if ( flag ) { int a = k1 ; k1 = k2 ; k2 = a ; flag = ! flag ; k1 ++ ; } else { int a = k1 ; k1 = k2 ; k2 = a ; flag = ! flag ; } System . out . println ( ) ; return false ; } System . out . print ( m [ i ] [ j ] + " ▁ " ) ; if ( traverseMatrixDiagonally ( m , i + 1 , j + 1 , row , col ) ) { return true ; } if ( traverseMatrixDiagonally ( m , k1 , k2 , row , col ) ) { return true ; } return true ; } public static void main ( String [ ] args ) { int mtrx [ ] [ ] = { { 10 , 11 , 12 , 13 , 14 } , { 15 , 16 , 17 , 18 , 19 } , { 20 , 21 , 22 , 23 , 24 } , { 25 , 26 , 27 , 28 , 29 } , { 30 , 31 , 32 , 33 , 34 } } ; traverseMatrixDiagonally ( mtrx , 0 , 0 , 5 , 5 ) ; } }
Minimum colors required such that edges forming cycle do not have same color | Java implementation to find the minimum colors required to such that edges forming cycle don 't have same color ; Variable to store the graph ; To store that the vertex is visited or not ; Boolean Value to store that graph contains cycle or not ; Variable to store the color of the edges of the graph ; Function to traverse graph using DFS Traversal ; Loop to iterate for all edges from the source vertex ; If the vertex is not visited ; Condition to check cross and forward edges of the graph ; Presence of Back Edge ; Driver Code ; Loop to run DFS Traversal on vertex which is not visited ; Loop to print the colors of the edges
import java . util . * ; class GFG { static int n = 5 , m = 7 ; static class pair { int first , second ; public pair ( int first , int second ) { this . first = first ; this . second = second ; } } static Vector < pair > [ ] g = new Vector [ m ] ; static int [ ] col = new int [ n ] ; static boolean cyc ; static int [ ] res = new int [ m ] ; static void dfs ( int v ) { col [ v ] = 1 ; for ( pair p : g [ v ] ) { int to = p . first , id = p . second ; if ( col [ to ] == 0 ) { dfs ( to ) ; res [ id ] = 1 ; } else if ( col [ to ] == 2 ) { res [ id ] = 1 ; } else { res [ id ] = 2 ; cyc = true ; } } col [ v ] = 2 ; } public static void main ( String [ ] args ) { for ( int i = 0 ; i < m ; i ++ ) g [ i ] = new Vector < pair > ( ) ; g [ 0 ] . add ( new pair ( 1 , 0 ) ) ; g [ 0 ] . add ( new pair ( 2 , 1 ) ) ; g [ 1 ] . add ( new pair ( 2 , 2 ) ) ; g [ 1 ] . add ( new pair ( 3 , 3 ) ) ; g [ 2 ] . add ( new pair ( 3 , 4 ) ) ; g [ 3 ] . add ( new pair ( 4 , 5 ) ) ; g [ 4 ] . add ( new pair ( 2 , 6 ) ) ; for ( int i = 0 ; i < n ; ++ i ) { if ( col [ i ] == 0 ) { dfs ( i ) ; } } System . out . print ( ( cyc ? 2 : 1 ) + "NEW_LINE"); for ( int i = 0 ; i < m ; ++ i ) { System . out . print ( res [ i ] + " ▁ " ) ; } } }
Perfect Sum Problem | Java implementation of the above approach ; Function to print the subsets whose sum is equal to the given target K ; Create the new array with size equal to array set [ ] to create binary array as per n ( decimal number ) ; Convert the array into binary array ; Calculate the sum of this subset ; Check whether sum is equal to target if it is equal , then print the subset ; Function to find the subsets with sum K ; Calculate the total no . of subsets ; Run loop till total no . of subsets and call the function for each subset ; Driver code
import java . util . * ; class GFG { public static void sumSubsets ( int set [ ] , int n , int target ) { int x [ ] = new int [ set . length ] ; int j = set . length - 1 ; while ( n > 0 ) { x [ j ] = n % 2 ; n = n / 2 ; j -- ; } int sum = 0 ; for ( int i = 0 ; i < set . length ; i ++ ) if ( x [ i ] == 1 ) sum = sum + set [ i ] ; if ( sum == target ) { System . out . print ( " { " ) ; for ( int i = 0 ; i < set . length ; i ++ ) if ( x [ i ] == 1 ) System . out . print ( set [ i ] + " , ▁ " ) ; System . out . print ( " } , ▁ " ) ; } } public static void findSubsets ( int [ ] arr , int K ) { int x = ( int ) Math . pow ( 2 , arr . length ) ; for ( int i = 1 ; i < x ; i ++ ) sumSubsets ( arr , i , K ) ; } public static void main ( String args [ ] ) { int arr [ ] = { 5 , 10 , 12 , 13 , 15 , 18 } ; int K = 30 ; findSubsets ( arr , K ) ; } }
Sum of subsets of all the subsets of an array | O ( N ) | Java implementation of the approach ; To store factorial values ; Function to return ncr ; Function to return the required sum ; Initialising factorial ; Multiplier ; Finding the value of multipler according to the formula ; To store the final answer ; Calculate the final answer ; Driver code
class GFG { static int maxN = 10 ; static int [ ] fact = new int [ maxN ] ; static int ncr ( int n , int r ) { return ( fact [ n ] / fact [ r ] ) / fact [ n - r ] ; } static int findSum ( int [ ] arr , int n ) { fact [ 0 ] = 1 ; for ( int i = 1 ; i < n ; i ++ ) fact [ i ] = i * fact [ i - 1 ] ; int mul = 0 ; for ( int i = 0 ; i <= n - 1 ; i ++ ) mul += ( int ) Math . pow ( 2 , i ) * ncr ( n - 1 , i ) ; int ans = 0 ; for ( int i = 0 ; i < n ; i ++ ) ans += mul * arr [ i ] ; return ans ; } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 1 } ; int n = arr . length ; System . out . println ( findSum ( arr , n ) ) ; } }
Count number of ways to reach destination in a maze | Java implementation of the approach ; Function to return the count of possible paths in a maze [ R ] [ C ] from ( 0 , 0 ) to ( R - 1 , C - 1 ) that do not pass through any of the marked cells ; If the initial cell is blocked , there is no way of moving anywhere ; Initializing the leftmost column ; If we encounter a blocked cell in leftmost row , there is no way of visiting any cell directly below it . ; Similarly initialize the topmost row ; If we encounter a blocked cell in bottommost row , there is no way of visiting any cell directly below it . ; The only difference is that if a cell is - 1 , simply ignore it else recursively compute count value maze [ i ] [ j ] ; If blockage is found , ignore this cell ; If we can reach maze [ i ] [ j ] from maze [ i - 1 ] [ j ] then increment count . ; If we can reach maze [ i ] [ j ] from maze [ i ] [ j - 1 ] then increment count . ; If the final cell is blocked , output 0 , otherwise the answer ; Function to return the count of all possible paths from ( 0 , 0 ) to ( n - 1 , m - 1 ) ; We have to calculate m + n - 2 C n - 1 here which will be ( m + n - 2 ) ! / ( n - 1 ) ! ( m - 1 ) ! ; Function to return the total count of paths from ( 0 , 0 ) to ( n - 1 , m - 1 ) that pass through at least one of the marked cells ; Total count of paths - Total paths that do not pass through any of the marked cell ; return answer ; Driver code
import java . io . * ; class GFG { static int R = 4 ; static int C = 4 ; static int countPaths ( int maze [ ] [ ] ) { if ( maze [ 0 ] [ 0 ] == - 1 ) return 0 ; for ( int i = 0 ; i < R ; i ++ ) { if ( maze [ i ] [ 0 ] == 0 ) maze [ i ] [ 0 ] = 1 ; else break ; } for ( int i = 1 ; i < C ; i ++ ) { if ( maze [ 0 ] [ i ] == 0 ) maze [ 0 ] [ i ] = 1 ; else break ; } for ( int i = 1 ; i < R ; i ++ ) { for ( int j = 1 ; j < C ; j ++ ) { if ( maze [ i ] [ j ] == - 1 ) continue ; if ( maze [ i - 1 ] [ j ] > 0 ) maze [ i ] [ j ] = ( maze [ i ] [ j ] + maze [ i - 1 ] [ j ] ) ; if ( maze [ i ] [ j - 1 ] > 0 ) maze [ i ] [ j ] = ( maze [ i ] [ j ] + maze [ i ] [ j - 1 ] ) ; } } return ( maze [ R - 1 ] [ C - 1 ] > 0 ) ? maze [ R - 1 ] [ C - 1 ] : 0 ; } static int numberOfPaths ( int m , int n ) { int path = 1 ; for ( int i = n ; i < ( m + n - 1 ) ; i ++ ) { path *= i ; path /= ( i - n + 1 ) ; } return path ; } static int solve ( int maze [ ] [ ] ) { int ans = numberOfPaths ( R , C ) - countPaths ( maze ) ; return ans ; } public static void main ( String [ ] args ) { int maze [ ] [ ] = { { 0 , 0 , 0 , 0 } , { 0 , - 1 , 0 , 0 } , { - 1 , 0 , 0 , 0 } , { 0 , 0 , 0 , 0 } } ; System . out . println ( solve ( maze ) ) ; } }
Rat in a Maze with multiple steps or jump allowed | Java program to solve Rat in a Maze problem using backtracking ; Maze size ; A utility function to print solution matrix sol [ N ] [ N ] ; A utility function to check if x , y is valid index for N * N maze ; if ( x , y outside maze ) return false ; This function solves the Maze problem using Backtracking . It mainly uses solveMazeUtil ( ) to solve the problem . It returns false if no path is possible , otherwise return true and prints the path in the form of 1 s . Please note that there may be more than one solutions , this function prints one of the feasible solutions . ; A recursive utility function to solve Maze problem ; if ( x , y is goal ) return true ; Check if maze [ x ] [ y ] is valid ; mark x , y as part of solution path ; Move forward in x direction ; Move forward in x direction ; If moving in x direction doesn 't give  solution then Move down in y direction  ; If none of the above movements work then BACKTRACK : unmark x , y as part of solution path ; Driver Code
class GFG { static int N = 4 ; static void printSolution ( int sol [ ] [ ] ) { for ( int i = 0 ; i < N ; i ++ ) { for ( int j = 0 ; j < N ; j ++ ) { System . out . printf ( " ▁ % d ▁ " , sol [ i ] [ j ] ) ; } System . out . printf ( "NEW_LINE"); } } static boolean isSafe ( int maze [ ] [ ] , int x , int y ) { if ( x >= 0 && x < N && y >= 0 && y < N && maze [ x ] [ y ] != 0 ) { return true ; } return false ; } static boolean solveMaze ( int maze [ ] [ ] ) { int sol [ ] [ ] = { { 0 , 0 , 0 , 0 } , { 0 , 0 , 0 , 0 } , { 0 , 0 , 0 , 0 } , { 0 , 0 , 0 , 0 } } ; if ( solveMazeUtil ( maze , 0 , 0 , sol ) == false ) { System . out . printf ( " Solution ▁ doesn ' t ▁ exist " ) ; return false ; } printSolution ( sol ) ; return true ; } static boolean solveMazeUtil ( int maze [ ] [ ] , int x , int y , int sol [ ] [ ] ) { if ( x == N - 1 && y == N - 1 ) { sol [ x ] [ y ] = 1 ; return true ; } if ( isSafe ( maze , x , y ) == true ) { sol [ x ] [ y ] = 1 ; for ( int i = 1 ; i <= maze [ x ] [ y ] && i < N ; i ++ ) { if ( solveMazeUtil ( maze , x + i , y , sol ) == true ) { return true ; } if ( solveMazeUtil ( maze , x , y + i , sol ) == true ) { return true ; } } sol [ x ] [ y ] = 0 ; return false ; } return false ; } public static void main ( String [ ] args ) { int maze [ ] [ ] = { { 2 , 1 , 0 , 0 } , { 3 , 0 , 0 , 1 } , { 0 , 1 , 0 , 1 } , { 0 , 0 , 0 , 1 } } ; solveMaze ( maze ) ; } }
Prime numbers after prime P with sum S | Java Program to print all N primes after prime P whose sum equals S ; vector to store prime and N primes whose sum equals given S ; function to check prime number ; square root of x ; since 1 is not prime number ; if any factor is found return false ; no factor found ; function to display N primes whose sum equals S ; function to evaluate all possible N primes whose sum equals S ; if total equals S And total is reached using N primes ; display the N primes ; if total is greater than S or if index has reached last element or if set size reached to maximum or greater than maximum ; add prime . get ( index ) to set vector ; include the ( index ) th prime to total ; remove element from set vector ; exclude ( index ) th prime ; function to generate all primes ; all primes less than S itself ; if i is prime add it to prime vector ; if primes are less than N ; Driver Code
import java . io . * ; import java . util . * ; class GFG { static ArrayList < Integer > set = new ArrayList < Integer > ( ) ; static ArrayList < Integer > prime = new ArrayList < Integer > ( ) ; static boolean isPrime ( int x ) { int sqroot = ( int ) Math . sqrt ( x ) ; if ( x == 1 ) return false ; for ( int i = 2 ; i <= sqroot ; i ++ ) if ( x % i == 0 ) return false ; return true ; } static void display ( ) { int length = set . size ( ) ; for ( int i = 0 ; i < length ; i ++ ) System . out . print ( set . get ( i ) + " ▁ " ) ; System . out . println ( ) ; } static void primeSum ( int total , int N , int S , int index ) { if ( total == S && set . size ( ) == N ) { display ( ) ; return ; } if ( total > S || index == prime . size ( ) || set . size ( ) >= N ) return ; set . add ( prime . get ( index ) ) ; primeSum ( total + prime . get ( index ) , N , S , index + 1 ) ; set . remove ( set . size ( ) - 1 ) ; primeSum ( total , N , S , index + 1 ) ; } static void allPrime ( int N , int S , int P ) { for ( int i = P + 1 ; i <= S ; i ++ ) { if ( isPrime ( i ) ) prime . add ( i ) ; } if ( prime . size ( ) < N ) return ; primeSum ( 0 , N , S , 0 ) ; } public static void main ( String args [ ] ) { int S = 54 , N = 2 , P = 3 ; allPrime ( N , S , P ) ; } }
A backtracking approach to generate n bit Gray Codes | JAVA program to find the gray sequence of n bits . ; we have 2 choices for each of the n bits either we can include i . e invert the bit or we can exclude the bit i . e we can leave the number as it is . ; base case when we run out bits to process we simply include it in gray code sequence . ; ignore the bit . ; invert the bit . ; returns the vector containing the gray code sequence of n bits . ; num is passed by reference to keep track of current code . ; Driver function .
import java . util . * ; class GFG { static int num ; static void grayCodeUtil ( Vector < Integer > res , int n ) { if ( n == 0 ) { res . add ( num ) ; return ; } grayCodeUtil ( res , n - 1 ) ; num = num ^ ( 1 << ( n - 1 ) ) ; grayCodeUtil ( res , n - 1 ) ; } static Vector < Integer > grayCodes ( int n ) { Vector < Integer > res = new Vector < Integer > ( ) ; num = 0 ; grayCodeUtil ( res , n ) ; return res ; } public static void main ( String [ ] args ) { int n = 3 ; Vector < Integer > code = grayCodes ( n ) ; for ( int i = 0 ; i < code . size ( ) ; i ++ ) System . out . print ( code . get ( i ) + "NEW_LINE"); } }
Partition of a set into K subsets with equal sum | Java program to check whether an array can be partitioned into K subsets of equal sum ; * array - given input array subsetSum array - sum to store each subset of the array taken - boolean array to check whether element is taken into sum partition or not K - number of partitions needed N - total number of element in array curIdx - current subsetSum index limitIdx - lastIdx from where array element should be taken ; current index ( K - 2 ) represents ( K - 1 ) subsets of equal sum last partition will already remain with sum ' subset ' ; recursive call for next subsetition ; start from limitIdx and include elements into current partition ; if already taken , continue ; if temp is less than subset then only include the element and call recursively ; mark the element and include into current partition sum ; after recursive call unmark the element and remove from subsetition sum ; Method returns true if arr can be partitioned into K subsets with equal sum ; If K is 1 , then complete array will be our answer ; If total number of partitions are more than N , then division is not possible ; if array sum is not divisible by K then we can 't divide  array into K partitions ; the sum of each subset should be subset ( = sum / K ) ; Initialize sum of each subset from 0 ; mark all elements as not taken ; initialize first subsubset sum as last element of array and mark that as taken ; call recursive method to check K - substitution condition ; Driver code
class GFG { static boolean isKPartitionPossibleRec ( int arr [ ] , int subsetSum [ ] , boolean taken [ ] , int subset , int K , int N , int curIdx , int limitIdx ) { if ( subsetSum [ curIdx ] == subset ) { if ( curIdx == K - 2 ) return true ; return isKPartitionPossibleRec ( arr , subsetSum , taken , subset , K , N , curIdx + 1 , N - 1 ) ; } for ( int i = limitIdx ; i >= 0 ; i -- ) { if ( taken [ i ] ) continue ; int tmp = subsetSum [ curIdx ] + arr [ i ] ; if ( tmp <= subset ) { taken [ i ] = true ; subsetSum [ curIdx ] += arr [ i ] ; boolean nxt = isKPartitionPossibleRec ( arr , subsetSum , taken , subset , K , N , curIdx , i - 1 ) ; taken [ i ] = false ; subsetSum [ curIdx ] -= arr [ i ] ; if ( nxt ) return true ; } } return false ; } static boolean isKPartitionPossible ( int arr [ ] , int N , int K ) { if ( K == 1 ) return true ; if ( N < K ) return false ; int sum = 0 ; for ( int i = 0 ; i < N ; i ++ ) sum += arr [ i ] ; if ( sum % K != 0 ) return false ; int subset = sum / K ; int [ ] subsetSum = new int [ K ] ; boolean [ ] taken = new boolean [ N ] ; for ( int i = 0 ; i < K ; i ++ ) subsetSum [ i ] = 0 ; for ( int i = 0 ; i < N ; i ++ ) taken [ i ] = false ; subsetSum [ 0 ] = arr [ N - 1 ] ; taken [ N - 1 ] = true ; return isKPartitionPossibleRec ( arr , subsetSum , taken , subset , K , N , 0 , N - 1 ) ; } public static void main ( String [ ] args ) { int arr [ ] = { 2 , 1 , 4 , 5 , 3 , 3 } ; int N = arr . length ; int K = 3 ; if ( isKPartitionPossible ( arr , N , K ) ) System . out . println ( " Partitions ▁ into ▁ equal ▁ sum ▁ is ▁ possible . " ) ; else System . out . println ( " Partitions ▁ into ▁ equal ▁ sum ▁ is ▁ not ▁ possible . " ) ; } }
Remove Invalid Parentheses | Java program to remove invalid parenthesis ; method checks if character is parenthesis ( openor closed ) ; method returns true if string contains valid parenthesis ; method to remove invalid parenthesis ; visit set to ignore already visited string ; queue to maintain BFS ; pushing given string as starting node into queue ; If answer is found , make level true so that valid string of only that level are processed . ; Removing parenthesis from str and pushing into queue , if not visited already ; Driver Code
import java . util . * ; class GFG { static boolean isParenthesis ( char c ) { return ( ( c == ' ( ' ) || ( c == ' ) ' ) ) ; } static boolean isValidString ( String str ) { int cnt = 0 ; for ( int i = 0 ; i < str . length ( ) ; i ++ ) { if ( str . charAt ( i ) == ' ( ' ) cnt ++ ; else if ( str . charAt ( i ) == ' ) ' ) cnt -- ; if ( cnt < 0 ) return false ; } return ( cnt == 0 ) ; } static void removeInvalidParenthesis ( String str ) { if ( str . isEmpty ( ) ) return ; HashSet < String > visit = new HashSet < String > ( ) ; Queue < String > q = new LinkedList < > ( ) ; String temp ; boolean level = false ; q . add ( str ) ; visit . add ( str ) ; while ( ! q . isEmpty ( ) ) { str = q . peek ( ) ; q . remove ( ) ; if ( isValidString ( str ) ) { System . out . println ( str ) ; level = true ; } if ( level ) continue ; for ( int i = 0 ; i < str . length ( ) ; i ++ ) { if ( ! isParenthesis ( str . charAt ( i ) ) ) continue ; temp = str . substring ( 0 , i ) + str . substring ( i + 1 ) ; if ( ! visit . contains ( temp ) ) { q . add ( temp ) ; visit . add ( temp ) ; } } } } public static void main ( String [ ] args ) { String expression = " ( ) ( ) ) ( ) " ; removeInvalidParenthesis ( expression ) ; expression = " ( ) v ) " ; removeInvalidParenthesis ( expression ) ; } }