Solving Leetcode Interviews in Seconds with AI: Minimum Remove to Make Valid Parentheses
Introduction
In this blog post, we will explore how to solve the LeetCode problem "1249" using AI. LeetCode is a popular platform for preparing for coding interviews, and with the help of AI tools like Chatmagic, we can generate solutions quickly and efficiently - helping you pass the interviews and get the job offer without having to study for months.
Problem Statement
Given a string s of '(' , ')' and lowercase English characters. Your task is to remove the minimum number of parentheses ( '(' or ')', in any positions ) so that the resulting parentheses string is valid and return any valid string. Formally, a parentheses string is valid if and only if: It is the empty string, contains only lowercase characters, or It can be written as AB (A concatenated with B), where A and B are valid strings, or It can be written as (A), where A is a valid string. Example 1: Input: s = "lee(t(c)o)de)" Output: "lee(t(c)o)de" Explanation: "lee(t(co)de)" , "lee(t(c)ode)" would also be accepted. Example 2: Input: s = "a)b(c)d" Output: "ab(c)d" Example 3: Input: s = "))((" Output: "" Explanation: An empty string is also valid. Constraints: 1 <= s.length <= 105 s[i] is either '(' , ')', or lowercase English letter.
Explanation
Here's the breakdown of the approach and the Python code:
- Identify Unmatched Parentheses: Iterate through the string to track the balance of open and close parentheses. Use a stack or counter to identify the indices of unmatched parentheses.
- Mark Invalid Parentheses: Mark the invalid parentheses (those that need to be removed) using a boolean array or by directly modifying the string (e.g., replacing them with an empty string placeholder).
Build the Result: Construct the final valid string by iterating through the original string (or the modified string with placeholders) and including only the characters that are not marked as invalid.
Time and Space Complexity: O(n) time complexity, O(n) space complexity.
Code
def minRemoveToMakeValid(s: str) -> str:
"""
Removes the minimum number of parentheses from a string to make it valid.
Args:
s: The input string containing '(', ')', and lowercase English characters.
Returns:
A valid string with the minimum number of parentheses removed.
"""
n = len(s)
indices_to_remove = set()
stack = []
for i, char in enumerate(s):
if char == '(':
stack.append(i)
elif char == ')':
if stack:
stack.pop()
else:
indices_to_remove.add(i)
indices_to_remove.update(stack) # Add any remaining open parentheses
result = ""
for i, char in enumerate(s):
if i not in indices_to_remove:
result += char
return result