Skip to content
Programmingoneonone
Programmingoneonone
  • Engineering Subjects
    • Internet of Things (IoT)
    • Digital Communication
    • Human Values
  • Programming Tutorials
    • C Programming
    • Data structures and Algorithms
    • 100+ Java Programs
    • 100+ C Programs
    • 100+ C++ Programs
  • Solutions
    • HackerRank
      • Algorithms Solutions
      • C solutions
      • C++ solutions
      • Java solutions
      • Python solutions
    • Leetcode Solutions
    • HackerEarth Solutions
  • Work with US
Programmingoneonone
Programmingoneonone

Leetcode Remove Invalid Parentheses problem solution

YASH PAL, 31 July 202419 January 2026

In this Leetcode Remove Invalid Parentheses problem solution, we have given a string s that contains parentheses and letters, remove the minimum number of invalid parentheses to make the input string valid. Return all the possible results. You may return the answer in any order.

Leetcode Remove Invalid Parentheses problem solution in Python.

class Solution:
    def removeInvalidParentheses(self, s: str) -> List[str]:
        def check(s):
            count = 0 
            for i in s:
                if i =='(':
                    count += 1
                elif i == ')':
                    count -= 1 
                    if count < 0 :
                        return False
            return count == 0 
        
        dict1 ={s}
        while True:
            temp = []
            for i in dict1:
                if check(i):
                    temp.append(i)
            if temp:
                return temp 
            
            new_set = set()
            for i in dict1:
                for j in range(len(i)):
                    new_set.add(i[:j]+i[j+1:])
            dict1 = new_set

Remove Invalid Parentheses problem solution in Java.

class Solution {
    private Set<String> candidates;
    private int min;
    private String s;
    
    private boolean isBraket(char c) {
        return c == '(' || c == ')';
    }
    
    public void recurse(StringBuilder buf, int idx, int left, int right, int removed) {
        if (right > left || removed > min) {
            return;
        }
        
        if (idx == s.length()) {
            if (left != right) {
                return;
            }
            
            if (removed < min) {
                candidates.clear();
                min = removed;
            }
            
            candidates.add(buf.toString());
            return;
        }
        
        char c = s.charAt(idx);
        if (isBraket(c)) {
            recurse(buf, idx+1, left, right, removed+1);
            buf.append(c);
            boolean isLeft = (c == '(');
            recurse(buf
                    , idx+1
                    , isLeft ? left + 1 : left
                    , isLeft ? right : right + 1
                    , removed);
        } else {
            buf.append(c);
            recurse(buf, idx+1, left, right, removed);
        }
        buf.deleteCharAt(buf.length()-1);
    }
    
    public List<String> removeInvalidParentheses(String s) {
        this.s = s;
        this.min = Integer.MAX_VALUE;
        this.candidates = new HashSet<>();
        
        recurse(new StringBuilder(), 0, 0, 0, 0);
        return new ArrayList<>(this.candidates);
    }
}

Problem solution in C++.

int getmin(string str)
{
	stack<char> st;
	st.push('a');
	for (int i=0;i<str.size();i++)
	{
		char ch = str[i];
		if (ch == '(')
		{
			st.push(ch);
		} else if ( ch == ')')
		{
			if ( st.top() == '(')
			{
				st.pop();
			} else {
				st.push(')');
			}
		}
	}
	return st.size()-1;
}

Problem solution in C.

void traverse(char* s, int len, int start, int left, int right, int pair, char* stack, int top, char*** arr, int *returnSize)
{
    if(start == len)
    {
        if(!left && !right && !pair)
        {
            int size = top+1;
            char *t = (char*)malloc(sizeof(char)*(size+1));
            for(int i = 0; i < size; i++)
                t[i] = stack[i];
            t[size] = '';
            int i = 0;
            while(i < *returnSize)
            {
                if(!strcmp(t, (*arr)[i]))
                    break;
                i++;
            }
            if(i == *returnSize)
            {
                *returnSize += 1;
                *arr = (char**)realloc(*arr, sizeof(char*)*(*returnSize));
                (*arr)[*returnSize-1] = t;
            }
        }
        return ;
    }
    char c = s[start];
    if(c == '(')
    {
        if(left)
            traverse(s, len, start+1, left-1, right, pair, stack, top, arr, returnSize);
        stack[top+1] = c;
        traverse(s, len, start+1, left, right, pair+1, stack, top+1, arr, returnSize);
    }
    else if(c == ')')
    {
        if(right) =
            traverse(s, len, start+1, left, right-1, pair, stack, top, arr, returnSize);
        if(pair)
        {
            stack[top+1] = c;
            traverse(s, len, start+1, left, right, pair-1, stack, top+1, arr, returnSize);
        }
    }
    else
    {
        stack[top+1] = c;
        traverse(s, len, start+1, left, right, pair, stack, top+1, arr, returnSize);
    }
}

char** removeInvalidParentheses(char* s, int* returnSize)
{
    char** arr = (char**)malloc(sizeof(char*));
    *returnSize = 0;
    int left=0, right=0;
    for(int i = 0; s[i]; i++) 
    {
        if(s[i] == '(') left++;
        else if(s[i] == ')')
        {
            if(left) left--;
            else right++;
        }
    }
    int len = strlen(s);
    char *stack = (char*)malloc(sizeof(char)*len);
    int top = -1;
    traverse(s, len, 0, left, right, 0, stack, top, &arr, returnSize);
    return arr;
}

coding problems solutions Leetcode Problems Solutions Leetcode

Post navigation

Previous post
Next post

Leave a Reply

Your email address will not be published. Required fields are marked *

Programmingoneonone

We at Programmingoneonone, also known as Programming101 is a learning hub of programming and other related stuff. We provide free learning tutorials/articles related to programming and other technical stuff to people who are eager to learn about it.

Pages

  • About US
  • Contact US
  • Privacy Policy

Practice

  • Java
  • C++
  • C

Follow US

  • YouTube
  • LinkedIn
  • Facebook
  • Pinterest
  • Instagram
©2026 Programmingoneonone | WordPress Theme by SuperbThemes