Identify Invalid Parentheses for Removal
Stacks & QueuesAuto-graded · 25 test casesLast updated
Tests stack-based matching to find the minimum set of parenthesis indices that must be removed to balance a string.
You are given a string s containing lowercase letters and parentheses characters ( and ). Your task is to determine which parentheses must be removed to make the string valid.
A valid string satisfies these rules:
- Every opening parenthesis
(has exactly one matching closing parenthesis)that comes after it - Every closing parenthesis
)has exactly one matching opening parenthesis(that comes before it - The parentheses are properly nested (no crossing matches)
Return a list of indices indicating which parentheses must be removed to achieve the minimum number of deletions. The indices should be in ascending order.
Use the greedy matching strategy: each closing parenthesis matches with the most recent unmatched opening parenthesis.
Constraints:
1 <= len(s) <= 10^5scontains only lowercase English letters and the characters(and)- The solution must run in O(n) time
Examples
Example 1
Input: find_invalid_parens('a(b)c)')
Output: [5]
Example 2
Input: find_invalid_parens('()())')
Output: [4]
Example 3
Input: find_invalid_parens('abc')
Output: []
Example 4
Input: find_invalid_parens('((a))')
Output: []
Hints
Hint 1
Track unmatched opening parentheses as you scan left to right
Hint 2
A closing parenthesis with no available opening parenthesis to match must be removed
Hint 3
Any opening parenthesis that remains unmatched at the end must be removed
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The core insight is that a valid string maintains a non-negative balance as you scan from left to right, where each ( adds 1 and each ) subtracts 1, and the final balance must be zero.
We use a stack to track the indices of unmatched opening parentheses:
- When we encounter an opening parenthesis
(, push its index onto the stack - When we encounter a closing parenthesis
):- If the stack is non-empty, pop from the stack (this matches the
)with the most recent unmatched() - If the stack is empty, record this index as a required deletion (no matching opener exists)
- If the stack is non-empty, pop from the stack (this matches the
- Ignore all letter characters
- After scanning the entire string, any indices remaining on the stack represent unmatched opening parentheses that must be deleted
The result is the combination of unmatched closers found during the scan and unmatched openers remaining on the stack.
Why It Works
Minimality: Every closing parenthesis without a preceding unmatched opener is forced to be deleted. Similarly, every opening parenthesis without a following closer must be deleted. The greedy matching ensures we only delete parentheses that cannot possibly be matched, giving us the minimum count.
Correctness: After removing the identified parentheses, every remaining ) has been matched to an earlier (, and every remaining ( has been matched to a later ). The balance never goes negative during a scan, and ends at zero.
Complexity
- Time: O(n) where n is the length of the string. We make a single pass through the string, with each character processed in constant time.
- Space: O(n) in the worst case. The stack can hold up to n indices if all characters are unmatched opening parentheses.
Solution
from typing import List
def find_invalid_parens(s: str) -> List[int]:
stack = []
deletions = []
for i, ch in enumerate(s):
if ch == '(':
stack.append(i)
elif ch == ')':
if stack:
stack.pop()
else:
deletions.append(i)
deletions.extend(stack)
deletions.sort()
return deletions