Leetcode 1249: Minimum Remove to Make Valid Parentheses

grid47
grid47
Exploring patterns and algorithms
Jul 5, 2024 6 min read

You are given a string s containing lowercase English letters and parentheses. Your task is to remove the minimum number of parentheses to make the string valid.
Problem
Approach
Steps
Complexity
Input: The input consists of a string s that contains parentheses and lowercase English letters.
Example: s = "abc(de(f)gh)"
Constraints:
• 1 <= s.length <= 10^5
• s[i] is either '(' , ')', or lowercase English letter
Output: Return the string after removing the minimum number of parentheses to make it valid.
Example: "abc(de(f)gh)"
Constraints:
• The output string should be valid after removing parentheses.
Goal: Ensure the string is valid by removing unnecessary parentheses.
Steps:
• Use a stack to track the indices of unmatched parentheses.
• Iterate through the string, removing parentheses that do not form a valid pair.
• Construct and return the new string without invalid parentheses.
Goal: The string is non-empty and can contain up to 100,000 characters.
Steps:
• 1 <= s.length <= 10^5
• s[i] is either '(' , ')', or lowercase English letter
Assumptions:
• The string contains only valid parentheses or lowercase English letters.
Input: s = "abc(de(f)gh)"
Explanation: The string is already valid, so no parentheses are removed.

Input: s = "a)b(c)d"
Explanation: The first ')' is removed to make the string valid, resulting in 'ab(c)d'.

Input: s = "))(("
Explanation: All parentheses are removed, leaving an empty string, which is valid.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus