Angad Sandhu
Search
Browse

301 Remove Invalid Parenthesis

Source name
301 Remove Invalid Parenthesis.py
# REMOVE INVALID PARENTHESES

# Problem number: 301
# Difficulty: Hard
# Tags: Backtracking, Breadth-First Search (BFS), String, Recursion
# Link: https://leetcode.com/problems/remove-invalid-parentheses/

from typing import List, Set

class Solution:
    """
    The goal of this problem is to remove the minimum number of invalid parentheses to make the input string valid.
    The problem can be solved using BFS to explore all possible states (strings) generated by removing one or more 
    parentheses and backtracking to ensure that all valid states are generated.

    We'll explore:
    1. BFS Approach
    2. Backtracking Approach (DFS-like behavior)

    The BFS approach ensures that the first valid solution we find is the one with the minimum number of parentheses removed.
    The backtracking approach will be used to explore all possible valid solutions.
    """

    def removeInvalidParentheses_BFS(self, s: str) -> List[str]:
        """
        BFS approach to find all valid strings after removing the minimum number of parentheses.

        T.C. : O(2^n * n) where n is the length of the string, since we explore all possible substrings.
        S.C. : O(2^n) to store all possible states in the queue.

        This method explores all possible substrings by removing one character at a time and checks if they are valid.
        """
        def is_valid(string: str) -> bool:
            count = 0
            for char in string:
                if char == '(':
                    count += 1
                elif char == ')':
                    count -= 1
                if count < 0:
                    return False
            return count == 0

        if not s:
            return [""]

        # Initialize BFS
        visited = set()
        queue = [s]
        visited.add(s)
        found = False
        result = []

        while queue:
            level_size = len(queue)
            level_visited = set()  # To avoid revisiting nodes in the same level

            for _ in range(level_size):
                current = queue.pop(0)

                # If valid, add to result
                if is_valid(current):
                    result.append(current)
                    found = True

                # If we already found valid strings, skip further exploration
                if found:
                    continue

                # Generate next level by removing one character
                for i in range(len(current)):
                    if current[i] not in ('(', ')'):
                        continue  # Skip letters
                    next_state = current[:i] + current[i+1:]
                    if next_state not in visited:
                        visited.add(next_state)
                        queue.append(next_state)

            if found:
                break  # Stop BFS once we've found valid strings at this level

        return result

    def removeInvalidParentheses_Backtracking(self, s: str) -> List[str]:
        """
        Backtracking (DFS) approach to find all valid strings.

        T.C. : O(2^n * n) where n is the length of the string, as it explores all possible substrings.
        S.C. : O(n) due to recursion stack and storage of valid results.
        """
        def is_valid(string: str) -> bool:
            count = 0
            for char in string:
                if char == '(':
                    count += 1
                elif char == ')':
                    count -= 1
                if count < 0:
                    return False
            return count == 0

        def backtrack(s: str, start: int, left_count: int, right_count: int, left_rem: int, right_rem: int, expr: List[str], result: Set[str]):
            if left_rem == 0 and right_rem == 0:
                if is_valid("".join(expr)):
                    result.add("".join(expr))
                return

            for i in range(start, len(s)):
                if i > start and s[i] == s[i - 1]:
                    continue

                # Remove a left parenthesis
                if s[i] == '(' and left_rem > 0:
                    backtrack(s, i + 1, left_count, right_count, left_rem - 1, right_rem, expr, result)
                
                # Remove a right parenthesis
                if s[i] == ')' and right_rem > 0:
                    backtrack(s, i + 1, left_count, right_count, left_rem, right_rem - 1, expr, result)

                expr.append(s[i])

                # Only backtrack when it makes sense (valid opening or closing)
                if s[i] == '(':
                    backtrack(s, i + 1, left_count + 1, right_count, left_rem, right_rem, expr, result)
                elif s[i] == ')' and left_count > right_count:
                    backtrack(s, i + 1, left_count, right_count + 1, left_rem, right_rem, expr, result)

                expr.pop()  # Backtrack

        left_rem, right_rem = 0, 0
        for char in s:
            if char == '(':
                left_rem += 1
            elif char == ')':
                if left_rem == 0:
                    right_rem += 1
                else:
                    left_rem -= 1

        result = set()
        backtrack(s, 0, 0, 0, left_rem, right_rem, [], result)
        return list(result)

# Best Method: The BFS approach ensures that the first valid solution found is the one with the minimum number of removals.

# Sample Inputs for Testing
s1 = "()())()"
s2 = "(a)())()"
s3 = ")("

# Testing BFS Method
print(Solution().removeInvalidParentheses_BFS(s1))  # Expected Output: ["(())()", "()()()"]
print(Solution().removeInvalidParentheses_BFS(s2))  # Expected Output: ["(a())()", "(a)()()"]
print(Solution().removeInvalidParentheses_BFS(s3))  # Expected Output: [""]

# Testing Backtracking Method
print(Solution().removeInvalidParentheses_Backtracking(s1))  # Expected Output: ["(())()", "()()()"]
print(Solution().removeInvalidParentheses_Backtracking(s2))  # Expected Output: ["(a())()", "(a)()()"]
print(Solution().removeInvalidParentheses_Backtracking(s3))  # Expected Output: [""]

Browse the library