Problem Description
Given a string s containing parentheses and lowercase letters, remove the minimum number of invalid parentheses so that the resulting string is valid. Return all possible valid strings (without duplicates) that can be obtained after the minimum removals. The answer can be returned in any order.
Key Insights
- Use BFS to generate all possible strings by removing one parenthesis at a time.
- Stop the BFS once valid strings are found at the current level (to ensure minimum removals).
- Use a set to avoid processing the same string multiple times.
- Use a helper function to check if a string has valid parentheses.
Space and Time Complexity
Time Complexity: O(n * 2^n) in the worst-case, as each character could be removed leading to exploring 2^n possibilities. Space Complexity: O(2^n) for storing all unique intermediate strings in the worst-case.
Solution
We solve this problem using a Breadth-First Search (BFS) approach. Start with the original string and generate all possible strings by removing one parenthesis at each step. For every generated string, check if it is valid using a helper function that traverses the string and maintains a balance counter. As soon as valid expressions are found at a particular level of BFS, add them to the result list and do not proceed to deeper levels. This ensures we remove the minimal number of parentheses. Data structures used include a queue for BFS and a set for visited strings to avoid duplicates.